Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Let an install use its own logo and color

Claudecabd68b8196a
diff --git a/db/migrations/20261114120000_branding.sql b/db/migrations/20261114120000_branding.sql
new file mode 100644
index 0000000..8fc4284
--- /dev/null
+++ b/db/migrations/20261114120000_branding.sql
@@ -0,0 +1,45 @@
+-- An install's own logo and color.
+--
+-- The logo is small (512 KB at most) and there is exactly one, so it lives
+-- in the settings row rather than in file storage: it is replaced and
+-- removed in one statement, and nothing can be left behind. logo_hash is
+-- the start of the image's SHA-256. The address the logo is served at
+-- carries it, so that address can be cached for good and still changes
+-- whenever the logo does. The color is stored as the administrator chose
+-- it; the shades the pages use are worked out from it when a page is built.
+
+alter table public.app_settings
+ add column if not exists brand_color text,
+ add column if not exists logo_content_type text,
+ add column if not exists logo_data bytea,
+ add column if not exists logo_hash text;
+
+alter table public.app_settings
+ drop constraint if exists app_settings_brand_color_check;
+
+alter table public.app_settings
+ add constraint app_settings_brand_color_check
+ check (brand_color is null or brand_color ~ '^#[0-9a-f]{6}$');
+
+alter table public.app_settings
+ drop constraint if exists app_settings_logo_check;
+
+alter table public.app_settings
+ add constraint app_settings_logo_check
+ check (
+ (
+ logo_data is null
+ and logo_content_type is null
+ and logo_hash is null
+ )
+ -- Each part is tested for null first: a check that comes out as
+ -- "unknown" is not a failed check, and would let a half-set logo in.
+ or (
+ logo_data is not null
+ and logo_content_type is not null
+ and logo_hash is not null
+ and logo_hash ~ '^[0-9a-f]{16}$'
+ and logo_content_type in ('image/png', 'image/jpeg', 'image/webp')
+ and octet_length(logo_data) between 1 and 524288
+ )
+ );
diff --git a/src/app/accessibility/page.tsx b/src/app/accessibility/page.tsx
index b4033d4..bd9ade1 100644
--- a/src/app/accessibility/page.tsx
+++ b/src/app/accessibility/page.tsx
@@ -93,7 +93,7 @@ export default async function AccessibilityPage() {
If you need help creating, sending, reviewing, or signing a document,
email{" "}
<Link
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href={`mailto:${supportAddress}`}
>
{supportAddress}
@@ -134,14 +134,14 @@ export default async function AccessibilityPage() {
Accessibility feedback helps us prioritize the right fixes. If you
find a barrier, email{" "}
<Link
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href={`mailto:${supportAddress}`}
>
{supportAddress}
</Link>{" "}
or use the{" "}
<Link
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href="/contact"
>
Contact
diff --git a/src/app/api/admin/logo/route.ts b/src/app/api/admin/logo/route.ts
new file mode 100644
index 0000000..6cea6fd
--- /dev/null
+++ b/src/app/api/admin/logo/route.ts
@@ -0,0 +1,134 @@
+import { NextResponse } from "next/server";
+
+import { requireAdminSession } from "@/lib/auth/admin";
+import {
+ BrandLogoError,
+ MAX_LOGO_BYTES,
+ removeBrandLogo,
+ saveBrandLogo,
+} from "@/lib/brand-logo";
+import { buildBrandLogoPath } from "@/lib/branding";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
+import { isHostedMode } from "@/lib/utils/env";
+import { readLimitedBody } from "@/lib/utils/limited-body";
+
+// The install's logo, set from the Organization tab in Settings.
+// Administrators only. The image is the request body itself.
+
+const privateNoStore = { "cache-control": "private, no-store" };
+
+const TOO_LARGE_MESSAGE = "The logo must be 512 KB or smaller.";
+
+async function authorize(request: Request) {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ // The hosted service runs under its own name and mark.
+ if (isHostedMode()) {
+ return NextResponse.json(
+ { error: "This site does not use its own logo." },
+ { headers: privateNoStore, status: 409 },
+ );
+ }
+
+ const rateLimitResponse = await applyRateLimit({
+ category: "brand_logo_update",
+ key: buildRateLimitKey(["brand-logo", sessionResult.user.id]),
+ limit: 30,
+ request,
+ userId: sessionResult.user.id,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ return rateLimitResponse ?? sessionResult;
+}
+
+export async function PUT(request: Request) {
+ const session = await authorize(request);
+
+ if (session instanceof Response) {
+ return session;
+ }
+
+ const declaredLength = Number(request.headers.get("content-length") ?? "0");
+
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_LOGO_BYTES) {
+ return NextResponse.json(
+ { error: TOO_LARGE_MESSAGE },
+ { headers: privateNoStore, status: 413 },
+ );
+ }
+
+ try {
+ const body = await readLimitedBody(request, MAX_LOGO_BYTES);
+
+ if (!body) {
+ return NextResponse.json(
+ { error: TOO_LARGE_MESSAGE },
+ { headers: privateNoStore, status: 413 },
+ );
+ }
+
+ const version = await saveBrandLogo(body);
+
+ return NextResponse.json(
+ { logoUrl: buildBrandLogoPath(version) },
+ { headers: privateNoStore },
+ );
+ } catch (error) {
+ if (error instanceof BrandLogoError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: privateNoStore, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "brand_logo_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while saving the logo.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "The logo could not be saved." },
+ { headers: privateNoStore, status: 500 },
+ );
+ }
+}
+
+export async function DELETE(request: Request) {
+ const session = await authorize(request);
+
+ if (session instanceof Response) {
+ return session;
+ }
+
+ try {
+ await removeBrandLogo();
+
+ return NextResponse.json({ logoUrl: null }, { headers: privateNoStore });
+ } catch (error) {
+ logRouteError(error, {
+ category: "brand_logo_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while removing the logo.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "The logo could not be removed." },
+ { headers: privateNoStore, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/brand/logo/route.ts b/src/app/api/brand/logo/route.ts
new file mode 100644
index 0000000..3f272b4
--- /dev/null
+++ b/src/app/api/brand/logo/route.ts
@@ -0,0 +1,66 @@
+import { readBrandLogo } from "@/lib/brand-logo";
+import { logRouteError } from "@/lib/security/logging";
+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
+import { isHostedMode } from "@/lib/utils/env";
+
+// The install's logo. Public: it is in the header of the pages signers see
+// and at the top of the emails they get.
+
+const YEAR_SECONDS = 365 * 24 * 60 * 60;
+
+function notFound() {
+ return new Response(null, {
+ headers: { "cache-control": "public, max-age=60" },
+ status: 404,
+ });
+}
+
+export async function GET(request: Request) {
+ if (isHostedMode()) {
+ return notFound();
+ }
+
+ try {
+ const logo = await readBrandLogo();
+
+ if (!logo) {
+ return notFound();
+ }
+
+ // Pages and emails ask for the logo by its version, which is part of
+ // the image's hash: that address never shows anything else, so it can
+ // be kept for good. Asked for any other way, the answer is kept only
+ // briefly, since the logo may change.
+ const requested = new URL(request.url).searchParams.get("v");
+ const cacheControl =
+ requested === logo.version
+ ? `public, max-age=${YEAR_SECONDS}, s-maxage=${YEAR_SECONDS}, immutable`
+ : "public, max-age=300";
+
+ return new Response(Buffer.from(logo.bytes), {
+ headers: {
+ "cache-control": cacheControl,
+ "content-disposition": "inline",
+ "content-length": String(logo.bytes.byteLength),
+ // An image and nothing else, whatever is in the file.
+ "content-security-policy": "default-src 'none'; sandbox",
+ "content-type": logo.contentType,
+ "cross-origin-resource-policy": "cross-origin",
+ "x-content-type-options": "nosniff",
+ },
+ status: 200,
+ });
+ } catch (error) {
+ logRouteError(error, {
+ category: "brand_logo_read_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while loading the logo.",
+ path: getRequestPathname(request),
+ });
+
+ return new Response(null, {
+ headers: { "cache-control": "no-store" },
+ status: 500,
+ });
+ }
+}
diff --git a/src/app/api/envelopes/[id]/thumbnail/route.ts b/src/app/api/envelopes/[id]/thumbnail/route.ts
index 52949ee..a3280ad 100644
--- a/src/app/api/envelopes/[id]/thumbnail/route.ts
+++ b/src/app/api/envelopes/[id]/thumbnail/route.ts
@@ -18,6 +18,7 @@ import {
THUMBNAIL_MAX_BYTES,
ThumbnailValidationError,
} from "@/lib/services/thumbnails";
+import { readLimitedBody } from "@/lib/utils/limited-body";
type EnvelopeThumbnailRouteContext = {
params: Promise<{
@@ -165,44 +166,3 @@ export async function PUT(
);
}
}
-
-/** Reads the body, giving up as soon as it is larger than the limit. */
-async function readLimitedBody(
- request: Request,
- maxBytes: number,
-): Promise<Uint8Array | null> {
- if (!request.body) {
- return new Uint8Array();
- }
-
- const reader = request.body.getReader();
- const chunks: Uint8Array[] = [];
- let total = 0;
-
- for (;;) {
- const { done, value } = await reader.read();
-
- if (done) {
- break;
- }
-
- total += value.byteLength;
-
- if (total > maxBytes) {
- await reader.cancel().catch(() => undefined);
- return null;
- }
-
- chunks.push(value);
- }
-
- const body = new Uint8Array(total);
- let offset = 0;
-
- for (const chunk of chunks) {
- body.set(chunk, offset);
- offset += chunk.byteLength;
- }
-
- return body;
-}
diff --git a/src/app/globals.css b/src/app/globals.css
index 76f784b..63bf23a 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -23,7 +23,7 @@
--color-destructive-foreground: #ffffff;
--color-border: var(--border);
--color-input: var(--border);
- --color-ring: rgba(83, 64, 214, 0.32);
+ --color-ring: rgb(var(--accent-rgb) / 0.32);
--color-chart-1: var(--signer-1);
--color-chart-2: var(--signer-2);
--color-chart-3: var(--signer-3);
@@ -58,9 +58,15 @@
--secondary: #575a6e;
--tertiary: #6e7183;
--placeholder: #8b8ea0;
+ /*
+ * The accent and its shades. An install with its own color replaces all
+ * of these together, from a rule the layout adds (see brand-color.ts).
+ */
--accent: #5340d6;
+ --accent-rgb: 83 64 214;
--accent-hover: #4433b8;
--accent-soft: #ece9fd;
+ --accent-soft-hover: #e0dbfb;
--accent-softer: #f4f2ff;
--accent-ink: #4433b8;
--danger: #b42318;
@@ -141,11 +147,11 @@
}
::selection {
- background: rgba(83, 64, 214, 0.18);
+ background: rgb(var(--accent-rgb) / 0.18);
}
:focus-visible {
- outline: 2px solid rgba(83, 64, 214, 0.55);
+ outline: 2px solid rgb(var(--accent-rgb) / 0.55);
outline-offset: 2px;
}
@@ -323,7 +329,7 @@
.field-input:focus-visible {
border-color: var(--accent);
- box-shadow: 0 0 0 3px rgba(83, 64, 214, 0.16);
+ box-shadow: 0 0 0 3px rgb(var(--accent-rgb) / 0.16);
}
.field-input:disabled {
diff --git a/src/app/privacy/page.tsx b/src/app/privacy/page.tsx
index 44bb4bd..b6bbc89 100644
--- a/src/app/privacy/page.tsx
+++ b/src/app/privacy/page.tsx
@@ -219,7 +219,7 @@ export default async function PrivacyPage() {
<p>
To request access, correction, deletion, or account closure, email{" "}
<Link
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href={`mailto:${privacyAddress}`}
>
{privacyAddress}
@@ -286,14 +286,14 @@ export default async function PrivacyPage() {
<p>
Privacy questions, requests, and complaints may be sent to{" "}
<Link
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href={`mailto:${privacyAddress}`}
>
{privacyAddress}
</Link>{" "}
or through the{" "}
<Link
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href="/contact"
>
Contact
diff --git a/src/app/terms/page.tsx b/src/app/terms/page.tsx
index 22c7e07..ad739f3 100644
--- a/src/app/terms/page.tsx
+++ b/src/app/terms/page.tsx
@@ -229,7 +229,7 @@ export default async function TermsPage() {
Account-closure requests may be submitted through the settings page or
by contacting{" "}
<Link
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href={`mailto:${supportAddress}`}
>
{supportAddress}
@@ -324,14 +324,14 @@ export default async function TermsPage() {
<p>
Questions about these Terms may be sent to{" "}
<Link
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href={`mailto:${supportAddress}`}
>
{supportAddress}
</Link>{" "}
or through the{" "}
<Link
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href="/contact"
>
Contact
diff --git a/src/components/envelopes/prepare-live-shell.tsx b/src/components/envelopes/prepare-live-shell.tsx
index 42397bc..b3114a9 100644
--- a/src/components/envelopes/prepare-live-shell.tsx
+++ b/src/components/envelopes/prepare-live-shell.tsx
@@ -925,7 +925,7 @@ function PrepareLiveShellContent({
})}
{armedTool ? (
- <div className="pointer-events-none absolute inset-x-4 bottom-4 z-11 rounded-2xl bg-white/95 px-4 py-3 shadow-(--shadow-lift) ring-1 ring-[rgba(83,64,214,0.18)] sm:inset-x-6 sm:bottom-6">
+ <div className="pointer-events-none absolute inset-x-4 bottom-4 z-11 rounded-2xl bg-white/95 px-4 py-3 shadow-(--shadow-lift) ring-1 ring-[rgb(var(--accent-rgb)/0.18)] sm:inset-x-6 sm:bottom-6">
<p className="text-[0.8125rem] font-bold text-(--accent-ink)">
Ready to place
</p>
diff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsx
index 5518f00..92ee3bc 100644
--- a/src/components/envelopes/review-shell.tsx
+++ b/src/components/envelopes/review-shell.tsx
@@ -509,7 +509,7 @@ function SendConfirmationDialog({
agreement and not a will, court order, legally required consumer
disclosure, or other{" "}
<a
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href={PERMITTED_USE_PATH}
rel="noreferrer"
target="_blank"
diff --git a/src/components/envelopes/signers-shell.tsx b/src/components/envelopes/signers-shell.tsx
index 25f5dca..c1d42b1 100644
--- a/src/components/envelopes/signers-shell.tsx
+++ b/src/components/envelopes/signers-shell.tsx
@@ -928,7 +928,7 @@ export function SignersShell({
<div className="flex flex-wrap items-center gap-3">
<button
- className="inline-flex min-h-11 items-center justify-center rounded-[0.875rem] bg-(--accent-soft) px-4.5 text-sm font-bold text-(--accent-ink) transition hover:bg-[#e0dbfb] disabled:cursor-not-allowed disabled:opacity-50"
+ className="inline-flex min-h-11 items-center justify-center rounded-[0.875rem] bg-(--accent-soft) px-4.5 text-sm font-bold text-(--accent-ink) transition hover:bg-(--accent-soft-hover) disabled:cursor-not-allowed disabled:opacity-50"
disabled={!canAddSigner || isSubmitting}
onClick={handleAddSigner}
type="button"
diff --git a/src/components/envelopes/upload-shell.tsx b/src/components/envelopes/upload-shell.tsx
index 2da7925..bdf2a1b 100644
--- a/src/components/envelopes/upload-shell.tsx
+++ b/src/components/envelopes/upload-shell.tsx
@@ -197,7 +197,7 @@ function UploadShellLayout({
</p>
<p className="text-sm text-(--secondary)">
or{" "}
- <span className="font-bold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4">
+ <span className="font-bold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4">
click to browse
</span>
</p>
diff --git a/src/components/landing/landing-shell.tsx b/src/components/landing/landing-shell.tsx
index 25971e9..e66e12a 100644
--- a/src/components/landing/landing-shell.tsx
+++ b/src/components/landing/landing-shell.tsx
@@ -400,7 +400,7 @@ function ComparisonTable() {
</td>
<td
className={cn(
- "border-t border-[rgba(83,64,214,0.12)] bg-(--accent-softer) px-5 py-4 text-center",
+ "border-t border-[rgb(var(--accent-rgb)/0.12)] bg-(--accent-softer) px-5 py-4 text-center",
index === comparisonRows.length - 1 && "rounded-b-2xl",
)}
>
diff --git a/src/components/layout/brand.tsx b/src/components/layout/brand.tsx
index 8a2868f..0d249de 100644
--- a/src/components/layout/brand.tsx
+++ b/src/components/layout/brand.tsx
@@ -18,7 +18,21 @@ export function Brand({
href = "/",
labelClassName = "",
}: BrandProps) {
- const { productName } = useBranding();
+ const { logoUrl, productName } = useBranding();
+
+ // An install's own logo stands in for the mark and the name. The link
+ // still carries the name, for people who cannot see the picture.
+ if (logoUrl) {
+ return (
+ <Link
+ aria-label={productName}
+ className={cn("inline-flex min-w-0 items-center", className)}
+ href={href}
+ >
+ <BrandLogo compact={compact} src={logoUrl} />
+ </Link>
+ );
+ }
return (
<Link
@@ -44,7 +58,34 @@ export function Brand({
);
}
-/** The signature stroke on a violet tile. Decorative: the link carries the name. */
+/** The install's own logo, kept to the height of the header. */
+export function BrandLogo({
+ className = "",
+ compact = false,
+ src,
+}: {
+ className?: string;
+ compact?: boolean;
+ src: string;
+}) {
+ return (
+ // Served by this site at an address that changes with the image:
+ // next/image would only add a second copy to keep in step.
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ alt=""
+ className={cn(
+ "block h-8 w-auto object-contain object-left",
+ compact ? "max-w-10" : "max-w-[44vw] sm:max-w-44",
+ className,
+ )}
+ decoding="async"
+ src={src}
+ />
+ );
+}
+
+/** The signature stroke on a tile in the accent color. Decorative: the link carries the name. */
export function BrandMark({ className = "" }: { className?: string }) {
return (
<span
diff --git a/src/components/layout/branding-provider.tsx b/src/components/layout/branding-provider.tsx
index cee8cab..8e7c7e5 100644
--- a/src/components/layout/branding-provider.tsx
+++ b/src/components/layout/branding-provider.tsx
@@ -2,6 +2,7 @@
import { createContext, useContext, type ReactNode } from "react";
+import { buildBrandColorCss } from "@/lib/brand-color";
import { HOSTED_BRANDING, type Branding } from "@/lib/branding";
// What this install calls itself, handed down from the server layouts that
@@ -19,8 +20,14 @@ export function BrandingProvider({
branding,
children,
}: BrandingProviderProps) {
+ // An install with its own color replaces the accent everywhere below
+ // this point. The rule is built from numbers, never from the stored text
+ // as it stands, so nothing but colors can end up in it.
+ const brandColorCss = buildBrandColorCss(branding.brandColor);
+
return (
<BrandingContext.Provider value={branding}>
+ {brandColorCss ? <style>{brandColorCss}</style> : null}
{children}
</BrandingContext.Provider>
);
diff --git a/src/components/settings/branding-panel.tsx b/src/components/settings/branding-panel.tsx
new file mode 100644
index 0000000..8494d71
--- /dev/null
+++ b/src/components/settings/branding-panel.tsx
@@ -0,0 +1,258 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useRef, useState, type CSSProperties, type ChangeEvent } from "react";
+
+import { BrandLogo } from "@/components/layout/brand";
+import {
+ DEFAULT_BRAND_COLOR,
+ DEFAULT_BRAND_PALETTE,
+ brandPaletteVariables,
+ buildBrandPalette,
+ normalizeBrandColor,
+} from "@/lib/brand-color";
+import { LOGO_CONTENT_TYPES, MAX_LOGO_BYTES } from "@/lib/branding";
+
+// The install's own logo and color, on the Organization tab in Settings.
+//
+// The logo is saved as soon as it is chosen. The color is part of the form
+// around this panel and is saved with it.
+
+const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";
+
+type BrandingPanelProps = {
+ brandColor: string;
+ brandColorError?: string;
+ disabled: boolean;
+ logoUrl: string | null;
+ onBrandColorChange: (value: string) => void;
+ onLogoChange: (logoUrl: string | null) => void;
+};
+
+type LogoResponse = { error?: string; logoUrl?: string | null } | null;
+
+export function BrandingPanel({
+ brandColor,
+ brandColorError,
+ disabled,
+ logoUrl,
+ onBrandColorChange,
+ onLogoChange,
+}: BrandingPanelProps) {
+ const router = useRouter();
+ const fileInput = useRef<HTMLInputElement>(null);
+ const [logoError, setLogoError] = useState<string | null>(null);
+ const [logoBusy, setLogoBusy] = useState<"removing" | "uploading" | null>(
+ null,
+ );
+
+ const typedColor = normalizeBrandColor(brandColor);
+ const palette =
+ (typedColor ? buildBrandPalette(typedColor) : null) ??
+ DEFAULT_BRAND_PALETTE;
+ const darkened = typedColor !== null && palette.accent !== typedColor;
+
+ async function sendLogo(file: File | null) {
+ setLogoError(null);
+ setLogoBusy(file ? "uploading" : "removing");
+
+ try {
+ const response = await fetch("/api/admin/logo", {
+ body: file,
+ headers: file ? { "content-type": "application/octet-stream" } : {},
+ method: file ? "PUT" : "DELETE",
+ });
+ const payload = (await response.json().catch(() => null)) as LogoResponse;
+
+ if (!response.ok || !payload || payload.logoUrl === undefined) {
+ setLogoError(payload?.error ?? GENERIC_ERROR_MESSAGE);
+ return;
+ }
+
+ onLogoChange(payload.logoUrl);
+ // The header above this page shows the logo too.
+ router.refresh();
+ } catch {
+ setLogoError(GENERIC_ERROR_MESSAGE);
+ } finally {
+ setLogoBusy(null);
+ }
+ }
+
+ function handleFileChosen(event: ChangeEvent<HTMLInputElement>) {
+ const file = event.target.files?.[0] ?? null;
+
+ // So choosing the same file again, after an error, is still a change.
+ event.target.value = "";
+
+ if (!file) {
+ return;
+ }
+
+ if (!(LOGO_CONTENT_TYPES as readonly string[]).includes(file.type)) {
+ setLogoError("The logo must be a PNG, JPEG or WebP image.");
+ return;
+ }
+
+ if (file.size > MAX_LOGO_BYTES) {
+ setLogoError("The logo must be 512 KB or smaller.");
+ return;
+ }
+
+ void sendLogo(file);
+ }
+
+ const busy = disabled || logoBusy !== null;
+
+ return (
+ <div className="space-y-5 border-t border-(--border) pt-8">
+ <div className="space-y-2">
+ <h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">
+ Logo and color
+ </h3>
+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">
+ Optional. Your logo goes in the header of this site, on the pages
+ signers see and at the top of emails. Your color is used for buttons
+ and links.
+ </p>
+ </div>
+
+ <div className="grid gap-4 sm:grid-cols-2">
+ <div className="well space-y-4 p-4">
+ <p className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Logo
+ </p>
+ <div className="flex min-h-16 items-center rounded-xl bg-(--paper) px-4 py-3">
+ {logoUrl ? (
+ <BrandLogo src={logoUrl} />
+ ) : (
+ <span className="text-sm leading-6 text-(--tertiary)">
+ No logo yet. The header shows your organization&rsquo;s name.
+ </span>
+ )}
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <input
+ accept={LOGO_CONTENT_TYPES.join(",")}
+ aria-label="Logo image"
+ className="hidden"
+ disabled={busy}
+ onChange={handleFileChosen}
+ ref={fileInput}
+ tabIndex={-1}
+ type="file"
+ />
+ <button
+ className="btn-quiet"
+ disabled={busy}
+ onClick={() => fileInput.current?.click()}
+ type="button"
+ >
+ {logoBusy === "uploading"
+ ? "Uploading..."
+ : logoUrl
+ ? "Replace logo"
+ : "Upload a logo"}
+ </button>
+ {logoUrl ? (
+ <button
+ className="btn-quiet btn-quiet-danger"
+ disabled={busy}
+ onClick={() => void sendLogo(null)}
+ type="button"
+ >
+ {logoBusy === "removing" ? "Removing..." : "Remove logo"}
+ </button>
+ ) : null}
+ </div>
+ {logoError ? (
+ <p className="text-xs font-semibold text-(--danger)" role="alert">
+ {logoError}
+ </p>
+ ) : (
+ <p className="text-xs leading-5 text-(--tertiary)">
+ PNG, JPEG or WebP, up to 512 KB. A wide logo on a transparent
+ background works best. It is saved as soon as you choose it.
+ </p>
+ )}
+ </div>
+
+ <div className="well space-y-4 p-4">
+ <label
+ className="block text-[0.8125rem] font-semibold text-(--secondary)"
+ htmlFor="brand-color"
+ >
+ Brand color
+ </label>
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ aria-label="Color picker"
+ className="size-12 shrink-0 cursor-pointer rounded-xl border-[1.5px] border-(--border-strong) bg-(--paper) p-1 disabled:cursor-not-allowed"
+ disabled={disabled}
+ onChange={(event) => onBrandColorChange(event.target.value)}
+ type="color"
+ value={typedColor ?? DEFAULT_BRAND_COLOR}
+ />
+ <input
+ aria-describedby="brand-color-description"
+ aria-invalid={brandColorError ? true : undefined}
+ autoCapitalize="none"
+ autoComplete="off"
+ className="field-input w-36 font-mono"
+ disabled={disabled}
+ id="brand-color"
+ maxLength={16}
+ name="brand-color"
+ onChange={(event) => onBrandColorChange(event.target.value)}
+ placeholder={DEFAULT_BRAND_COLOR}
+ spellCheck={false}
+ value={brandColor}
+ />
+ {brandColor ? (
+ <button
+ className="btn-quiet"
+ disabled={disabled}
+ onClick={() => onBrandColorChange("")}
+ type="button"
+ >
+ Use the default
+ </button>
+ ) : null}
+ </div>
+ {/* What the color will look like, before it is saved. */}
+ <div
+ aria-hidden="true"
+ className="flex flex-wrap items-center gap-3 rounded-xl bg-(--paper) px-4 py-3"
+ style={brandPaletteVariables(palette) as CSSProperties}
+ >
+ <span className="inline-flex min-h-9 items-center rounded-[0.75rem] bg-(--accent) px-3.5 text-[0.8125rem] font-bold text-white">
+ Button
+ </span>
+ <span className="pill pill-accent">Status</span>
+ <span className="text-[0.8125rem] font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4">
+ Link
+ </span>
+ </div>
+ {brandColorError ? (
+ <p
+ className="text-xs font-semibold text-(--danger)"
+ id="brand-color-description"
+ role="alert"
+ >
+ {brandColorError}
+ </p>
+ ) : (
+ <p
+ className="text-xs leading-5 text-(--tertiary)"
+ id="brand-color-description"
+ >
+ {darkened
+ ? "This color is too light for white text to be read on it, so a darker shade of it is used."
+ : "Six letters and digits, such as #1a73e8. Leave empty for the default. Saved with the button below."}
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsx
index 12195d5..09d2a17 100644
--- a/src/components/settings/organization-settings.tsx
+++ b/src/components/settings/organization-settings.tsx
@@ -1,8 +1,10 @@
"use client";
+import { useRouter } from "next/navigation";
import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";
import { FieldShell, ShellButton } from "@/components/shared/form-shell";
+import { BrandingPanel } from "@/components/settings/branding-panel";
import { PeoplePanel } from "@/components/settings/people-panel";
import { SignerDataPanel } from "@/components/settings/signer-data-panel";
import type { EmailDnsRecord, EmailStatus } from "@/lib/email-status";
@@ -69,6 +71,7 @@ const signupModeOptions: Array<{
export function OrganizationSettings({
initialSettings,
}: OrganizationSettingsProps) {
+ const router = useRouter();
const [values, setValues] = useState(initialSettings);
const [errors, setErrors] = useState<FormErrors>({});
const [feedback, setFeedback] = useState<Feedback>(null);
@@ -87,6 +90,12 @@ export function OrganizationSettings({
};
}
+ function handleBrandColorChange(brandColor: string) {
+ setValues((currentValues) => ({ ...currentValues, brandColor }));
+ setErrors((currentErrors) => ({ ...currentErrors, brandColor: undefined }));
+ setFeedback(null);
+ }
+
function handleSignupModeChange(signupMode: SignupMode) {
setValues((currentValues) => ({ ...currentValues, signupMode }));
setErrors((currentErrors) => ({
@@ -112,6 +121,7 @@ export function OrganizationSettings({
const response = await fetch("/api/admin/settings", {
body: JSON.stringify({
allowedEmailDomains: values.allowedEmailDomains,
+ brandColor: values.brandColor,
organizationName: values.organizationName,
privacyUrl: values.privacyUrl,
retentionDays: values.retentionDays,
@@ -139,6 +149,9 @@ export function OrganizationSettings({
setValues(payload.settings);
setEmailRevision((revision) => revision + 1);
setFeedback({ message: "Organization settings saved.", tone: "success" });
+ // The header and the accent color come from the layout around this
+ // page, which only looks them up again when asked to.
+ router.refresh();
} catch {
setFeedback({ message: GENERIC_ERROR_MESSAGE, tone: "error" });
} finally {
@@ -190,6 +203,20 @@ export function OrganizationSettings({
/>
</div>
+ {/* The hosted service runs under its own name, mark and color. */}
+ {!values.hosted ? (
+ <BrandingPanel
+ brandColor={values.brandColor}
+ brandColorError={errors.brandColor}
+ disabled={isSaving}
+ logoUrl={values.logoUrl}
+ onBrandColorChange={handleBrandColorChange}
+ onLogoChange={(logoUrl) =>
+ setValues((currentValues) => ({ ...currentValues, logoUrl }))
+ }
+ />
+ ) : null}
+
<fieldset className="space-y-4 border-t border-(--border) pt-8">
<legend className="float-left mb-4 w-full text-lg font-extrabold tracking-[-0.02em] text-(--fg)">
Who can create an account
@@ -317,7 +344,7 @@ export function OrganizationSettings({
<p className="max-w-2xl text-sm leading-6 text-(--secondary)">
Without a privacy policy link, signers see{" "}
<a
- className="font-semibold text-(--accent-ink) underline decoration-[rgba(83,64,214,0.35)] underline-offset-4"
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
href="/signer-privacy"
target="_blank"
>
diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsx
index 098f291..88f614f 100644
--- a/src/components/signing/signing-live-shell.tsx
+++ b/src/components/signing/signing-live-shell.tsx
@@ -1179,8 +1179,8 @@ function CurrentSignerField({
aria-label={getSummaryLabel(field)}
className={`absolute z-2 overflow-hidden rounded-[0.375rem] border-2 border-(--accent) text-(--accent-ink) transition ${
signatureEntry?.value
- ? "bg-[rgba(83,64,214,0.10)]"
- : "bg-[rgba(83,64,214,0.07)] hover:bg-[rgba(83,64,214,0.16)]"
+ ? "bg-[rgb(var(--accent-rgb)/0.10)]"
+ : "bg-[rgb(var(--accent-rgb)/0.07)] hover:bg-[rgb(var(--accent-rgb)/0.16)]"
}`}
data-signing-field="true"
onClick={onSignatureClick}
@@ -1244,7 +1244,7 @@ function CurrentSignerField({
if (field.type === "text") {
return (
<div
- className="absolute z-2 overflow-hidden rounded-[0.375rem] border-2 border-(--accent) bg-[rgba(83,64,214,0.07)] focus-within:bg-white"
+ className="absolute z-2 overflow-hidden rounded-[0.375rem] border-2 border-(--accent) bg-[rgb(var(--accent-rgb)/0.07)] focus-within:bg-white"
data-signing-field="true"
style={frame}
>
@@ -1267,8 +1267,8 @@ function CurrentSignerField({
aria-pressed={checkboxValue}
className={`absolute z-2 flex items-center justify-center rounded-[0.25rem] border-2 border-(--accent) text-(--accent-ink) transition ${
checkboxValue
- ? "bg-[rgba(83,64,214,0.14)]"
- : "bg-white hover:bg-[rgba(83,64,214,0.10)]"
+ ? "bg-[rgb(var(--accent-rgb)/0.14)]"
+ : "bg-white hover:bg-[rgb(var(--accent-rgb)/0.10)]"
}`}
data-signing-field="true"
onClick={() => onCheckboxChange(!checkboxValue)}
diff --git a/src/lib/brand-color.test.ts b/src/lib/brand-color.test.ts
new file mode 100644
index 0000000..a4c438c
--- /dev/null
+++ b/src/lib/brand-color.test.ts
@@ -0,0 +1,124 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ buildBrandColorCss,
+ buildBrandPalette,
+ contrastRatio,
+ normalizeBrandColor,
+} from "./brand-color.ts";
+
+test("normalizeBrandColor accepts plain hex colors only", () => {
+ assert.equal(normalizeBrandColor("#1A73E8"), "#1a73e8");
+ assert.equal(normalizeBrandColor(" 1a73e8 "), "#1a73e8");
+ assert.equal(normalizeBrandColor("#17e"), "#1177ee");
+
+ for (const input of [
+ "",
+ "red",
+ "#12345",
+ "#1234567",
+ "#12345g",
+ "rgb(1,2,3)",
+ "#fff;}body{display:none",
+ "url(https://example.com)",
+ null,
+ undefined,
+ 42,
+ ]) {
+ assert.equal(normalizeBrandColor(input), null, String(input));
+ }
+});
+
+test("a color that is already readable is kept as it is", () => {
+ const palette = buildBrandPalette("#5340d6");
+
+ assert.ok(palette);
+ assert.equal(palette.accent, "#5340d6");
+ assert.equal(palette.accentRgb, "83 64 214");
+ // Close to the tints the design was drawn with.
+ assert.equal(palette.accentSoft, "#eceafa");
+ assert.equal(palette.accentSofter, "#f4f3fc");
+});
+
+test("every palette is readable, whatever color it starts from", () => {
+ const colors = [
+ "#000000",
+ "#ffffff",
+ "#ffd400",
+ "#00e676",
+ "#ff0000",
+ "#1a73e8",
+ "#0b3d2e",
+ "#ff69b4",
+ "#808080",
+ "#00ffff",
+ ];
+
+ for (const color of colors) {
+ const palette = buildBrandPalette(color);
+
+ assert.ok(palette, color);
+
+ // White text on a button.
+ assert.ok(contrastRatio(palette.accent, "#ffffff") >= 4.5, color);
+ assert.ok(contrastRatio(palette.accentHover, "#ffffff") >= 4.5, color);
+
+ // Brand-colored text on white, on the page and on the tints.
+ for (const background of [
+ "#ffffff",
+ "#f3f4f8",
+ palette.accentSoft,
+ palette.accentSofter,
+ palette.accentSoftHover,
+ ]) {
+ assert.ok(
+ contrastRatio(palette.accentInk, background) >= 4.5,
+ `${color} ink on ${background}`,
+ );
+ }
+
+ for (const shade of Object.values(palette)) {
+ assert.match(shade, /^(#[0-9a-f]{6}|\d{1,3} \d{1,3} \d{1,3})$/);
+ }
+ }
+});
+
+test("a light color is darkened rather than refused", () => {
+ const palette = buildBrandPalette("#ffd400");
+
+ assert.ok(palette);
+ assert.notEqual(palette.accent, "#ffd400");
+ assert.ok(contrastRatio(palette.accent, "#ffffff") >= 4.5);
+});
+
+test("buildBrandColorCss writes one rule made only of colors", () => {
+ assert.equal(buildBrandColorCss(null), null);
+ assert.equal(buildBrandColorCss("not a color"), null);
+ assert.equal(buildBrandColorCss("#fff;}*{display:none}"), null);
+
+ const css = buildBrandColorCss("#1A73E8");
+
+ assert.ok(css);
+ assert.match(
+ css,
+ /^:root\{(--accent(-[a-z]+)*:(#[0-9a-f]{6}|\d{1,3} \d{1,3} \d{1,3});)+\}$/,
+ );
+ assert.ok(css.includes("--accent:#1a73e8;"));
+});
+
+test("the default palette is the one the stylesheet ships with", async () => {
+ const { readFile } = await import("node:fs/promises");
+ const css = await readFile(
+ new URL("../app/globals.css", import.meta.url),
+ "utf8",
+ );
+ const { DEFAULT_BRAND_PALETTE, brandPaletteVariables } =
+ await import("./brand-color.ts");
+
+ for (const [name, value] of Object.entries(
+ brandPaletteVariables(DEFAULT_BRAND_PALETTE),
+ )) {
+ assert.ok(css.includes(`${name}: ${value};`), `${name}: ${value}`);
+ }
+});
diff --git a/src/lib/brand-color.ts b/src/lib/brand-color.ts
new file mode 100644
index 0000000..2832bff
--- /dev/null
+++ b/src/lib/brand-color.ts
@@ -0,0 +1,202 @@
+// An install's own color.
+//
+// The administrator picks one color. Everything the pages need is worked
+// out from it: the color itself for buttons (darkened until white text on
+// it is readable), a darker shade for hover and for text, and pale tints
+// for backgrounds. Nothing here trusts its input: the only thing that ever
+// reaches a page is a set of six-digit hex colors built from numbers.
+
+export type BrandPalette = {
+ /** Buttons, links and focus rings. White text on it is readable. */
+ accent: string;
+ accentHover: string;
+ /** Text in the brand color, readable on white and on the pale tints. */
+ accentInk: string;
+ /** "83 64 214", for shades with transparency. */
+ accentRgb: string;
+ accentSoft: string;
+ accentSoftHover: string;
+ accentSofter: string;
+};
+
+/** The accent the design ships with. Keep in step with globals.css. */
+export const DEFAULT_BRAND_COLOR = "#5340d6";
+
+export const DEFAULT_BRAND_PALETTE: BrandPalette = {
+ accent: DEFAULT_BRAND_COLOR,
+ accentHover: "#4433b8",
+ accentInk: "#4433b8",
+ accentRgb: "83 64 214",
+ accentSoft: "#ece9fd",
+ accentSoftHover: "#e0dbfb",
+ accentSofter: "#f4f2ff",
+};
+
+type Rgb = [red: number, green: number, blue: number];
+
+const WHITE: Rgb = [255, 255, 255];
+const BLACK: Rgb = [0, 0, 0];
+
+/** WCAG AA for normal text. */
+const READABLE_CONTRAST = 4.5;
+
+const HEX_COLOR = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;
+
+/**
+ * "#1A73E8", "1a73e8" or "#17e" as "#1a73e8". Null for anything that is not
+ * a plain hex color.
+ */
+export function normalizeBrandColor(input: unknown): string | null {
+ if (typeof input !== "string") {
+ return null;
+ }
+
+ const match = HEX_COLOR.exec(input.trim());
+
+ if (!match) {
+ return null;
+ }
+
+ const digits = match[1].toLowerCase();
+
+ return digits.length === 3
+ ? `#${digits[0]}${digits[0]}${digits[1]}${digits[1]}${digits[2]}${digits[2]}`
+ : `#${digits}`;
+}
+
+function toRgb(hex: string): Rgb {
+ return [
+ Number.parseInt(hex.slice(1, 3), 16),
+ Number.parseInt(hex.slice(3, 5), 16),
+ Number.parseInt(hex.slice(5, 7), 16),
+ ];
+}
+
+function toHex(color: Rgb): string {
+ return `#${color
+ .map((channel) =>
+ Math.min(255, Math.max(0, Math.round(channel)))
+ .toString(16)
+ .padStart(2, "0"),
+ )
+ .join("")}`;
+}
+
+/** `amount` of `other` mixed into `color`, from 0 (none) to 1 (all). */
+function mix(color: Rgb, other: Rgb, amount: number): Rgb {
+ return [
+ color[0] + (other[0] - color[0]) * amount,
+ color[1] + (other[1] - color[1]) * amount,
+ color[2] + (other[2] - color[2]) * amount,
+ ];
+}
+
+function relativeLuminance(color: Rgb): number {
+ const [red, green, blue] = color.map((channel) => {
+ const value = Math.min(255, Math.max(0, Math.round(channel))) / 255;
+
+ return value <= 0.039_28
+ ? value / 12.92
+ : Math.pow((value + 0.055) / 1.055, 2.4);
+ });
+
+ return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
+}
+
+function contrast(first: Rgb, second: Rgb): number {
+ const lighter = Math.max(relativeLuminance(first), relativeLuminance(second));
+ const darker = Math.min(relativeLuminance(first), relativeLuminance(second));
+
+ return (lighter + 0.05) / (darker + 0.05);
+}
+
+/** The WCAG contrast ratio between two hex colors, from 1 to 21. */
+export function contrastRatio(first: string, second: string): number {
+ return contrast(toRgb(first), toRgb(second));
+}
+
+/**
+ * The color, darkened a little at a time until text in it (or white text on
+ * it) is readable against every background given. Black always is, so this
+ * ends.
+ */
+function darkenUntilReadable(color: Rgb, backgrounds: Rgb[]): Rgb {
+ for (let step = 0; step <= 100; step += 1) {
+ const candidate = mix(color, BLACK, step / 100);
+
+ if (
+ backgrounds.every(
+ (background) => contrast(candidate, background) >= READABLE_CONTRAST,
+ )
+ ) {
+ return candidate;
+ }
+ }
+
+ return BLACK;
+}
+
+/** The shades the pages use, worked out from one color. */
+export function buildBrandPalette(color: string): BrandPalette | null {
+ const normalized = normalizeBrandColor(color);
+
+ if (!normalized) {
+ return null;
+ }
+
+ // Rounded to whole channels straight away, so the readability checks
+ // below judge the colors that will really be on the page.
+ const accent = toRgb(toHex(darkenUntilReadable(toRgb(normalized), [WHITE])));
+ const accentSoft = toRgb(toHex(mix(WHITE, accent, 0.11)));
+ const accentSoftHover = toRgb(toHex(mix(WHITE, accent, 0.18)));
+ const accentSofter = mix(WHITE, accent, 0.065);
+ const accentHover = toRgb(toHex(mix(accent, BLACK, 0.16)));
+ // Brand-colored text sits on white, on the page and on both tints. The
+ // darker tint is the hardest of them to read against.
+ const accentInk = darkenUntilReadable(accentHover, [
+ accentSoftHover,
+ accentSoft,
+ ]);
+
+ return {
+ accent: toHex(accent),
+ accentHover: toHex(accentHover),
+ accentInk: toHex(accentInk),
+ accentRgb: accent.join(" "),
+ accentSoft: toHex(accentSoft),
+ accentSoftHover: toHex(accentSoftHover),
+ accentSofter: toHex(accentSofter),
+ };
+}
+
+/**
+ * A style rule that replaces the default accent with this color, or null
+ * when the color is not one. Safe to put in a page: every value in it is a
+ * hex color or three numbers made here.
+ */
+export function buildBrandColorCss(color: string | null): string | null {
+ const palette = color ? buildBrandPalette(color) : null;
+
+ if (!palette) {
+ return null;
+ }
+
+ return `:root{${Object.entries(brandPaletteVariables(palette))
+ .map(([name, value]) => `${name}:${value};`)
+ .join("")}}`;
+}
+
+/** The palette as the custom properties the stylesheet reads. */
+export function brandPaletteVariables(
+ palette: BrandPalette,
+): Record<string, string> {
+ return {
+ "--accent": palette.accent,
+ "--accent-hover": palette.accentHover,
+ "--accent-ink": palette.accentInk,
+ "--accent-rgb": palette.accentRgb,
+ "--accent-soft": palette.accentSoft,
+ "--accent-soft-hover": palette.accentSoftHover,
+ "--accent-softer": palette.accentSofter,
+ };
+}
diff --git a/src/lib/brand-logo.dbtest.ts b/src/lib/brand-logo.dbtest.ts
new file mode 100644
index 0000000..dd8d046
--- /dev/null
+++ b/src/lib/brand-logo.dbtest.ts
@@ -0,0 +1,163 @@
+import assert from "node:assert/strict";
+import { after, before, test } from "node:test";
+
+import type pg from "pg";
+
+import {
+ BrandLogoError,
+ readBrandLogo,
+ removeBrandLogo,
+ saveBrandLogo,
+} from "./brand-logo.ts";
+import { openTestDatabase } from "./db/test-database.ts";
+import { readStoredSettings, saveSettings } from "./settings.ts";
+
+// The install's logo and color against a real Postgres: they are kept in
+// the one settings row, and saving either leaves the other alone. Run with
+// `npm run test:db`.
+
+type SettingsSnapshot = Record<string, unknown> | null;
+
+let database: pg.Pool;
+let settingsBefore: SettingsSnapshot = null;
+
+function png(marker: number): Uint8Array {
+ return Uint8Array.from([
+ 0x89,
+ 0x50,
+ 0x4e,
+ 0x47,
+ 0x0d,
+ 0x0a,
+ 0x1a,
+ 0x0a,
+ marker,
+ ]);
+}
+
+before(async () => {
+ database = await openTestDatabase();
+
+ // There is one settings row for the whole database. Whatever other tests
+ // left in it is put back afterwards.
+ const existing = await database.query(
+ "select * from public.app_settings where id",
+ );
+
+ settingsBefore = existing.rows[0] ?? null;
+});
+
+after(async () => {
+ if (settingsBefore) {
+ await database.query(
+ `
+ update public.app_settings
+ set
+ brand_color = $1,
+ logo_content_type = $2,
+ logo_data = $3,
+ logo_hash = $4,
+ organization_name = $5,
+ signup_mode = $6
+ where id
+ `,
+ [
+ settingsBefore.brand_color,
+ settingsBefore.logo_content_type,
+ settingsBefore.logo_data,
+ settingsBefore.logo_hash,
+ settingsBefore.organization_name,
+ settingsBefore.signup_mode,
+ ],
+ );
+ } else {
+ await database.query("delete from public.app_settings where id");
+ }
+
+ await database.end();
+});
+
+test("a logo is stored, read back and replaced, and its version follows the image", async () => {
+ const first = await saveBrandLogo(png(1), database);
+
+ assert.match(first, /^[0-9a-f]{16}$/);
+
+ const stored = await readBrandLogo(database);
+
+ assert.ok(stored);
+ assert.equal(stored.contentType, "image/png");
+ assert.equal(stored.version, first);
+ assert.deepEqual([...stored.bytes], [...png(1)]);
+ assert.equal((await readStoredSettings(database))?.logoVersion, first);
+
+ // A different image gets a different version; the same one keeps its own.
+ const second = await saveBrandLogo(png(2), database);
+
+ assert.notEqual(second, first);
+ assert.equal(await saveBrandLogo(png(2), database), second);
+ assert.deepEqual([...(await readBrandLogo(database))!.bytes], [...png(2)]);
+});
+
+test("saving the other settings leaves the logo where it is, and the color beside it", async () => {
+ const version = await saveBrandLogo(png(3), database);
+ const saved = await saveSettings(
+ { brandColor: "#1a73e8", organizationName: "Logo Test Org" },
+ database,
+ );
+
+ assert.equal(saved.brandColor, "#1a73e8");
+ assert.equal(saved.logoVersion, version);
+ assert.deepEqual([...(await readBrandLogo(database))!.bytes], [...png(3)]);
+
+ // And the other way round: a new logo does not touch the color.
+ await saveBrandLogo(png(4), database);
+ assert.equal((await readStoredSettings(database))?.brandColor, "#1a73e8");
+
+ const cleared = await saveSettings({ brandColor: null }, database);
+
+ assert.equal(cleared.brandColor, null);
+});
+
+test("removing the logo clears every trace of it", async () => {
+ await saveBrandLogo(png(5), database);
+ await removeBrandLogo(database);
+
+ assert.equal(await readBrandLogo(database), null);
+ assert.equal((await readStoredSettings(database))?.logoVersion, null);
+
+ // Removing what is not there is not an error.
+ await removeBrandLogo(database);
+});
+
+test("what is not an image never reaches the database", async () => {
+ await removeBrandLogo(database);
+
+ await assert.rejects(
+ saveBrandLogo(new TextEncoder().encode("<svg></svg>"), database),
+ BrandLogoError,
+ );
+ assert.equal(await readBrandLogo(database), null);
+});
+
+test("the database itself refuses a color or a logo that is not one", async () => {
+ await saveSettings({ organizationName: "Logo Test Org" }, database);
+
+ await assert.rejects(
+ database.query(
+ "update public.app_settings set brand_color = 'red' where id",
+ ),
+ /app_settings_brand_color_check/,
+ );
+ await assert.rejects(
+ database.query(
+ "update public.app_settings set logo_data = '\\x00', logo_content_type = 'image/svg+xml', logo_hash = '0123456789abcdef' where id",
+ ),
+ /app_settings_logo_check/,
+ );
+ await assert.rejects(
+ database.query(
+ "update public.app_settings set logo_data = '\\x00' where id",
+ ),
+ /app_settings_logo_check/,
+ );
+});
diff --git a/src/lib/brand-logo.test.ts b/src/lib/brand-logo.test.ts
new file mode 100644
index 0000000..86a0204
--- /dev/null
+++ b/src/lib/brand-logo.test.ts
@@ -0,0 +1,62 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ BrandLogoError,
+ MAX_LOGO_BYTES,
+ checkLogoUpload,
+ sniffLogoContentType,
+} from "./brand-logo.ts";
+
+const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13];
+const JPEG = [0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46, 0x49, 0x46];
+const WEBP = [
+ 0x52, 0x49, 0x46, 0x46, 0x24, 0, 0, 0, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50,
+];
+
+test("the kind of image is read from the bytes", () => {
+ assert.equal(sniffLogoContentType(Uint8Array.from(PNG)), "image/png");
+ assert.equal(sniffLogoContentType(Uint8Array.from(JPEG)), "image/jpeg");
+ assert.equal(sniffLogoContentType(Uint8Array.from(WEBP)), "image/webp");
+});
+
+test("anything else is not a logo, SVG and HTML included", () => {
+ const encoder = new TextEncoder();
+
+ for (const bytes of [
+ encoder.encode('<svg xmlns="http://www.w3.org/2000/svg"><script/></svg>'),
+ encoder.encode("<!doctype html><script>alert(1)</script>"),
+ encoder.encode("GIF89a"),
+ encoder.encode("%PDF-1.7"),
+ // A RIFF file that is not WebP (a WAV sound).
+ Uint8Array.from([
+ 0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x41, 0x56, 0x45,
+ ]),
+ Uint8Array.from([0x89, 0x50]),
+ ]) {
+ assert.equal(sniffLogoContentType(bytes), null);
+ assert.throws(() => checkLogoUpload(bytes), BrandLogoError);
+ }
+});
+
+test("an empty or oversized upload is refused with a reason", () => {
+ assert.throws(
+ () => checkLogoUpload(new Uint8Array()),
+ (error: unknown) =>
+ error instanceof BrandLogoError && error.statusCode === 400,
+ );
+
+ const tooLarge = new Uint8Array(MAX_LOGO_BYTES + 1);
+
+ tooLarge.set(PNG);
+ assert.throws(
+ () => checkLogoUpload(tooLarge),
+ (error: unknown) =>
+ error instanceof BrandLogoError && error.statusCode === 413,
+ );
+
+ const largest = new Uint8Array(MAX_LOGO_BYTES);
+
+ largest.set(PNG);
+ assert.equal(checkLogoUpload(largest), "image/png");
+});
diff --git a/src/lib/brand-logo.ts b/src/lib/brand-logo.ts
new file mode 100644
index 0000000..835a1d6
--- /dev/null
+++ b/src/lib/brand-logo.ts
@@ -0,0 +1,183 @@
+import { createHash } from "node:crypto";
+
+import { MAX_LOGO_BYTES, type LogoContentType } from "./branding.ts";
+import { getDb, queryOne, type DbExecutor } from "./db/connection.ts";
+import { invalidateSettingsCache, isMissingSchemaError } from "./settings.ts";
+
+// The install's logo: one small image, kept in the settings row.
+//
+// It is shown to everyone, signers included, so what is stored is decided
+// by looking at the bytes, never by what the upload claimed to be. SVG is
+// not accepted: it can carry scripts, and email programs do not show it.
+
+export { MAX_LOGO_BYTES, type LogoContentType } from "./branding.ts";
+
+export type BrandLogo = {
+ bytes: Uint8Array;
+ contentType: LogoContentType;
+ /** The start of the image's SHA-256: the same image, the same version. */
+ version: string;
+};
+
+export class BrandLogoError extends Error {
+ readonly statusCode: number;
+
+ constructor(message: string, statusCode = 400) {
+ super(message);
+ this.name = "BrandLogoError";
+ this.statusCode = statusCode;
+ }
+}
+
+function startsWith(bytes: Uint8Array, signature: number[], offset = 0) {
+ return (
+ bytes.length >= offset + signature.length &&
+ signature.every((value, index) => bytes[offset + index] === value)
+ );
+}
+
+/** What kind of image these bytes are, or null when it is not one we take. */
+export function sniffLogoContentType(
+ bytes: Uint8Array,
+): LogoContentType | null {
+ if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {
+ return "image/png";
+ }
+
+ if (startsWith(bytes, [0xff, 0xd8, 0xff])) {
+ return "image/jpeg";
+ }
+
+ // "RIFF" <size> "WEBP"
+ if (
+ startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) &&
+ startsWith(bytes, [0x57, 0x45, 0x42, 0x50], 8)
+ ) {
+ return "image/webp";
+ }
+
+ return null;
+}
+
+/** Checks an upload and says what it is. Throws when it cannot be a logo. */
+export function checkLogoUpload(bytes: Uint8Array): LogoContentType {
+ if (bytes.length === 0) {
+ throw new BrandLogoError("Choose an image to upload.");
+ }
+
+ if (bytes.length > MAX_LOGO_BYTES) {
+ throw new BrandLogoError("The logo must be 512 KB or smaller.", 413);
+ }
+
+ const contentType = sniffLogoContentType(bytes);
+
+ if (!contentType) {
+ throw new BrandLogoError("The logo must be a PNG, JPEG or WebP image.");
+ }
+
+ return contentType;
+}
+
+type LogoRow = {
+ logo_content_type: LogoContentType | null;
+ logo_data: Buffer | null;
+ logo_hash: string | null;
+};
+
+/**
+ * Stores the logo, replacing any there was, and returns its version.
+ *
+ * The version is the start of the image's hash. The address the logo is
+ * served at carries it and is cached for good, so a different image always
+ * gets a different address and the same image keeps the one it had.
+ */
+export async function saveBrandLogo(
+ bytes: Uint8Array,
+ database: DbExecutor = getDb(),
+ now = Math.floor(Date.now() / 1000),
+): Promise<string> {
+ const contentType = checkLogoUpload(bytes);
+ const version = createHash("sha256").update(bytes).digest("hex").slice(0, 16);
+
+ // An install that was never set up has no settings row. Sign-up stays as
+ // it was without one: open.
+ await database.query(
+ `
+ insert into public.app_settings (
+ id,
+ signup_mode,
+ logo_content_type,
+ logo_data,
+ logo_hash,
+ created_at,
+ updated_at
+ )
+ values (true, 'open', $1, $2, $3, $4, $4)
+ on conflict (id) do update set
+ logo_content_type = excluded.logo_content_type,
+ logo_data = excluded.logo_data,
+ logo_hash = excluded.logo_hash,
+ updated_at = excluded.updated_at
+ `,
+ [contentType, Buffer.from(bytes), version, now],
+ );
+
+ invalidateSettingsCache();
+
+ return version;
+}
+
+/** Removes the logo. Nothing happens when there is none. */
+export async function removeBrandLogo(
+ database: DbExecutor = getDb(),
+ now = Math.floor(Date.now() / 1000),
+): Promise<void> {
+ await database.query(
+ `
+ update public.app_settings
+ set
+ logo_content_type = null,
+ logo_data = null,
+ logo_hash = null,
+ updated_at = $1
+ where id and logo_data is not null
+ `,
+ [now],
+ );
+
+ invalidateSettingsCache();
+}
+
+/** The stored logo, or null when there is none (or no column for it yet). */
+export async function readBrandLogo(
+ database: DbExecutor = getDb(),
+): Promise<BrandLogo | null> {
+ let row: LogoRow | null;
+
+ try {
+ row = await queryOne<LogoRow>(
+ database,
+ `
+ select logo_content_type, logo_data, logo_hash
+ from public.app_settings
+ where id
+ `,
+ );
+ } catch (error) {
+ if (isMissingSchemaError(error)) {
+ return null;
+ }
+
+ throw error;
+ }
+
+ if (!row?.logo_data || !row.logo_content_type || !row.logo_hash) {
+ return null;
+ }
+
+ return {
+ bytes: new Uint8Array(row.logo_data),
+ contentType: row.logo_content_type,
+ version: row.logo_hash,
+ };
+}
diff --git a/src/lib/branding.ts b/src/lib/branding.ts
index ea34fa1..3aca105 100644
--- a/src/lib/branding.ts
+++ b/src/lib/branding.ts
@@ -1,3 +1,4 @@
+import { normalizeBrandColor } from "./brand-color.ts";
import type { ResolvedSettings } from "./settings.ts";
// What an install calls itself.
@@ -6,15 +7,40 @@ import type { ResolvedSettings } from "./settings.ts";
// runs it, links to that organization's own terms and privacy policy, and
// says "Powered by SignuDoc" in the footer. Hosted mode (HOSTED_MODE=1) is
// SignuDoc run as a public service: its own name, landing page and legal
-// pages.
+// pages. An install's own logo and color are not used there.
export const SIGNUDOC_NAME = "SignuDoc";
export const SIGNUDOC_URL = "https://signudoc.app";
+/** Where the install's logo is served. Public: it is shown to signers. */
+export const BRAND_LOGO_PATH = "/api/brand/logo";
+
+/** The largest logo an install can upload. */
+export const MAX_LOGO_BYTES = 512 * 1024;
+
+export const LOGO_CONTENT_TYPES = [
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+] as const;
+
+export type LogoContentType = (typeof LOGO_CONTENT_TYPES)[number];
+
+export function buildBrandLogoPath(version: string): string {
+ return `${BRAND_LOGO_PATH}?v=${encodeURIComponent(version)}`;
+}
+
export type Branding = {
+ /** The install's own color as "#rrggbb", or null for the default violet. */
+ brandColor: string | null;
/** Where "Contact" should point: a page on this site, or null. */
contactUrl: string | null;
hosted: boolean;
+ /**
+ * The install's logo, as a path on this site, or null when it has none.
+ * The path changes whenever the logo does, so it can be cached for good.
+ */
+ logoUrl: string | null;
/** The organization's name, when one has been set. */
organizationName: string | null;
privacyUrl: string | null;
@@ -28,8 +54,10 @@ export type Branding = {
/** SignuDoc under its own name. Also what a page shows before it knows better. */
export const HOSTED_BRANDING: Branding = {
+ brandColor: null,
contactUrl: "/contact",
hosted: true,
+ logoUrl: null,
organizationName: null,
privacyUrl: "/privacy",
productName: SIGNUDOC_NAME,
@@ -55,8 +83,13 @@ export function buildBranding(settings: ResolvedSettings): Branding {
const organizationName = settings.organizationName?.trim() || null;
return {
+ brandColor: normalizeBrandColor(settings.brandColor),
contactUrl: null,
hosted: false,
+ logoUrl:
+ settings.logoVersion === null
+ ? null
+ : buildBrandLogoPath(settings.logoVersion),
organizationName,
privacyUrl: settings.privacyUrl,
productName: organizationName ?? SIGNUDOC_NAME,
diff --git a/src/lib/email-status.test.ts b/src/lib/email-status.test.ts
index 73c7f77..4e58775 100644
--- a/src/lib/email-status.test.ts
+++ b/src/lib/email-status.test.ts
@@ -13,7 +13,9 @@ import { resolveSettings, type AppSettings } from "./settings.ts";
const stored: AppSettings = {
allowedEmailDomains: ["acme.com"],
+ brandColor: null,
emailReadyAt: null,
+ logoVersion: null,
organizationName: "Acme Corp",
privacyUrl: null,
retentionDays: null,
diff --git a/src/lib/organization-settings.test.ts b/src/lib/organization-settings.test.ts
index aabe214..65c4cbd 100644
--- a/src/lib/organization-settings.test.ts
+++ b/src/lib/organization-settings.test.ts
@@ -10,7 +10,9 @@ import { resolveSettings, type AppSettings } from "./settings.ts";
const stored: AppSettings = {
allowedEmailDomains: ["acme.com"],
+ brandColor: null,
emailReadyAt: null,
+ logoVersion: null,
organizationName: "Acme Corp",
privacyUrl: null,
retentionDays: null,
@@ -23,7 +25,9 @@ const stored: AppSettings = {
const storedRow = {
allowed_email_domains: stored.allowedEmailDomains,
+ brand_color: stored.brandColor,
email_ready_at: stored.emailReadyAt,
+ logo_hash: stored.logoVersion,
organization_name: stored.organizationName,
privacy_url: stored.privacyUrl,
retention_days: stored.retentionDays,
@@ -168,3 +172,55 @@ test("under the domain rule the list is checked and saved", async () => {
assert.equal(refused.saved.values, null);
}
});
+
+test("the brand color is stored as #rrggbb however it was typed, and empty clears it", async () => {
+ const current = resolveSettings(stored, {});
+
+ for (const [typed, expected] of [
+ ["1A73E8", "#1a73e8"],
+ ["#17e", "#1177ee"],
+ [" #0b3d2e ", "#0b3d2e"],
+ ["", null],
+ [undefined, null],
+ ] as const) {
+ const { database } = fakeDatabase();
+ const result = await updateOrganizationSettings(
+ { ...form, brandColor: typed },
+ current,
+ database,
+ );
+
+ assert.equal(result.brandColor, expected, String(typed));
+ }
+});
+
+test("something that is not a color is refused", async () => {
+ const current = resolveSettings(stored, {});
+
+ for (const brandColor of ["red", "#12345", "#fff;}body{display:none}", 7]) {
+ const { database, saved } = fakeDatabase();
+
+ await assert.rejects(
+ updateOrganizationSettings({ ...form, brandColor }, current, database),
+ (error: unknown) => {
+ assert.ok(error instanceof OrganizationSettingsError);
+ assert.deepEqual(Object.keys(error.fieldErrors), ["brandColor"]);
+
+ return true;
+ },
+ );
+ assert.equal(saved.values, null);
+ }
+});
+
+test("the hosted service keeps its own color whatever the form sends", async () => {
+ const current = resolveSettings(stored, { HOSTED_MODE: "1" });
+ const { database } = fakeDatabase();
+ const result = await updateOrganizationSettings(
+ { ...form, brandColor: "not a color" },
+ current,
+ database,
+ );
+
+ assert.equal(result.brandColor, null);
+});
diff --git a/src/lib/organization-settings.ts b/src/lib/organization-settings.ts
index bd0b4d8..f9c9c43 100644
--- a/src/lib/organization-settings.ts
+++ b/src/lib/organization-settings.ts
@@ -1,5 +1,7 @@
import { z } from "zod";
+import { normalizeBrandColor } from "./brand-color.ts";
+import { buildBrandLogoPath } from "./branding.ts";
import { getDb, type DbExecutor } from "./db/connection.ts";
import { emailSchema } from "./schemas/common.ts";
import {
@@ -13,6 +15,7 @@ import { parseEmailDomainList, SIGNUP_MODES } from "./signup-policy.ts";
export type OrganizationSettingsField =
| "allowedEmailDomains"
+ | "brandColor"
| "organizationName"
| "privacyUrl"
| "retentionDays"
@@ -34,7 +37,11 @@ export class OrganizationSettingsError extends Error {
/** The values the Organization form shows and sends back. */
export type OrganizationSettingsView = {
allowedEmailDomains: string;
+ /** "#rrggbb", or empty for the default color. */
+ brandColor: string;
hosted: boolean;
+ /** Where the logo is served, or null when there is none. */
+ logoUrl: string | null;
organizationName: string;
privacyUrl: string;
/** Days, as typed. Empty keeps finished envelopes until deleted by hand. */
@@ -52,7 +59,12 @@ export function toOrganizationSettingsView(
): OrganizationSettingsView {
return {
allowedEmailDomains: settings.allowedEmailDomains.join(", "),
+ brandColor: settings.brandColor ?? "",
hosted: settings.hosted,
+ logoUrl:
+ settings.logoVersion === null
+ ? null
+ : buildBrandLogoPath(settings.logoVersion),
organizationName: settings.organizationName ?? "",
privacyUrl: settings.privacyUrl ?? "",
retentionDays:
@@ -89,8 +101,29 @@ const optionalWebUrl = z.preprocess(
.nullable(),
);
+// Stored as "#rrggbb" whatever way it was typed. Empty means the default.
+const optionalBrandColor = z.preprocess(
+ blankToNull,
+ z
+ .string()
+ .max(16)
+ .transform((value, context) => {
+ const color = normalizeBrandColor(value);
+
+ if (!color) {
+ context.addIssue({ code: "custom", message: "Not a color" });
+
+ return z.NEVER;
+ }
+
+ return color;
+ })
+ .nullable(),
+);
+
const organizationSettingsSchema = z.object({
allowedEmailDomains: z.string().max(4000).default(""),
+ brandColor: optionalBrandColor.default(null),
organizationName: z.string().trim().min(1).max(120),
privacyUrl: optionalWebUrl.default(null),
retentionDays: z
@@ -108,6 +141,7 @@ const organizationSettingsSchema = z.object({
const FIELD_MESSAGES: Record<OrganizationSettingsField, string> = {
allowedEmailDomains: "Enter one or more domains, such as yourcompany.com",
+ brandColor: "Enter a color as six letters and digits, such as #1a73e8",
organizationName: "Enter the name of your organization",
privacyUrl: "Enter a full web address starting with https://",
retentionDays: "Enter a number of days, 30 or more, or leave this empty",
@@ -142,6 +176,7 @@ function withoutLockedFields(
}
if (current.hosted) {
+ delete input.brandColor;
delete input.privacyUrl;
delete input.termsUrl;
}
@@ -204,7 +239,11 @@ export async function updateOrganizationSettings(
signupMode: input.signupMode,
...(current.hosted
? {}
- : { privacyUrl: input.privacyUrl, termsUrl: input.termsUrl }),
+ : {
+ brandColor: input.brandColor,
+ privacyUrl: input.privacyUrl,
+ termsUrl: input.termsUrl,
+ }),
...(current.senderAddressFromEnv
? {}
: { senderAddress: input.senderAddress?.toLowerCase() ?? null }),
diff --git a/src/lib/services/email-legal-footer.test.ts b/src/lib/services/email-legal-footer.test.ts
index dfbd181..f62a7a8 100644
--- a/src/lib/services/email-legal-footer.test.ts
+++ b/src/lib/services/email-legal-footer.test.ts
@@ -8,8 +8,10 @@ const env = { APP_URL: "https://sign.acme.com" };
const body = { htmlBody: "<p>Hello</p>", textBody: "Hello" };
const neutral: Branding = {
+ brandColor: null,
contactUrl: null,
hosted: false,
+ logoUrl: null,
organizationName: "Acme Corp",
privacyUrl: null,
productName: "Acme Corp",
@@ -125,3 +127,33 @@ test("the organization's name and links are escaped in the HTML part", () => {
test("a neutral install with no links does not need to know its own URL", () => {
assert.doesNotThrow(() => withUserEmailLegalFooter(body, neutral, {}));
});
+
+test("an install with a logo puts it at the top of the HTML part only", () => {
+ const result = withUserEmailLegalFooter(
+ body,
+ {
+ ...neutral,
+ logoUrl: "/api/brand/logo?v=0123456789abcdef",
+ productName: 'Acme "Signing" & Co',
+ },
+ env,
+ );
+
+ assert.ok(
+ result.htmlBody.startsWith(
+ '<p style="margin:0 0 24px;"><img src="https://sign.acme.com/api/brand/logo?v=0123456789abcdef" alt="Acme &quot;Signing&quot; &amp; Co"',
+ ),
+ );
+ assert.ok(result.htmlBody.includes("<p>Hello</p>"));
+ assert.doesNotMatch(result.textBody, /logo/);
+});
+
+test("without the site's address there is nowhere to fetch a logo from", () => {
+ const result = withUserEmailLegalFooter(
+ body,
+ { ...neutral, logoUrl: "/api/brand/logo?v=0123456789abcdef" },
+ {},
+ );
+
+ assert.doesNotMatch(result.htmlBody, /<img/);
+});
diff --git a/src/lib/services/email-legal-footer.ts b/src/lib/services/email-legal-footer.ts
index 2813dc6..127b49e 100644
--- a/src/lib/services/email-legal-footer.ts
+++ b/src/lib/services/email-legal-footer.ts
@@ -41,11 +41,34 @@ function buildFooterLinks(branding: Branding, env: EnvSource): FooterLink[] {
}));
}
+/**
+ * The install's logo for the top of an email, or nothing when it has none.
+ * Email programs fetch it from this site, so it needs the site's address;
+ * many hide pictures until asked, which is why the name is the alt text.
+ */
+function buildLogoHeader(branding: Branding, env: EnvSource): string {
+ const appUrl = getEnv(env).appUrl;
+
+ if (!branding.logoUrl || !appUrl) {
+ return "";
+ }
+
+ const source = new URL(branding.logoUrl, appUrl).toString();
+
+ return [
+ '<p style="margin:0 0 24px;">',
+ `<img src="${escapeHtml(source)}" alt="${escapeHtml(branding.productName)}" height="40" `,
+ 'style="display:block;height:40px;width:auto;max-width:240px;border:0;" />',
+ "</p>",
+ ].join("");
+}
+
/**
* Appends the footer every email to a person carries: the install's terms,
* privacy and contact links, where it has them. On a neutral install the
* footer also names the organization's support address and says the message
- * was sent with SignuDoc.
+ * was sent with SignuDoc, and the organization's logo, when it has one,
+ * goes at the top.
*/
export function withUserEmailLegalFooter(
input: EmailBodyContent,
@@ -53,6 +76,7 @@ export function withUserEmailLegalFooter(
env: EnvSource = process.env,
): EmailBodyContent {
const links = buildFooterLinks(branding, env);
+ const logoHeader = buildLogoHeader(branding, env);
const textLines: string[] = [];
const htmlLines: string[] = [];
@@ -78,7 +102,9 @@ export function withUserEmailLegalFooter(
}
if (htmlLines.length === 0) {
- return input;
+ return logoHeader
+ ? { htmlBody: `${logoHeader}${input.htmlBody}`, textBody: input.textBody }
+ : input;
}
const htmlFooter = [
@@ -87,7 +113,7 @@ export function withUserEmailLegalFooter(
].join("");
return {
- htmlBody: `${input.htmlBody}${htmlFooter}`,
+ htmlBody: `${logoHeader}${input.htmlBody}${htmlFooter}`,
// Each entry starts with an empty line; one more newline puts that
// empty line between the message and the footer.
textBody: `${input.textBody}\n${textLines.join("\n")}`,
diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.ts
index 500ff71..cbaad6e 100644
--- a/src/lib/settings.test.ts
+++ b/src/lib/settings.test.ts
@@ -10,7 +10,9 @@ import {
const stored: AppSettings = {
allowedEmailDomains: ["acme.com"],
+ brandColor: null,
emailReadyAt: null,
+ logoVersion: null,
organizationName: "Acme Corp",
privacyUrl: "https://acme.com/privacy",
retentionDays: null,
@@ -60,8 +62,10 @@ test("hosted mode is switched on by HOSTED_MODE", () => {
test("a neutral install goes by the organization's name and links", () => {
assert.deepEqual(buildBranding(resolveSettings(stored, {})), {
+ brandColor: null,
contactUrl: null,
hosted: false,
+ logoUrl: null,
organizationName: "Acme Corp",
privacyUrl: "https://acme.com/privacy",
productName: "Acme Corp",
@@ -114,3 +118,33 @@ test("a missing table or column is recognized, other failures are not", () => {
assert.equal(isMissingSchemaError(new Error("connection refused")), false);
assert.equal(isMissingSchemaError(null), false);
});
+
+test("a neutral install carries its own color and logo, hosted mode never does", () => {
+ const branded: AppSettings = {
+ ...stored,
+ brandColor: "#1a73e8",
+ logoVersion: "0123456789abcdef",
+ };
+ const neutral = buildBranding(resolveSettings(branded, {}));
+
+ assert.equal(neutral.brandColor, "#1a73e8");
+ assert.equal(neutral.logoUrl, "/api/brand/logo?v=0123456789abcdef");
+
+ const plain = buildBranding(resolveSettings(stored, {}));
+
+ assert.equal(plain.brandColor, null);
+ assert.equal(plain.logoUrl, null);
+
+ const hosted = buildBranding(resolveSettings(branded, { HOSTED_MODE: "1" }));
+
+ assert.equal(hosted.brandColor, null);
+ assert.equal(hosted.logoUrl, null);
+});
+
+test("a stored color that is not one is ignored rather than put on a page", () => {
+ const branding = buildBranding(
+ resolveSettings({ ...stored, brandColor: "red;}body{display:none" }, {}),
+ );
+
+ assert.equal(branding.brandColor, null);
+});
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index 01b8950..3cac3cc 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -18,7 +18,14 @@ import { getEnv, isHostedMode, type EnvSource } from "./utils/env.ts";
/** What is stored. Null means "not set". */
export type AppSettings = {
allowedEmailDomains: string[];
+ /** The install's own color as "#rrggbb", or null for the default. */
+ brandColor: string | null;
emailReadyAt: number | null;
+ /**
+ * A short hash of the install's logo, or null when it has none. The logo
+ * itself is read and written in brand-logo.ts, never here.
+ */
+ logoVersion: string | null;
organizationName: string | null;
privacyUrl: string | null;
/**
@@ -40,7 +47,7 @@ export type ResolvedSettings = AppSettings & {
supportAddressFromEnv: boolean;
};
-export type SettingsUpdate = Partial<AppSettings>;
+export type SettingsUpdate = Partial<Omit<AppSettings, "logoVersion">>;
/**
* Where an install stands on first-run setup.
@@ -65,7 +72,9 @@ export type SetupRequiredDecision = {
type AppSettingsRow = {
allowed_email_domains: string[] | null;
+ brand_color: string | null;
email_ready_at: number | null;
+ logo_hash: string | null;
organization_name: string | null;
privacy_url: string | null;
retention_days: number | null;
@@ -78,7 +87,9 @@ type AppSettingsRow = {
const SETTINGS_COLUMNS = `
allowed_email_domains,
+ brand_color,
email_ready_at,
+ logo_hash,
organization_name,
privacy_url,
retention_days,
@@ -94,7 +105,9 @@ const SETTINGS_COLUMNS = `
// until someone decides otherwise.
const UNSET_SETTINGS: AppSettings = {
allowedEmailDomains: [],
+ brandColor: null,
emailReadyAt: null,
+ logoVersion: null,
organizationName: null,
privacyUrl: null,
retentionDays: null,
@@ -149,7 +162,9 @@ export function isMissingSchemaError(error: unknown): boolean {
function mapSettingsRow(row: AppSettingsRow): AppSettings {
return {
allowedEmailDomains: row.allowed_email_domains ?? [],
+ brandColor: row.brand_color,
emailReadyAt: row.email_ready_at,
+ logoVersion: row.logo_hash,
organizationName: row.organization_name,
privacyUrl: row.privacy_url,
retentionDays: row.retention_days,
@@ -274,10 +289,11 @@ export async function saveSettings(
support_address,
terms_url,
retention_days,
+ brand_color,
created_at,
updated_at
)
- values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $10, $10)
+ values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $12, $10, $10)
on conflict (id) do update set
allowed_email_domains = excluded.allowed_email_domains,
email_ready_at = excluded.email_ready_at,
@@ -289,6 +305,7 @@ export async function saveSettings(
support_address = excluded.support_address,
terms_url = excluded.terms_url,
retention_days = excluded.retention_days,
+ brand_color = excluded.brand_color,
updated_at = excluded.updated_at
returning ${SETTINGS_COLUMNS}
`,
@@ -304,6 +321,7 @@ export async function saveSettings(
next.termsUrl,
now,
next.retentionDays,
+ next.brandColor,
],
);
diff --git a/src/lib/utils/limited-body.ts b/src/lib/utils/limited-body.ts
new file mode 100644
index 0000000..da5b4e9
--- /dev/null
+++ b/src/lib/utils/limited-body.ts
@@ -0,0 +1,40 @@
+/** Reads a request body, giving up as soon as it is larger than the limit. */
+export async function readLimitedBody(
+ request: Request,
+ maxBytes: number,
+): Promise<Uint8Array | null> {
+ if (!request.body) {
+ return new Uint8Array();
+ }
+
+ const reader = request.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+
+ for (;;) {
+ const { done, value } = await reader.read();
+
+ if (done) {
+ break;
+ }
+
+ total += value.byteLength;
+
+ if (total > maxBytes) {
+ await reader.cancel().catch(() => undefined);
+ return null;
+ }
+
+ chunks.push(value);
+ }
+
+ const body = new Uint8Array(total);
+ let offset = 0;
+
+ for (const chunk of chunks) {
+ body.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+
+ return body;
+}