commit
initial commit
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..07352a2
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,79 @@
+# ---------------------------------------------------------------------------
+# pkviewer configuration
+#
+# Every origin below is deployment configuration, never an architectural fact.
+# No absolute pkviewer URL is ever persisted to the database; URLs are composed
+# at render time from these values. See docs/decisions.md §17.
+# ---------------------------------------------------------------------------
+
+NODE_ENV=development
+
+# --- origins -------------------------------------------------------------
+#
+# Two origins, split by a single rule:
+# anything rendering user-authored presentation -> PUBLIC_USERCONTENT_ORIGIN
+# anything reading or writing a session -> PUBLIC_APP_ORIGIN
+#
+# Public system and member pages (/s/...) are served from the USERCONTENT origin
+# from day one. They are user-authored presentation the moment custom CSS lands
+# in v1.1, and moving them then would break every public URL ever shared. That
+# makes the usercontent origin the public, shareable, flagship one -- it gets
+# the memorable hostname -- while the app origin is the one nobody types.
+#
+# Beta: public pages https://system.doughmination.gay
+# app / manage https://app.doughmination.gay
+# Production: filled in when the dedicated pkviewer domain exists.
+
+# Session-bearing: /, /login, /docs, /manage, /auth. Never renders user content.
+PUBLIC_APP_ORIGIN=http://app.localhost:3000
+
+# Public pages (/s/...). Never receives the session cookie: __Host- forbids a
+# Domain attribute, so the cookie cannot reach a sibling host. Must never equal
+# PUBLIC_APP_ORIGIN, in any environment, including development.
+PUBLIC_USERCONTENT_ORIGIN=http://system.localhost:3000
+
+# May equal the usercontent origin during beta.
+PUBLIC_ASSET_ORIGIN=http://system.localhost:3000
+
+# Documentation lives on a separate site, not inside this application. Leave
+# empty to hide the documentation links entirely.
+# Beta: https://docs.doughmination.gay
+PUBLIC_DOCS_URL=
+
+# --- api -----------------------------------------------------------------
+API_PORT=3001
+# Where the Next.js tier reaches the API. Internal; never public.
+INTERNAL_API_ORIGIN=http://127.0.0.1:3001
+
+# --- database ------------------------------------------------------------
+DATABASE_PATH=./data/pkviewer.db
+
+# --- pluralkit -----------------------------------------------------------
+PK_API_BASE=https://api.pluralkit.me/v2
+# Contact URL embedded in the User-Agent. Point this at the REPOSITORY, not the
+# deployment origin, so it survives the beta -> production domain move. The UA
+# must be identical across every instance and must never vary by user or server.
+PK_USER_AGENT_CONTACT=https://github.com/OWNER/pkviewer
+# Self-imposed ceilings, deliberately below PluralKit's documented 10/s reads
+# and 3/s writes, leaving headroom for burst and clock imprecision.
+PK_RATE_LIMIT_READ_RPS=6
+PK_RATE_LIMIT_WRITE_RPS=2
+
+# --- discord oauth -------------------------------------------------------
+DISCORD_CLIENT_ID=
+DISCORD_CLIENT_SECRET=
+# Comma-separated, so beta and production URIs can both be registered ahead of
+# the domain move and the cutover needs no flag day.
+DISCORD_REDIRECT_URIS=http://app.localhost:3000/auth/discord/callback
+
+# --- beta ----------------------------------------------------------------
+# While true: X-Robots-Tag noindex on every response, claiming restricted to
+# BETA_ALLOWED_DISCORD_IDS, and a third-party/beta indicator on public pages.
+BETA_MODE=true
+SIGNUP_ENABLED=true
+BETA_ALLOWED_DISCORD_IDS=
+
+# --- secrets -------------------------------------------------------------
+# 32+ random bytes, base64. Rotate by generating a new one; sessions are
+# server-side, so rotation invalidates them rather than corrupting them.
+SESSION_SECRET=
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..83d79cd
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,16 @@
+node_modules/
+dist/
+.next/
+.next-prod/
+*.log
+
+# SQLite: the database and its WAL sidecars are never committed.
+data/
+*.db
+*.db-shm
+*.db-wal
+
+# Secrets. Only .env.example is tracked.
+.env
+.env.*
+!.env.example
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..45f4013
--- /dev/null
+++ b/README.md
@@ -0,0 +1,156 @@
+# pkviewer
+
+Websites for [PluralKit](https://pluralkit.me) systems.
+
+PluralKit holds the identity and the data. pkviewer handles how that identity is
+presented on the web: every system gets a public page, every member can have one,
+and systems that sign in can choose a readable address and customise how their
+pages look.
+
+**pkviewer is a third-party project. It is not PluralKit, and is not affiliated
+with or endorsed by the PluralKit project.** It reads PluralKit's public API and
+shows only information PluralKit already makes public.
+
+Status: **pre-beta.** The feature set is deliberately small and things will
+change.
+
+---
+
+## What is in here
+
+```
+apps/api Hono on Bun. Owns SQLite, sessions, the PluralKit client,
+ Discord OAuth, and all business logic. The only process that
+ opens the database.
+apps/web Next.js on Node. Renders pages and the management UI. Has no
+ database driver and no PluralKit client — it reaches the API
+ over HTTP.
+packages/shared Types, the theme vocabulary, and validation shared by both.
+docs/ Decision log. Start with docs/decisions.md.
+scripts/ Dev runner and the hardcoded-origin guard.
+```
+
+The split is deliberate: SQLite permits one writer at a time, and confining all
+database access to one long-lived process removes write contention as a category
+of bug rather than managing it. See `docs/decisions.md` (A1).
+
+## Two origins
+
+pkviewer serves two hostnames from one Next process, split by a single rule:
+**anything rendering user-authored presentation goes on the public origin;
+anything reading or writing a session goes on the app origin.**
+
+| | Serves |
+|---|---|
+| Public origin | `/`, `/s/<id>`, `/s/<address>`, `/s/<address>/<member>` |
+| App origin | `/login`, `/auth/...`, `/manage/...` |
+
+The session cookie uses the `__Host-` prefix, which forbids a `Domain`
+attribute — so it is pinned to the app host and *cannot* reach the public
+origin. That is what makes it safe to serve user-authored presentation there.
+
+In development both hostnames resolve to 127.0.0.1 through `*.localhost`, which
+Chrome and Firefox handle with no setup. The Host header therefore behaves
+exactly as in production and the origin split is genuinely exercised locally.
+**Safari does not resolve `*.localhost`**; add `/etc/hosts` entries if you use it.
+
+## Prerequisites
+
+- [Bun](https://bun.sh) 1.4 or newer — runs the API, the tests, and the tooling
+- Node 20 or newer — Next.js runs on Node, not Bun
+- No database server. SQLite is a file.
+
+## Getting started
+
+```bash
+bun install
+cp .env.example .env # then read the comments in it
+bun run dev
+```
+
+That is the supported entry point. It starts both tiers with prefixed output and
+shuts both down together, and prints the URLs:
+
+```
+public http://system.localhost:3000 /, /s/...
+app http://app.localhost:3000 /login, /manage
+api http://127.0.0.1:3001/health
+```
+
+Migrations run automatically on API start, so a fresh checkout needs no bootstrap
+step.
+
+> **The API's environment comes from the repository root.** `bun run dev` loads
+> `.env` from the root and passes it to both tiers. Running the API directly from
+> `apps/api` will *not* find it and will fail at startup naming the missing
+> variable. Use `bun run dev`.
+
+Signing in needs Discord OAuth credentials; see
+[docs/deployment.md](docs/deployment.md#environment-variables). Everything else —
+public pages, the whole rendering path — works without them.
+
+## Commands
+
+| Command | What it does |
+|---|---|
+| `bun run dev` | Both tiers, prefixed output, shared shutdown |
+| `bun test` | Full test suite |
+| `bun run typecheck` | All three workspaces |
+| `bun run build` | Production build of the web tier. Writes to `.next-prod`, so it is safe to run while `bun run dev` is up. |
+| `bun run migrate` | Apply migrations without starting the server |
+| `bun run check` | Origin guard, typecheck and tests — run before pushing |
+| `bun run check:domain` | Fails if a deployment hostname is hardcoded |
+
+## Local test data
+
+Claiming a system needs Discord OAuth. To poke at the management UI without it,
+seed a local account and session:
+
+```bash
+bun scripts/seed-dev.ts <system-id> # any publicly visible PluralKit system
+```
+
+It prints a session token and the cookie line to paste into the browser console.
+The seed **reads the system's identifiers from PluralKit** rather than inventing
+them, so a seeded row satisfies the same invariant a real claim does. It uses a
+fabricated Discord id, so it never ties local data to a real account.
+
+It is a development script and refuses to run when `NODE_ENV=production`.
+
+## Testing
+
+```bash
+bun test # everything
+bun test apps/api/test/slugs # one file
+```
+
+Tests use in-memory SQLite and a stubbed PluralKit, so they need no network and
+no local database.
+
+## Documentation
+
+**User-facing documentation is a separate site and is not served by this
+application.** Its URL is configuration (`PUBLIC_DOCS_URL`); leave it empty and
+the documentation links simply do not appear.
+
+Developer documentation lives here:
+
+- [docs/decisions.md](docs/decisions.md) — every signed-off decision and the
+ invariants that follow from it, each naming the test that guards it. Read this
+ before changing anything structural.
+- [docs/deployment.md](docs/deployment.md) — environment variables, deployment
+ shape, backups.
+
+## Third-party notices
+
+pkviewer reads the public [PluralKit API](https://pluralkit.me/api/) and sends a
+consistent `User-Agent` identifying itself, as PluralKit asks. It never asks for
+a PluralKit token in order to claim a system.
+
+Built with [Hono](https://hono.dev), [Next.js](https://nextjs.org),
+[React](https://react.dev), [Bun](https://bun.sh), [Zod](https://zod.dev) and
+[Bootstrap Icons](https://icons.getbootstrap.com) via
+[react-bootstrap-icons](https://github.com/ricardo-ch/react-bootstrap-icons).
+Fonts are served from [Google Fonts](https://fonts.google.com).
+
+No licence has been chosen yet.
diff --git a/apps/api/package.json b/apps/api/package.json
new file mode 100644
index 0000000..56244a3
--- /dev/null
+++ b/apps/api/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "@pkviewer/api",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "bun run --hot src/index.ts",
+ "start": "bun run src/index.ts",
+ "migrate": "bun run src/db/migrate.ts",
+ "typecheck": "tsc -p tsconfig.json"
+ },
+ "dependencies": {
+ "@pkviewer/shared": "workspace:*",
+ "hono": "^4.6.0",
+ "zod": "^3.23.8"
+ }
+}
diff --git a/apps/api/src/auth/crypto.ts b/apps/api/src/auth/crypto.ts
new file mode 100644
index 0000000..0f63928
--- /dev/null
+++ b/apps/api/src/auth/crypto.ts
@@ -0,0 +1,77 @@
+import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
+
+/** URL-safe base64 with no padding. */
+export function base64url(buf: Buffer | Uint8Array): string {
+ return Buffer.from(buf).toString("base64url");
+}
+
+/** A cryptographically random opaque token. 32 bytes by default. */
+export function randomToken(bytes = 32): string {
+ return base64url(randomBytes(bytes));
+}
+
+/**
+ * Hash used for anything stored at rest that is presented as a bearer value.
+ * Session cookies are stored hashed so a database read does not yield usable
+ * sessions.
+ */
+export function sha256(value: string): string {
+ return createHash("sha256").update(value, "utf8").digest("hex");
+}
+
+export function sha256Raw(value: string): Buffer {
+ return createHash("sha256").update(value, "utf8").digest();
+}
+
+/** Constant-time comparison. Both sides are hex/base64 text of equal length. */
+export function safeEqual(a: string, b: string): boolean {
+ const ba = Buffer.from(a, "utf8");
+ const bb = Buffer.from(b, "utf8");
+ if (ba.length !== bb.length) return false;
+ return timingSafeEqual(ba, bb);
+}
+
+/**
+ * Signs a short-lived payload carried in a cookie (the OAuth state and PKCE
+ * verifier). The cookie is already __Host- and httpOnly; the signature means a
+ * forged value cannot be accepted even if one were somehow set.
+ */
+export function sign(secret: string, payload: string): string {
+ return base64url(createHmac("sha256", secret).update(payload, "utf8").digest());
+}
+
+export function signedValue(secret: string, payload: string): string {
+ return `${base64url(Buffer.from(payload, "utf8"))}.${sign(secret, payload)}`;
+}
+
+export function verifySignedValue(secret: string, value: string): string | null {
+ const dot = value.lastIndexOf(".");
+ if (dot <= 0) return null;
+ const encoded = value.slice(0, dot);
+ const signature = value.slice(dot + 1);
+ let payload: string;
+ try {
+ payload = Buffer.from(encoded, "base64url").toString("utf8");
+ } catch {
+ return null;
+ }
+ if (!safeEqual(sign(secret, payload), signature)) return null;
+ return payload;
+}
+
+/**
+ * PKCE pair. The verifier stays with us (in the signed cookie); only the
+ * challenge goes to Discord, so an intercepted authorization code cannot be
+ * exchanged by anyone else.
+ */
+export function createPkcePair(): { verifier: string; challenge: string } {
+ const verifier = base64url(randomBytes(48)); // 64 chars, within the 43-128 range
+ const challenge = base64url(sha256Raw(verifier));
+ return { verifier, challenge };
+}
+
+/** Hashes request metadata for session records. We never store raw IPs. */
+export function hashMeta(value: string | undefined, secret: string): string | null {
+ if (!value) return null;
+ return createHmac("sha256", secret).update(value, "utf8").digest("hex").slice(0, 32);
+}
diff --git a/apps/api/src/auth/discord.ts b/apps/api/src/auth/discord.ts
new file mode 100644
index 0000000..2c306ba
--- /dev/null
+++ b/apps/api/src/auth/discord.ts
@@ -0,0 +1,152 @@
+import type { DiscordProfile } from "./sessions.ts";
+
+/**
+ * Discord OAuth2, authorization code with PKCE.
+ *
+ * Scope is `identify` only. Not `email`, not `guilds`: we have no use for
+ * either, and not requesting them is both a privacy stance and a smaller breach
+ * surface.
+ *
+ * The access token is used once, to read the user's id, and then discarded. We
+ * never call the Discord API again, so there is no refresh token, no token
+ * table, and no rotation logic to get wrong.
+ */
+
+const AUTHORIZE_URL = "https://discord.com/oauth2/authorize";
+const TOKEN_URL = "https://discord.com/api/oauth2/token";
+const USER_URL = "https://discord.com/api/users/@me";
+
+export const DISCORD_SCOPES = "identify";
+
+export class DiscordAuthError extends Error {
+ override readonly name = "DiscordAuthError";
+ constructor(message: string, readonly cause_?: unknown) {
+ super(message);
+ }
+}
+
+export type DiscordOptions = {
+ clientId: string;
+ clientSecret: string;
+ fetchImpl?: typeof fetch;
+ timeoutMs?: number;
+};
+
+export function buildAuthorizeUrl(opts: {
+ clientId: string;
+ redirectUri: string;
+ state: string;
+ codeChallenge: string;
+}): string {
+ const params = new URLSearchParams({
+ client_id: opts.clientId,
+ redirect_uri: opts.redirectUri,
+ response_type: "code",
+ scope: DISCORD_SCOPES,
+ state: opts.state,
+ code_challenge: opts.codeChallenge,
+ code_challenge_method: "S256",
+ prompt: "none",
+ });
+ return `${AUTHORIZE_URL}?${params.toString()}`;
+}
+
+export class DiscordClient {
+ private readonly fetchImpl: typeof fetch;
+ private readonly timeoutMs: number;
+
+ constructor(private readonly opts: DiscordOptions) {
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
+ this.timeoutMs = opts.timeoutMs ?? 8000;
+ }
+
+ /**
+ * Exchanges the authorization code for an access token.
+ *
+ * The returned token is deliberately not persisted anywhere by callers: read
+ * the profile with it, then let it fall out of scope.
+ */
+ async exchangeCode(params: {
+ code: string;
+ redirectUri: string;
+ codeVerifier: string;
+ }): Promise<string> {
+ const body = new URLSearchParams({
+ client_id: this.opts.clientId,
+ client_secret: this.opts.clientSecret,
+ grant_type: "authorization_code",
+ code: params.code,
+ redirect_uri: params.redirectUri,
+ code_verifier: params.codeVerifier,
+ });
+
+ let res: Response;
+ try {
+ res = await this.fetchImpl(TOKEN_URL, {
+ method: "POST",
+ headers: { "content-type": "application/x-www-form-urlencoded" },
+ body: body.toString(),
+ signal: AbortSignal.timeout(this.timeoutMs),
+ });
+ } catch (err) {
+ throw new DiscordAuthError("could not reach Discord to exchange the code", err);
+ }
+
+ if (!res.ok) {
+ // The response body can echo request parameters, so it is not logged.
+ throw new DiscordAuthError(`Discord rejected the code exchange (${res.status})`);
+ }
+
+ const json = (await res.json().catch(() => null)) as { access_token?: unknown } | null;
+ const token = json?.access_token;
+ if (typeof token !== "string" || token.length === 0) {
+ throw new DiscordAuthError("Discord returned no access token");
+ }
+ return token;
+ }
+
+ /** Reads the authenticated user's identity. The only Discord call we make. */
+ async fetchProfile(accessToken: string): Promise<DiscordProfile> {
+ let res: Response;
+ try {
+ res = await this.fetchImpl(USER_URL, {
+ headers: { authorization: `Bearer ${accessToken}` },
+ signal: AbortSignal.timeout(this.timeoutMs),
+ });
+ } catch (err) {
+ throw new DiscordAuthError("could not reach Discord to read the profile", err);
+ }
+ if (!res.ok) throw new DiscordAuthError(`Discord profile request failed (${res.status})`);
+
+ const json = (await res.json().catch(() => null)) as Record<string, unknown> | null;
+ const id = json?.["id"];
+ if (typeof id !== "string" || id.length === 0) {
+ throw new DiscordAuthError("Discord profile response had no user id");
+ }
+
+ return {
+ id,
+ username: typeof json?.["username"] === "string" ? (json["username"] as string) : null,
+ globalName:
+ typeof json?.["global_name"] === "string" ? (json["global_name"] as string) : null,
+ avatarHash: typeof json?.["avatar"] === "string" ? (json["avatar"] as string) : null,
+ };
+ }
+}
+
+/**
+ * Chooses which registered redirect URI to use for this request.
+ *
+ * Several are registered at once so the beta and the eventual production domain
+ * can both be live in the Discord developer portal, making the domain move a
+ * cutover rather than a flag day. We must send back exactly one of the
+ * registered values, so an unknown host falls back to the configured app origin
+ * rather than reflecting whatever the request claimed.
+ */
+export function pickRedirectUri(
+ redirectUris: readonly string[],
+ appOrigin: string,
+): string | null {
+ const preferred = redirectUris.find((uri) => uri.startsWith(`${appOrigin}/`));
+ return preferred ?? redirectUris[0] ?? null;
+}
diff --git a/apps/api/src/auth/sessions.ts b/apps/api/src/auth/sessions.ts
new file mode 100644
index 0000000..633f51e
--- /dev/null
+++ b/apps/api/src/auth/sessions.ts
@@ -0,0 +1,210 @@
+import { randomUUID } from "node:crypto";
+import type { Db } from "../db/index.ts";
+import { writeTx } from "../db/index.ts";
+import { randomToken, sha256 } from "./crypto.ts";
+
+/**
+ * Server-side opaque sessions.
+ *
+ * Not JWTs: we have the database on the same box, so stateless verification
+ * buys nothing, while a session table buys instant revocation — which account
+ * deletion and "log out everywhere" both actually need.
+ *
+ * Idle and absolute expiry are separate. Idle slides on use; absolute never
+ * extends, so a stolen session cannot be kept alive indefinitely by using it.
+ */
+
+export const IDLE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+export const ABSOLUTE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
+
+/** Idle expiry is only rewritten when it would move by more than this, to avoid
+ * a database write on every single request. */
+const IDLE_REFRESH_THRESHOLD_MS = 60 * 60 * 1000;
+
+export type SessionMeta = { uaHash?: string | null; ipHash?: string | null };
+
+export type CreatedSession = {
+ /** Given to the browser. Never stored — only its hash is. */
+ token: string;
+ sessionId: string;
+ absoluteExpiresAt: number;
+};
+
+export function createSession(
+ db: Db,
+ accountId: string,
+ now: number,
+ meta: SessionMeta = {},
+): CreatedSession {
+ const token = randomToken(32);
+ const id = sha256(token);
+ const absoluteExpiresAt = now + ABSOLUTE_TTL_MS;
+
+ db.query(
+ `INSERT INTO sessions
+ (id, account_id, created_at, idle_expires_at, abs_expires_at, ua_hash, ip_hash)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ ).run(id, accountId, now, now + IDLE_TTL_MS, absoluteExpiresAt, meta.uaHash ?? null, meta.ipHash ?? null);
+
+ return { token, sessionId: id, absoluteExpiresAt };
+}
+
+export type ResolvedSession = { sessionId: string; accountId: string };
+
+type SessionRow = {
+ id: string;
+ account_id: string;
+ idle_expires_at: number;
+ abs_expires_at: number;
+ revoked_at: number | null;
+};
+
+/**
+ * Validates a session cookie value and slides its idle window.
+ *
+ * Returns null for anything not currently valid — unknown, revoked, idle-expired
+ * or past absolute expiry — without distinguishing between them to the caller.
+ */
+export function resolveSession(db: Db, token: string, now: number): ResolvedSession | null {
+ if (!token) return null;
+ const id = sha256(token);
+
+ const row = db
+ .query<SessionRow, [string]>(
+ `SELECT id, account_id, idle_expires_at, abs_expires_at, revoked_at
+ FROM sessions WHERE id = ?`,
+ )
+ .get(id);
+
+ if (!row) return null;
+ if (row.revoked_at !== null) return null;
+ if (now >= row.abs_expires_at) return null;
+ if (now >= row.idle_expires_at) return null;
+
+ // Deleted accounts must not resolve, even while a session row survives.
+ const account = db
+ .query<{ deleted_at: number | null }, [string]>(
+ "SELECT deleted_at FROM accounts WHERE id = ?",
+ )
+ .get(row.account_id);
+ if (!account || account.deleted_at !== null) return null;
+
+ const nextIdle = Math.min(now + IDLE_TTL_MS, row.abs_expires_at);
+ if (nextIdle - row.idle_expires_at > IDLE_REFRESH_THRESHOLD_MS) {
+ db.query("UPDATE sessions SET idle_expires_at = ? WHERE id = ?").run(nextIdle, id);
+ }
+
+ return { sessionId: row.id, accountId: row.account_id };
+}
+
+export function revokeSession(db: Db, token: string, now: number): void {
+ db.query("UPDATE sessions SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL").run(
+ now,
+ sha256(token),
+ );
+}
+
+/** Used by "log out everywhere", account deletion, and privilege changes. */
+export function revokeAllSessionsForAccount(db: Db, accountId: string, now: number): number {
+ const result = db
+ .query("UPDATE sessions SET revoked_at = ? WHERE account_id = ? AND revoked_at IS NULL")
+ .run(now, accountId);
+ return Number(result.changes ?? 0);
+}
+
+/**
+ * Rotates a session, keeping the account. Called on privilege change so a
+ * session captured before the change cannot be replayed after it.
+ */
+export function rotateSession(
+ db: Db,
+ oldToken: string,
+ now: number,
+ meta: SessionMeta = {},
+): CreatedSession | null {
+ return writeTx(db, (tx) => {
+ const current = resolveSession(tx, oldToken, now);
+ if (!current) return null;
+ revokeSession(tx, oldToken, now);
+ return createSession(tx, current.accountId, now, meta);
+ });
+}
+
+/** Housekeeping. Sessions are cheap, but expired rows need not accumulate. */
+export function pruneExpiredSessions(db: Db, now: number): number {
+ const result = db
+ .query("DELETE FROM sessions WHERE abs_expires_at < ? OR (revoked_at IS NOT NULL AND revoked_at < ?)")
+ .run(now, now - 7 * 24 * 60 * 60 * 1000);
+ return Number(result.changes ?? 0);
+}
+
+// ------------------------------------------------------------------ accounts
+
+export type Account = { id: string; createdAt: number };
+
+export type DiscordProfile = {
+ id: string;
+ username: string | null;
+ globalName: string | null;
+ avatarHash: string | null;
+};
+
+export function findAccountByDiscordId(db: Db, discordUserId: string): Account | null {
+ const row = db
+ .query<{ id: string; created_at: number }, [string]>(
+ `SELECT a.id AS id, a.created_at AS created_at
+ FROM discord_identities d
+ JOIN accounts a ON a.id = d.account_id
+ WHERE d.discord_user_id = ? AND a.deleted_at IS NULL`,
+ )
+ .get(discordUserId);
+ return row ? { id: row.id, createdAt: row.created_at } : null;
+}
+
+/**
+ * Links a Discord identity to an account, creating the account when needed.
+ *
+ * The identity lives in its own table rather than as a column on accounts, so
+ * attaching a second Discord account later needs no migration.
+ */
+export function upsertAccountForDiscord(
+ db: Db,
+ profile: DiscordProfile,
+ now: number,
+ opts: { allowCreate: boolean },
+): { account: Account; created: boolean } | { account: null; created: false } {
+ return writeTx(db, (tx) => {
+ const existing = findAccountByDiscordId(tx, profile.id);
+ if (existing) {
+ tx.query(
+ `UPDATE discord_identities
+ SET username = ?, global_name = ?, avatar_hash = ?, last_login_at = ?
+ WHERE discord_user_id = ?`,
+ ).run(profile.username, profile.globalName, profile.avatarHash, now, profile.id);
+ return { account: existing, created: false };
+ }
+
+ if (!opts.allowCreate) return { account: null, created: false } as const;
+
+ const accountId = randomUUID();
+ tx.query("INSERT INTO accounts (id, created_at) VALUES (?, ?)").run(accountId, now);
+ tx.query(
+ `INSERT INTO discord_identities
+ (discord_user_id, account_id, username, global_name, avatar_hash, linked_at, last_login_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ ).run(profile.id, accountId, profile.username, profile.globalName, profile.avatarHash, now, now);
+
+ return { account: { id: accountId, createdAt: now }, created: true };
+ });
+}
+
+/** Discord identities attached to an account. Never exposed publicly unless the
+ * user has chosen to display one. */
+export function discordIdsForAccount(db: Db, accountId: string): string[] {
+ return db
+ .query<{ discord_user_id: string }, [string]>(
+ "SELECT discord_user_id FROM discord_identities WHERE account_id = ?",
+ )
+ .all(accountId)
+ .map((r) => r.discord_user_id);
+}
diff --git a/apps/api/src/claims/index.ts b/apps/api/src/claims/index.ts
new file mode 100644
index 0000000..10b15a2
--- /dev/null
+++ b/apps/api/src/claims/index.ts
@@ -0,0 +1,516 @@
+import { randomUUID } from "node:crypto";
+import { randomToken } from "../auth/crypto.ts";
+import type { Db } from "../db/index.ts";
+import { writeTx } from "../db/index.ts";
+import type { PkClient } from "../pk/client.ts";
+import { PkError, PkNotFound } from "../pk/errors.ts";
+import type { PkSystem } from "../pk/types.ts";
+import { releaseSlugsForSubject, reclaimSlugsForSubject } from "../slugs/lifecycle.ts";
+
+/**
+ * System claiming.
+ *
+ * Claiming a system on pkviewer is NOT ownership of the underlying PluralKit
+ * system. It grants control over presentation here and nothing else.
+ *
+ * Three verification tiers, in preference order. Providing a PluralKit token is
+ * never required: tiers 1 and 2 both work without one.
+ */
+
+export const CHALLENGE_TTL_MS = 30 * 60 * 1000;
+export const CHALLENGE_MAX_ATTEMPTS = 10;
+/** Configuration survives an unclaim this long; re-claiming restores it. */
+export const UNCLAIM_GRACE_MS = 30 * 24 * 60 * 60 * 1000;
+
+export type ClaimMethod = "discord_link" | "description_challenge" | "pk_token";
+
+export type ClaimFailure =
+ | "not_found"
+ | "already_claimed"
+ | "not_verified"
+ | "beta_not_allowed"
+ | "upstream_unavailable";
+
+export type ClaimResult =
+ | { ok: true; systemId: string; pkSystemHid: string; method: ClaimMethod; restored: boolean }
+ | { ok: false; reason: ClaimFailure };
+
+export type ClaimDeps = {
+ db: Db;
+ pk: PkClient;
+ now?: () => number;
+};
+
+// ---------------------------------------------------------------- system rows
+
+/**
+ * Finds or creates our local row for a PluralKit system.
+ *
+ * Keyed on PluralKit's UUID, which is the immutable identity. The 5-6 character
+ * HID is stored alongside for display and lookup but is never the key.
+ */
+export function ensureSystemRow(db: Db, system: PkSystem, now: number): string {
+ const existing = db
+ .query<{ id: string }, [string]>("SELECT id FROM systems WHERE pk_system_uuid = ?")
+ .get(system.uuid);
+ if (existing) {
+ // The HID can be re-rolled by the user; keep our copy current.
+ db.query("UPDATE systems SET pk_system_hid = ? WHERE id = ?").run(system.id, existing.id);
+ return existing.id;
+ }
+ const id = randomUUID();
+ db.query(
+ "INSERT INTO systems (id, pk_system_uuid, pk_system_hid, created_at) VALUES (?,?,?,?)",
+ ).run(id, system.uuid, system.id, now);
+ return id;
+}
+
+export function currentOwner(db: Db, systemId: string): string | null {
+ const row = db
+ .query<{ account_id: string }, [string]>(
+ "SELECT account_id FROM grants WHERE subject_type = 'system' AND subject_id = ? AND role = 'owner'",
+ )
+ .get(systemId);
+ return row?.account_id ?? null;
+}
+
+export function accountManagesSystem(db: Db, accountId: string, systemId: string): boolean {
+ const row = db
+ .query<{ role: string }, [string, string]>(
+ "SELECT role FROM grants WHERE account_id = ? AND subject_type = 'system' AND subject_id = ?",
+ )
+ .get(accountId, systemId);
+ return Boolean(row);
+}
+
+function audit(
+ db: Db,
+ now: number,
+ accountId: string | null,
+ action: string,
+ target: string | null,
+ detail: string | null = null,
+): void {
+ db.query(
+ "INSERT INTO audit_events (at, account_id, action, target, detail) VALUES (?,?,?,?,?)",
+ ).run(now, accountId, action, target, detail);
+}
+
+/**
+ * Records ownership after a tier has verified it.
+ *
+ * The single-owner unique index is the real gate. An existing owner is checked
+ * first for a clean error message, but the index is what makes two simultaneous
+ * claimants safe — the loser hits the constraint rather than winning a race.
+ */
+function grantOwnership(
+ db: Db,
+ accountId: string,
+ system: PkSystem,
+ method: ClaimMethod,
+ now: number,
+): ClaimResult {
+ return writeTx(db, (tx) => {
+ const systemId = ensureSystemRow(tx, system, now);
+
+ const owner = currentOwner(tx, systemId);
+ if (owner !== null && owner !== accountId) {
+ // Decision 7: block, do not take over. We never reveal who the owner is.
+ audit(tx, now, accountId, "system.claim.blocked", systemId, method);
+ return { ok: false, reason: "already_claimed" } as const;
+ }
+
+ // Re-claiming inside the grace window restores what unclaiming soft-deleted.
+ const sys = tx
+ .query<{ unclaimed_at: number | null }, [string]>(
+ "SELECT unclaimed_at FROM systems WHERE id = ?",
+ )
+ .get(systemId);
+ const restorable =
+ sys?.unclaimed_at != null && now - sys.unclaimed_at <= UNCLAIM_GRACE_MS;
+
+ if (owner === accountId) {
+ tx.query(
+ "UPDATE grants SET verification_method = ?, verified_at = ? WHERE subject_type = 'system' AND subject_id = ? AND account_id = ?",
+ ).run(method, now, systemId, accountId);
+ return {
+ ok: true,
+ systemId,
+ pkSystemHid: system.id,
+ method,
+ restored: false,
+ } as const;
+ }
+
+ try {
+ tx.query(
+ `INSERT INTO grants
+ (account_id, subject_type, subject_id, role, granted_at, verification_method, verified_at)
+ VALUES (?, 'system', ?, 'owner', ?, ?, ?)`,
+ ).run(accountId, systemId, now, method, now);
+ } catch {
+ // The unique index fired: someone claimed it between our check and write.
+ audit(tx, now, accountId, "system.claim.raced", systemId, method);
+ return { ok: false, reason: "already_claimed" } as const;
+ }
+
+ let restored = false;
+ if (restorable) {
+ tx.query(
+ "UPDATE themes SET deleted_at = NULL WHERE owner_type = 'system' AND owner_id = ?",
+ ).run(systemId);
+ const memberIds = tx
+ .query<{ id: string }, [string]>("SELECT id FROM members WHERE system_id = ?")
+ .all(systemId)
+ .map((r) => r.id);
+ for (const memberId of memberIds) {
+ tx.query(
+ "UPDATE themes SET deleted_at = NULL WHERE owner_type = 'member' AND owner_id = ?",
+ ).run(memberId);
+ reclaimSlugsForSubject(tx, "member", memberId, now, accountId);
+ }
+ reclaimSlugsForSubject(tx, "system", systemId, now, accountId);
+ restored = true;
+ }
+
+ tx.query("UPDATE systems SET claimed_at = ?, unclaimed_at = NULL WHERE id = ?").run(
+ now,
+ systemId,
+ );
+ audit(tx, now, accountId, "system.claimed", systemId, method);
+
+ return { ok: true, systemId, pkSystemHid: system.id, method, restored } as const;
+ });
+}
+
+// ------------------------------------------------------- tier 1: discord link
+
+/**
+ * Systems reachable by tier-1 proof for this account.
+ *
+ * PluralKit resolves a linked Discord account id to its system, publicly and
+ * with no credential. Combined with Discord OAuth having already verified who
+ * the user is, that is a complete ownership proof: Discord asserts the identity,
+ * PluralKit asserts the link.
+ *
+ * The Discord ids come from the session, never from user input.
+ */
+export async function discoverLinkedSystems(
+ deps: ClaimDeps,
+ discordIds: readonly string[],
+): Promise<PkSystem[]> {
+ const found = new Map<string, PkSystem>();
+ for (const discordId of discordIds) {
+ try {
+ const system = await deps.pk.getSystem(discordId);
+ found.set(system.uuid, system);
+ } catch (err) {
+ // No linked system, or PluralKit is unhappy: not an error for discovery.
+ if (err instanceof PkError) continue;
+ throw err;
+ }
+ }
+ return [...found.values()];
+}
+
+export async function claimViaDiscordLink(
+ deps: ClaimDeps,
+ params: { accountId: string; discordIds: readonly string[]; pkSystemRef: string },
+): Promise<ClaimResult> {
+ const now = deps.now?.() ?? Date.now();
+
+ let target: PkSystem;
+ try {
+ target = await deps.pk.getSystem(params.pkSystemRef);
+ } catch (err) {
+ if (err instanceof PkNotFound) return { ok: false, reason: "not_found" };
+ if (err instanceof PkError) return { ok: false, reason: "upstream_unavailable" };
+ throw err;
+ }
+
+ const linked = await discoverLinkedSystems(deps, params.discordIds);
+ if (!linked.some((s) => s.uuid === target.uuid)) {
+ return { ok: false, reason: "not_verified" };
+ }
+
+ return grantOwnership(deps.db, params.accountId, target, "discord_link", now);
+}
+
+// ------------------------------------------------ tier 2: description challenge
+
+export type Challenge = {
+ id: string;
+ nonce: string;
+ pkSystemHid: string;
+ expiresAt: number;
+};
+
+export type ChallengeCreation =
+ | { ok: true; challenge: Challenge }
+ | { ok: false; reason: "not_found" | "upstream_unavailable" | "already_claimed" };
+
+/**
+ * Issues a nonce for the user to place in their system description.
+ *
+ * This is the standard domain-verification pattern and needs no credential:
+ * only someone who can edit the system through PluralKit can put the nonce
+ * there. One active challenge per account/system pair.
+ */
+export async function createDescriptionChallenge(
+ deps: ClaimDeps,
+ params: { accountId: string; pkSystemRef: string },
+): Promise<ChallengeCreation> {
+ const now = deps.now?.() ?? Date.now();
+
+ let system: PkSystem;
+ try {
+ system = await deps.pk.getSystem(params.pkSystemRef);
+ } catch (err) {
+ if (err instanceof PkNotFound) return { ok: false, reason: "not_found" };
+ if (err instanceof PkError) return { ok: false, reason: "upstream_unavailable" };
+ throw err;
+ }
+
+ const existingSystemId = deps.db
+ .query<{ id: string }, [string]>("SELECT id FROM systems WHERE pk_system_uuid = ?")
+ .get(system.uuid);
+ if (existingSystemId) {
+ const owner = currentOwner(deps.db, existingSystemId.id);
+ if (owner !== null && owner !== params.accountId) {
+ return { ok: false, reason: "already_claimed" };
+ }
+ }
+
+ const challenge: Challenge = {
+ id: randomUUID(),
+ nonce: `pkv-verify-${randomToken(9)}`,
+ pkSystemHid: system.id,
+ expiresAt: now + CHALLENGE_TTL_MS,
+ };
+
+ deps.db
+ .query(
+ `INSERT INTO claim_challenges
+ (id, account_id, pk_system_uuid, pk_system_hid, nonce, created_at, expires_at)
+ VALUES (?,?,?,?,?,?,?)
+ ON CONFLICT (account_id, pk_system_uuid) DO UPDATE SET
+ id = excluded.id,
+ nonce = excluded.nonce,
+ created_at = excluded.created_at,
+ expires_at = excluded.expires_at,
+ attempts = 0,
+ consumed_at = NULL`,
+ )
+ .run(
+ challenge.id,
+ params.accountId,
+ system.uuid,
+ system.id,
+ challenge.nonce,
+ now,
+ challenge.expiresAt,
+ );
+
+ return { ok: true, challenge };
+}
+
+export type ChallengeVerification =
+ | ClaimResult
+ | { ok: false; reason: "challenge_not_found" | "challenge_expired" | "too_many_attempts" | "description_unavailable" };
+
+/**
+ * Re-reads the system description and matches the nonce.
+ *
+ * The fetch is forced fresh (`maxAgeMs: 0`) — verifying against a cached
+ * description would let a stale copy prove ownership the user no longer has.
+ */
+export async function verifyDescriptionChallenge(
+ deps: ClaimDeps,
+ params: { accountId: string; challengeId: string },
+): Promise<ChallengeVerification> {
+ const now = deps.now?.() ?? Date.now();
+
+ const row = deps.db
+ .query<
+ {
+ id: string;
+ pk_system_uuid: string;
+ nonce: string;
+ expires_at: number;
+ attempts: number;
+ consumed_at: number | null;
+ },
+ [string, string]
+ >(
+ `SELECT id, pk_system_uuid, nonce, expires_at, attempts, consumed_at
+ FROM claim_challenges WHERE id = ? AND account_id = ?`,
+ )
+ .get(params.challengeId, params.accountId);
+
+ if (!row || row.consumed_at !== null) return { ok: false, reason: "challenge_not_found" };
+ if (now >= row.expires_at) return { ok: false, reason: "challenge_expired" };
+ if (row.attempts >= CHALLENGE_MAX_ATTEMPTS) return { ok: false, reason: "too_many_attempts" };
+
+ deps.db
+ .query("UPDATE claim_challenges SET attempts = attempts + 1 WHERE id = ?")
+ .run(row.id);
+
+ let system: PkSystem;
+ try {
+ system = await deps.pk.getSystem(row.pk_system_uuid, { maxAgeMs: 0, allowStale: false });
+ } catch (err) {
+ if (err instanceof PkNotFound) return { ok: false, reason: "not_found" };
+ if (err instanceof PkError) return { ok: false, reason: "upstream_unavailable" };
+ throw err;
+ }
+
+ // A private description reads as null publicly, so the challenge simply cannot
+ // be completed. Tier 1 or tier 3 remain available.
+ if (!system.description) return { ok: false, reason: "description_unavailable" };
+ if (!system.description.includes(row.nonce)) return { ok: false, reason: "not_verified" };
+
+ const result = grantOwnership(deps.db, params.accountId, system, "description_challenge", now);
+ if (result.ok) {
+ deps.db.query("UPDATE claim_challenges SET consumed_at = ? WHERE id = ?").run(now, row.id);
+ }
+ return result;
+}
+
+// --------------------------------------------------- tier 3: transient PK token
+
+/**
+ * Verifies with a PluralKit token supplied for this one request.
+ *
+ * The token is used within this function and never persisted, cached or logged.
+ * It is the last resort, offered only when tiers 1 and 2 cannot work — a PK
+ * token is full read/write and can delete members, so the product must never
+ * require one.
+ */
+export async function claimViaToken(
+ deps: ClaimDeps,
+ params: { accountId: string; pkSystemRef: string; token: string },
+): Promise<ClaimResult> {
+ const now = deps.now?.() ?? Date.now();
+
+ let ownSystem: PkSystem;
+ try {
+ ownSystem = await deps.pk.getOwnSystem(params.token);
+ } catch (err) {
+ if (err instanceof PkError) return { ok: false, reason: "not_verified" };
+ throw err;
+ }
+
+ let target: PkSystem;
+ try {
+ target = await deps.pk.getSystem(params.pkSystemRef);
+ } catch (err) {
+ if (err instanceof PkNotFound) return { ok: false, reason: "not_found" };
+ if (err instanceof PkError) return { ok: false, reason: "upstream_unavailable" };
+ throw err;
+ }
+
+ if (ownSystem.uuid !== target.uuid) return { ok: false, reason: "not_verified" };
+
+ return grantOwnership(deps.db, params.accountId, target, "pk_token", now);
+}
+
+// ------------------------------------------------------------------ unclaiming
+
+export type UnclaimResult =
+ | { ok: true; slugsReleased: number }
+ | { ok: false; reason: "not_found" | "not_owner" };
+
+/**
+ * Releases a system.
+ *
+ * Decision 11: slugs enter their 7-day reservation, configuration is soft
+ * deleted with a 30-day grace, and re-claiming inside that window restores
+ * everything. Nothing is hard deleted here — an unclaim made by accident, or
+ * under pressure, must be recoverable.
+ */
+export function unclaimSystem(
+ deps: ClaimDeps,
+ params: { accountId: string; systemId: string },
+): UnclaimResult {
+ const now = deps.now?.() ?? Date.now();
+
+ return writeTx(deps.db, (tx) => {
+ const system = tx
+ .query<{ id: string }, [string]>("SELECT id FROM systems WHERE id = ?")
+ .get(params.systemId);
+ if (!system) return { ok: false, reason: "not_found" } as const;
+
+ if (currentOwner(tx, params.systemId) !== params.accountId) {
+ return { ok: false, reason: "not_owner" } as const;
+ }
+
+ let slugsReleased = releaseSlugsForSubject(
+ tx,
+ "system",
+ params.systemId,
+ now,
+ params.accountId,
+ );
+
+ const memberIds = tx
+ .query<{ id: string }, [string]>("SELECT id FROM members WHERE system_id = ?")
+ .all(params.systemId)
+ .map((r) => r.id);
+
+ for (const memberId of memberIds) {
+ slugsReleased += releaseSlugsForSubject(tx, "member", memberId, now, params.accountId);
+ tx.query(
+ "UPDATE themes SET deleted_at = ? WHERE owner_type = 'member' AND owner_id = ? AND deleted_at IS NULL",
+ ).run(now, memberId);
+ }
+
+ tx.query(
+ "UPDATE themes SET deleted_at = ? WHERE owner_type = 'system' AND owner_id = ? AND deleted_at IS NULL",
+ ).run(now, params.systemId);
+
+ // Every grant goes, not just the owner's: managers do not survive an unclaim.
+ tx.query("DELETE FROM grants WHERE subject_type = 'system' AND subject_id = ?").run(
+ params.systemId,
+ );
+
+ tx.query("UPDATE systems SET unclaimed_at = ?, claimed_at = NULL WHERE id = ?").run(
+ now,
+ params.systemId,
+ );
+
+ audit(tx, now, params.accountId, "system.unclaimed", params.systemId);
+ return { ok: true, slugsReleased } as const;
+ });
+}
+
+/** Systems an account manages. */
+export function systemsForAccount(
+ db: Db,
+ accountId: string,
+): Array<{ systemId: string; pkSystemHid: string; pkSystemUuid: string; role: string }> {
+ return db
+ .query<
+ { subject_id: string; pk_system_hid: string; pk_system_uuid: string; role: string },
+ [string]
+ >(
+ `SELECT g.subject_id AS subject_id, s.pk_system_hid AS pk_system_hid,
+ s.pk_system_uuid AS pk_system_uuid, g.role AS role
+ FROM grants g
+ JOIN systems s ON s.id = g.subject_id
+ WHERE g.account_id = ? AND g.subject_type = 'system'
+ ORDER BY g.granted_at`,
+ )
+ .all(accountId)
+ .map((r) => ({
+ systemId: r.subject_id,
+ pkSystemHid: r.pk_system_hid,
+ pkSystemUuid: r.pk_system_uuid,
+ role: r.role,
+ }));
+}
+
+/** Removes expired challenges. Housekeeping only; nothing depends on it running. */
+export function pruneExpiredChallenges(db: Db, now: number): number {
+ const result = db.query("DELETE FROM claim_challenges WHERE expires_at < ?").run(now);
+ return Number(result.changes ?? 0);
+}
diff --git a/apps/api/src/config/index.ts b/apps/api/src/config/index.ts
new file mode 100644
index 0000000..fe5a438
--- /dev/null
+++ b/apps/api/src/config/index.ts
@@ -0,0 +1,255 @@
+import { randomBytes } from "node:crypto";
+import { z } from "zod";
+import { PKVIEWER_VERSION } from "./version.ts";
+
+/**
+ * All deployment-varying values enter the application here and nowhere else.
+ *
+ * The domain the beta happens to run on is configuration, not architecture: no
+ * absolute pkviewer URL is persisted to the database, and every public URL is
+ * composed at render time from these origins. Moving from the beta host to the
+ * eventual production domain is then an env change, not a migration.
+ */
+
+const originSchema = z
+ .string()
+ .min(1)
+ .transform((raw, ctx) => {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `not an absolute URL: ${raw}` });
+ return z.NEVER;
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `origin must be http(s): ${raw}` });
+ return z.NEVER;
+ }
+ if (url.pathname !== "/" || url.search || url.hash) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `origin must have no path: ${raw}` });
+ return z.NEVER;
+ }
+ // Normalised: no trailing slash, so callers can concatenate paths freely.
+ return url.origin;
+ });
+
+const csv = z
+ .string()
+ .default("")
+ .transform((s) => s.split(",").map((v) => v.trim()).filter(Boolean));
+
+const boolish = z
+ .enum(["true", "false", "1", "0"])
+ .default("false")
+ .transform((v) => v === "true" || v === "1");
+
+const envSchema = z.object({
+ NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
+
+ PUBLIC_APP_ORIGIN: originSchema,
+ PUBLIC_USERCONTENT_ORIGIN: originSchema,
+ PUBLIC_ASSET_ORIGIN: originSchema,
+
+ API_PORT: z.coerce.number().int().positive().default(3001),
+ INTERNAL_API_ORIGIN: originSchema,
+
+ DATABASE_PATH: z.string().min(1).default("./data/pkviewer.db"),
+
+ PK_API_BASE: z.string().url().default("https://api.pluralkit.me/v2"),
+ PK_USER_AGENT_CONTACT: z.string().url(),
+ PK_RATE_LIMIT_READ_RPS: z.coerce.number().positive().default(6),
+ PK_RATE_LIMIT_WRITE_RPS: z.coerce.number().positive().default(2),
+
+ DISCORD_CLIENT_ID: z.string().default(""),
+ DISCORD_CLIENT_SECRET: z.string().default(""),
+ DISCORD_REDIRECT_URIS: csv,
+
+ BETA_MODE: boolish,
+ SIGNUP_ENABLED: boolish,
+ BETA_ALLOWED_DISCORD_IDS: csv,
+
+ SESSION_SECRET: z.string().default(""),
+});
+
+export type Config = Readonly<{
+ nodeEnv: "development" | "test" | "production";
+ isProduction: boolean;
+
+ appOrigin: string;
+ userContentOrigin: string;
+ assetOrigin: string;
+ internalApiOrigin: string;
+ apiPort: number;
+
+ databasePath: string;
+
+ pk: {
+ apiBase: string;
+ /** The single canonical User-Agent. Never varies by user, server or shard. */
+ userAgent: string;
+ readRps: number;
+ writeRps: number;
+ };
+
+ discord: {
+ clientId: string;
+ clientSecret: string;
+ redirectUris: readonly string[];
+ };
+
+ beta: {
+ enabled: boolean;
+ signupEnabled: boolean;
+ allowedDiscordIds: ReadonlySet<string>;
+ };
+
+ sessionSecret: string;
+}>;
+
+export class ConfigError extends Error {
+ override readonly name = "ConfigError";
+}
+
+/**
+ * Parses and validates configuration. Throws rather than returning a partial
+ * config: a process that boots with an invalid security-relevant origin is
+ * worse than one that refuses to boot.
+ */
+export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
+ const parsed = envSchema.safeParse(env);
+ if (!parsed.success) {
+ const detail = parsed.error.issues
+ .map((i) => ` ${i.path.join(".") || "(root)"}: ${i.message}`)
+ .join("\n");
+ throw new ConfigError(`invalid configuration:\n${detail}`);
+ }
+ const e = parsed.data;
+ const isProduction = e.NODE_ENV === "production";
+
+ /**
+ * Outside production, an absent session secret becomes a random one rather
+ * than an empty string.
+ *
+ * An empty HMAC key would still "work", which is the problem: the OAuth
+ * handshake cookie would be trivially forgeable locally and nothing would say
+ * so. A per-start random value keeps development honest and costs nothing —
+ * sessions are opaque database tokens, not signed with this, so a restart
+ * only invalidates in-flight logins.
+ */
+ let sessionSecret = e.SESSION_SECRET;
+ if (!isProduction && sessionSecret.length === 0) {
+ sessionSecret = randomBytes(32).toString("base64url");
+ console.warn(
+ "[config] SESSION_SECRET is not set; generated an ephemeral one for this run. " +
+ "Set it in .env to keep logins working across restarts.",
+ );
+ }
+
+ // The user-content origin is the boundary that keeps user-authored
+ // presentation away from session cookies. Sharing an origin with the app
+ // would silently void that, so this is fatal in every environment including
+ // development — a dev setup that differs from production here would train us
+ // to write code that is only safe by accident.
+ if (e.PUBLIC_USERCONTENT_ORIGIN === e.PUBLIC_APP_ORIGIN) {
+ throw new ConfigError(
+ "PUBLIC_USERCONTENT_ORIGIN must not equal PUBLIC_APP_ORIGIN — " +
+ "user-authored presentation requires its own origin.",
+ );
+ }
+
+ if (isProduction) {
+ for (const [key, value] of [
+ ["PUBLIC_APP_ORIGIN", e.PUBLIC_APP_ORIGIN],
+ ["PUBLIC_USERCONTENT_ORIGIN", e.PUBLIC_USERCONTENT_ORIGIN],
+ ["PUBLIC_ASSET_ORIGIN", e.PUBLIC_ASSET_ORIGIN],
+ ] as const) {
+ if (!value.startsWith("https://")) {
+ throw new ConfigError(`${key} must be https in production (got ${value})`);
+ }
+ }
+ if (e.DISCORD_REDIRECT_URIS.length === 0) {
+ throw new ConfigError("DISCORD_REDIRECT_URIS must list at least one URI in production");
+ }
+ if (e.SESSION_SECRET.length < 32) {
+ throw new ConfigError(
+ "SESSION_SECRET must be at least 32 characters in production. " +
+ "Generate one with: openssl rand -base64 32",
+ );
+ }
+ if (!e.DISCORD_CLIENT_ID || !e.DISCORD_CLIENT_SECRET) {
+ throw new ConfigError(
+ "DISCORD_CLIENT_ID and DISCORD_CLIENT_SECRET are required in production; " +
+ "without them nobody can sign in.",
+ );
+ }
+ }
+
+ for (const uri of e.DISCORD_REDIRECT_URIS) {
+ try {
+ new URL(uri);
+ } catch {
+ throw new ConfigError(`DISCORD_REDIRECT_URIS contains a non-URL entry: ${uri}`);
+ }
+ }
+
+ // Claiming on a beta deployment is gated by an explicit allow-list. Public
+ // viewing is never gated — that is the point of the platform.
+ if (e.BETA_MODE && e.SIGNUP_ENABLED && e.BETA_ALLOWED_DISCORD_IDS.length === 0 && isProduction) {
+ throw new ConfigError(
+ "BETA_MODE with SIGNUP_ENABLED requires BETA_ALLOWED_DISCORD_IDS to be non-empty",
+ );
+ }
+
+ return Object.freeze({
+ nodeEnv: e.NODE_ENV,
+ isProduction,
+
+ appOrigin: e.PUBLIC_APP_ORIGIN,
+ userContentOrigin: e.PUBLIC_USERCONTENT_ORIGIN,
+ assetOrigin: e.PUBLIC_ASSET_ORIGIN,
+ internalApiOrigin: e.INTERNAL_API_ORIGIN,
+ apiPort: e.API_PORT,
+
+ databasePath: e.DATABASE_PATH,
+
+ pk: Object.freeze({
+ apiBase: e.PK_API_BASE.replace(/\/+$/, ""),
+ userAgent: buildUserAgent(e.PK_USER_AGENT_CONTACT),
+ readRps: e.PK_RATE_LIMIT_READ_RPS,
+ writeRps: e.PK_RATE_LIMIT_WRITE_RPS,
+ }),
+
+ discord: Object.freeze({
+ clientId: e.DISCORD_CLIENT_ID,
+ clientSecret: e.DISCORD_CLIENT_SECRET,
+ redirectUris: Object.freeze(e.DISCORD_REDIRECT_URIS),
+ }),
+
+ beta: Object.freeze({
+ enabled: e.BETA_MODE,
+ signupEnabled: e.SIGNUP_ENABLED,
+ allowedDiscordIds: new Set(e.BETA_ALLOWED_DISCORD_IDS),
+ }),
+
+ sessionSecret,
+ });
+}
+
+/**
+ * The canonical User-Agent, e.g. `pkviewer/0.1.0 (+https://github.com/o/pkviewer)`.
+ *
+ * The contact URL points at the repository rather than the deployment origin on
+ * purpose: PluralKit asks that an application's UA be stable and identifiable,
+ * and the repository URL survives the beta -> production domain move that the
+ * deployment origin would not.
+ */
+export function buildUserAgent(contactUrl: string): string {
+ return `pkviewer/${PKVIEWER_VERSION} (+${contactUrl})`;
+}
+
+let cached: Config | undefined;
+/** Process-wide config, parsed once. */
+export function config(): Config {
+ return (cached ??= loadConfig());
+}
diff --git a/apps/api/src/config/version.ts b/apps/api/src/config/version.ts
new file mode 100644
index 0000000..8570110
--- /dev/null
+++ b/apps/api/src/config/version.ts
@@ -0,0 +1,6 @@
+/**
+ * Application version. Part of the PluralKit User-Agent, so bumping it is
+ * visible to PluralKit's maintainers — bump on meaningful behaviour changes to
+ * our API usage, not on every deploy.
+ */
+export const PKVIEWER_VERSION = "0.1.0";
diff --git a/apps/api/src/db/index.ts b/apps/api/src/db/index.ts
new file mode 100644
index 0000000..2036ecb
--- /dev/null
+++ b/apps/api/src/db/index.ts
@@ -0,0 +1,71 @@
+import { Database } from "bun:sqlite";
+import { mkdirSync } from "node:fs";
+import { dirname } from "node:path";
+
+export type Db = Database;
+
+/**
+ * Opens a SQLite connection with the pragmas this application depends on.
+ *
+ * `foreign_keys` is off by default in SQLite and is per-connection, so it must
+ * be set here or every ON DELETE CASCADE in the schema silently does nothing.
+ */
+export function openDb(path: string): Db {
+ if (path !== ":memory:") {
+ mkdirSync(dirname(path), { recursive: true });
+ }
+ const db = new Database(path, { create: true, strict: false });
+
+ db.exec("PRAGMA journal_mode = WAL");
+ db.exec("PRAGMA foreign_keys = ON");
+ db.exec("PRAGMA busy_timeout = 5000");
+ db.exec("PRAGMA synchronous = NORMAL");
+
+ return db;
+}
+
+/**
+ * Runs `fn` inside an IMMEDIATE transaction.
+ *
+ * Deferred transactions take a read lock first and try to upgrade on the first
+ * write; if another writer holds the lock that upgrade fails with SQLITE_BUSY
+ * *after* the work is done, and busy_timeout does not help because retrying
+ * would deadlock. Taking the write lock upfront makes the transaction wait
+ * instead. Every transaction that may write must use this.
+ */
+export function writeTx<T>(db: Db, fn: (db: Db) => T): T {
+ db.exec("BEGIN IMMEDIATE");
+ try {
+ const result = fn(db);
+ db.exec("COMMIT");
+ return result;
+ } catch (err) {
+ try {
+ db.exec("ROLLBACK");
+ } catch {
+ // A failed rollback must not mask the original error.
+ }
+ throw err;
+ }
+}
+
+/** Read-only transaction, for multi-statement reads needing a consistent view. */
+export function readTx<T>(db: Db, fn: (db: Db) => T): T {
+ db.exec("BEGIN DEFERRED");
+ try {
+ const result = fn(db);
+ db.exec("COMMIT");
+ return result;
+ } catch (err) {
+ try {
+ db.exec("ROLLBACK");
+ } catch {
+ /* see above */
+ }
+ throw err;
+ }
+}
+
+/** Current time as integer Unix milliseconds. Injected so tests can control it. */
+export type Clock = () => number;
+export const systemClock: Clock = () => Date.now();
diff --git a/apps/api/src/db/migrate.ts b/apps/api/src/db/migrate.ts
new file mode 100644
index 0000000..967fe19
--- /dev/null
+++ b/apps/api/src/db/migrate.ts
@@ -0,0 +1,78 @@
+import { readdirSync, readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { openDb, writeTx, type Db } from "./index.ts";
+
+const MIGRATIONS_DIR = join(dirname(fileURLToPath(import.meta.url)), "migrations");
+
+export type MigrationResult = { applied: string[]; alreadyApplied: string[] };
+
+function ensureMigrationsTable(db: Db): void {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS schema_migrations (
+ name TEXT PRIMARY KEY,
+ applied_at INTEGER NOT NULL
+ ) STRICT
+ `);
+}
+
+function listMigrations(dir: string): string[] {
+ return readdirSync(dir)
+ .filter((f) => f.endsWith(".sql"))
+ .sort(); // Filenames are zero-padded, so lexical order is apply order.
+}
+
+/**
+ * Applies pending migrations in filename order.
+ *
+ * SQLite makes DDL transactional, so each migration commits atomically: a
+ * migration that fails partway leaves no half-applied schema behind.
+ */
+export function migrate(db: Db, dir: string = MIGRATIONS_DIR): MigrationResult {
+ ensureMigrationsTable(db);
+
+ const done = new Set(
+ db.query<{ name: string }, []>("SELECT name FROM schema_migrations").all().map((r) => r.name),
+ );
+
+ const applied: string[] = [];
+ const alreadyApplied: string[] = [];
+
+ for (const name of listMigrations(dir)) {
+ if (done.has(name)) {
+ alreadyApplied.push(name);
+ continue;
+ }
+ const sql = readFileSync(join(dir, name), "utf8");
+ writeTx(db, (tx) => {
+ tx.exec(sql);
+ tx.query("INSERT INTO schema_migrations (name, applied_at) VALUES (?, ?)").run(
+ name,
+ Date.now(),
+ );
+ });
+ applied.push(name);
+ }
+
+ return { applied, alreadyApplied };
+}
+
+/** Opens the database at `path`, migrates it, and returns the connection. */
+export function openAndMigrate(path: string): Db {
+ const db = openDb(path);
+ migrate(db);
+ return db;
+}
+
+if (import.meta.main) {
+ const { config } = await import("../config/index.ts");
+ const cfg = config();
+ const db = openDb(cfg.databasePath);
+ const result = migrate(db);
+ if (result.applied.length === 0) {
+ console.log(`up to date (${result.alreadyApplied.length} migrations)`);
+ } else {
+ for (const name of result.applied) console.log(`applied ${name}`);
+ }
+ db.close();
+}
diff --git a/apps/api/src/db/migrations/001_init.sql b/apps/api/src/db/migrations/001_init.sql
new file mode 100644
index 0000000..292271d
--- /dev/null
+++ b/apps/api/src/db/migrations/001_init.sql
@@ -0,0 +1,222 @@
+-- pkviewer initial schema.
+--
+-- Three data domains are kept structurally apart:
+-- * pkviewer metadata — accounts, grants, slugs, themes, socials (authoritative)
+-- * PluralKit cache — pk_snapshots (never authoritative, always re-derivable)
+-- * audit — append-only record of security-relevant actions
+--
+-- All timestamps are integer Unix milliseconds UTC. Text dates make the slug
+-- reservation comparison subtly wrong, so they are not used anywhere.
+
+-- ---------------------------------------------------------------- identity --
+
+CREATE TABLE accounts (
+ id TEXT PRIMARY KEY,
+ created_at INTEGER NOT NULL,
+ deleted_at INTEGER
+) STRICT;
+
+-- Separate from accounts so one account can hold several Discord identities
+-- later without a migration.
+CREATE TABLE discord_identities (
+ discord_user_id TEXT PRIMARY KEY,
+ account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
+ username TEXT,
+ global_name TEXT,
+ avatar_hash TEXT,
+ linked_at INTEGER NOT NULL,
+ last_login_at INTEGER
+) STRICT;
+
+CREATE INDEX idx_discord_identities_account ON discord_identities(account_id);
+
+-- `id` holds the SHA-256 of the cookie value, never the value itself, so a
+-- database read does not yield usable sessions.
+CREATE TABLE sessions (
+ id TEXT PRIMARY KEY,
+ account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
+ created_at INTEGER NOT NULL,
+ idle_expires_at INTEGER NOT NULL,
+ abs_expires_at INTEGER NOT NULL,
+ revoked_at INTEGER,
+ ua_hash TEXT,
+ ip_hash TEXT
+) STRICT;
+
+CREATE INDEX idx_sessions_account ON sessions(account_id);
+CREATE INDEX idx_sessions_expiry ON sessions(abs_expires_at);
+
+-- ---------------------------------------------------------------- subjects --
+
+CREATE TABLE systems (
+ id TEXT PRIMARY KEY,
+ pk_system_uuid TEXT NOT NULL UNIQUE,
+ pk_system_hid TEXT NOT NULL,
+ claimed_at INTEGER,
+ unclaimed_at INTEGER,
+ created_at INTEGER NOT NULL
+) STRICT;
+
+CREATE INDEX idx_systems_hid ON systems(pk_system_hid);
+
+-- Rows are created lazily: only members we hold local data about (a slug, a
+-- theme, socials) need one.
+CREATE TABLE members (
+ id TEXT PRIMARY KEY,
+ system_id TEXT NOT NULL REFERENCES systems(id) ON DELETE CASCADE,
+ pk_member_uuid TEXT NOT NULL UNIQUE,
+ pk_member_hid TEXT NOT NULL,
+ first_seen_at INTEGER NOT NULL
+) STRICT;
+
+CREATE INDEX idx_members_system ON members(system_id);
+
+-- Authorization is expressed as grants over a subject rather than a column on
+-- systems. MVP only ever writes subject_type='system', but member-level
+-- principals (decision 9) can be added later by writing 'member' rows — no
+-- schema migration, and one authorization module to update.
+CREATE TABLE grants (
+ id INTEGER PRIMARY KEY,
+ account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
+ subject_type TEXT NOT NULL CHECK (subject_type IN ('system','member')),
+ subject_id TEXT NOT NULL,
+ role TEXT NOT NULL CHECK (role IN ('owner','manager')),
+ granted_at INTEGER NOT NULL,
+ granted_by TEXT REFERENCES accounts(id),
+ UNIQUE (account_id, subject_type, subject_id)
+) STRICT;
+
+CREATE INDEX idx_grants_subject ON grants(subject_type, subject_id);
+
+-- ------------------------------------------------------------------- slugs --
+--
+-- A slug is an entity with a lifecycle, not a string column on its subject.
+-- Uniqueness is enforced here by the database, which is what makes simultaneous
+-- claims safe: a claim is a single conditional write, never read-then-write.
+--
+-- Namespaces: system slugs are global (scope_key = ''); member slugs are scoped
+-- to their system (scope_key = systems.id).
+--
+-- Reservation is subject-owned (decision 6): the reclaim right follows the
+-- system or member, not the account that happened to hold it.
+
+CREATE TABLE slugs (
+ id INTEGER PRIMARY KEY,
+ scope TEXT NOT NULL CHECK (scope IN ('system','member')),
+ scope_key TEXT NOT NULL,
+ slug_normalized TEXT NOT NULL,
+ slug_display TEXT NOT NULL,
+
+ state TEXT NOT NULL CHECK (state IN ('active','reserved')),
+ subject_id TEXT,
+
+ reserved_principal_type TEXT CHECK (reserved_principal_type IN ('system','member')),
+ reserved_principal_id TEXT,
+ reserved_until INTEGER,
+
+ claimed_at INTEGER,
+ released_at INTEGER,
+
+ UNIQUE (scope, scope_key, slug_normalized),
+
+ -- State consistency is a constraint, not a convention: an 'active' row with a
+ -- reservation, or a 'reserved' row with no expiry, cannot be written at all.
+ CHECK (
+ (state = 'active'
+ AND subject_id IS NOT NULL
+ AND reserved_until IS NULL
+ AND reserved_principal_type IS NULL
+ AND reserved_principal_id IS NULL)
+ OR
+ (state = 'reserved'
+ AND subject_id IS NULL
+ AND reserved_until IS NOT NULL
+ AND reserved_principal_type IS NOT NULL
+ AND reserved_principal_id IS NOT NULL)
+ )
+) STRICT;
+
+CREATE INDEX idx_slugs_subject ON slugs(scope, subject_id);
+CREATE INDEX idx_slugs_reserved ON slugs(state, reserved_until);
+
+CREATE TABLE slug_history (
+ id INTEGER PRIMARY KEY,
+ slug_id INTEGER NOT NULL REFERENCES slugs(id) ON DELETE CASCADE,
+ event TEXT NOT NULL CHECK (event IN ('claimed','released','reclaimed','expired','transferred')),
+ subject_id TEXT,
+ account_id TEXT,
+ at INTEGER NOT NULL
+) STRICT;
+
+CREATE INDEX idx_slug_history_slug ON slug_history(slug_id, at);
+
+-- ------------------------------------------------------------ presentation --
+--
+-- Tokens are a sparse JSON blob validated in application code. They are always
+-- read as a complete set and never queried by individual key, so a key/value
+-- table would add joins on every page render and buy nothing.
+--
+-- css_source / css_compiled are unused in MVP (custom CSS is v1.1, decision 12)
+-- but the columns exist so adding it later is not a schema change.
+
+CREATE TABLE themes (
+ owner_type TEXT NOT NULL CHECK (owner_type IN ('system','member')),
+ owner_id TEXT NOT NULL,
+ schema_version INTEGER NOT NULL,
+ tokens TEXT NOT NULL DEFAULT '{}',
+ css_source TEXT,
+ css_compiled TEXT,
+ css_hash TEXT,
+ css_errors TEXT,
+ updated_at INTEGER NOT NULL,
+ updated_by TEXT REFERENCES accounts(id),
+ deleted_at INTEGER,
+ PRIMARY KEY (owner_type, owner_id)
+) STRICT;
+
+CREATE TABLE social_links (
+ id INTEGER PRIMARY KEY,
+ owner_type TEXT NOT NULL CHECK (owner_type IN ('system','member')),
+ owner_id TEXT NOT NULL,
+ platform TEXT NOT NULL,
+ label TEXT,
+ url TEXT NOT NULL,
+ visible INTEGER NOT NULL DEFAULT 1,
+ sort_order INTEGER NOT NULL DEFAULT 0
+) STRICT;
+
+CREATE INDEX idx_socials_owner ON social_links(owner_type, owner_id, sort_order);
+
+-- ------------------------------------------------------------- PK snapshots --
+--
+-- auth_scope sits in the primary key deliberately. It is the structural reason
+-- an authenticated PluralKit response can never be served to a public visitor —
+-- a code convention someone can forget would not be good enough.
+-- 'public' = fetched with no credential
+-- <acct id> = fetched with that account's explicitly provided credential
+
+CREATE TABLE pk_snapshots (
+ ref_type TEXT NOT NULL CHECK (ref_type IN ('system','members','member','fronters')),
+ ref_key TEXT NOT NULL,
+ auth_scope TEXT NOT NULL DEFAULT 'public',
+ payload TEXT NOT NULL,
+ fetched_at INTEGER NOT NULL,
+ etag TEXT,
+ PRIMARY KEY (ref_type, ref_key, auth_scope)
+) STRICT;
+
+CREATE INDEX idx_pk_snapshots_fetched ON pk_snapshots(fetched_at);
+
+-- ------------------------------------------------------------------- audit --
+
+CREATE TABLE audit_events (
+ id INTEGER PRIMARY KEY,
+ at INTEGER NOT NULL,
+ account_id TEXT,
+ action TEXT NOT NULL,
+ target TEXT,
+ detail TEXT
+) STRICT;
+
+CREATE INDEX idx_audit_at ON audit_events(at);
+CREATE INDEX idx_audit_account ON audit_events(account_id, at);
diff --git a/apps/api/src/db/migrations/002_claims.sql b/apps/api/src/db/migrations/002_claims.sql
new file mode 100644
index 0000000..faefe4a
--- /dev/null
+++ b/apps/api/src/db/migrations/002_claims.sql
@@ -0,0 +1,35 @@
+-- System claiming.
+--
+-- Claiming a system on pkviewer is NOT ownership of the underlying PluralKit
+-- system. It grants control of how that system is presented here, nothing more.
+
+CREATE TABLE claim_challenges (
+ id TEXT PRIMARY KEY,
+ account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
+ pk_system_uuid TEXT NOT NULL,
+ pk_system_hid TEXT NOT NULL,
+ -- Published by the user into their own system description, so this is a
+ -- proof token rather than a secret. It is still single-use and expiring.
+ nonce TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ consumed_at INTEGER,
+ UNIQUE (account_id, pk_system_uuid)
+) STRICT;
+
+CREATE INDEX idx_claim_challenges_expiry ON claim_challenges(expires_at);
+
+-- At most one owner per subject, enforced by the database.
+--
+-- Decision 7 blocks a contested takeover automatically. Doing that with a
+-- SELECT-then-INSERT would leave a race between two simultaneous claimants;
+-- this index removes the race entirely, exactly as the slug UNIQUE does.
+CREATE UNIQUE INDEX idx_grants_single_owner
+ ON grants (subject_type, subject_id) WHERE role = 'owner';
+
+-- How ownership was proven, and when. Re-verification flags a stale claim for
+-- review; it never auto-revokes, because a PluralKit API hiccup must not cost
+-- someone their system.
+ALTER TABLE grants ADD COLUMN verification_method TEXT;
+ALTER TABLE grants ADD COLUMN verified_at INTEGER;
diff --git a/apps/api/src/db/migrations/003_composition.sql b/apps/api/src/db/migrations/003_composition.sql
new file mode 100644
index 0000000..902de12
--- /dev/null
+++ b/apps/api/src/db/migrations/003_composition.sql
@@ -0,0 +1,8 @@
+-- Composition configuration.
+--
+-- Stored alongside theme tokens but kept a SEPARATE column, because it is a
+-- separate vocabulary: composition changes what appears and how it is arranged,
+-- theme changes how it looks. Merging them into one blob would be the first
+-- step towards the two becoming one confused thing (T1).
+
+ALTER TABLE themes ADD COLUMN composition TEXT NOT NULL DEFAULT '{}';
diff --git a/apps/api/src/db/migrations/004_account_deletion.sql b/apps/api/src/db/migrations/004_account_deletion.sql
new file mode 100644
index 0000000..fbbb1fc
--- /dev/null
+++ b/apps/api/src/db/migrations/004_account_deletion.sql
@@ -0,0 +1,64 @@
+-- Make account deletion possible.
+--
+-- `grants.granted_by` and `themes.updated_by` are audit breadcrumbs: they record
+-- who did something, and are not ownership. They were declared as plain
+-- references with no ON DELETE rule, which defaults to RESTRICT — so deleting an
+-- account that had ever granted a role or saved a theme failed with a foreign
+-- key error, and account deletion is a stated requirement.
+--
+-- SQLite cannot alter a constraint, so both tables are rebuilt. Nothing
+-- references either table, so no dependent rows are disturbed.
+
+CREATE TABLE grants_new (
+ id INTEGER PRIMARY KEY,
+ account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
+ subject_type TEXT NOT NULL CHECK (subject_type IN ('system','member')),
+ subject_id TEXT NOT NULL,
+ role TEXT NOT NULL CHECK (role IN ('owner','manager')),
+ granted_at INTEGER NOT NULL,
+ -- The breadcrumb survives as NULL rather than blocking the delete.
+ granted_by TEXT REFERENCES accounts(id) ON DELETE SET NULL,
+ verification_method TEXT,
+ verified_at INTEGER,
+ UNIQUE (account_id, subject_type, subject_id)
+) STRICT;
+
+INSERT INTO grants_new
+ (id, account_id, subject_type, subject_id, role, granted_at, granted_by, verification_method, verified_at)
+SELECT id, account_id, subject_type, subject_id, role, granted_at, granted_by, verification_method, verified_at
+ FROM grants;
+
+DROP TABLE grants;
+ALTER TABLE grants_new RENAME TO grants;
+
+CREATE INDEX idx_grants_subject ON grants(subject_type, subject_id);
+
+-- At most one owner per subject. Rebuilt with the table it guards.
+CREATE UNIQUE INDEX idx_grants_single_owner
+ ON grants (subject_type, subject_id) WHERE role = 'owner';
+
+CREATE TABLE themes_new (
+ owner_type TEXT NOT NULL CHECK (owner_type IN ('system','member')),
+ owner_id TEXT NOT NULL,
+ schema_version INTEGER NOT NULL,
+ tokens TEXT NOT NULL DEFAULT '{}',
+ composition TEXT NOT NULL DEFAULT '{}',
+ css_source TEXT,
+ css_compiled TEXT,
+ css_hash TEXT,
+ css_errors TEXT,
+ updated_at INTEGER NOT NULL,
+ updated_by TEXT REFERENCES accounts(id) ON DELETE SET NULL,
+ deleted_at INTEGER,
+ PRIMARY KEY (owner_type, owner_id)
+) STRICT;
+
+INSERT INTO themes_new
+ (owner_type, owner_id, schema_version, tokens, composition,
+ css_source, css_compiled, css_hash, css_errors, updated_at, updated_by, deleted_at)
+SELECT owner_type, owner_id, schema_version, tokens, composition,
+ css_source, css_compiled, css_hash, css_errors, updated_at, updated_by, deleted_at
+ FROM themes;
+
+DROP TABLE themes;
+ALTER TABLE themes_new RENAME TO themes;
diff --git a/apps/api/src/http/cookies.ts b/apps/api/src/http/cookies.ts
new file mode 100644
index 0000000..3b0a83a
--- /dev/null
+++ b/apps/api/src/http/cookies.ts
@@ -0,0 +1,60 @@
+import type { Context } from "hono";
+
+/**
+ * Cookie names carry the __Host- prefix, which is load-bearing rather than
+ * decorative.
+ *
+ * __Host- forbids a Domain attribute, so the cookie is pinned to exactly one
+ * host and cannot be sent to — or set from — a sibling subdomain. That is what
+ * makes it safe to serve user-authored presentation from a sibling origin: the
+ * session cookie provably cannot reach it, and a cookie set over there cannot
+ * shadow this one.
+ *
+ * Browsers treat localhost as a trustworthy origin, so the required Secure
+ * attribute does not break local development.
+ */
+export const SESSION_COOKIE = "__Host-pkv_session";
+export const OAUTH_COOKIE = "__Host-pkv_oauth";
+
+/** The OAuth handshake cookie is short-lived: it only spans the redirect. */
+export const OAUTH_COOKIE_MAX_AGE_S = 10 * 60;
+
+type CookieOptions = {
+ maxAgeSeconds?: number;
+ sameSite?: "Lax" | "Strict";
+};
+
+function serialize(name: string, value: string, opts: CookieOptions = {}): string {
+ const parts = [
+ `${name}=${value}`,
+ "Path=/",
+ "HttpOnly",
+ "Secure",
+ `SameSite=${opts.sameSite ?? "Lax"}`,
+ ];
+ if (opts.maxAgeSeconds !== undefined) parts.push(`Max-Age=${opts.maxAgeSeconds}`);
+ // No Domain attribute, ever: __Host- forbids it, and it is the attribute that
+ // would let this cookie leak across subdomains.
+ return parts.join("; ");
+}
+
+export function setCookie(c: Context, name: string, value: string, opts?: CookieOptions): void {
+ c.header("Set-Cookie", serialize(name, value, opts), { append: true });
+}
+
+export function clearCookie(c: Context, name: string): void {
+ c.header("Set-Cookie", `${name}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`, {
+ append: true,
+ });
+}
+
+export function readCookie(c: Context, name: string): string | null {
+ const header = c.req.header("cookie");
+ if (!header) return null;
+ for (const part of header.split(";")) {
+ const eq = part.indexOf("=");
+ if (eq === -1) continue;
+ if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
+ }
+ return null;
+}
diff --git a/apps/api/src/http/middleware.ts b/apps/api/src/http/middleware.ts
new file mode 100644
index 0000000..5a59c63
--- /dev/null
+++ b/apps/api/src/http/middleware.ts
@@ -0,0 +1,54 @@
+import type { MiddlewareHandler } from "hono";
+import type { Config } from "../config/index.ts";
+
+/**
+ * Keeps the beta deployment out of search indexes.
+ *
+ * Two reasons, and the second is the one that is easy to forget: testers' pages
+ * would be indexed before they intended, which is a privacy problem on a
+ * privacy-first platform; and the eventual domain move would leave stale
+ * results pointing at a host that no longer serves the site.
+ */
+export function betaNoIndex(cfg: Config): MiddlewareHandler {
+ return async (c, next) => {
+ await next();
+ if (cfg.beta.enabled) {
+ c.header("X-Robots-Tag", "noindex, nofollow");
+ }
+ };
+}
+
+export function securityHeaders(): MiddlewareHandler {
+ return async (c, next) => {
+ await next();
+ c.header("X-Content-Type-Options", "nosniff");
+ c.header("Referrer-Policy", "strict-origin-when-cross-origin");
+ c.header("X-Frame-Options", "DENY");
+ };
+}
+
+const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
+
+/**
+ * CSRF defence: every state-changing request must carry an Origin we recognise.
+ *
+ * An Origin check is the primary defence rather than a synchronised token
+ * because it has no plumbing and no failure mode where a stale token locks a
+ * user out. Requests with no Origin header at all are rejected on mutating
+ * methods; browsers always send one for cross-origin state changes.
+ */
+export function requireKnownOrigin(cfg: Config): MiddlewareHandler {
+ const allowed = new Set([cfg.appOrigin, cfg.internalApiOrigin]);
+ return async (c, next) => {
+ if (SAFE_METHODS.has(c.req.method)) return next();
+
+ const origin = c.req.header("origin");
+ if (!origin || !allowed.has(origin)) {
+ return c.json(
+ { error: "forbidden", detail: "missing or unrecognised Origin on a state-changing request" },
+ 403,
+ );
+ }
+ return next();
+ };
+}
diff --git a/apps/api/src/http/routes/auth.ts b/apps/api/src/http/routes/auth.ts
new file mode 100644
index 0000000..6278a4c
--- /dev/null
+++ b/apps/api/src/http/routes/auth.ts
@@ -0,0 +1,235 @@
+import { Hono } from "hono";
+import type { Context } from "hono";
+import type { Config } from "../../config/index.ts";
+import {
+ createPkcePair,
+ hashMeta,
+ randomToken,
+ safeEqual,
+ signedValue,
+ verifySignedValue,
+} from "../../auth/crypto.ts";
+import {
+ buildAuthorizeUrl,
+ DiscordAuthError,
+ DiscordClient,
+ pickRedirectUri,
+} from "../../auth/discord.ts";
+import {
+ createSession,
+ discordIdsForAccount,
+ resolveSession,
+ revokeAllSessionsForAccount,
+ revokeSession,
+ upsertAccountForDiscord,
+} from "../../auth/sessions.ts";
+import type { Db } from "../../db/index.ts";
+import { clearCookie, OAUTH_COOKIE, OAUTH_COOKIE_MAX_AGE_S, readCookie, SESSION_COOKIE, setCookie } from "../cookies.ts";
+
+type Deps = {
+ cfg: Config;
+ db: Db;
+ discord: DiscordClient;
+ now?: () => number;
+};
+
+type HandshakePayload = {
+ state: string;
+ verifier: string;
+ redirectUri: string;
+ returnTo: string;
+ createdAt: number;
+};
+
+/**
+ * Only same-origin paths are accepted as a post-login destination, so the login
+ * flow cannot be used as an open redirect.
+ *
+ * The default is the control plane, not "/". Someone who has just signed in
+ * wants the thing they signed in for; landing them on the public front page
+ * meant finding /manage by hand.
+ */
+export function safeReturnTo(raw: string | undefined): string {
+ if (!raw) return "/manage";
+ if (!raw.startsWith("/") || raw.startsWith("//")) return "/manage";
+ return raw;
+}
+
+export function authRoutes(deps: Deps): Hono {
+ const { cfg, db, discord } = deps;
+ const now = deps.now ?? (() => Date.now());
+ const app = new Hono();
+
+ /**
+ * Starts the OAuth handshake.
+ *
+ * The state and PKCE verifier are held in a signed, short-lived __Host-
+ * cookie and validated on return. State alone would not prevent login CSRF
+ * (an attacker can complete their own handshake and graft the result onto a
+ * victim's browser), so both halves are required.
+ */
+ app.get("/discord/start", (c) => {
+ if (!cfg.discord.clientId || !cfg.discord.clientSecret) {
+ return c.json({ error: "discord_not_configured" }, 503);
+ }
+ const redirectUri = pickRedirectUri(cfg.discord.redirectUris, cfg.appOrigin);
+ if (!redirectUri) return c.json({ error: "no_redirect_uri_configured" }, 503);
+
+ const state = randomToken(24);
+ const { verifier, challenge } = createPkcePair();
+ const payload: HandshakePayload = {
+ state,
+ verifier,
+ redirectUri,
+ returnTo: safeReturnTo(c.req.query("return_to")),
+ createdAt: now(),
+ };
+
+ setCookie(c, OAUTH_COOKIE, signedValue(cfg.sessionSecret, JSON.stringify(payload)), {
+ maxAgeSeconds: OAUTH_COOKIE_MAX_AGE_S,
+ sameSite: "Lax",
+ });
+
+ return c.redirect(
+ buildAuthorizeUrl({
+ clientId: cfg.discord.clientId,
+ redirectUri,
+ state,
+ codeChallenge: challenge,
+ }),
+ 302,
+ );
+ });
+
+ app.get("/discord/callback", async (c) => {
+ const cookie = readCookie(c, OAUTH_COOKIE);
+ clearCookie(c, OAUTH_COOKIE); // Single use, whatever the outcome.
+
+ if (!cookie) return fail(c, cfg, "missing_handshake");
+
+ const raw = verifySignedValue(cfg.sessionSecret, cookie);
+ if (!raw) return fail(c, cfg, "invalid_handshake");
+
+ let payload: HandshakePayload;
+ try {
+ payload = JSON.parse(raw) as HandshakePayload;
+ } catch {
+ return fail(c, cfg, "invalid_handshake");
+ }
+
+ if (now() - payload.createdAt > OAUTH_COOKIE_MAX_AGE_S * 1000) {
+ return fail(c, cfg, "handshake_expired");
+ }
+
+ const returnedState = c.req.query("state");
+ if (!returnedState || !safeEqual(returnedState, payload.state)) {
+ return fail(c, cfg, "state_mismatch");
+ }
+
+ if (c.req.query("error")) return fail(c, cfg, "discord_denied");
+
+ const code = c.req.query("code");
+ if (!code) return fail(c, cfg, "missing_code");
+
+ let profile;
+ try {
+ // The access token lives only for these two statements and is never
+ // stored, logged, or returned.
+ const accessToken = await discord.exchangeCode({
+ code,
+ redirectUri: payload.redirectUri,
+ codeVerifier: payload.verifier,
+ });
+ profile = await discord.fetchProfile(accessToken);
+ } catch (err) {
+ if (err instanceof DiscordAuthError) return fail(c, cfg, "discord_error");
+ throw err;
+ }
+
+ const t = now();
+ // SIGNUP_ENABLED gates creating a NEW account. Existing accounts can always
+ // sign in, so turning signup off never locks current testers out.
+ const result = upsertAccountForDiscord(db, profile, t, {
+ allowCreate: cfg.beta.signupEnabled,
+ });
+
+ if (!result.account) return fail(c, cfg, "signup_disabled");
+
+ const session = createSession(db, result.account.id, t, {
+ uaHash: hashMeta(c.req.header("user-agent"), cfg.sessionSecret),
+ ipHash: hashMeta(
+ c.req.header("x-forwarded-for")?.split(",")[0]?.trim(),
+ cfg.sessionSecret,
+ ),
+ });
+
+ setCookie(c, SESSION_COOKIE, session.token, {
+ maxAgeSeconds: Math.floor((session.absoluteExpiresAt - t) / 1000),
+ sameSite: "Lax",
+ });
+
+ db.query(
+ "INSERT INTO audit_events (at, account_id, action, target, detail) VALUES (?,?,?,?,?)",
+ ).run(t, result.account.id, result.created ? "account.created" : "account.login", null, null);
+
+ return c.redirect(`${cfg.appOrigin}${payload.returnTo}`, 302);
+ });
+
+ /** Current account. Never includes the Discord identity unless asked for by
+ * management UI, and never exposes it publicly. */
+ app.get("/me", (c) => {
+ const token = readCookie(c, SESSION_COOKIE);
+ if (!token) return c.json({ authenticated: false }, 200);
+
+ const session = resolveSession(db, token, now());
+ if (!session) {
+ clearCookie(c, SESSION_COOKIE);
+ return c.json({ authenticated: false }, 200);
+ }
+
+ return c.json({
+ authenticated: true,
+ accountId: session.accountId,
+ discordIds: discordIdsForAccount(db, session.accountId),
+ canClaim: canClaim(cfg, discordIdsForAccount(db, session.accountId)),
+ });
+ });
+
+ app.post("/logout", (c) => {
+ const token = readCookie(c, SESSION_COOKIE);
+ if (token) revokeSession(db, token, now());
+ clearCookie(c, SESSION_COOKIE);
+ return c.json({ ok: true });
+ });
+
+ app.post("/logout-all", (c) => {
+ const token = readCookie(c, SESSION_COOKIE);
+ const session = token ? resolveSession(db, token, now()) : null;
+ if (!session) return c.json({ error: "unauthenticated" }, 401);
+ const count = revokeAllSessionsForAccount(db, session.accountId, now());
+ clearCookie(c, SESSION_COOKIE);
+ return c.json({ ok: true, revoked: count });
+ });
+
+ return app;
+}
+
+/**
+ * Beta claiming gate.
+ *
+ * Public viewing is never gated — that is the point of the platform. Claiming a
+ * system on infrastructure still being reshaped weekly is gated to an
+ * allow-list of Discord ids.
+ */
+export function canClaim(cfg: Config, discordIds: readonly string[]): boolean {
+ if (!cfg.beta.enabled) return true;
+ if (cfg.beta.allowedDiscordIds.size === 0) return false;
+ return discordIds.some((id) => cfg.beta.allowedDiscordIds.has(id));
+}
+
+/** Failures return the user to a single login page with a coarse reason code.
+ * The codes are deliberately non-specific: they tell the user what to do, not
+ * an attacker which half of the handshake failed. */
+function fail(c: Context, cfg: Config, reason: string) {
+ return c.redirect(`${cfg.appOrigin}/login?error=${encodeURIComponent(reason)}`, 302);
+}
diff --git a/apps/api/src/http/routes/claims.ts b/apps/api/src/http/routes/claims.ts
new file mode 100644
index 0000000..8db4b3a
--- /dev/null
+++ b/apps/api/src/http/routes/claims.ts
@@ -0,0 +1,205 @@
+import { Hono } from "hono";
+import type { Context } from "hono";
+import { discordIdsForAccount, resolveSession } from "../../auth/sessions.ts";
+import {
+ claimViaDiscordLink,
+ claimViaToken,
+ createDescriptionChallenge,
+ discoverLinkedSystems,
+ systemsForAccount,
+ unclaimSystem,
+ verifyDescriptionChallenge,
+} from "../../claims/index.ts";
+import type { Config } from "../../config/index.ts";
+import type { Db } from "../../db/index.ts";
+import type { PkClient } from "../../pk/client.ts";
+import { readCookie, SESSION_COOKIE } from "../cookies.ts";
+import { canClaim } from "./auth.ts";
+
+type Deps = { cfg: Config; db: Db; pk: PkClient; now?: () => number };
+
+type Caller = { accountId: string; discordIds: string[] };
+
+function caller(c: Context, db: Db, now: number): Caller | null {
+ const token = readCookie(c, SESSION_COOKIE);
+ if (!token) return null;
+ const session = resolveSession(db, token, now);
+ if (!session) return null;
+ return { accountId: session.accountId, discordIds: discordIdsForAccount(db, session.accountId) };
+}
+
+/**
+ * Claim-flow endpoints.
+ *
+ * Every route requires a session. Claiming is additionally gated during beta by
+ * an allow-list of Discord ids — public viewing never is.
+ */
+export function claimRoutes(deps: Deps): Hono {
+ const { cfg, db, pk } = deps;
+ const now = deps.now ?? (() => Date.now());
+ const app = new Hono();
+ const claimDeps = { db, pk, now };
+
+ const requireClaimant = (c: Context): Caller | Response => {
+ const who = caller(c, db, now());
+ if (!who) return c.json({ error: "unauthenticated" }, 401);
+ if (!canClaim(cfg, who.discordIds)) {
+ return c.json(
+ { error: "beta_not_allowed", detail: "claiming is limited during the beta" },
+ 403,
+ );
+ }
+ return who;
+ };
+
+ /** Systems this account manages. */
+ app.get("/mine", (c) => {
+ const who = caller(c, db, now());
+ if (!who) return c.json({ error: "unauthenticated" }, 401);
+ return c.json({ systems: systemsForAccount(db, who.accountId) });
+ });
+
+ /**
+ * Tier 1 discovery: systems linked to this account's verified Discord ids.
+ *
+ * The ids come from the session, never from the request body, so a caller
+ * cannot probe arbitrary Discord accounts through us.
+ */
+ app.post("/discover", async (c) => {
+ const who = requireClaimant(c);
+ if (who instanceof Response) return who;
+
+ const systems = await discoverLinkedSystems(claimDeps, who.discordIds);
+ return c.json({
+ systems: systems.map((s) => ({ hid: s.id, uuid: s.uuid, name: s.name })),
+ });
+ });
+
+ app.post("/discord-link", async (c) => {
+ const who = requireClaimant(c);
+ if (who instanceof Response) return who;
+
+ const body = await c.req.json().catch(() => null);
+ const ref = typeof body?.systemRef === "string" ? body.systemRef : null;
+ if (!ref) return c.json({ error: "bad_request" }, 400);
+
+ const result = await claimViaDiscordLink(claimDeps, {
+ accountId: who.accountId,
+ discordIds: who.discordIds,
+ pkSystemRef: ref,
+ });
+ return claimResponse(c, result);
+ });
+
+ app.post("/challenge", async (c) => {
+ const who = requireClaimant(c);
+ if (who instanceof Response) return who;
+
+ const body = await c.req.json().catch(() => null);
+ const ref = typeof body?.systemRef === "string" ? body.systemRef : null;
+ if (!ref) return c.json({ error: "bad_request" }, 400);
+
+ const result = await createDescriptionChallenge(claimDeps, {
+ accountId: who.accountId,
+ pkSystemRef: ref,
+ });
+ if (!result.ok) return c.json({ error: result.reason }, statusFor(result.reason));
+
+ return c.json({
+ challengeId: result.challenge.id,
+ nonce: result.challenge.nonce,
+ systemHid: result.challenge.pkSystemHid,
+ expiresAt: result.challenge.expiresAt,
+ });
+ });
+
+ app.post("/challenge/verify", async (c) => {
+ const who = requireClaimant(c);
+ if (who instanceof Response) return who;
+
+ const body = await c.req.json().catch(() => null);
+ const id = typeof body?.challengeId === "string" ? body.challengeId : null;
+ if (!id) return c.json({ error: "bad_request" }, 400);
+
+ const result = await verifyDescriptionChallenge(claimDeps, {
+ accountId: who.accountId,
+ challengeId: id,
+ });
+ return claimResponse(c, result);
+ });
+
+ /**
+ * Tier 3. The token arrives in a POST body, never a URL, and is discarded
+ * inside the handler. Nothing here logs the request body.
+ */
+ app.post("/token", async (c) => {
+ const who = requireClaimant(c);
+ if (who instanceof Response) return who;
+
+ const body = await c.req.json().catch(() => null);
+ const ref = typeof body?.systemRef === "string" ? body.systemRef : null;
+ const token = typeof body?.token === "string" ? body.token : null;
+ if (!ref || !token) return c.json({ error: "bad_request" }, 400);
+
+ const result = await claimViaToken(claimDeps, {
+ accountId: who.accountId,
+ pkSystemRef: ref,
+ token,
+ });
+ return claimResponse(c, result);
+ });
+
+ app.post("/unclaim", async (c) => {
+ const who = caller(c, db, now());
+ if (!who) return c.json({ error: "unauthenticated" }, 401);
+
+ const body = await c.req.json().catch(() => null);
+ const systemId = typeof body?.systemId === "string" ? body.systemId : null;
+ const confirm = body?.confirm === true;
+ if (!systemId) return c.json({ error: "bad_request" }, 400);
+ // Unclaiming is destructive from the user's point of view; the client must
+ // say so explicitly rather than a stray request doing it.
+ if (!confirm) return c.json({ error: "confirmation_required" }, 400);
+
+ const result = unclaimSystem(claimDeps, { accountId: who.accountId, systemId });
+ if (!result.ok) {
+ return c.json({ error: result.reason }, result.reason === "not_owner" ? 403 : 404);
+ }
+ return c.json({ ok: true, slugsReleased: result.slugsReleased });
+ });
+
+ return app;
+}
+
+function statusFor(reason: string): 400 | 403 | 404 | 409 | 502 {
+ switch (reason) {
+ case "not_found":
+ case "challenge_not_found":
+ return 404;
+ case "already_claimed":
+ return 409;
+ case "beta_not_allowed":
+ return 403;
+ case "upstream_unavailable":
+ return 502;
+ default:
+ return 400;
+ }
+}
+
+function claimResponse(
+ c: Context,
+ result: { ok: true; systemId: string; pkSystemHid: string; method: string; restored: boolean } | { ok: false; reason: string },
+) {
+ if (result.ok) {
+ return c.json({
+ ok: true,
+ systemId: result.systemId,
+ systemHid: result.pkSystemHid,
+ method: result.method,
+ restored: result.restored,
+ });
+ }
+ // "already_claimed" deliberately carries no information about who holds it.
+ return c.json({ error: result.reason }, statusFor(result.reason));
+}
diff --git a/apps/api/src/http/routes/manage.ts b/apps/api/src/http/routes/manage.ts
new file mode 100644
index 0000000..b87677f
--- /dev/null
+++ b/apps/api/src/http/routes/manage.ts
@@ -0,0 +1,256 @@
+import { Hono } from "hono";
+import type { Context } from "hono";
+import { resolveSession } from "../../auth/sessions.ts";
+import type { Config } from "../../config/index.ts";
+import type { Db } from "../../db/index.ts";
+import {
+ authorizeSystem,
+ ensureMemberRow,
+ listManagedMembers,
+ listManagedSystems,
+ listSocialLinks,
+ readTheme,
+ saveSocialLinks,
+ saveTheme,
+ type SystemRow,
+} from "../../manage/index.ts";
+import type { PkClient } from "../../pk/client.ts";
+import { PkError } from "../../pk/errors.ts";
+import { activeSlugFor } from "../../slugs/claim.ts";
+import { readCookie, SESSION_COOKIE } from "../cookies.ts";
+
+type Deps = { cfg: Config; db: Db; pk: PkClient; now?: () => number };
+
+/**
+ * The management API.
+ *
+ * Every route requires a session, and every system-scoped route re-checks the
+ * grant. Authorization is never inferred from a path the client chose: the
+ * client can ask about any system id it likes and will be told 404 for every
+ * one it does not manage.
+ */
+export function manageRoutes(deps: Deps): Hono {
+ const { db, pk } = deps;
+ const now = deps.now ?? (() => Date.now());
+ const app = new Hono();
+ const manageDeps = { db, pk, now };
+
+ const account = (c: Context): string | null => {
+ const token = readCookie(c, SESSION_COOKIE);
+ if (!token) return null;
+ return resolveSession(db, token, now())?.accountId ?? null;
+ };
+
+ /**
+ * Resolves the system for a request, or the response to send instead.
+ *
+ * A system the caller cannot manage is reported as 404, not 403: 403 would
+ * confirm the system exists on pkviewer, which is not something an
+ * unauthorised caller should be able to probe for.
+ */
+ const withSystem = (
+ c: Context,
+ ): { accountId: string; system: SystemRow } | Response => {
+ const accountId = account(c);
+ if (!accountId) return c.json({ error: "unauthenticated" }, 401);
+ const system = authorizeSystem(db, accountId, c.req.param("systemId") ?? "");
+ if (!system) return c.json({ error: "not_found" }, 404);
+ return { accountId, system };
+ };
+
+ app.get("/systems", async (c) => {
+ const accountId = account(c);
+ if (!accountId) return c.json({ error: "unauthenticated" }, 401);
+ return c.json({ systems: await listManagedSystems(manageDeps, accountId) });
+ });
+
+ app.get("/systems/:systemId", async (c) => {
+ const ctx = withSystem(c);
+ if (ctx instanceof Response) return ctx;
+ const { system } = ctx;
+
+ const slug = activeSlugFor(db, "system", system.id)?.slug_display ?? null;
+ let name: string | null = null;
+ let avatarUrl: string | null = null;
+ let description: string | null = null;
+ let memberCount: number | null = null;
+ let reachable = true;
+
+ try {
+ const pkSystem = await pk.getSystem(system.pk_system_uuid);
+ name = pkSystem.name;
+ avatarUrl = pkSystem.avatar_url;
+ description = pkSystem.description;
+ memberCount = (await pk.getMembers(system.pk_system_uuid)).length;
+ } catch (err) {
+ if (!(err instanceof PkError)) throw err;
+ reachable = false;
+ }
+
+ return c.json({
+ systemId: system.id,
+ pkSystemHid: system.pk_system_hid,
+ name,
+ avatarUrl,
+ description,
+ memberCount,
+ slug,
+ publicPath: `/s/${slug ?? system.pk_system_hid}`,
+ snapshotAgeMs: pk.snapshotAge("system", system.pk_system_uuid),
+ reachable,
+ });
+ });
+
+ // ------------------------------------------------------------------ theme
+
+ app.get("/systems/:systemId/theme", (c) => {
+ const ctx = withSystem(c);
+ if (ctx instanceof Response) return ctx;
+ const stored = readTheme(db, "system", ctx.system.id);
+ return c.json({ tokens: stored.tokens, composition: stored.composition });
+ });
+
+ app.put("/systems/:systemId/theme", async (c) => {
+ const ctx = withSystem(c);
+ if (ctx instanceof Response) return ctx;
+
+ const body = (await c.req.json().catch(() => null)) as {
+ tokens?: unknown;
+ composition?: unknown;
+ } | null;
+ if (!body) return c.json({ error: "bad_request" }, 400);
+
+ // Only the layers actually present are written, so saving appearance can
+ // never wipe directory settings, and vice versa.
+ const result = saveTheme(db, {
+ ownerType: "system",
+ ownerId: ctx.system.id,
+ accountId: ctx.accountId,
+ now: now(),
+ ...(body.tokens !== undefined ? { tokens: body.tokens } : {}),
+ ...(body.composition !== undefined ? { composition: body.composition } : {}),
+ });
+
+ // Rejected means nothing was written: the caller's existing settings stand.
+ if (!result.ok) {
+ return c.json({ ok: false, error: "validation_failed", rejected: result.rejected }, 422);
+ }
+
+ audit(db, now(), ctx.accountId, "theme.system.saved", ctx.system.id);
+ return c.json({ ok: true });
+ });
+
+ // ---------------------------------------------------------------- members
+
+ app.get("/systems/:systemId/members", async (c) => {
+ const ctx = withSystem(c);
+ if (ctx instanceof Response) return ctx;
+ const result = await listManagedMembers(manageDeps, ctx.system);
+ return c.json(result);
+ });
+
+ app.get("/systems/:systemId/members/:memberRef", async (c) => {
+ const ctx = withSystem(c);
+ if (ctx instanceof Response) return ctx;
+
+ const found = await ensureMemberRow(manageDeps, ctx.system, c.req.param("memberRef") ?? "");
+ // A member PluralKit does not return publicly is a 404 here too. Being the
+ // owner does not make a private member visible through pkviewer.
+ if (!found) return c.json({ error: "not_found" }, 404);
+
+ const stored = readTheme(db, "member", found.memberId);
+ return c.json({
+ memberId: found.memberId,
+ pkMemberHid: found.member.id,
+ name: found.member.name,
+ displayName: found.member.display_name,
+ avatarUrl: found.member.avatar_url,
+ pronouns: found.member.pronouns,
+ slug: activeSlugFor(db, "member", found.memberId)?.slug_display ?? null,
+ tokens: stored.tokens,
+ socials: listSocialLinks(db, "member", found.memberId),
+ systemTokens: readTheme(db, "system", ctx.system.id).tokens,
+ });
+ });
+
+ app.put("/systems/:systemId/members/:memberRef/theme", async (c) => {
+ const ctx = withSystem(c);
+ if (ctx instanceof Response) return ctx;
+
+ const found = await ensureMemberRow(manageDeps, ctx.system, c.req.param("memberRef") ?? "");
+ if (!found) return c.json({ error: "not_found" }, 404);
+
+ const body = (await c.req.json().catch(() => null)) as { tokens?: unknown } | null;
+ if (!body) return c.json({ error: "bad_request" }, 400);
+
+ const result = saveTheme(db, {
+ ownerType: "member",
+ ownerId: found.memberId,
+ accountId: ctx.accountId,
+ now: now(),
+ ...(body.tokens !== undefined ? { tokens: body.tokens } : {}),
+ });
+
+ if (!result.ok) {
+ return c.json({ ok: false, error: "validation_failed", rejected: result.rejected }, 422);
+ }
+
+ audit(db, now(), ctx.accountId, "theme.member.saved", found.memberId);
+ return c.json({ ok: true });
+ });
+
+ // ----------------------------------------------------------------- social
+
+ app.get("/systems/:systemId/socials", (c) => {
+ const ctx = withSystem(c);
+ if (ctx instanceof Response) return ctx;
+ return c.json({ links: listSocialLinks(db, "system", ctx.system.id) });
+ });
+
+ app.put("/systems/:systemId/socials", async (c) => {
+ const ctx = withSystem(c);
+ if (ctx instanceof Response) return ctx;
+
+ const body = (await c.req.json().catch(() => null)) as { links?: unknown } | null;
+ if (!body) return c.json({ error: "bad_request" }, 400);
+
+ const result = saveSocialLinks(db, {
+ ownerType: "system",
+ ownerId: ctx.system.id,
+ links: body.links,
+ });
+ if (!result.ok) return c.json({ error: "validation_failed", errors: result.errors }, 422);
+
+ audit(db, now(), ctx.accountId, "socials.system.saved", ctx.system.id);
+ return c.json({ ok: true, saved: result.saved });
+ });
+
+ app.put("/systems/:systemId/members/:memberRef/socials", async (c) => {
+ const ctx = withSystem(c);
+ if (ctx instanceof Response) return ctx;
+
+ const found = await ensureMemberRow(manageDeps, ctx.system, c.req.param("memberRef") ?? "");
+ if (!found) return c.json({ error: "not_found" }, 404);
+
+ const body = (await c.req.json().catch(() => null)) as { links?: unknown } | null;
+ if (!body) return c.json({ error: "bad_request" }, 400);
+
+ const result = saveSocialLinks(db, {
+ ownerType: "member",
+ ownerId: found.memberId,
+ links: body.links,
+ });
+ if (!result.ok) return c.json({ error: "validation_failed", errors: result.errors }, 422);
+
+ audit(db, now(), ctx.accountId, "socials.member.saved", found.memberId);
+ return c.json({ ok: true, saved: result.saved });
+ });
+
+ return app;
+}
+
+function audit(db: Db, at: number, accountId: string, action: string, target: string): void {
+ db.query(
+ "INSERT INTO audit_events (at, account_id, action, target, detail) VALUES (?,?,?,?,?)",
+ ).run(at, accountId, action, target, null);
+}
diff --git a/apps/api/src/http/routes/public.ts b/apps/api/src/http/routes/public.ts
new file mode 100644
index 0000000..3826e2d
--- /dev/null
+++ b/apps/api/src/http/routes/public.ts
@@ -0,0 +1,42 @@
+import { Hono } from "hono";
+import type { Config } from "../../config/index.ts";
+import type { Db } from "../../db/index.ts";
+import type { PkClient } from "../../pk/client.ts";
+import { buildMemberPage, buildSystemPage, type PageFailure } from "../../public/page-model.ts";
+
+type Deps = { cfg: Config; db: Db; pk: PkClient; now?: () => number };
+
+/**
+ * Public page models. No session is read here and none is required: public
+ * browsing never depends on an account.
+ */
+export function publicRoutes(deps: Deps): Hono {
+ const { cfg, db, pk } = deps;
+ const app = new Hono();
+ const pageDeps = { db, pk, ...(deps.now ? { now: deps.now } : {}) };
+
+ app.get("/systems/:ref", async (c) => {
+ const result = await buildSystemPage(pageDeps, c.req.param("ref"));
+ if (!result.ok) return c.json({ error: result.reason }, statusFor(result.reason));
+ return c.json({ ...result.value, beta: cfg.beta.enabled });
+ });
+
+ app.get("/systems/:ref/members/:memberRef", async (c) => {
+ const result = await buildMemberPage(
+ pageDeps,
+ c.req.param("ref"),
+ c.req.param("memberRef"),
+ );
+ if (!result.ok) return c.json({ error: result.reason }, statusFor(result.reason));
+ return c.json({ ...result.value, beta: cfg.beta.enabled });
+ });
+
+ return app;
+}
+
+function statusFor(reason: PageFailure): 404 | 502 {
+ // "unsupported_reference" is reported as 404 rather than 400: a Discord
+ // snowflake is simply not a public pkviewer identifier, and distinguishing it
+ // would confirm the shape is meaningful somewhere (S7).
+ return reason === "upstream_unavailable" ? 502 : 404;
+}
diff --git a/apps/api/src/http/routes/slugs.ts b/apps/api/src/http/routes/slugs.ts
new file mode 100644
index 0000000..234f68f
--- /dev/null
+++ b/apps/api/src/http/routes/slugs.ts
@@ -0,0 +1,256 @@
+import { Hono } from "hono";
+import type { Context } from "hono";
+import { discordIdsForAccount, resolveSession } from "../../auth/sessions.ts";
+import { accountManagesSystem } from "../../claims/index.ts";
+import type { Config } from "../../config/index.ts";
+import type { Db } from "../../db/index.ts";
+import type { PkClient } from "../../pk/client.ts";
+import { PkError } from "../../pk/errors.ts";
+import { activeSlugFor, checkSlugAvailability, claimSlug } from "../../slugs/claim.ts";
+import { RESERVATION_MS, findSlug, releaseSlug, reservationsForSubject } from "../../slugs/lifecycle.ts";
+import { SLUG_REJECTION_MESSAGES, type SlugScope } from "../../slugs/normalize.ts";
+import { readCookie, SESSION_COOKIE } from "../cookies.ts";
+
+type Deps = { cfg: Config; db: Db; pk: PkClient; now?: () => number };
+
+function accountFor(c: Context, db: Db, now: number): string | null {
+ const token = readCookie(c, SESSION_COOKIE);
+ if (!token) return null;
+ return resolveSession(db, token, now)?.accountId ?? null;
+}
+
+/**
+ * Slug management. Lives under /manage on the app origin (decision 3), never
+ * under /s/, so a member slug can never collide with an application route.
+ */
+export function slugRoutes(deps: Deps): Hono {
+ const { db, pk } = deps;
+ const now = deps.now ?? (() => Date.now());
+ const app = new Hono();
+
+ /**
+ * Resolves the caller's authority over a subject.
+ *
+ * Member slugs are authorised through the member's SYSTEM: members are not
+ * independent principals in MVP (decision 9), and the grants table already
+ * models them for when they become one.
+ */
+ const authorize = (
+ c: Context,
+ accountId: string,
+ scope: SlugScope,
+ subjectId: string,
+ ): { scopeKey: string; systemId: string } | Response => {
+ if (scope === "system") {
+ if (!accountManagesSystem(db, accountId, subjectId)) {
+ return c.json({ error: "forbidden" }, 403);
+ }
+ return { scopeKey: "", systemId: subjectId };
+ }
+ const member = db
+ .query<{ system_id: string }, [string]>("SELECT system_id FROM members WHERE id = ?")
+ .get(subjectId);
+ if (!member) return c.json({ error: "not_found" }, 404);
+ if (!accountManagesSystem(db, accountId, member.system_id)) {
+ return c.json({ error: "forbidden" }, 403);
+ }
+ return { scopeKey: member.system_id, systemId: member.system_id };
+ };
+
+ app.get("/check", (c) => {
+ const accountId = accountFor(c, db, now());
+ if (!accountId) return c.json({ error: "unauthenticated" }, 401);
+
+ const scope = c.req.query("scope") === "member" ? "member" : "system";
+ const requested = c.req.query("slug") ?? "";
+ const subjectId = c.req.query("subjectId") ?? undefined;
+
+ let scopeKey = "";
+ if (scope === "member") {
+ const systemId = c.req.query("systemId");
+ if (!systemId) return c.json({ error: "bad_request" }, 400);
+ if (!accountManagesSystem(db, accountId, systemId)) {
+ return c.json({ error: "forbidden" }, 403);
+ }
+ scopeKey = systemId;
+ }
+
+ const result = checkSlugAvailability(db, {
+ scope,
+ scopeKey,
+ ...(subjectId ? { subjectId } : {}),
+ requested,
+ now: now(),
+ });
+
+ return c.json({
+ ...result,
+ message:
+ !result.available && result.reason === "invalid"
+ ? SLUG_REJECTION_MESSAGES[result.detail]
+ : undefined,
+ });
+ });
+
+ /**
+ * Everything the address editor needs for one subject: the address in use,
+ * and any addresses still held for it after a change.
+ */
+ app.get("/status", (c) => {
+ const accountId = accountFor(c, db, now());
+ if (!accountId) return c.json({ error: "unauthenticated" }, 401);
+
+ const scope: SlugScope = c.req.query("scope") === "member" ? "member" : "system";
+ const subjectId = c.req.query("subjectId");
+ if (!subjectId) return c.json({ error: "bad_request" }, 400);
+
+ const auth = authorize(c, accountId, scope, subjectId);
+ if (auth instanceof Response) return auth;
+
+ const t = now();
+ const current = activeSlugFor(db, scope, subjectId);
+ return c.json({
+ current: current
+ ? { slug: current.slug_display, claimedAt: current.claimed_at ?? null }
+ : null,
+ reservations: reservationsForSubject(db, scope, subjectId, t),
+ reservationDays: Math.round(RESERVATION_MS / 86_400_000),
+ });
+ });
+
+ app.post("/claim", async (c) => {
+ const accountId = accountFor(c, db, now());
+ if (!accountId) return c.json({ error: "unauthenticated" }, 401);
+
+ const body = await c.req.json().catch(() => null);
+ const scope: SlugScope = body?.scope === "member" ? "member" : "system";
+ const subjectId = typeof body?.subjectId === "string" ? body.subjectId : null;
+ const requested = typeof body?.slug === "string" ? body.slug : null;
+ if (!subjectId || !requested) return c.json({ error: "bad_request" }, 400);
+
+ const auth = authorize(c, accountId, scope, subjectId);
+ if (auth instanceof Response) return auth;
+
+ // Sibling ids let us warn when a member slug shadows another member's id
+ // URL inside the same system. Advisory only, and a PluralKit hiccup must
+ // not block a slug change, so failure here is swallowed.
+ let siblingHids: string[] = [];
+ if (scope === "member") {
+ const system = db
+ .query<{ pk_system_uuid: string }, [string]>(
+ "SELECT pk_system_uuid FROM systems WHERE id = ?",
+ )
+ .get(auth.systemId);
+ const self = db
+ .query<{ pk_member_uuid: string }, [string]>(
+ "SELECT pk_member_uuid FROM members WHERE id = ?",
+ )
+ .get(subjectId);
+ if (system) {
+ try {
+ const members = await pk.getMembers(system.pk_system_uuid);
+ siblingHids = members
+ .filter((m) => m.uuid !== self?.pk_member_uuid)
+ .map((m) => m.id);
+ } catch (err) {
+ if (!(err instanceof PkError)) throw err;
+ }
+ }
+ }
+
+ const result = claimSlug(db, {
+ scope,
+ scopeKey: auth.scopeKey,
+ subjectId,
+ requested,
+ accountId,
+ now: now(),
+ siblingHids,
+ });
+
+ if (!result.ok) {
+ switch (result.kind) {
+ case "invalid":
+ return c.json(
+ { error: "invalid", detail: result.reason, message: SLUG_REJECTION_MESSAGES[result.reason] },
+ 400,
+ );
+ case "taken":
+ return c.json({ error: "taken" }, 409);
+ case "reserved":
+ // Never reveals who holds the reservation, only when it lapses.
+ return c.json({ error: "reserved", availableAt: result.until }, 409);
+ case "conflict":
+ return c.json({ error: "conflict" }, 409);
+ }
+ }
+
+ db.query(
+ "INSERT INTO audit_events (at, account_id, action, target, detail) VALUES (?,?,?,?,?)",
+ ).run(now(), accountId, `slug.${result.kind}`, subjectId, result.slug);
+
+ return c.json({
+ ok: true,
+ kind: result.kind,
+ slug: result.slug,
+ previousSlug: result.previousSlug,
+ warnings: result.warnings,
+ });
+ });
+
+ app.post("/release", async (c) => {
+ const accountId = accountFor(c, db, now());
+ if (!accountId) return c.json({ error: "unauthenticated" }, 401);
+
+ const body = await c.req.json().catch(() => null);
+ const scope: SlugScope = body?.scope === "member" ? "member" : "system";
+ const subjectId = typeof body?.subjectId === "string" ? body.subjectId : null;
+ if (!subjectId) return c.json({ error: "bad_request" }, 400);
+ if (body?.confirm !== true) return c.json({ error: "confirmation_required" }, 400);
+
+ const auth = authorize(c, accountId, scope, subjectId);
+ if (auth instanceof Response) return auth;
+
+ const current = activeSlugFor(db, scope, subjectId);
+ if (!current) return c.json({ error: "no_slug" }, 404);
+
+ const t = now();
+ if (!releaseSlug(db, current, t, accountId)) return c.json({ error: "conflict" }, 409);
+
+ db.query(
+ "INSERT INTO audit_events (at, account_id, action, target, detail) VALUES (?,?,?,?,?)",
+ ).run(t, accountId, "slug.released", subjectId, current.slug_display);
+
+ const row = findSlug(db, scope, auth.scopeKey, current.slug_normalized);
+ return c.json({
+ ok: true,
+ released: current.slug_display,
+ // The previous holder can reclaim until this moment; afterwards anyone can.
+ reservedUntil: row?.reserved_until ?? null,
+ });
+ });
+
+ app.get("/mine", (c) => {
+ const accountId = accountFor(c, db, now());
+ if (!accountId) return c.json({ error: "unauthenticated" }, 401);
+ void discordIdsForAccount(db, accountId);
+
+ const rows = db
+ .query<
+ { subject_id: string; slug_display: string; scope: string },
+ [string]
+ >(
+ `SELECT sl.subject_id AS subject_id, sl.slug_display AS slug_display, sl.scope AS scope
+ FROM slugs sl
+ JOIN grants g
+ ON g.subject_type = 'system'
+ AND (g.subject_id = sl.subject_id OR g.subject_id = sl.scope_key)
+ WHERE g.account_id = ? AND sl.state = 'active'`,
+ )
+ .all(accountId);
+
+ return c.json({ slugs: rows });
+ });
+
+ return app;
+}
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
new file mode 100644
index 0000000..c252133
--- /dev/null
+++ b/apps/api/src/index.ts
@@ -0,0 +1,93 @@
+import { Hono } from "hono";
+import { config } from "./config/index.ts";
+import { openDb } from "./db/index.ts";
+import { migrate } from "./db/migrate.ts";
+import { betaNoIndex, requireKnownOrigin, securityHeaders } from "./http/middleware.ts";
+import { authRoutes } from "./http/routes/auth.ts";
+import { claimRoutes } from "./http/routes/claims.ts";
+import { slugRoutes } from "./http/routes/slugs.ts";
+import { publicRoutes } from "./http/routes/public.ts";
+import { manageRoutes } from "./http/routes/manage.ts";
+import { DiscordClient } from "./auth/discord.ts";
+import { PkClient } from "./pk/client.ts";
+import { SqliteSnapshotStore } from "./pk/snapshots.ts";
+import { PKVIEWER_VERSION } from "./config/version.ts";
+
+/**
+ * The API tier. This process is the only one that opens the SQLite database,
+ * which is what removes write contention as a category of bug: SQLite permits
+ * one writer at a time, and here there is exactly one writer.
+ *
+ * The Next.js tier renders and never imports anything from ./db.
+ */
+
+const cfg = config();
+const db = openDb(cfg.databasePath);
+const migration = migrate(db);
+for (const name of migration.applied) console.log(`[db] applied ${name}`);
+
+const pk = new PkClient({
+ apiBase: cfg.pk.apiBase,
+ userAgent: cfg.pk.userAgent,
+ readRps: cfg.pk.readRps,
+ writeRps: cfg.pk.writeRps,
+ snapshots: new SqliteSnapshotStore(db),
+ onLog: (entry) => {
+ // Structured, and free of the Authorization header by construction.
+ console.log(JSON.stringify({ src: "pk", ...entry }));
+ },
+});
+
+export type AppEnv = { Variables: { db: typeof db; pk: PkClient } };
+
+const app = new Hono<AppEnv>();
+
+app.use("*", securityHeaders());
+app.use("*", betaNoIndex(cfg));
+app.use("*", requireKnownOrigin(cfg));
+app.use("*", async (c, next) => {
+ c.set("db", db);
+ c.set("pk", pk);
+ await next();
+});
+
+app.route(
+ "/auth",
+ authRoutes({
+ cfg,
+ db,
+ discord: new DiscordClient({
+ clientId: cfg.discord.clientId,
+ clientSecret: cfg.discord.clientSecret,
+ }),
+ }),
+);
+
+app.route("/claims", claimRoutes({ cfg, db, pk }));
+
+app.route("/manage/slugs", slugRoutes({ cfg, db, pk }));
+app.route("/manage", manageRoutes({ cfg, db, pk }));
+
+app.route("/public", publicRoutes({ cfg, db, pk }));
+
+app.get("/health", (c) =>
+ c.json({
+ ok: true,
+ version: PKVIEWER_VERSION,
+ beta: cfg.beta.enabled,
+ // Echoed so a deploy can be checked for the domain-portability rules without
+ // shell access. Never includes secrets.
+ origins: {
+ app: cfg.appOrigin,
+ userContent: cfg.userContentOrigin,
+ asset: cfg.assetOrigin,
+ },
+ pkUserAgent: cfg.pk.userAgent,
+ }),
+);
+
+console.log(`[api] pkviewer ${PKVIEWER_VERSION} on :${cfg.apiPort} (beta=${cfg.beta.enabled})`);
+console.log(`[api] pk user-agent: ${cfg.pk.userAgent}`);
+
+export default { port: cfg.apiPort, fetch: app.fetch };
+export { app, db, pk, cfg };
diff --git a/apps/api/src/manage/index.ts b/apps/api/src/manage/index.ts
new file mode 100644
index 0000000..dff1111
--- /dev/null
+++ b/apps/api/src/manage/index.ts
@@ -0,0 +1,476 @@
+import { randomUUID } from "node:crypto";
+import {
+ MAX_SOCIAL_LABEL_LENGTH,
+ MAX_SOCIAL_LINKS,
+ SOCIAL_PLATFORM_IDS,
+ sanitizeComposition,
+ sanitizeTheme,
+ validateSocialUrl,
+ type SocialUrlFailure,
+ type ValidationFailure,
+} from "@pkviewer/shared";
+import { accountManagesSystem } from "../claims/index.ts";
+import type { Db } from "../db/index.ts";
+import { writeTx } from "../db/index.ts";
+import type { PkClient } from "../pk/client.ts";
+import { PkError } from "../pk/errors.ts";
+import type { PkMember, PkSystem } from "../pk/types.ts";
+import { activeSlugFor } from "../slugs/claim.ts";
+
+/**
+ * Management-plane data access.
+ *
+ * The server stays authoritative for everything that matters: which systems an
+ * account may touch, what a valid theme is, and what inheritance means. The
+ * management client is a view over this, never a source of truth.
+ */
+
+export type ManageDeps = { db: Db; pk: PkClient; now?: () => number };
+
+export type ManagedSystem = {
+ systemId: string;
+ pkSystemHid: string;
+ role: string;
+ name: string | null;
+ avatarUrl: string | null;
+ slug: string | null;
+ /** Path on the public origin, composed at render time and never stored. */
+ publicPath: string;
+ memberCount: number | null;
+ /** Age of the PluralKit snapshot in ms, or null when never fetched. */
+ snapshotAgeMs: number | null;
+ reachable: boolean;
+};
+
+/** Systems this account may manage, enriched with public PluralKit identity. */
+export async function listManagedSystems(
+ deps: ManageDeps,
+ accountId: string,
+): Promise<ManagedSystem[]> {
+ const rows = deps.db
+ .query<
+ { subject_id: string; pk_system_hid: string; pk_system_uuid: string; role: string },
+ [string]
+ >(
+ `SELECT g.subject_id AS subject_id, s.pk_system_hid AS pk_system_hid,
+ s.pk_system_uuid AS pk_system_uuid, g.role AS role
+ FROM grants g
+ JOIN systems s ON s.id = g.subject_id
+ WHERE g.account_id = ? AND g.subject_type = 'system'
+ ORDER BY g.granted_at`,
+ )
+ .all(accountId);
+
+ const out: ManagedSystem[] = [];
+ for (const row of rows) {
+ const slug = activeSlugFor(deps.db, "system", row.subject_id)?.slug_display ?? null;
+
+ let system: PkSystem | null = null;
+ let members: PkMember[] | null = null;
+ try {
+ system = await deps.pk.getSystem(row.pk_system_uuid);
+ members = await deps.pk.getMembers(row.pk_system_uuid);
+ } catch (err) {
+ // PluralKit being unreachable must not empty the dashboard. The row still
+ // appears, marked unreachable, with whatever we already knew.
+ if (!(err instanceof PkError)) throw err;
+ }
+
+ out.push({
+ systemId: row.subject_id,
+ pkSystemHid: system?.id ?? row.pk_system_hid,
+ role: row.role,
+ name: system?.name ?? null,
+ avatarUrl: system?.avatar_url ?? null,
+ slug,
+ publicPath: `/s/${slug ?? system?.id ?? row.pk_system_hid}`,
+ memberCount: members?.length ?? null,
+ snapshotAgeMs: deps.pk.snapshotAge("system", row.pk_system_uuid),
+ reachable: system !== null,
+ });
+ }
+ return out;
+}
+
+export type SystemRow = { id: string; pk_system_uuid: string; pk_system_hid: string };
+
+/**
+ * Loads a system only if this account may manage it.
+ *
+ * Every management read and write goes through this. Authorization is a
+ * property of the request, checked server-side against the grants table; the
+ * client is never trusted to have checked it.
+ */
+export function authorizeSystem(db: Db, accountId: string, systemId: string): SystemRow | null {
+ if (!accountManagesSystem(db, accountId, systemId)) return null;
+ return (
+ db
+ .query<SystemRow, [string]>(
+ "SELECT id, pk_system_uuid, pk_system_hid FROM systems WHERE id = ?",
+ )
+ .get(systemId) ?? null
+ );
+}
+
+// ------------------------------------------------------------------- themes
+
+export type StoredTheme = { tokens: unknown; composition: unknown };
+
+export function readTheme(db: Db, ownerType: "system" | "member", ownerId: string): StoredTheme {
+ const row = db
+ .query<{ tokens: string; composition: string }, [string, string]>(
+ `SELECT tokens, composition FROM themes
+ WHERE owner_type = ? AND owner_id = ? AND deleted_at IS NULL`,
+ )
+ .get(ownerType, ownerId);
+ if (!row) return { tokens: {}, composition: {} };
+ return { tokens: safeParse(row.tokens), composition: safeParse(row.composition) };
+}
+
+function safeParse(raw: string): unknown {
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return {};
+ }
+}
+
+export type SaveThemeResult =
+ | { ok: true }
+ | { ok: false; reason: "invalid"; rejected: Array<{ key: string; reason: ValidationFailure }> };
+
+/**
+ * Writes a theme.
+ *
+ * Two properties worth stating because both are easy to get wrong:
+ *
+ * - The incoming blob replaces only the layer it names. Tokens and composition
+ * are written independently, so saving appearance can never silently wipe
+ * directory settings.
+ * - Every value is revalidated here. The client's validation is a convenience;
+ * this is the one that counts.
+ * - A save is all or nothing. If ANY value is rejected, nothing is written at
+ * all. Dropping the bad keys and saving the rest would silently discard the
+ * settings the user already had, which is a destructive save wearing the
+ * costume of a validation error.
+ */
+export function saveTheme(
+ db: Db,
+ params: {
+ ownerType: "system" | "member";
+ ownerId: string;
+ accountId: string;
+ now: number;
+ tokens?: unknown;
+ composition?: unknown;
+ },
+): SaveThemeResult {
+ const level = params.ownerType === "member" ? "member" : "system";
+ const rejected: Array<{ key: string; reason: ValidationFailure }> = [];
+
+ let tokensJson: string | undefined;
+ if (params.tokens !== undefined) {
+ const clean = sanitizeTheme(params.tokens, { level });
+ rejected.push(...clean.rejected);
+ // Resets are stored as explicit nulls: absent means inherit, null means
+ // reset to the platform default. Collapsing the two would lose the third
+ // state entirely.
+ const merged: Record<string, string | null> = { ...clean.values };
+ for (const key of clean.resets) merged[key] = null;
+ tokensJson = JSON.stringify(merged);
+ }
+
+ let compositionJson: string | undefined;
+ if (params.composition !== undefined) {
+ const clean = sanitizeComposition(params.composition, { level });
+ rejected.push(...clean.rejected);
+ const merged: Record<string, string | null> = { ...clean.values };
+ for (const key of clean.resets) merged[key] = null;
+ compositionJson = JSON.stringify(merged);
+ }
+
+ // Nothing is written unless everything validated.
+ if (rejected.length > 0) return { ok: false, reason: "invalid", rejected };
+
+ writeTx(db, (tx) => {
+ const existing = tx
+ .query<{ owner_id: string }, [string, string]>(
+ "SELECT owner_id FROM themes WHERE owner_type = ? AND owner_id = ?",
+ )
+ .get(params.ownerType, params.ownerId);
+
+ if (!existing) {
+ tx.query(
+ `INSERT INTO themes (owner_type, owner_id, schema_version, tokens, composition, updated_at, updated_by)
+ VALUES (?, ?, 1, ?, ?, ?, ?)`,
+ ).run(
+ params.ownerType,
+ params.ownerId,
+ tokensJson ?? "{}",
+ compositionJson ?? "{}",
+ params.now,
+ params.accountId,
+ );
+ return;
+ }
+
+ // Only the named layer is touched.
+ if (tokensJson !== undefined) {
+ tx.query(
+ "UPDATE themes SET tokens = ?, updated_at = ?, updated_by = ?, deleted_at = NULL WHERE owner_type = ? AND owner_id = ?",
+ ).run(tokensJson, params.now, params.accountId, params.ownerType, params.ownerId);
+ }
+ if (compositionJson !== undefined) {
+ tx.query(
+ "UPDATE themes SET composition = ?, updated_at = ?, updated_by = ?, deleted_at = NULL WHERE owner_type = ? AND owner_id = ?",
+ ).run(compositionJson, params.now, params.accountId, params.ownerType, params.ownerId);
+ }
+ });
+
+ return { ok: true };
+}
+
+// ------------------------------------------------------------------ members
+
+export type ManagedMember = {
+ memberId: string | null;
+ pkMemberHid: string;
+ pkMemberUuid: string;
+ name: string | null;
+ displayName: string | null;
+ avatarUrl: string | null;
+ pronouns: string | null;
+ slug: string | null;
+ hasThemeOverrides: boolean;
+};
+
+/**
+ * Public members of a system, for the management list.
+ *
+ * Sourced from the same public PluralKit response the public site uses, so a
+ * member PluralKit withholds is absent here too. The management UI must not
+ * become a way to confirm that a private member exists (decision 5) — being
+ * signed in as the owner does not change what the public API returns, and we do
+ * not ask for more.
+ */
+export async function listManagedMembers(
+ deps: ManageDeps,
+ system: SystemRow,
+): Promise<{ members: ManagedMember[]; reachable: boolean }> {
+ let pkMembers: PkMember[];
+ try {
+ pkMembers = await deps.pk.getMembers(system.pk_system_uuid);
+ } catch (err) {
+ if (!(err instanceof PkError)) throw err;
+ return { members: [], reachable: false };
+ }
+
+ const localRows = deps.db
+ .query<{ id: string; pk_member_uuid: string }, [string]>(
+ "SELECT id, pk_member_uuid FROM members WHERE system_id = ?",
+ )
+ .all(system.id);
+ const localByUuid = new Map(localRows.map((r) => [r.pk_member_uuid, r.id]));
+
+ const themed = new Set(
+ deps.db
+ .query<{ owner_id: string }, []>(
+ "SELECT owner_id FROM themes WHERE owner_type = 'member' AND deleted_at IS NULL AND tokens != '{}'",
+ )
+ .all()
+ .map((r) => r.owner_id),
+ );
+
+ const members = pkMembers.map((m) => {
+ const memberId = localByUuid.get(m.uuid) ?? null;
+ return {
+ memberId,
+ pkMemberHid: m.id,
+ pkMemberUuid: m.uuid,
+ name: m.name,
+ displayName: m.display_name,
+ avatarUrl: m.avatar_url,
+ pronouns: m.pronouns,
+ slug: memberId ? (activeSlugFor(deps.db, "member", memberId)?.slug_display ?? null) : null,
+ hasThemeOverrides: memberId ? themed.has(memberId) : false,
+ };
+ });
+
+ return { members, reachable: true };
+}
+
+/**
+ * Finds or creates our local row for a member.
+ *
+ * Member rows are created lazily: one exists only once there is pkviewer data
+ * to attach to it. Creating a row for every member of every system would store
+ * a copy of PluralKit's roster for no reason.
+ *
+ * The member must be publicly visible to be given a row, so this cannot be used
+ * to create records for members PluralKit withholds.
+ */
+export async function ensureMemberRow(
+ deps: ManageDeps,
+ system: SystemRow,
+ memberRef: string,
+): Promise<{ memberId: string; member: PkMember } | null> {
+ let members: PkMember[];
+ try {
+ members = await deps.pk.getMembers(system.pk_system_uuid);
+ } catch (err) {
+ if (!(err instanceof PkError)) throw err;
+ return null;
+ }
+
+ const ref = memberRef.toLowerCase();
+ const member = members.find((m) => m.id.toLowerCase() === ref || m.uuid.toLowerCase() === ref);
+ if (!member) return null;
+
+ const existing = deps.db
+ .query<{ id: string }, [string]>("SELECT id FROM members WHERE pk_member_uuid = ?")
+ .get(member.uuid);
+ if (existing) return { memberId: existing.id, member };
+
+ const id = randomUUID();
+ deps.db
+ .query(
+ "INSERT INTO members (id, system_id, pk_member_uuid, pk_member_hid, first_seen_at) VALUES (?,?,?,?,?)",
+ )
+ .run(id, system.id, member.uuid, member.id, deps.now?.() ?? Date.now());
+ return { memberId: id, member };
+}
+
+// ------------------------------------------------------------ social links
+
+export type StoredSocialLink = {
+ id: number;
+ platform: string;
+ label: string | null;
+ url: string;
+ visible: boolean;
+ sortOrder: number;
+};
+
+export function listSocialLinks(
+ db: Db,
+ ownerType: "system" | "member",
+ ownerId: string,
+): StoredSocialLink[] {
+ return db
+ .query<
+ {
+ id: number;
+ platform: string;
+ label: string | null;
+ url: string;
+ visible: number;
+ sort_order: number;
+ },
+ [string, string]
+ >(
+ `SELECT id, platform, label, url, visible, sort_order
+ FROM social_links WHERE owner_type = ? AND owner_id = ?
+ ORDER BY sort_order, id`,
+ )
+ .all(ownerType, ownerId)
+ .map((r) => ({
+ id: r.id,
+ platform: r.platform,
+ label: r.label,
+ url: r.url,
+ visible: r.visible === 1,
+ sortOrder: r.sort_order,
+ }));
+}
+
+export type SocialInput = {
+ platform: string;
+ label?: string | null;
+ url: string;
+ visible?: boolean;
+};
+
+export type SocialSaveFailure =
+ | { field: "platform"; reason: "unknown_platform" }
+ | { field: "url"; reason: SocialUrlFailure }
+ | { field: "label"; reason: "too_long" }
+ | { field: "links"; reason: "too_many" };
+
+/**
+ * Replaces an owner's social links with the given ordered list.
+ *
+ * Whole-list replacement keeps ordering trivially consistent — position in the
+ * array is the order — and makes reordering, editing and deleting one operation
+ * instead of three that can interleave badly.
+ */
+export function saveSocialLinks(
+ db: Db,
+ params: {
+ ownerType: "system" | "member";
+ ownerId: string;
+ links: unknown;
+ },
+): { ok: true; saved: number } | { ok: false; errors: Array<SocialSaveFailure & { index: number }> } {
+ if (!Array.isArray(params.links)) {
+ return { ok: false, errors: [{ index: -1, field: "links", reason: "too_many" }] };
+ }
+ if (params.links.length > MAX_SOCIAL_LINKS) {
+ return { ok: false, errors: [{ index: -1, field: "links", reason: "too_many" }] };
+ }
+
+ const errors: Array<SocialSaveFailure & { index: number }> = [];
+ const clean: Array<{ platform: string; label: string | null; url: string; visible: number }> = [];
+
+ params.links.forEach((raw, index) => {
+ const item = raw as Partial<SocialInput> | null;
+ const platform = typeof item?.platform === "string" ? item.platform : "";
+ if (!SOCIAL_PLATFORM_IDS.includes(platform)) {
+ errors.push({ index, field: "platform", reason: "unknown_platform" });
+ return;
+ }
+
+ const url = validateSocialUrl(item?.url);
+ if (!url.ok) {
+ errors.push({ index, field: "url", reason: url.reason });
+ return;
+ }
+
+ const label = typeof item?.label === "string" ? item.label.trim() : "";
+ if (label.length > MAX_SOCIAL_LABEL_LENGTH) {
+ errors.push({ index, field: "label", reason: "too_long" });
+ return;
+ }
+
+ clean.push({
+ platform,
+ label: label.length > 0 ? label : null,
+ url: url.url,
+ visible: item?.visible === false ? 0 : 1,
+ });
+ });
+
+ if (errors.length > 0) return { ok: false, errors };
+
+ writeTx(db, (tx) => {
+ tx.query("DELETE FROM social_links WHERE owner_type = ? AND owner_id = ?").run(
+ params.ownerType,
+ params.ownerId,
+ );
+ clean.forEach((link, index) => {
+ tx.query(
+ `INSERT INTO social_links (owner_type, owner_id, platform, label, url, visible, sort_order)
+ VALUES (?,?,?,?,?,?,?)`,
+ ).run(
+ params.ownerType,
+ params.ownerId,
+ link.platform,
+ link.label,
+ link.url,
+ link.visible,
+ index,
+ );
+ });
+ });
+
+ return { ok: true, saved: clean.length };
+}
diff --git a/apps/api/src/pk/client.ts b/apps/api/src/pk/client.ts
new file mode 100644
index 0000000..e120a06
--- /dev/null
+++ b/apps/api/src/pk/client.ts
@@ -0,0 +1,385 @@
+import {
+ PkBadRequest,
+ PkMalformedResponse,
+ PkNotFound,
+ PkRateLimited,
+ PkUnauthorized,
+ PkUpstreamDown,
+} from "./errors.ts";
+import { TokenBucket } from "./limiter.ts";
+import { MemorySnapshotStore, type SnapshotRefType, type SnapshotStore } from "./snapshots.ts";
+import type { PkFronters, PkMember, PkRef, PkSystem } from "./types.ts";
+
+/**
+ * The single PluralKit API client.
+ *
+ * Nothing else in the codebase may construct a request to PluralKit. That is
+ * what makes the User-Agent, the rate limiter, the cache and token redaction
+ * enforceable rather than aspirational.
+ */
+
+/**
+ * Credential for a request. Passing this is always explicit at the call site,
+ * never ambient and never inherited from request context, so credential use can
+ * be audited by searching for `as:`.
+ *
+ * `accountId` scopes the cache. Without it an authenticated response is never
+ * cached at all, which is the safe default: a response fetched with someone's
+ * credential must never be reachable from the public scope.
+ */
+export type PkAuth = { token: string; accountId?: string };
+
+export type PkRequestOptions = {
+ as?: PkAuth;
+ /** How old a cached value may be and still be returned without a refetch. */
+ maxAgeMs?: number;
+ /** Serve a stale snapshot when PluralKit is unreachable. Default true. */
+ allowStale?: boolean;
+ signal?: AbortSignal;
+};
+
+export type PkClientOptions = {
+ apiBase: string;
+ userAgent: string;
+ readRps: number;
+ writeRps: number;
+ snapshots?: SnapshotStore;
+ fetchImpl?: typeof fetch;
+ clock?: () => number;
+ sleep?: (ms: number) => Promise<void>;
+ /** Default freshness window for reads. */
+ defaultMaxAgeMs?: number;
+ timeoutMs?: number;
+ maxRetries?: number;
+ onLog?: (entry: PkLogEntry) => void;
+};
+
+export type PkLogEntry = {
+ at: number;
+ method: string;
+ path: string;
+ status?: number;
+ durationMs: number;
+ authenticated: boolean;
+ outcome: "ok" | "error" | "cache" | "stale";
+ error?: string;
+};
+
+const PUBLIC_SCOPE = "public";
+
+export class PkClient {
+ private readonly apiBase: string;
+ private readonly userAgent: string;
+ private readonly snapshots: SnapshotStore;
+ private readonly fetchImpl: typeof fetch;
+ private readonly clock: () => number;
+ private readonly sleep: (ms: number) => Promise<void>;
+ private readonly defaultMaxAgeMs: number;
+ private readonly timeoutMs: number;
+ private readonly maxRetries: number;
+ private readonly onLog: ((entry: PkLogEntry) => void) | undefined;
+
+ private readonly readBucket: TokenBucket;
+ private readonly writeBucket: TokenBucket;
+
+ /** In-flight requests keyed by cache key, so N concurrent visitors to one
+ * popular page produce one upstream call rather than N. */
+ private readonly inFlight = new Map<string, Promise<unknown>>();
+
+ constructor(opts: PkClientOptions) {
+ this.apiBase = opts.apiBase.replace(/\/+$/, "");
+ this.userAgent = opts.userAgent;
+ this.snapshots = opts.snapshots ?? new MemorySnapshotStore();
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
+ this.clock = opts.clock ?? (() => Date.now());
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+ this.defaultMaxAgeMs = opts.defaultMaxAgeMs ?? 60_000;
+ this.timeoutMs = opts.timeoutMs ?? 5_000;
+ this.maxRetries = opts.maxRetries ?? 3;
+ this.onLog = opts.onLog;
+
+ if (!this.userAgent || this.userAgent.trim().length === 0) {
+ // PluralKit rejects a missing User-Agent with 400. Failing at construction
+ // turns that into a startup error rather than a runtime mystery.
+ throw new Error("PkClient requires a non-empty User-Agent");
+ }
+
+ this.readBucket = new TokenBucket(opts.readRps, undefined, this.clock, this.sleep);
+ this.writeBucket = new TokenBucket(opts.writeRps, undefined, this.clock, this.sleep);
+ }
+
+ // --------------------------------------------------------------- endpoints
+
+ /**
+ * A system by HID, UUID, or the Discord account ID of a linked account.
+ *
+ * The Discord-ID form is the basis of tier-1 claim verification: Discord
+ * asserts who the user is, PluralKit asserts which system that account is
+ * linked to, and no credential changes hands.
+ */
+ getSystem(ref: PkRef, opts: PkRequestOptions = {}): Promise<PkSystem> {
+ return this.readJson<PkSystem>("system", ref, `/systems/${encodeURIComponent(ref)}`, opts);
+ }
+
+ getMembers(ref: PkRef, opts: PkRequestOptions = {}): Promise<PkMember[]> {
+ return this.readJson<PkMember[]>(
+ "members",
+ ref,
+ `/systems/${encodeURIComponent(ref)}/members`,
+ opts,
+ );
+ }
+
+ getMember(ref: PkRef, opts: PkRequestOptions = {}): Promise<PkMember> {
+ return this.readJson<PkMember>("member", ref, `/members/${encodeURIComponent(ref)}`, opts);
+ }
+
+ getFronters(ref: PkRef, opts: PkRequestOptions = {}): Promise<PkFronters> {
+ return this.readJson<PkFronters>(
+ "fronters",
+ ref,
+ `/systems/${encodeURIComponent(ref)}/fronters`,
+ opts,
+ );
+ }
+
+ /**
+ * The authenticated system for a token. Used only for transient claim
+ * verification (tier 3): the token is used within one request and discarded.
+ * Never cached, because there is no account scope to cache it under.
+ */
+ async getOwnSystem(token: string, opts: { signal?: AbortSignal } = {}): Promise<PkSystem> {
+ const res = await this.request("GET", "/systems/@me", {
+ auth: { token },
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ });
+ return (await this.parseJson(res)) as PkSystem;
+ }
+
+ // ----------------------------------------------------------------- caching
+
+ private cacheScope(auth: PkAuth | undefined): string | null {
+ if (!auth) return PUBLIC_SCOPE;
+ // An authenticated response with no account to scope it to is never cached.
+ return auth.accountId ?? null;
+ }
+
+ private async readJson<T>(
+ refType: SnapshotRefType,
+ refKey: string,
+ path: string,
+ opts: PkRequestOptions,
+ ): Promise<T> {
+ const scope = this.cacheScope(opts.as);
+ const maxAge = opts.maxAgeMs ?? this.defaultMaxAgeMs;
+ const allowStale = opts.allowStale ?? true;
+ const now = this.clock();
+
+ // maxAge <= 0 is an unconditional bypass, not "fresh within 0ms". Claim
+ // verification depends on this: matching a nonce against a cached
+ // description would let a stale copy prove ownership the user may no longer
+ // have.
+ if (scope !== null && maxAge > 0) {
+ const cached = this.snapshots.read(refType, refKey, scope);
+ if (cached && now - cached.fetchedAt <= maxAge) {
+ this.log({
+ at: now,
+ method: "GET",
+ path,
+ durationMs: 0,
+ authenticated: Boolean(opts.as),
+ outcome: "cache",
+ });
+ return cached.payload as T;
+ }
+ }
+
+ const key = `${refType}:${refKey}:${scope ?? "nocache"}`;
+ const existing = this.inFlight.get(key);
+ if (existing) return existing as Promise<T>;
+
+ const work = (async (): Promise<T> => {
+ try {
+ const res = await this.request("GET", path, {
+ ...(opts.as ? { auth: opts.as } : {}),
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ });
+ const payload = (await this.parseJson(res)) as T;
+ if (scope !== null) {
+ this.snapshots.write(
+ refType,
+ refKey,
+ scope,
+ payload,
+ this.clock(),
+ res.headers.get("etag"),
+ );
+ }
+ return payload;
+ } catch (err) {
+ // PluralKit being down must not take public pages down with it. A stale
+ // snapshot with a visible "may be out of date" marker beats a 502.
+ if (allowStale && scope !== null && err instanceof PkUpstreamDown) {
+ const stale = this.snapshots.read(refType, refKey, scope);
+ if (stale) {
+ this.log({
+ at: this.clock(),
+ method: "GET",
+ path,
+ durationMs: 0,
+ authenticated: Boolean(opts.as),
+ outcome: "stale",
+ });
+ return stale.payload as T;
+ }
+ }
+ throw err;
+ } finally {
+ this.inFlight.delete(key);
+ }
+ })();
+
+ this.inFlight.set(key, work);
+ return work;
+ }
+
+ /** Age of the cached snapshot backing a reference, if any. Lets callers mark
+ * a page as possibly out of date without refetching. */
+ snapshotAge(refType: SnapshotRefType, refKey: string, authScope = PUBLIC_SCOPE): number | null {
+ const snap = this.snapshots.read(refType, refKey, authScope);
+ return snap ? this.clock() - snap.fetchedAt : null;
+ }
+
+ // ---------------------------------------------------------------- transport
+
+ private async request(
+ method: "GET" | "POST" | "PATCH" | "DELETE",
+ path: string,
+ opts: { auth?: PkAuth; signal?: AbortSignal } = {},
+ ): Promise<Response> {
+ const isWrite = method !== "GET";
+ const url = `${this.apiBase}${path}`;
+ let lastError: unknown;
+
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
+ await (isWrite ? this.writeBucket : this.readBucket).acquire();
+
+ const started = this.clock();
+ const headers: Record<string, string> = {
+ // The one canonical User-Agent. Never varies by user, server or shard.
+ "User-Agent": this.userAgent,
+ Accept: "application/json",
+ };
+ if (opts.auth) headers["Authorization"] = opts.auth.token;
+
+ const timeout = AbortSignal.timeout(this.timeoutMs);
+ const signal = opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout;
+
+ let res: Response;
+ try {
+ res = await this.fetchImpl(url, { method, headers, signal });
+ } catch (err) {
+ lastError = new PkUpstreamDown(
+ `network error contacting PluralKit: ${errMessage(err)}`,
+ );
+ this.log({
+ at: started,
+ method,
+ path,
+ durationMs: this.clock() - started,
+ authenticated: Boolean(opts.auth),
+ outcome: "error",
+ error: errMessage(err),
+ });
+ // Writes are never retried automatically: PluralKit may have applied the
+ // change before the connection failed.
+ if (isWrite || attempt === this.maxRetries) throw lastError;
+ await this.sleep(backoffMs(attempt));
+ continue;
+ }
+
+ this.log({
+ at: started,
+ method,
+ path,
+ status: res.status,
+ durationMs: this.clock() - started,
+ authenticated: Boolean(opts.auth),
+ outcome: res.ok ? "ok" : "error",
+ });
+
+ if (res.ok) return res;
+
+ if (res.status === 429) {
+ const retryAfterMs = parseRetryAfter(res.headers.get("retry-after"));
+ lastError = new PkRateLimited("PluralKit rate limit exceeded", retryAfterMs, 429);
+ if (isWrite || attempt === this.maxRetries) throw lastError;
+ await this.sleep(retryAfterMs ?? backoffMs(attempt));
+ continue;
+ }
+
+ if (res.status >= 500) {
+ lastError = new PkUpstreamDown(`PluralKit returned ${res.status}`, res.status);
+ if (isWrite || attempt === this.maxRetries) throw lastError;
+ await this.sleep(backoffMs(attempt));
+ continue;
+ }
+
+ throw mapClientError(res.status);
+ }
+
+ throw lastError ?? new PkUpstreamDown("PluralKit request failed");
+ }
+
+ private async parseJson(res: Response): Promise<unknown> {
+ try {
+ return await res.json();
+ } catch (err) {
+ throw new PkMalformedResponse(`could not parse PluralKit response: ${errMessage(err)}`);
+ }
+ }
+
+ /**
+ * Log entries never carry the Authorization header. Redaction lives here, in
+ * the one place every request passes through, rather than at each call site,
+ * because the call site you forget is the one that leaks.
+ */
+ private log(entry: PkLogEntry): void {
+ this.onLog?.(entry);
+ }
+}
+
+function mapClientError(status: number): Error {
+ switch (status) {
+ case 400:
+ // Includes the missing-User-Agent case, which would be our bug.
+ return new PkBadRequest("PluralKit rejected the request as malformed", 400);
+ case 401:
+ case 403:
+ return new PkUnauthorized("PluralKit rejected the credential", status);
+ case 404:
+ // Not found and private are indistinguishable here, deliberately.
+ return new PkNotFound("not found", 404);
+ default:
+ return new PkUpstreamDown(`unexpected PluralKit status ${status}`, status);
+ }
+}
+
+/** Exponential backoff starting at 500ms, with jitter to avoid lockstep retry. */
+function backoffMs(attempt: number): number {
+ const base = 500 * 2 ** attempt;
+ return Math.round(base * (0.5 + Math.random() * 0.5));
+}
+
+function parseRetryAfter(value: string | null): number | undefined {
+ if (!value) return undefined;
+ const seconds = Number(value);
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);
+ const date = Date.parse(value);
+ if (Number.isFinite(date)) return Math.max(0, date - Date.now());
+ return undefined;
+}
+
+function errMessage(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
diff --git a/apps/api/src/pk/errors.ts b/apps/api/src/pk/errors.ts
new file mode 100644
index 0000000..b3b87a9
--- /dev/null
+++ b/apps/api/src/pk/errors.ts
@@ -0,0 +1,54 @@
+/**
+ * Typed PluralKit errors so callers branch on a type rather than string-matching
+ * a message. Every failure mode the application reacts to differently gets its
+ * own class.
+ */
+
+export abstract class PkError extends Error {
+ abstract readonly kind: string;
+ constructor(message: string, readonly status?: number) {
+ super(message);
+ }
+}
+
+/** The reference does not exist, or is private. PluralKit does not distinguish
+ * these, and neither do we — which is exactly the behaviour decision 5 wants. */
+export class PkNotFound extends PkError {
+ override readonly kind = "not_found";
+ override readonly name = "PkNotFound";
+}
+
+/** Authenticated request rejected: bad or revoked token. */
+export class PkUnauthorized extends PkError {
+ override readonly kind = "unauthorized";
+ override readonly name = "PkUnauthorized";
+}
+
+/** We exceeded a rate limit. `retryAfterMs` comes from Retry-After when sent. */
+export class PkRateLimited extends PkError {
+ override readonly kind = "rate_limited";
+ override readonly name = "PkRateLimited";
+ constructor(message: string, readonly retryAfterMs: number | undefined, status?: number) {
+ super(message, status);
+ }
+}
+
+/** PluralKit is unreachable, timed out, or returned 5xx. Public pages should
+ * fall back to the last good snapshot rather than surfacing this. */
+export class PkUpstreamDown extends PkError {
+ override readonly kind = "upstream_down";
+ override readonly name = "PkUpstreamDown";
+}
+
+/** A request we constructed was rejected — a bug on our side. A missing
+ * User-Agent lands here, which is why the UA has its own test. */
+export class PkBadRequest extends PkError {
+ override readonly kind = "bad_request";
+ override readonly name = "PkBadRequest";
+}
+
+/** Response was not the JSON shape we expected. */
+export class PkMalformedResponse extends PkError {
+ override readonly kind = "malformed";
+ override readonly name = "PkMalformedResponse";
+}
diff --git a/apps/api/src/pk/limiter.ts b/apps/api/src/pk/limiter.ts
new file mode 100644
index 0000000..bf9ff63
--- /dev/null
+++ b/apps/api/src/pk/limiter.ts
@@ -0,0 +1,76 @@
+/**
+ * Token-bucket rate limiter.
+ *
+ * Sized below PluralKit's documented limits (10/s reads, 3/s writes) to leave
+ * headroom for burst and clock imprecision.
+ *
+ * IMPORTANT: PluralKit's limits are per-IP and this limiter is per-process.
+ * That is correct while pkviewer runs as a single API process, which is the
+ * deployment the SQLite design already implies. If a second instance is ever
+ * placed behind the same egress IP, this must become a shared limiter or the
+ * two processes will silently exceed the limit between them.
+ */
+export class TokenBucket {
+ private tokens: number;
+ private lastRefill: number;
+ private readonly queue: Array<() => void> = [];
+ private draining = false;
+
+ constructor(
+ private readonly ratePerSecond: number,
+ private readonly burst: number = Math.max(1, Math.ceil(ratePerSecond)),
+ private readonly now: () => number = () => Date.now(),
+ private readonly sleep: (ms: number) => Promise<void> = (ms) =>
+ new Promise((r) => setTimeout(r, ms)),
+ ) {
+ this.tokens = this.burst;
+ this.lastRefill = this.now();
+ }
+
+ private refill(): void {
+ const t = this.now();
+ const elapsed = Math.max(0, t - this.lastRefill);
+ if (elapsed > 0) {
+ this.tokens = Math.min(this.burst, this.tokens + (elapsed / 1000) * this.ratePerSecond);
+ this.lastRefill = t;
+ }
+ }
+
+ /** Resolves once a token is available. FIFO, so callers cannot starve. */
+ async acquire(): Promise<void> {
+ this.refill();
+ if (this.tokens >= 1 && this.queue.length === 0) {
+ this.tokens -= 1;
+ return;
+ }
+ await new Promise<void>((resolve) => {
+ this.queue.push(resolve);
+ void this.drain();
+ });
+ }
+
+ private async drain(): Promise<void> {
+ if (this.draining) return;
+ this.draining = true;
+ try {
+ while (this.queue.length > 0) {
+ this.refill();
+ if (this.tokens >= 1) {
+ this.tokens -= 1;
+ this.queue.shift()?.();
+ continue;
+ }
+ const deficit = 1 - this.tokens;
+ await this.sleep(Math.max(1, Math.ceil((deficit / this.ratePerSecond) * 1000)));
+ }
+ } finally {
+ this.draining = false;
+ }
+ }
+
+ /** Tokens currently available. Test/observability aid. */
+ get available(): number {
+ this.refill();
+ return this.tokens;
+ }
+}
diff --git a/apps/api/src/pk/snapshots.ts b/apps/api/src/pk/snapshots.ts
new file mode 100644
index 0000000..4e7b71a
Binary files /dev/null and b/apps/api/src/pk/snapshots.ts differ
diff --git a/apps/api/src/pk/types.ts b/apps/api/src/pk/types.ts
new file mode 100644
index 0000000..2c858a9
--- /dev/null
+++ b/apps/api/src/pk/types.ts
@@ -0,0 +1,70 @@
+/** Shapes we consume from the PluralKit v2 API. Only fields pkviewer uses are
+ * modelled; PluralKit may send more and that is fine. */
+
+export type PkPrivacyValue = "public" | "private";
+
+export type PkSystemPrivacy = Partial<{
+ name_privacy: PkPrivacyValue;
+ description_privacy: PkPrivacyValue;
+ avatar_privacy: PkPrivacyValue;
+ banner_privacy: PkPrivacyValue;
+ pronoun_privacy: PkPrivacyValue;
+ member_list_privacy: PkPrivacyValue;
+ group_list_privacy: PkPrivacyValue;
+ front_privacy: PkPrivacyValue;
+ front_history_privacy: PkPrivacyValue;
+}>;
+
+export type PkSystem = {
+ id: string;
+ uuid: string;
+ name: string | null;
+ description: string | null;
+ tag: string | null;
+ pronouns: string | null;
+ avatar_url: string | null;
+ banner: string | null;
+ color: string | null;
+ created: string | null;
+ privacy?: PkSystemPrivacy | null;
+};
+
+export type PkMemberPrivacy = Partial<{
+ visibility: PkPrivacyValue;
+ name_privacy: PkPrivacyValue;
+ description_privacy: PkPrivacyValue;
+ birthday_privacy: PkPrivacyValue;
+ pronoun_privacy: PkPrivacyValue;
+ avatar_privacy: PkPrivacyValue;
+ banner_privacy: PkPrivacyValue;
+ metadata_privacy: PkPrivacyValue;
+ proxy_privacy: PkPrivacyValue;
+}>;
+
+export type PkMember = {
+ id: string;
+ uuid: string;
+ system?: string | null;
+ name: string | null;
+ display_name: string | null;
+ color: string | null;
+ birthday: string | null;
+ pronouns: string | null;
+ avatar_url: string | null;
+ banner: string | null;
+ description: string | null;
+ created: string | null;
+ privacy?: PkMemberPrivacy | null;
+};
+
+export type PkFronters = {
+ timestamp: string | null;
+ members: PkMember[];
+};
+
+/**
+ * A PluralKit reference. Accepts a 5 or 6 character HID, a UUID, or the Discord
+ * account ID of a linked account. That last form is what makes tier-1 system
+ * claiming possible without any credential.
+ */
+export type PkRef = string;
diff --git a/apps/api/src/public/page-model.ts b/apps/api/src/public/page-model.ts
new file mode 100644
index 0000000..cd68db4
--- /dev/null
+++ b/apps/api/src/public/page-model.ts
@@ -0,0 +1,304 @@
+import { resolveComposition, type MemberView, type PageModel, type SocialLink, type SystemView } from "@pkviewer/shared";
+import type { Db } from "../db/index.ts";
+import type { PkClient } from "../pk/client.ts";
+import type { PkMember, PkSystem } from "../pk/types.ts";
+import { activeSlugFor } from "../slugs/claim.ts";
+import { memberPath, resolveMemberRef, resolveSystemRef, systemPath } from "../slugs/resolve.ts";
+
+/**
+ * Builds the fully resolved model a public page renders from.
+ *
+ * The rendering tier makes ONE call per page and receives everything already
+ * merged — PluralKit data, slugs, socials, theme tokens. Server-side rendering
+ * is then a single hop rather than a fan-out, and the web tier never needs to
+ * know how any of it is assembled.
+ *
+ * Only data PluralKit already returns publicly appears here. Members PluralKit
+ * withholds are simply absent, which is what makes a private member
+ * indistinguishable from one that never existed (decision 5).
+ */
+
+export type PageFailure = "not_found" | "unsupported_reference" | "upstream_unavailable";
+export type PageResult<T> = { ok: true; value: T } | { ok: false; reason: PageFailure };
+
+type Deps = { db: Db; pk: PkClient; now?: () => number; freshnessMs?: number };
+
+function socialsFor(db: Db, ownerType: "system" | "member", ownerId: string | null): SocialLink[] {
+ if (!ownerId) return [];
+ return db
+ .query<{ platform: string; label: string | null; url: string }, [string, string]>(
+ `SELECT platform, label, url FROM social_links
+ WHERE owner_type = ? AND owner_id = ? AND visible = 1
+ ORDER BY sort_order, id`,
+ )
+ .all(ownerType, ownerId)
+ .map((r) => ({ platform: r.platform, label: r.label, url: r.url }));
+}
+
+/**
+ * Stored theme tokens for an owner.
+ *
+ * Returned as an opaque flat map. The renderer turns whatever keys exist into
+ * CSS custom properties without knowing their names, so the token VOCABULARY
+ * can be defined by the design pass without touching this code.
+ */
+function layerFor(
+ db: Db,
+ ownerType: "system" | "member",
+ ownerId: string | null,
+ column: "tokens" | "composition",
+): Record<string, string | null> {
+ if (!ownerId) return {};
+ const row = db
+ .query<{ value: string }, [string, string]>(
+ `SELECT ${column} AS value FROM themes
+ WHERE owner_type = ? AND owner_id = ? AND deleted_at IS NULL`,
+ )
+ .get(ownerType, ownerId);
+ if (!row) return {};
+ try {
+ const parsed = JSON.parse(row.value) as unknown;
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
+ const out: Record<string, string | null> = {};
+ for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
+ // null is meaningful: it is the explicit "reset to the platform default"
+ // state. Filtering it out here silently collapsed three inheritance
+ // states into two, so a member reset landed on the system value instead.
+ if (typeof v === "string" || v === null) out[k] = v;
+ }
+ return out;
+ } catch {
+ return {};
+ }
+}
+
+function tokensFor(db: Db, ownerType: "system" | "member", ownerId: string | null) {
+ return layerFor(db, ownerType, ownerId, "tokens");
+}
+
+function compositionFor(db: Db, ownerType: "system" | "member", ownerId: string | null) {
+ return layerFor(db, ownerType, ownerId, "composition");
+}
+
+/**
+ * Merges system tokens under member tokens.
+ *
+ * Absent key means inherit; an explicit null means reset to the platform
+ * default, which is represented here by omitting the key entirely so the
+ * renderer falls back. The three-state model lives in this one function.
+ */
+export function resolveTokens(
+ systemTokens: Record<string, string | null>,
+ memberTokens: Record<string, string | null> | null,
+): Record<string, string> {
+ const merged: Record<string, string> = {};
+ for (const [key, value] of Object.entries(systemTokens)) {
+ if (typeof value === "string") merged[key] = value;
+ }
+ if (!memberTokens) return merged;
+ for (const [key, value] of Object.entries(memberTokens)) {
+ if (value === null) delete merged[key];
+ else merged[key] = value;
+ }
+ return merged;
+}
+
+function toSystemView(
+ system: PkSystem,
+ opts: {
+ slug: string | null;
+ memberCount: number;
+ claimed: boolean;
+ staleSinceMs: number | null;
+ showPronouns: boolean;
+ bannerVisible: boolean;
+ },
+): SystemView {
+ return {
+ hid: system.id,
+ slug: opts.slug,
+ name: system.name,
+ description: system.description,
+ tag: system.tag,
+ pronouns: opts.showPronouns ? system.pronouns : null,
+ avatarUrl: system.avatar_url,
+ bannerUrl: opts.bannerVisible ? system.banner : null,
+ color: system.color,
+ memberCount: opts.memberCount,
+ claimed: opts.claimed,
+ staleSinceMs: opts.staleSinceMs,
+ };
+}
+
+/**
+ * Fields hidden by composition are removed here, not merely hidden in markup.
+ *
+ * A visibility setting that only styles a value away still ships it in the page
+ * source, which is not what "hide pronouns" reasonably means. This is public
+ * PluralKit data either way, so nothing private is at stake — but a privacy
+ * setting should do what it says.
+ */
+function toMemberView(
+ member: PkMember,
+ ctx: {
+ systemHid: string;
+ systemSlug: string | null;
+ slug: string | null;
+ showPronouns: boolean;
+ showBirthday: boolean;
+ },
+): MemberView {
+ return {
+ hid: member.id,
+ slug: ctx.slug,
+ systemHid: ctx.systemHid,
+ systemSlug: ctx.systemSlug,
+ name: member.name,
+ displayName: member.display_name,
+ description: member.description,
+ pronouns: ctx.showPronouns ? member.pronouns : null,
+ avatarUrl: member.avatar_url,
+ bannerUrl: member.banner,
+ color: member.color,
+ birthday: ctx.showBirthday ? member.birthday : null,
+ };
+}
+
+/** Slugs for a batch of members, so the directory can link canonically. */
+function memberSlugMap(db: Db, systemId: string | null): Map<string, string> {
+ const out = new Map<string, string>();
+ if (!systemId) return out;
+ const rows = db
+ .query<{ pk_member_uuid: string; slug_display: string }, [string]>(
+ `SELECT m.pk_member_uuid AS pk_member_uuid, s.slug_display AS slug_display
+ FROM slugs s
+ JOIN members m ON m.id = s.subject_id
+ WHERE s.scope = 'member' AND s.scope_key = ? AND s.state = 'active'`,
+ )
+ .all(systemId);
+ for (const r of rows) out.set(r.pk_member_uuid, r.slug_display);
+ return out;
+}
+
+export async function buildSystemPage(
+ deps: Deps,
+ ref: string,
+): Promise<PageResult<PageModel & { canonicalPath: string }>> {
+ const resolved = await resolveSystemRef(deps, ref);
+ if (!resolved.ok) return resolved;
+
+ const { system, systemId, slug, cacheRef } = resolved.value;
+
+ let members: PkMember[] = [];
+ try {
+ members = await deps.pk.getMembers(system.uuid);
+ } catch {
+ // A system whose member list is private still has a page; it simply has no
+ // directory. This is indistinguishable from a system with no members, by
+ // design.
+ members = [];
+ }
+
+ const slugs = memberSlugMap(deps.db, systemId);
+ const composition = resolveComposition(compositionFor(deps.db, "system", systemId), {});
+ const showPronouns = composition["show.pronouns"] !== "false";
+ const showBirthday = composition["show.birthday"] !== "false";
+ const bannerVisible = composition["banner.display"] !== "hidden";
+
+ return {
+ ok: true,
+ value: {
+ system: toSystemView(system, {
+ slug,
+ memberCount: members.length,
+ claimed: systemId !== null,
+ staleSinceMs: stalenessFor(deps, "system", cacheRef),
+ showPronouns,
+ bannerVisible,
+ }),
+ member: null,
+ members: members.map((m) =>
+ toMemberView(m, {
+ systemHid: system.id,
+ systemSlug: slug,
+ slug: slugs.get(m.uuid) ?? null,
+ showPronouns,
+ showBirthday,
+ }),
+ ),
+ socials: socialsFor(deps.db, "system", systemId),
+ tokens: resolveTokens(tokensFor(deps.db, "system", systemId), null),
+ composition,
+ beta: false, // set by the route from config
+ canonicalPath: systemPath(system.id, slug),
+ },
+ };
+}
+
+export async function buildMemberPage(
+ deps: Deps,
+ ref: string,
+ memberRef: string,
+): Promise<PageResult<PageModel & { canonicalPath: string }>> {
+ const resolvedSystem = await resolveSystemRef(deps, ref);
+ if (!resolvedSystem.ok) return resolvedSystem;
+
+ const resolvedMember = await resolveMemberRef(deps, resolvedSystem.value, memberRef);
+ if (!resolvedMember.ok) return resolvedMember;
+
+ const { system, systemId, slug: systemSlug, cacheRef } = resolvedSystem.value;
+ const { member, memberId, slug: memberSlug } = resolvedMember.value;
+
+ // Member tokens override the system's; an explicit null resets to platform
+ // default rather than inheriting.
+ const systemTokens = tokensFor(deps.db, "system", systemId);
+ const memberTokens = tokensFor(deps.db, "member", memberId);
+ const composition = resolveComposition(
+ compositionFor(deps.db, "system", systemId),
+ compositionFor(deps.db, "member", memberId),
+ );
+ const showPronouns = composition["show.pronouns"] !== "false";
+ const showBirthday = composition["show.birthday"] !== "false";
+ const bannerVisible = composition["banner.display"] !== "hidden";
+
+ return {
+ ok: true,
+ value: {
+ system: toSystemView(system, {
+ slug: systemSlug,
+ memberCount: 0,
+ claimed: systemId !== null,
+ staleSinceMs: stalenessFor(deps, "system", cacheRef),
+ showPronouns,
+ bannerVisible,
+ }),
+ member: toMemberView(member, {
+ systemHid: system.id,
+ systemSlug,
+ slug: memberSlug,
+ showPronouns,
+ showBirthday,
+ }),
+ members: [],
+ socials: socialsFor(deps.db, "member", memberId),
+ tokens: resolveTokens(systemTokens, memberTokens),
+ composition,
+ beta: false,
+ canonicalPath: memberPath(system.id, systemSlug, member.id, memberSlug),
+ },
+ };
+}
+
+/**
+ * How stale the data behind this page is, in milliseconds, or null when fresh.
+ *
+ * PluralKit downtime must not take public pages down (P3): the client falls
+ * back to the last good snapshot, and this is what lets the page say so rather
+ * than presenting old data as current.
+ */
+function stalenessFor(deps: Deps, refType: "system", refKey: string): number | null {
+ const age = deps.pk.snapshotAge(refType, refKey);
+ if (age === null) return null;
+ const threshold = deps.freshnessMs ?? 60_000;
+ return age > threshold ? age : null;
+}
diff --git a/apps/api/src/slugs/claim.ts b/apps/api/src/slugs/claim.ts
new file mode 100644
index 0000000..bb72160
--- /dev/null
+++ b/apps/api/src/slugs/claim.ts
@@ -0,0 +1,233 @@
+import type { Db } from "../db/index.ts";
+import { writeTx } from "../db/index.ts";
+import {
+ effectiveState,
+ findSlug,
+ releaseSlug,
+ slugsForSubject,
+ type SlugRow,
+ RESERVATION_MS,
+} from "./lifecycle.ts";
+import { looksLikeHid, validateSlug, type SlugRejection, type SlugScope } from "./normalize.ts";
+
+/**
+ * Slug claiming.
+ *
+ * The race safety story is the same one used for system ownership: uniqueness
+ * and state transitions are enforced by the database, never by a read followed
+ * by a decision followed by a write.
+ *
+ * - A brand new slug is a single INSERT guarded by
+ * `UNIQUE (scope, scope_key, slug_normalized)`.
+ * - Taking over a reserved-but-lapsed slug, or reclaiming one, is an UPDATE
+ * whose WHERE clause re-asserts every precondition, checked via `changes()`.
+ *
+ * Two simultaneous claimants therefore cannot both win: the loser either hits
+ * the constraint or updates zero rows, and reports a conflict.
+ */
+
+export type ClaimSlugFailure =
+ | { kind: "invalid"; reason: SlugRejection }
+ | { kind: "taken" }
+ | { kind: "reserved"; until: number }
+ | { kind: "conflict" };
+
+export type ClaimSlugSuccess = {
+ kind: "claimed" | "reclaimed" | "unchanged";
+ slug: string;
+ previousSlug: string | null;
+ /** Non-blocking advisories, e.g. shadowing one of your own member ids. */
+ warnings: SlugWarning[];
+};
+
+export type SlugWarning =
+ | { code: "shadows_member_id"; memberHid: string }
+ | { code: "previous_slug_reserved"; slug: string; until: number };
+
+export type ClaimSlugResult =
+ | ({ ok: true } & ClaimSlugSuccess)
+ | ({ ok: false } & ClaimSlugFailure);
+
+export type ClaimSlugParams = {
+ scope: SlugScope;
+ /** '' for system slugs (global); the owning system id for member slugs. */
+ scopeKey: string;
+ subjectId: string;
+ requested: string;
+ accountId: string | null;
+ now: number;
+ /**
+ * Short ids of other members in the same system, when claiming a member slug.
+ *
+ * Used only to warn: a member slug that matches a sibling's id shadows that
+ * sibling's id URL. It is contained inside one system the claimant already
+ * controls, so it is advisory rather than forbidden.
+ */
+ siblingHids?: readonly string[];
+};
+
+export function claimSlug(db: Db, params: ClaimSlugParams): ClaimSlugResult {
+ const validation = validateSlug(params.requested, params.scope);
+ if (!validation.ok) return { ok: false, kind: "invalid", reason: validation.reason };
+
+ const { normalized, display } = validation;
+ const warnings: SlugWarning[] = [];
+
+ if (params.scope === "member" && looksLikeHid(normalized)) {
+ const clash = params.siblingHids?.find((hid) => hid.toLowerCase() === normalized);
+ if (clash) warnings.push({ code: "shadows_member_id", memberHid: clash });
+ }
+
+ return writeTx(db, (tx) => {
+ const existing = findSlug(tx, params.scope, params.scopeKey, normalized);
+
+ // Already ours and active: nothing to do, and no reservation churn.
+ if (existing) {
+ const state = effectiveState(existing, params.now);
+ if (state.kind === "active" && state.subjectId === params.subjectId) {
+ return { ok: true, kind: "unchanged", slug: display, previousSlug: null, warnings };
+ }
+ if (state.kind === "active") return { ok: false, kind: "taken" };
+ if (state.kind === "reserved" && state.principalId !== params.subjectId) {
+ // Never say who holds the reservation.
+ return { ok: false, kind: "reserved", until: state.until };
+ }
+ }
+
+ // A subject holds at most one active slug per scope. Claiming a new one
+ // releases the old into its own 7-day reservation rather than freeing it
+ // immediately, so a rename cannot be used to snipe someone's old URL and
+ // the owner can change their mind.
+ const previous = slugsForSubject(tx, params.scope, params.subjectId).find(
+ (row) => row.slug_normalized !== normalized,
+ );
+ let previousSlug: string | null = null;
+ if (previous) {
+ if (releaseSlug(tx, previous, params.now, params.accountId)) {
+ previousSlug = previous.slug_display;
+ warnings.push({
+ code: "previous_slug_reserved",
+ slug: previous.slug_display,
+ until: params.now + RESERVATION_MS,
+ });
+ }
+ }
+
+ if (!existing) {
+ try {
+ tx.query(
+ `INSERT INTO slugs
+ (scope, scope_key, slug_normalized, slug_display, state, subject_id, claimed_at)
+ VALUES (?, ?, ?, ?, 'active', ?, ?)`,
+ ).run(params.scope, params.scopeKey, normalized, display, params.subjectId, params.now);
+ } catch {
+ // The unique index fired: another claimant got there first.
+ return { ok: false, kind: "conflict" };
+ }
+ recordHistory(tx, params.scope, params.scopeKey, normalized, "claimed", params);
+ return { ok: true, kind: "claimed", slug: display, previousSlug, warnings };
+ }
+
+ // Reserved for us, or lapsed and free. Both preconditions are re-asserted
+ // in the WHERE clause so a concurrent claim cannot slip between the read
+ // above and this write.
+ const isOurReservation =
+ existing.state === "reserved" && existing.reserved_principal_id === params.subjectId;
+
+ const result = tx
+ .query(
+ `UPDATE slugs
+ SET state = 'active',
+ subject_id = ?,
+ slug_display = ?,
+ reserved_principal_type = NULL,
+ reserved_principal_id = NULL,
+ reserved_until = NULL,
+ claimed_at = ?
+ WHERE id = ?
+ AND state = 'reserved'
+ AND (reserved_principal_id = ? OR reserved_until <= ?)`,
+ )
+ .run(params.subjectId, display, params.now, existing.id, params.subjectId, params.now);
+
+ if (Number(result.changes ?? 0) === 0) return { ok: false, kind: "conflict" };
+
+ recordHistory(
+ tx,
+ params.scope,
+ params.scopeKey,
+ normalized,
+ isOurReservation ? "reclaimed" : "claimed",
+ params,
+ );
+
+ return {
+ ok: true,
+ kind: isOurReservation ? "reclaimed" : "claimed",
+ slug: display,
+ previousSlug,
+ warnings,
+ };
+ });
+}
+
+function recordHistory(
+ db: Db,
+ scope: SlugScope,
+ scopeKey: string,
+ normalized: string,
+ event: "claimed" | "reclaimed",
+ params: ClaimSlugParams,
+): void {
+ const row = findSlug(db, scope, scopeKey, normalized);
+ if (!row) return;
+ db.query(
+ "INSERT INTO slug_history (slug_id, event, subject_id, account_id, at) VALUES (?,?,?,?,?)",
+ ).run(row.id, event, params.subjectId, params.accountId, params.now);
+}
+
+export type SlugAvailability =
+ | { available: true }
+ | { available: false; reason: "invalid"; detail: SlugRejection }
+ | { available: false; reason: "taken" }
+ | { available: false; reason: "reserved"; until: number }
+ | { available: true; reason: "yours" };
+
+/**
+ * Availability for a live-checking UI.
+ *
+ * Advisory only: availability can change between this call and a claim, which
+ * is why the claim path re-checks everything transactionally rather than
+ * trusting an earlier answer.
+ */
+export function checkSlugAvailability(
+ db: Db,
+ params: { scope: SlugScope; scopeKey: string; subjectId?: string; requested: string; now: number },
+): SlugAvailability {
+ const validation = validateSlug(params.requested, params.scope);
+ if (!validation.ok) {
+ return { available: false, reason: "invalid", detail: validation.reason };
+ }
+
+ const existing = findSlug(db, params.scope, params.scopeKey, validation.normalized);
+ if (!existing) return { available: true };
+
+ const state = effectiveState(existing, params.now);
+ switch (state.kind) {
+ case "free":
+ return { available: true };
+ case "active":
+ return state.subjectId === params.subjectId
+ ? { available: true, reason: "yours" }
+ : { available: false, reason: "taken" };
+ case "reserved":
+ return state.principalId === params.subjectId
+ ? { available: true, reason: "yours" }
+ : { available: false, reason: "reserved", until: state.until };
+ }
+}
+
+/** The active slug for a subject, if any. */
+export function activeSlugFor(db: Db, scope: SlugScope, subjectId: string): SlugRow | null {
+ return slugsForSubject(db, scope, subjectId)[0] ?? null;
+}
diff --git a/apps/api/src/slugs/lifecycle.ts b/apps/api/src/slugs/lifecycle.ts
new file mode 100644
index 0000000..c04ca1c
--- /dev/null
+++ b/apps/api/src/slugs/lifecycle.ts
@@ -0,0 +1,259 @@
+import type { Db } from "../db/index.ts";
+
+/**
+ * Slug lifecycle: release, reservation, reclaim.
+ *
+ * Claiming and validation land in the next step; unclaiming a system needs
+ * release and reclaim now, and they are the security-relevant half.
+ *
+ * Two rules carry this feature:
+ *
+ * 1. Uniqueness is enforced by the database (`UNIQUE (scope, scope_key,
+ * slug_normalized)`), so a claim is a single conditional write and two
+ * simultaneous claimants cannot both win.
+ *
+ * 2. Expiry is computed at read time, never by a scheduled job. A cron that
+ * "frees expired slugs" is wrong in every failure mode: a missed run locks a
+ * slug forever, clock skew frees it early, and a slow run lets two claimants
+ * both see it as free. Deriving state from `reserved_until` at the moment of
+ * the query is always correct.
+ */
+
+export const RESERVATION_MS = 7 * 24 * 60 * 60 * 1000;
+
+export type SlugScope = "system" | "member";
+export type PrincipalType = "system" | "member";
+
+export type SlugRow = {
+ id: number;
+ scope: SlugScope;
+ scope_key: string;
+ slug_normalized: string;
+ slug_display: string;
+ state: "active" | "reserved";
+ subject_id: string | null;
+ reserved_principal_type: PrincipalType | null;
+ reserved_principal_id: string | null;
+ reserved_until: number | null;
+ claimed_at?: number | null;
+};
+
+/** What a slug effectively is right now, given the clock. */
+export type EffectiveState =
+ | { kind: "active"; subjectId: string }
+ | { kind: "reserved"; principalType: PrincipalType; principalId: string; until: number }
+ | { kind: "free" };
+
+export function effectiveState(row: SlugRow, now: number): EffectiveState {
+ if (row.state === "active" && row.subject_id) {
+ return { kind: "active", subjectId: row.subject_id };
+ }
+ if (
+ row.state === "reserved" &&
+ row.reserved_until !== null &&
+ row.reserved_principal_type !== null &&
+ row.reserved_principal_id !== null
+ ) {
+ if (now >= row.reserved_until) return { kind: "free" };
+ return {
+ kind: "reserved",
+ principalType: row.reserved_principal_type,
+ principalId: row.reserved_principal_id,
+ until: row.reserved_until,
+ };
+ }
+ return { kind: "free" };
+}
+
+export function findSlug(
+ db: Db,
+ scope: SlugScope,
+ scopeKey: string,
+ slugNormalized: string,
+): SlugRow | null {
+ return (
+ db
+ .query<SlugRow, [string, string, string]>(
+ `SELECT id, scope, scope_key, slug_normalized, slug_display, state, subject_id,
+ reserved_principal_type, reserved_principal_id, reserved_until
+ FROM slugs
+ WHERE scope = ? AND scope_key = ? AND slug_normalized = ?`,
+ )
+ .get(scope, scopeKey, slugNormalized) ?? null
+ );
+}
+
+export function slugsForSubject(db: Db, scope: SlugScope, subjectId: string): SlugRow[] {
+ return db
+ .query<SlugRow, [string, string]>(
+ `SELECT id, scope, scope_key, slug_normalized, slug_display, state, subject_id,
+ reserved_principal_type, reserved_principal_id, reserved_until, claimed_at
+ FROM slugs
+ WHERE scope = ? AND subject_id = ? AND state = 'active'`,
+ )
+ .all(scope, subjectId);
+}
+
+function recordHistory(
+ db: Db,
+ slugId: number,
+ event: "claimed" | "released" | "reclaimed" | "expired" | "transferred",
+ subjectId: string | null,
+ accountId: string | null,
+ now: number,
+): void {
+ db.query(
+ "INSERT INTO slug_history (slug_id, event, subject_id, account_id, at) VALUES (?,?,?,?,?)",
+ ).run(slugId, event, subjectId, accountId, now);
+}
+
+/**
+ * Moves an active slug into its reservation window.
+ *
+ * The reclaim right belongs to the SUBJECT — the system or member — not the
+ * account that happened to hold it (decision 6). If a system changes hands, the
+ * reclaim right goes with the system.
+ *
+ * The compare-and-swap on `state = 'active'` means a concurrent release cannot
+ * double-fire and reset the reservation clock.
+ */
+export function releaseSlug(
+ db: Db,
+ slug: SlugRow,
+ now: number,
+ accountId: string | null = null,
+): boolean {
+ if (slug.state !== "active" || !slug.subject_id) return false;
+ const principalType: PrincipalType = slug.scope;
+ const result = db
+ .query(
+ `UPDATE slugs
+ SET state = 'reserved',
+ subject_id = NULL,
+ reserved_principal_type = ?,
+ reserved_principal_id = ?,
+ reserved_until = ?,
+ released_at = ?
+ WHERE id = ? AND state = 'active'`,
+ )
+ .run(principalType, slug.subject_id, now + RESERVATION_MS, now, slug.id);
+
+ if (Number(result.changes ?? 0) === 0) return false;
+ recordHistory(db, slug.id, "released", slug.subject_id, accountId, now);
+ return true;
+}
+
+/** Releases every active slug held by a subject. Used when a system is unclaimed. */
+export function releaseSlugsForSubject(
+ db: Db,
+ scope: SlugScope,
+ subjectId: string,
+ now: number,
+ accountId: string | null = null,
+): number {
+ let released = 0;
+ for (const slug of slugsForSubject(db, scope, subjectId)) {
+ if (releaseSlug(db, slug, now, accountId)) released += 1;
+ }
+ return released;
+}
+
+export type ReclaimResult =
+ | { ok: true }
+ | { ok: false; reason: "not_reserved" | "reserved_for_someone_else" | "expired" };
+
+/**
+ * Returns a reserved slug to its previous subject.
+ *
+ * The guard runs inside the UPDATE rather than as a prior SELECT, so a claim
+ * arriving between the check and the write cannot slip through.
+ */
+export function reclaimSlug(
+ db: Db,
+ slug: SlugRow,
+ subjectId: string,
+ now: number,
+ accountId: string | null = null,
+): ReclaimResult {
+ const state = effectiveState(slug, now);
+ if (state.kind === "active") return { ok: false, reason: "not_reserved" };
+ if (state.kind === "free") return { ok: false, reason: "expired" };
+ if (state.principalId !== subjectId) {
+ return { ok: false, reason: "reserved_for_someone_else" };
+ }
+
+ const result = db
+ .query(
+ `UPDATE slugs
+ SET state = 'active',
+ subject_id = ?,
+ reserved_principal_type = NULL,
+ reserved_principal_id = NULL,
+ reserved_until = NULL,
+ claimed_at = ?
+ WHERE id = ?
+ AND state = 'reserved'
+ AND reserved_principal_id = ?
+ AND reserved_until > ?`,
+ )
+ .run(subjectId, now, slug.id, subjectId, now);
+
+ if (Number(result.changes ?? 0) === 0) return { ok: false, reason: "expired" };
+ recordHistory(db, slug.id, "reclaimed", subjectId, accountId, now);
+ return { ok: true };
+}
+
+/** Reclaims every slug still reserved for a subject. Used when a system is
+ * re-claimed inside its grace window. */
+export function reclaimSlugsForSubject(
+ db: Db,
+ scope: SlugScope,
+ subjectId: string,
+ now: number,
+ accountId: string | null = null,
+): number {
+ const rows = db
+ .query<SlugRow, [string, string]>(
+ `SELECT id, scope, scope_key, slug_normalized, slug_display, state, subject_id,
+ reserved_principal_type, reserved_principal_id, reserved_until
+ FROM slugs
+ WHERE scope = ? AND state = 'reserved' AND reserved_principal_id = ?`,
+ )
+ .all(scope, subjectId);
+
+ let reclaimed = 0;
+ for (const row of rows) {
+ if (reclaimSlug(db, row, subjectId, now, accountId).ok) reclaimed += 1;
+ }
+ return reclaimed;
+}
+
+/**
+ * Slugs still held in reservation for a subject, newest first.
+ *
+ * These are addresses this system or member released and can still take back.
+ * Expiry is evaluated here against the clock rather than read from a state
+ * column, so a lapsed reservation simply stops appearing.
+ */
+export function reservationsForSubject(
+ db: Db,
+ scope: SlugScope,
+ subjectId: string,
+ now: number,
+): Array<{ slug: string; until: number }> {
+ return db
+ .query<SlugRow, [string, string]>(
+ `SELECT id, scope, scope_key, slug_normalized, slug_display, state, subject_id,
+ reserved_principal_type, reserved_principal_id, reserved_until
+ FROM slugs
+ WHERE scope = ? AND state = 'reserved' AND reserved_principal_id = ?
+ ORDER BY reserved_until DESC`,
+ )
+ .all(scope, subjectId)
+ .flatMap((row) => {
+ const state = effectiveState(row, now);
+ return state.kind === "reserved"
+ ? [{ slug: row.slug_display, until: state.until }]
+ : [];
+ });
+}
diff --git a/apps/api/src/slugs/normalize.ts b/apps/api/src/slugs/normalize.ts
new file mode 100644
index 0000000..4bc7758
--- /dev/null
+++ b/apps/api/src/slugs/normalize.ts
@@ -0,0 +1,172 @@
+/**
+ * Slug normalisation and validation.
+ *
+ * A PluralKit ID is immutable external identity. A pkviewer slug is a mutable,
+ * human-readable navigation label. They are never interchangeable: grants,
+ * cache keys, foreign keys and reservations are all keyed on PluralKit's UUID,
+ * never on a slug and never on a HID.
+ *
+ * MVP restricts slugs to [a-z0-9-] (decision 4). That eliminates homograph
+ * squatting outright rather than mitigating it — no Cyrillic "а" masquerading
+ * as Latin "a" — and Unicode slugs can be added later behind a confusable
+ * folding pass without changing any of this.
+ */
+
+export type SlugScope = "system" | "member";
+
+/**
+ * Maximum length is deliberately below 36, the length of a UUID.
+ *
+ * That single constraint guarantees a UUID can never be mistaken for a slug, so
+ * `/s/<uuid>` is always an unambiguous route to a system regardless of what
+ * slugs anyone claims. It is the escape hatch that makes slug-first resolution
+ * safe.
+ */
+export const SLUG_MAX_LENGTH = 32;
+
+/** Systems live in one global namespace, where short names are contested, so
+ * they carry a higher floor than members, who are namespaced per system. */
+export const SYSTEM_SLUG_MIN_LENGTH = 3;
+export const MEMBER_SLUG_MIN_LENGTH = 2;
+
+/**
+ * Reserved at the system level.
+ *
+ * `/s/` already namespaces system slugs away from application routes, so this
+ * is mostly future-proofing: it keeps the door open to per-system subdomains or
+ * bare-path URLs without having to claw names back from people who hold them.
+ */
+export const RESERVED_SLUGS: ReadonlySet<string> = new Set([
+ "about", "abuse", "account", "accounts", "admin", "administrator", "api",
+ "app", "assets", "auth", "billing", "blog", "cdn", "contact", "dashboard",
+ "dev", "docs", "documentation", "edit", "email", "faq", "favicon", "help",
+ "home", "id", "ids", "images", "img", "legal", "login", "logout", "mail",
+ "manage", "me", "media", "member", "members", "my", "new", "news", "null",
+ "pk", "pkviewer", "privacy", "public", "robots", "root", "s", "search",
+ "security", "settings", "signin", "signout", "signup", "sitemap", "static",
+ "status", "support", "system", "systems", "terms", "undefined", "user",
+ "users", "www",
+]);
+
+export type SlugRejection =
+ | "empty"
+ | "too_short"
+ | "too_long"
+ | "invalid_characters"
+ | "edge_hyphen"
+ | "double_hyphen"
+ | "reserved"
+ | "id_shaped";
+
+export type SlugValidation =
+ | { ok: true; normalized: string; display: string }
+ | { ok: false; reason: SlugRejection };
+
+/**
+ * Casefolds and normalises a candidate slug.
+ *
+ * NFKC runs first so visually identical inputs collapse before validation; any
+ * character that survives outside [a-z0-9-] is then rejected rather than
+ * silently transliterated. Silently rewriting someone's input into a different
+ * slug than they typed is worse than telling them it is not allowed.
+ *
+ * SQLite's COLLATE NOCASE is ASCII-only and cannot be trusted for uniqueness,
+ * so normalisation happens here and `slug_normalized` is the unique column.
+ */
+export function normalizeSlug(input: string): string {
+ return input.normalize("NFKC").trim().toLowerCase();
+}
+
+export function validateSlug(input: string, scope: SlugScope): SlugValidation {
+ const normalized = normalizeSlug(input);
+
+ if (normalized.length === 0) return { ok: false, reason: "empty" };
+
+ const min = scope === "system" ? SYSTEM_SLUG_MIN_LENGTH : MEMBER_SLUG_MIN_LENGTH;
+ if (normalized.length < min) return { ok: false, reason: "too_short" };
+ if (normalized.length > SLUG_MAX_LENGTH) return { ok: false, reason: "too_long" };
+
+ if (!/^[a-z0-9-]+$/.test(normalized)) return { ok: false, reason: "invalid_characters" };
+ if (normalized.startsWith("-") || normalized.endsWith("-")) {
+ return { ok: false, reason: "edge_hyphen" };
+ }
+ // Invariant L1b: a slug must not contain "--" ANYWHERE. Stated as the literal
+ // substring rather than "no consecutive hyphens" so every validator enforces
+ // exactly the same rule. The purpose is to keep the punycode marker "xn--"
+ // unclaimable, so slugs stay safe to place in a hostname if per-system
+ // subdomains ever happen.
+ if (normalized.includes("--")) return { ok: false, reason: "double_hyphen" };
+
+ // Reserved names apply to the global system namespace. Member slugs live
+ // under their system, so they cannot collide with application routes.
+ if (scope === "system" && RESERVED_SLUGS.has(normalized)) {
+ return { ok: false, reason: "reserved" };
+ }
+
+ // A system slug may not take the shape of a PluralKit short id.
+ //
+ // System slugs and system ids share ONE global namespace at /s/<ref>, so a
+ // slug shaped like an id could shadow the id URL of somebody else's system —
+ // cross-tenant hijacking of a URL its owner never gave up. Removing the shape
+ // from the namespace removes the ambiguity entirely, with no lookup needed.
+ //
+ // Member slugs are deliberately NOT restricted this way: they are namespaced
+ // per system, so a collision can only ever shadow another member of the same
+ // system, which the claimant already controls. That is self-inflicted rather
+ // than an attack, so it is warned about at claim time instead of forbidden —
+ // which keeps ordinary names like "clove" available where people want them.
+ if (scope === "system" && looksLikeHid(normalized)) {
+ return { ok: false, reason: "id_shaped" };
+ }
+
+ return { ok: true, normalized, display: normalized };
+}
+
+/**
+ * True for a Discord snowflake.
+ *
+ * PluralKit will happily resolve a linked Discord account id to its system, and
+ * that is exactly what tier-1 claiming relies on. It must NOT be reachable as a
+ * public pkviewer URL, though: `/s/<snowflake>` would turn the Discord-account
+ * to system mapping into something anyone can browse by guessing ids. Tier-1
+ * verification uses this lookup with ids taken from the session; public
+ * resolution refuses it.
+ */
+export function looksLikeSnowflake(ref: string): boolean {
+ return /^\d{16,20}$/.test(ref);
+}
+
+/** True for a PluralKit UUID. Always unambiguous — a UUID is longer than any
+ * slug may be, so it can never be shadowed. */
+export function looksLikeUuid(ref: string): boolean {
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(ref);
+}
+
+/**
+ * True for the shape of a PluralKit short id: 5 or 6 lowercase letters.
+ *
+ * Used to keep the shape out of the SYSTEM slug namespace, and to decide
+ * whether a reference is worth trying as an id at all. Member slugs are not
+ * restricted by it.
+ *
+ * This encodes an assumption about PluralKit's id format: 5 or 6 lowercase
+ * letters. If PluralKit ever issues ids containing digits, system slugs claimed
+ * before that change could shadow one. The UUID form of every URL stays
+ * unambiguous regardless, because a UUID is longer than any slug may be.
+ */
+export function looksLikeHid(ref: string): boolean {
+ return /^[a-z]{5,6}$/.test(ref);
+}
+
+export const SLUG_REJECTION_MESSAGES: Readonly<Record<SlugRejection, string>> = {
+ empty: "Enter a slug.",
+ too_short: "That is too short.",
+ too_long: `Use ${SLUG_MAX_LENGTH} characters or fewer.`,
+ invalid_characters: "Use lowercase letters, numbers and hyphens only.",
+ edge_hyphen: "Slugs cannot start or end with a hyphen.",
+ double_hyphen: "Slugs cannot contain two hyphens in a row.",
+ reserved: "That name is reserved.",
+ id_shaped:
+ "System slugs cannot be 5 or 6 letters with no numbers or hyphens, because " +
+ "that is the shape of a PluralKit system ID. Add a number or a hyphen.",
+};
diff --git a/apps/api/src/slugs/resolve.ts b/apps/api/src/slugs/resolve.ts
new file mode 100644
index 0000000..b7b4663
--- /dev/null
+++ b/apps/api/src/slugs/resolve.ts
@@ -0,0 +1,227 @@
+import type { Db } from "../db/index.ts";
+import type { PkClient } from "../pk/client.ts";
+import { PkNotFound } from "../pk/errors.ts";
+import type { PkMember, PkSystem } from "../pk/types.ts";
+import { activeSlugFor } from "./claim.ts";
+import { effectiveState, findSlug } from "./lifecycle.ts";
+import { looksLikeSnowflake, normalizeSlug } from "./normalize.ts";
+
+/**
+ * Resolving `/s/<ref>` and `/s/<ref>/<memberRef>`.
+ *
+ * Both the PluralKit id and the pkviewer slug resolve (decision 8), and the
+ * slug is canonical. Neither is a redirect: a 301 would outlive slug ownership
+ * and permanently point a cached URL at whoever holds the name next, so both
+ * forms return 200 and the canonical one is advertised via <link rel=canonical>.
+ *
+ * Resolution order is slug first, then id. That is safe because a system slug
+ * can never take the shape of a system id (see normalize.ts), so the two
+ * namespaces do not overlap at the system level.
+ */
+
+export type ResolvedSystem = {
+ system: PkSystem;
+ /** Our row, when the system has been claimed here. */
+ systemId: string | null;
+ slug: string | null;
+ matchedBy: "slug" | "id";
+ /** The URL this page should advertise as canonical. */
+ canonicalPath: string;
+ /**
+ * The reference the PluralKit response was actually cached under.
+ *
+ * A slug resolves via the stored UUID while an id resolves via the id itself,
+ * so callers asking "how old is this data" must use the same key the fetch
+ * used. Guessing the UUID silently misses for id-based URLs, which is how the
+ * stale-data notice came to appear on address URLs but not id URLs.
+ */
+ cacheRef: string;
+};
+
+export type ResolveFailure = "not_found" | "unsupported_reference" | "upstream_unavailable";
+
+export type ResolveResult<T> = { ok: true; value: T } | { ok: false; reason: ResolveFailure };
+
+/** Path for a system, preferring its slug. */
+export function systemPath(hid: string, slug: string | null): string {
+ return `/s/${slug ?? hid}`;
+}
+
+/** Path for a member, preferring slugs at both levels. */
+export function memberPath(
+ systemHid: string,
+ systemSlug: string | null,
+ memberHid: string,
+ memberSlug: string | null,
+): string {
+ return `${systemPath(systemHid, systemSlug)}/${memberSlug ?? memberHid}`;
+}
+
+/**
+ * Resolves a public system reference.
+ *
+ * A Discord snowflake is refused. PluralKit resolves a linked account id to its
+ * system, which is what tier-1 claiming depends on, but accepting it here would
+ * turn the Discord-account to system mapping into something anyone could browse
+ * by walking ids. Claiming uses that lookup with ids taken from the session;
+ * public URLs do not expose it.
+ */
+export async function resolveSystemRef(
+ deps: { db: Db; pk: PkClient; now?: () => number },
+ ref: string,
+): Promise<ResolveResult<ResolvedSystem>> {
+ const now = deps.now?.() ?? Date.now();
+
+ if (looksLikeSnowflake(ref)) return { ok: false, reason: "unsupported_reference" };
+
+ const normalized = normalizeSlug(ref);
+ const slugRow = findSlug(deps.db, "system", "", normalized);
+
+ if (slugRow) {
+ const state = effectiveState(slugRow, now);
+ if (state.kind === "active") {
+ const row = deps.db
+ .query<{ pk_system_uuid: string; pk_system_hid: string }, [string]>(
+ "SELECT pk_system_uuid, pk_system_hid FROM systems WHERE id = ?",
+ )
+ .get(state.subjectId);
+ if (row) {
+ try {
+ const system = await deps.pk.getSystem(row.pk_system_uuid);
+ return {
+ ok: true,
+ value: {
+ system,
+ systemId: state.subjectId,
+ slug: slugRow.slug_display,
+ matchedBy: "slug",
+ canonicalPath: systemPath(system.id, slugRow.slug_display),
+ cacheRef: row.pk_system_uuid,
+ },
+ };
+ } catch (err) {
+ return { ok: false, reason: failureFor(err) };
+ }
+ }
+ }
+ // A reserved or lapsed slug is not a live page. Falling through lets the
+ // same string still resolve as a PluralKit id if it happens to be one.
+ }
+
+ try {
+ const system = await deps.pk.getSystem(ref);
+ const local = deps.db
+ .query<{ id: string }, [string]>("SELECT id FROM systems WHERE pk_system_uuid = ?")
+ .get(system.uuid);
+ const slug = local ? (activeSlugFor(deps.db, "system", local.id)?.slug_display ?? null) : null;
+
+ return {
+ ok: true,
+ value: {
+ system,
+ systemId: local?.id ?? null,
+ slug,
+ matchedBy: "id",
+ canonicalPath: systemPath(system.id, slug),
+ cacheRef: ref,
+ },
+ };
+ } catch (err) {
+ return { ok: false, reason: failureFor(err) };
+ }
+}
+
+export type ResolvedMember = {
+ member: PkMember;
+ memberId: string | null;
+ slug: string | null;
+ matchedBy: "slug" | "id";
+ canonicalPath: string;
+};
+
+/**
+ * Resolves a member within an already-resolved system.
+ *
+ * Member slugs MAY take the shape of a member id, because their namespace is
+ * scoped to one system. Slug wins when both match, so a deliberate slug always
+ * beats an incidental id collision inside the same system — and claiming such a
+ * slug warns the owner that it shadows a sibling's id URL.
+ *
+ * Members that PluralKit does not return publicly are simply absent here, which
+ * is what makes a private member indistinguishable from one that never existed
+ * (decision 5).
+ */
+export async function resolveMemberRef(
+ deps: { db: Db; pk: PkClient; now?: () => number },
+ system: ResolvedSystem,
+ memberRef: string,
+): Promise<ResolveResult<ResolvedMember>> {
+ const now = deps.now?.() ?? Date.now();
+ const normalized = normalizeSlug(memberRef);
+
+ let members: PkMember[];
+ try {
+ members = await deps.pk.getMembers(system.system.uuid);
+ } catch (err) {
+ return { ok: false, reason: failureFor(err) };
+ }
+
+ if (system.systemId) {
+ const slugRow = findSlug(deps.db, "member", system.systemId, normalized);
+ if (slugRow) {
+ const state = effectiveState(slugRow, now);
+ if (state.kind === "active") {
+ const row = deps.db
+ .query<{ pk_member_uuid: string }, [string]>(
+ "SELECT pk_member_uuid FROM members WHERE id = ?",
+ )
+ .get(state.subjectId);
+ const member = row ? members.find((m) => m.uuid === row.pk_member_uuid) : undefined;
+ // A slug pointing at a member PluralKit no longer returns publicly
+ // resolves to nothing, rather than revealing that the member exists.
+ if (member) {
+ return {
+ ok: true,
+ value: {
+ member,
+ memberId: state.subjectId,
+ slug: slugRow.slug_display,
+ matchedBy: "slug",
+ canonicalPath: memberPath(
+ system.system.id,
+ system.slug,
+ member.id,
+ slugRow.slug_display,
+ ),
+ },
+ };
+ }
+ }
+ }
+ }
+
+ const byId = members.find(
+ (m) => m.id.toLowerCase() === normalized || m.uuid.toLowerCase() === normalized,
+ );
+ if (!byId) return { ok: false, reason: "not_found" };
+
+ const local = deps.db
+ .query<{ id: string }, [string]>("SELECT id FROM members WHERE pk_member_uuid = ?")
+ .get(byId.uuid);
+ const slug = local ? (activeSlugFor(deps.db, "member", local.id)?.slug_display ?? null) : null;
+
+ return {
+ ok: true,
+ value: {
+ member: byId,
+ memberId: local?.id ?? null,
+ slug,
+ matchedBy: "id",
+ canonicalPath: memberPath(system.system.id, system.slug, byId.id, slug),
+ },
+ };
+}
+
+function failureFor(err: unknown): ResolveFailure {
+ return err instanceof PkNotFound ? "not_found" : "upstream_unavailable";
+}
diff --git a/apps/api/test/audit.test.ts b/apps/api/test/audit.test.ts
new file mode 100644
index 0000000..ea25503
--- /dev/null
+++ b/apps/api/test/audit.test.ts
@@ -0,0 +1,488 @@
+import { describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import { claimViaDiscordLink, ensureSystemRow } from "../src/claims/index.ts";
+import { openDb, type Db } from "../src/db/index.ts";
+import { migrate } from "../src/db/migrate.ts";
+import { saveTheme } from "../src/manage/index.ts";
+import { PkClient } from "../src/pk/client.ts";
+import { resolveTheme } from "@pkviewer/shared";
+import { MemorySnapshotStore } from "../src/pk/snapshots.ts";
+import { buildMemberPage, buildSystemPage } from "../src/public/page-model.ts";
+
+/**
+ * Regressions found during the end-to-end audit.
+ *
+ * Most of these guard behaviour that was previously only checked by hand.
+ */
+
+const SYS = { id: "tythty", uuid: "8b0655f4-055a-46b9-a5fc-a099e8a6b810", name: "Doughmination", description: null };
+const MEMBERS = [
+ { id: "kzsbyo", uuid: "mu-1", name: "Clove", display_name: null, pronouns: "she/her", birthday: "2000-01-01", description: "first", avatar_url: null, banner: null, color: null, created: null },
+ { id: "wrenxy", uuid: "mu-2", name: "Ash", display_name: null, pronouns: "they/them", birthday: null, description: "second", avatar_url: null, banner: null, color: null, created: null },
+];
+
+function freshDb(): Db {
+ const db = openDb(":memory:");
+ migrate(db);
+ return db;
+}
+
+function pkClient(members: unknown[] = MEMBERS, system: unknown = SYS) {
+ const impl = (async (input: string | URL) => {
+ const path = String(input).replace("https://api.pluralkit.me/v2", "");
+ if (path.endsWith("/members")) return Response.json(members);
+ const ref = decodeURIComponent(path.replace("/systems/", ""));
+ const s = system as { id: string; uuid: string };
+ return ref === s.uuid || ref === s.id || ref === "111"
+ ? Response.json(system)
+ : new Response("", { status: 404 });
+ }) as unknown as typeof fetch;
+
+ return new PkClient({
+ apiBase: "https://api.pluralkit.me/v2",
+ userAgent: "pkviewer/test (+https://github.com/owner/pkviewer)",
+ readRps: 1000,
+ writeRps: 1000,
+ fetchImpl: impl,
+ snapshots: new MemorySnapshotStore(),
+ sleep: async () => {},
+ maxRetries: 0,
+ });
+}
+
+function account(db: Db): string {
+ const id = randomUUID();
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run(id, Date.now());
+ return id;
+}
+
+describe("claimed systems stay internally consistent", () => {
+ /**
+ * A system row's stored PluralKit UUID must be the one the claim source
+ * returned. A mismatch makes the address resolve to a system PluralKit does
+ * not have, so the chosen address 404s while the ID address still works —
+ * which is exactly the confusing state a hand-written fixture produced during
+ * the step 10 audit.
+ */
+ test("the stored external id is the one the claim source returned", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const pk = pkClient();
+
+ const result = await claimViaDiscordLink(
+ { db, pk },
+ { accountId: acct, discordIds: ["111"], pkSystemRef: "tythty" },
+ );
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+
+ const row = db
+ .query<{ pk_system_uuid: string; pk_system_hid: string }, [string]>(
+ "SELECT pk_system_uuid, pk_system_hid FROM systems WHERE id = ?",
+ )
+ .get(result.systemId);
+
+ expect(row?.pk_system_uuid).toBe(SYS.uuid);
+ expect(row?.pk_system_hid).toBe(SYS.id);
+ db.close();
+ });
+
+ test("every stored system row resolves to a page", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const pk = pkClient();
+ await claimViaDiscordLink(
+ { db, pk },
+ { accountId: acct, discordIds: ["111"], pkSystemRef: "tythty" },
+ );
+
+ const rows = db
+ .query<{ pk_system_uuid: string }, []>("SELECT pk_system_uuid FROM systems")
+ .all();
+ for (const row of rows) {
+ const page = await buildSystemPage({ db, pk }, row.pk_system_uuid);
+ expect(page.ok, row.pk_system_uuid).toBe(true);
+ }
+ db.close();
+ });
+});
+
+describe("layout settings reach the public page", () => {
+ function claimedSystem(db: Db): string {
+ const systemId = ensureSystemRow(db, SYS as never, Date.now());
+ const acct = account(db);
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(acct, systemId, Date.now());
+ return systemId;
+ }
+
+ // Composition was editable in /manage long before it changed anything a
+ // visitor could see. That is worse than an unimplemented feature: the setting
+ // saved, and appeared to work.
+ test("system composition is resolved into the page model", async () => {
+ const db = freshDb();
+ const systemId = claimedSystem(db);
+ const acct = account(db);
+
+ saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId: acct,
+ now: 1,
+ composition: { "directory.columns": "two", "show.pronouns": "false" },
+ });
+
+ const page = await buildSystemPage({ db, pk: pkClient() }, "tythty");
+ expect(page.ok).toBe(true);
+ if (!page.ok) return;
+ expect(page.value.composition["directory.columns"]).toBe("two");
+ expect(page.value.composition["show.pronouns"]).toBe("false");
+ db.close();
+ });
+
+ test("unset composition still arrives fully resolved with platform defaults", async () => {
+ const db = freshDb();
+ claimedSystem(db);
+ const page = await buildSystemPage({ db, pk: pkClient() }, "tythty");
+ expect(page.ok).toBe(true);
+ if (!page.ok) return;
+ expect(page.value.composition["directory.columns"]).toBe("auto");
+ expect(page.value.composition["show.birthday"]).toBe("true");
+ db.close();
+ });
+
+ test("a member override reaches the page, and system-only values do not", async () => {
+ const db = freshDb();
+ const systemId = claimedSystem(db);
+ const acct = account(db);
+ const memberId = randomUUID();
+ db.query(
+ "INSERT INTO members (id, system_id, pk_member_uuid, pk_member_hid, first_seen_at) VALUES (?,?,?,?,?)",
+ ).run(memberId, systemId, "mu-1", "kzsbyo", Date.now());
+
+ saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId: acct,
+ now: 1,
+ composition: { "banner.display": "auto", "directory.columns": "two" },
+ });
+ saveTheme(db, {
+ ownerType: "member",
+ ownerId: memberId,
+ accountId: acct,
+ now: 2,
+ composition: { "banner.display": "hidden" },
+ });
+
+ const page = await buildMemberPage({ db, pk: pkClient() }, "tythty", "kzsbyo");
+ expect(page.ok).toBe(true);
+ if (!page.ok) return;
+ expect(page.value.composition["banner.display"]).toBe("hidden");
+ // Not member-overridable, so the system's value stands.
+ expect(page.value.composition["directory.columns"]).toBe("two");
+ db.close();
+ });
+
+ // All-or-nothing (M3) and member-overridability interact: a save containing a
+ // system-only key is rejected entirely, rather than partially applied.
+ test("a member save containing a system-only value is rejected whole", () => {
+ const db = freshDb();
+ const systemId = claimedSystem(db);
+ const acct = account(db);
+ const memberId = randomUUID();
+ db.query(
+ "INSERT INTO members (id, system_id, pk_member_uuid, pk_member_hid, first_seen_at) VALUES (?,?,?,?,?)",
+ ).run(memberId, systemId, "mu-1", "kzsbyo", Date.now());
+
+ const result = saveTheme(db, {
+ ownerType: "member",
+ ownerId: memberId,
+ accountId: acct,
+ now: 1,
+ composition: { "banner.display": "hidden", "directory.columns": "three" },
+ });
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.rejected.map((r) => r.key)).toEqual(["directory.columns"]);
+ }
+ // Nothing was written, including the value that was on its own acceptable.
+ const stored = db
+ .query<{ composition: string }, [string]>(
+ "SELECT composition FROM themes WHERE owner_type = 'member' AND owner_id = ?",
+ )
+ .get(memberId);
+ expect(stored).toBeNull();
+ db.close();
+ });
+});
+
+describe("public/private boundary", () => {
+ test("public pages need no session and expose no account information", async () => {
+ const db = freshDb();
+ ensureSystemRow(db, SYS as never, Date.now());
+
+ const page = await buildSystemPage({ db, pk: pkClient() }, "tythty");
+ expect(page.ok).toBe(true);
+ if (!page.ok) return;
+
+ // "token" is deliberately absent from this list: `tokens` is the theme
+ // field name, so it would match legitimate output and make the test useless.
+ const dump = JSON.stringify(page.value).toLowerCase();
+ for (const leak of [
+ "account",
+ "grant",
+ "discord",
+ "session",
+ "authorization",
+ "pk_token",
+ "updated_by",
+ ]) {
+ expect(dump, leak).not.toContain(leak);
+ }
+ db.close();
+ });
+
+ test("a member PluralKit withholds never appears in the page model", async () => {
+ const db = freshDb();
+ ensureSystemRow(db, SYS as never, Date.now());
+ const pk = pkClient([MEMBERS[0]]);
+
+ const page = await buildSystemPage({ db, pk }, "tythty");
+ expect(page.ok).toBe(true);
+ if (!page.ok) return;
+ expect(page.value.members.map((m) => m.hid)).toEqual(["kzsbyo"]);
+ expect(JSON.stringify(page.value)).not.toContain("wrenxy");
+
+ // And is not reachable directly.
+ const direct = await buildMemberPage({ db, pk }, "tythty", "wrenxy");
+ expect(direct).toEqual({ ok: false, reason: "not_found" });
+ db.close();
+ });
+
+ test("a Discord snowflake cannot be used to reach a system page", async () => {
+ const db = freshDb();
+ ensureSystemRow(db, SYS as never, Date.now());
+ const page = await buildSystemPage({ db, pk: pkClient() }, "123456789012345678");
+ expect(page).toEqual({ ok: false, reason: "unsupported_reference" });
+ db.close();
+ });
+});
+
+describe("no absolute pkviewer URL is ever persisted", () => {
+ test("across every table after a full configuration", async () => {
+ const db = freshDb();
+ const systemId = ensureSystemRow(db, SYS as never, Date.now());
+ const acct = account(db);
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(acct, systemId, Date.now());
+ saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId: acct,
+ now: 1,
+ tokens: { "color.accent": "#112233" },
+ composition: { "directory.card": "detailed" },
+ });
+ db.query(
+ "INSERT INTO slugs (scope, scope_key, slug_normalized, slug_display, state, subject_id, claimed_at) VALUES ('system','','doughmination','doughmination','active',?,?)",
+ ).run(systemId, Date.now());
+
+ const tables = db
+ .query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE type='table'")
+ .all()
+ .map((r) => r.name);
+
+ for (const table of tables) {
+ const dump = JSON.stringify(db.query(`SELECT * FROM ${table}`).all());
+ // PluralKit's own asset URLs are external and legitimately stored in the
+ // response cache; ours never are.
+ expect(dump, table).not.toContain("system.localhost");
+ expect(dump, table).not.toContain("app.localhost");
+ }
+ db.close();
+ });
+});
+
+describe("stale upstream data", () => {
+ test("a page still renders from the last good snapshot", async () => {
+ let up = true;
+ const impl = (async (input: string | URL) => {
+ if (!up) return new Response("", { status: 502 });
+ const path = String(input).replace("https://api.pluralkit.me/v2", "");
+ return path.endsWith("/members") ? Response.json(MEMBERS) : Response.json(SYS);
+ }) as unknown as typeof fetch;
+
+ let now = 1_000_000;
+ const pk = new PkClient({
+ apiBase: "https://api.pluralkit.me/v2",
+ userAgent: "pkviewer/test (+https://github.com/owner/pkviewer)",
+ readRps: 1000,
+ writeRps: 1000,
+ fetchImpl: impl,
+ snapshots: new MemorySnapshotStore(),
+ sleep: async () => {},
+ maxRetries: 0,
+ clock: () => now,
+ defaultMaxAgeMs: 1000,
+ });
+
+ const db = freshDb();
+ ensureSystemRow(db, SYS as never, now);
+
+ expect((await buildSystemPage({ db, pk, now: () => now }, "tythty")).ok).toBe(true);
+
+ up = false;
+ now += 600_000;
+
+ const page = await buildSystemPage({ db, pk, now: () => now }, "tythty");
+ expect(page.ok).toBe(true);
+ if (!page.ok) return;
+ // The page reports its own staleness so the renderer can say so.
+ expect(page.value.system.staleSinceMs).toBeGreaterThan(0);
+ db.close();
+ });
+});
+
+describe("hidden fields are removed, not merely styled away", () => {
+ function claimed(db: Db): { systemId: string; acct: string } {
+ const systemId = ensureSystemRow(db, SYS as never, Date.now());
+ const acct = account(db);
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(acct, systemId, Date.now());
+ return { systemId, acct };
+ }
+
+ // A visibility setting that only hides a value in markup still ships it in
+ // the page source. This is public PluralKit data either way, but a setting
+ // should do what it says.
+ test("pronouns and birthdays are absent from the model when hidden", async () => {
+ const db = freshDb();
+ const { systemId, acct } = claimed(db);
+ saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId: acct,
+ now: 1,
+ composition: { "show.pronouns": "false", "show.birthday": "false" },
+ });
+
+ const page = await buildSystemPage({ db, pk: pkClient() }, "tythty");
+ expect(page.ok).toBe(true);
+ if (!page.ok) return;
+
+ const dump = JSON.stringify(page.value);
+ expect(dump).not.toContain("she/her");
+ expect(dump).not.toContain("they/them");
+ expect(dump).not.toContain("2000-01-01");
+ for (const m of page.value.members) {
+ expect(m.pronouns).toBeNull();
+ expect(m.birthday).toBeNull();
+ }
+ db.close();
+ });
+
+ test("they are present again when shown", async () => {
+ const db = freshDb();
+ claimed(db);
+ const page = await buildSystemPage({ db, pk: pkClient() }, "tythty");
+ expect(page.ok).toBe(true);
+ if (!page.ok) return;
+ expect(page.value.members[0]?.pronouns).toBe("she/her");
+ expect(page.value.members[0]?.birthday).toBe("2000-01-01");
+ db.close();
+ });
+
+ test("a hidden banner is not published either", async () => {
+ const db = freshDb();
+ const { systemId, acct } = claimed(db);
+ const withBanner = { ...SYS, banner: "https://example.test/banner.png" };
+ saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId: acct,
+ now: 1,
+ composition: { "banner.display": "hidden" },
+ });
+
+ const page = await buildSystemPage({ db, pk: pkClient(MEMBERS, withBanner) }, "tythty");
+ expect(page.ok).toBe(true);
+ if (!page.ok) return;
+ expect(page.value.system.bannerUrl).toBeNull();
+ expect(JSON.stringify(page.value)).not.toContain("banner.png");
+ db.close();
+ });
+});
+
+describe("the reset state survives storage", () => {
+ /**
+ * A member reset is stored as an explicit null. Reading it back through a
+ * filter that only accepted strings silently collapsed three inheritance
+ * states into two, so "use the platform default" landed on the system's value
+ * instead — visible only on the live page, never in a unit test of resolution.
+ */
+ test("an explicit reset lands on the platform default, not the system value", async () => {
+ const db = freshDb();
+ const systemId = ensureSystemRow(db, SYS as never, Date.now());
+ const acct = account(db);
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(acct, systemId, Date.now());
+ const memberId = randomUUID();
+ db.query(
+ "INSERT INTO members (id, system_id, pk_member_uuid, pk_member_hid, first_seen_at) VALUES (?,?,?,?,?)",
+ ).run(memberId, systemId, "mu-1", "kzsbyo", Date.now());
+
+ saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId: acct,
+ now: 1,
+ tokens: { "color.accent": "#2E7D5B" },
+ });
+ saveTheme(db, {
+ ownerType: "member",
+ ownerId: memberId,
+ accountId: acct,
+ now: 2,
+ tokens: { "color.accent": null },
+ });
+
+ const page = await buildMemberPage({ db, pk: pkClient() }, "tythty", "kzsbyo");
+ expect(page.ok).toBe(true);
+ if (!page.ok) return;
+
+ // The key is absent from the merged tokens, so resolution falls to the
+ // platform default rather than inheriting the system's colour.
+ expect(page.value.tokens["color.accent"]).toBeUndefined();
+ expect(resolveTheme(page.value.tokens, {}).light["color.accent"]).toBe("#A23B72");
+ db.close();
+ });
+
+ test("inheriting (key absent) still takes the system value", async () => {
+ const db = freshDb();
+ const systemId = ensureSystemRow(db, SYS as never, Date.now());
+ const acct = account(db);
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(acct, systemId, Date.now());
+ const memberId = randomUUID();
+ db.query(
+ "INSERT INTO members (id, system_id, pk_member_uuid, pk_member_hid, first_seen_at) VALUES (?,?,?,?,?)",
+ ).run(memberId, systemId, "mu-1", "kzsbyo", Date.now());
+
+ saveTheme(db, {
+ ownerType: "system", ownerId: systemId, accountId: acct, now: 1,
+ tokens: { "color.accent": "#2E7D5B" },
+ });
+ saveTheme(db, { ownerType: "member", ownerId: memberId, accountId: acct, now: 2, tokens: {} });
+
+ const page = await buildMemberPage({ db, pk: pkClient() }, "tythty", "kzsbyo");
+ expect(page.ok && page.value.tokens["color.accent"]).toBe("#2E7D5B");
+ db.close();
+ });
+});
diff --git a/apps/api/test/auth.test.ts b/apps/api/test/auth.test.ts
new file mode 100644
index 0000000..29b3790
--- /dev/null
+++ b/apps/api/test/auth.test.ts
@@ -0,0 +1,325 @@
+import { describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import {
+ createPkcePair,
+ safeEqual,
+ sha256,
+ signedValue,
+ verifySignedValue,
+} from "../src/auth/crypto.ts";
+import { buildAuthorizeUrl, pickRedirectUri } from "../src/auth/discord.ts";
+import {
+ ABSOLUTE_TTL_MS,
+ createSession,
+ findAccountByDiscordId,
+ IDLE_TTL_MS,
+ resolveSession,
+ revokeAllSessionsForAccount,
+ revokeSession,
+ rotateSession,
+ upsertAccountForDiscord,
+} from "../src/auth/sessions.ts";
+import { openDb } from "../src/db/index.ts";
+import { migrate } from "../src/db/migrate.ts";
+import { canClaim, safeReturnTo } from "../src/http/routes/auth.ts";
+import { loadConfig } from "../src/config/index.ts";
+
+function freshDb() {
+ const db = openDb(":memory:");
+ migrate(db);
+ return db;
+}
+
+function seedAccount(db: ReturnType<typeof freshDb>, now = Date.now()) {
+ const id = randomUUID();
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run(id, now);
+ return id;
+}
+
+const baseEnv = {
+ PUBLIC_APP_ORIGIN: "http://localhost:3000",
+ PUBLIC_USERCONTENT_ORIGIN: "http://localhost:3002",
+ PUBLIC_ASSET_ORIGIN: "http://localhost:3002",
+ INTERNAL_API_ORIGIN: "http://127.0.0.1:3001",
+ PK_USER_AGENT_CONTACT: "https://github.com/owner/pkviewer",
+};
+
+describe("session tokens", () => {
+ // The cookie value must never be recoverable from the database.
+ test("only a hash of the token is stored", () => {
+ const db = freshDb();
+ const account = seedAccount(db);
+ const { token, sessionId } = createSession(db, account, Date.now());
+
+ expect(sessionId).toBe(sha256(token));
+ const row = db
+ .query<{ id: string }, [string]>("SELECT id FROM sessions WHERE account_id = ?")
+ .get(account);
+ expect(row?.id).not.toBe(token);
+ expect(row?.id).toBe(sha256(token));
+ db.close();
+ });
+
+ test("resolves a valid session", () => {
+ const db = freshDb();
+ const account = seedAccount(db);
+ const now = Date.now();
+ const { token } = createSession(db, account, now);
+ expect(resolveSession(db, token, now)?.accountId).toBe(account);
+ db.close();
+ });
+
+ test("rejects an unknown token", () => {
+ const db = freshDb();
+ expect(resolveSession(db, "not-a-real-token", Date.now())).toBeNull();
+ db.close();
+ });
+
+ test("rejects a revoked session immediately", () => {
+ const db = freshDb();
+ const account = seedAccount(db);
+ const now = Date.now();
+ const { token } = createSession(db, account, now);
+ revokeSession(db, token, now);
+ expect(resolveSession(db, token, now + 1000)).toBeNull();
+ db.close();
+ });
+
+ test("expires on idle", () => {
+ const db = freshDb();
+ const account = seedAccount(db);
+ const now = Date.now();
+ const { token } = createSession(db, account, now);
+ expect(resolveSession(db, token, now + IDLE_TTL_MS + 1)).toBeNull();
+ db.close();
+ });
+
+ // Absolute expiry never extends, so a stolen session cannot be kept alive
+ // indefinitely simply by using it.
+ test("absolute expiry is not extended by use", () => {
+ const db = freshDb();
+ const account = seedAccount(db);
+ let now = Date.now();
+ const { token } = createSession(db, account, now);
+
+ // Use it repeatedly, well inside the idle window each time.
+ for (let i = 0; i < 40; i++) {
+ now += IDLE_TTL_MS / 2;
+ resolveSession(db, token, now);
+ }
+ expect(now).toBeGreaterThan(Date.now() + ABSOLUTE_TTL_MS);
+ expect(resolveSession(db, token, now)).toBeNull();
+ db.close();
+ });
+
+ test("idle window slides on use", () => {
+ const db = freshDb();
+ const account = seedAccount(db);
+ const now = Date.now();
+ const { token } = createSession(db, account, now);
+
+ const later = now + IDLE_TTL_MS - 1000;
+ expect(resolveSession(db, token, later)).not.toBeNull();
+ // Without sliding this would be expired.
+ expect(resolveSession(db, token, later + IDLE_TTL_MS - 2000)).not.toBeNull();
+ db.close();
+ });
+
+ test("a deleted account stops resolving even with a live session row", () => {
+ const db = freshDb();
+ const account = seedAccount(db);
+ const now = Date.now();
+ const { token } = createSession(db, account, now);
+ db.query("UPDATE accounts SET deleted_at = ? WHERE id = ?").run(now, account);
+ expect(resolveSession(db, token, now + 1)).toBeNull();
+ db.close();
+ });
+
+ test("logout-all revokes every session for the account", () => {
+ const db = freshDb();
+ const account = seedAccount(db);
+ const now = Date.now();
+ const a = createSession(db, account, now);
+ const b = createSession(db, account, now);
+
+ expect(revokeAllSessionsForAccount(db, account, now)).toBe(2);
+ expect(resolveSession(db, a.token, now)).toBeNull();
+ expect(resolveSession(db, b.token, now)).toBeNull();
+ db.close();
+ });
+
+ test("rotation invalidates the old token and keeps the account", () => {
+ const db = freshDb();
+ const account = seedAccount(db);
+ const now = Date.now();
+ const { token } = createSession(db, account, now);
+
+ const rotated = rotateSession(db, token, now);
+ expect(rotated).not.toBeNull();
+ expect(resolveSession(db, token, now)).toBeNull();
+ expect(resolveSession(db, rotated!.token, now)?.accountId).toBe(account);
+ db.close();
+ });
+});
+
+describe("account linking", () => {
+ test("creates an account on first Discord login", () => {
+ const db = freshDb();
+ const now = Date.now();
+ const result = upsertAccountForDiscord(
+ db,
+ { id: "123", username: "clove", globalName: "Clove", avatarHash: "abc" },
+ now,
+ { allowCreate: true },
+ );
+ expect(result.created).toBe(true);
+ expect(findAccountByDiscordId(db, "123")?.id).toBe(result.account!.id);
+ db.close();
+ });
+
+ test("reuses the account on subsequent logins", () => {
+ const db = freshDb();
+ const now = Date.now();
+ const profile = { id: "123", username: "clove", globalName: "Clove", avatarHash: null };
+ const first = upsertAccountForDiscord(db, profile, now, { allowCreate: true });
+ const second = upsertAccountForDiscord(db, profile, now + 1000, { allowCreate: true });
+
+ expect(second.created).toBe(false);
+ expect(second.account!.id).toBe(first.account!.id);
+ db.close();
+ });
+
+ // Turning signup off must not lock existing testers out.
+ test("signup disabled blocks new accounts but not existing ones", () => {
+ const db = freshDb();
+ const now = Date.now();
+ const profile = { id: "123", username: "clove", globalName: null, avatarHash: null };
+
+ const blocked = upsertAccountForDiscord(
+ db,
+ { id: "999", username: "stranger", globalName: null, avatarHash: null },
+ now,
+ { allowCreate: false },
+ );
+ expect(blocked.account).toBeNull();
+
+ upsertAccountForDiscord(db, profile, now, { allowCreate: true });
+ const existing = upsertAccountForDiscord(db, profile, now + 1, { allowCreate: false });
+ expect(existing.account).not.toBeNull();
+ db.close();
+ });
+});
+
+describe("oauth handshake", () => {
+ test("PKCE challenge is the S256 hash of the verifier, not the verifier", () => {
+ const { verifier, challenge } = createPkcePair();
+ expect(challenge).not.toBe(verifier);
+ expect(verifier.length).toBeGreaterThanOrEqual(43);
+ expect(verifier.length).toBeLessThanOrEqual(128);
+ });
+
+ test("signed handshake payload round-trips", () => {
+ const payload = JSON.stringify({ state: "abc", verifier: "def" });
+ const value = signedValue("secret-key", payload);
+ expect(verifySignedValue("secret-key", value)).toBe(payload);
+ });
+
+ test("a tampered handshake payload is rejected", () => {
+ const value = signedValue("secret-key", JSON.stringify({ state: "abc" }));
+ const tampered = `${Buffer.from('{"state":"evil"}', "utf8").toString("base64url")}.${value.split(".")[1]}`;
+ expect(verifySignedValue("secret-key", tampered)).toBeNull();
+ });
+
+ test("a payload signed with another key is rejected", () => {
+ const value = signedValue("key-one", "payload");
+ expect(verifySignedValue("key-two", value)).toBeNull();
+ });
+
+ test("authorize URL requests only the identify scope and uses S256", () => {
+ const url = new URL(
+ buildAuthorizeUrl({
+ clientId: "client",
+ redirectUri: "https://app.example/auth/discord/callback",
+ state: "state-value",
+ codeChallenge: "challenge-value",
+ }),
+ );
+ expect(url.searchParams.get("scope")).toBe("identify");
+ expect(url.searchParams.get("code_challenge_method")).toBe("S256");
+ expect(url.searchParams.get("response_type")).toBe("code");
+ // The verifier must never travel to Discord.
+ expect(url.searchParams.get("code_verifier")).toBeNull();
+ });
+
+ // Several URIs are registered so beta and production can both be live.
+ test("redirect URI is chosen from the registered list, matching the app origin", () => {
+ const uris = [
+ "https://prod.example/auth/discord/callback",
+ "https://beta.example/auth/discord/callback",
+ ];
+ expect(pickRedirectUri(uris, "https://beta.example")).toBe(
+ "https://beta.example/auth/discord/callback",
+ );
+ });
+
+ test("an unknown app origin falls back to a registered URI rather than reflecting input", () => {
+ const uris = ["https://prod.example/auth/discord/callback"];
+ expect(pickRedirectUri(uris, "https://attacker.example")).toBe(
+ "https://prod.example/auth/discord/callback",
+ );
+ });
+
+ test("safeEqual is length-safe", () => {
+ expect(safeEqual("abc", "abc")).toBe(true);
+ expect(safeEqual("abc", "abcd")).toBe(false);
+ expect(safeEqual("abc", "abd")).toBe(false);
+ });
+});
+
+describe("beta claim gating", () => {
+ test("public viewing is never gated, but claiming is", () => {
+ const cfg = loadConfig({
+ ...baseEnv,
+ BETA_MODE: "true",
+ BETA_ALLOWED_DISCORD_IDS: "111,222",
+ });
+ expect(canClaim(cfg, ["111"])).toBe(true);
+ expect(canClaim(cfg, ["333"])).toBe(false);
+ expect(canClaim(cfg, [])).toBe(false);
+ });
+
+ test("an empty allow-list denies everyone while in beta", () => {
+ const cfg = loadConfig({ ...baseEnv, BETA_MODE: "true" });
+ expect(canClaim(cfg, ["111"])).toBe(false);
+ });
+
+ test("outside beta, claiming is open", () => {
+ const cfg = loadConfig({ ...baseEnv, BETA_MODE: "false" });
+ expect(canClaim(cfg, ["anyone"])).toBe(true);
+ });
+});
+
+describe("post-login destination", () => {
+ // Landing on the public front page after signing in meant finding /manage by
+ // hand, which is not what someone signed in for.
+ test("defaults to the control plane", () => {
+ expect(safeReturnTo(undefined)).toBe("/manage");
+ expect(safeReturnTo("")).toBe("/manage");
+ });
+
+ test("keeps a same-origin path", () => {
+ expect(safeReturnTo("/manage/abc/appearance")).toBe("/manage/abc/appearance");
+ });
+
+ // The login flow must never become an open redirect.
+ test("refuses anything that could leave the origin", () => {
+ for (const hostile of [
+ "//evil.test/x",
+ "https://evil.test",
+ "http://evil.test",
+ "evil.test",
+ ]) {
+ expect(safeReturnTo(hostile), hostile).toBe("/manage");
+ }
+ });
+});
diff --git a/apps/api/test/claims.test.ts b/apps/api/test/claims.test.ts
new file mode 100644
index 0000000..5db6920
--- /dev/null
+++ b/apps/api/test/claims.test.ts
@@ -0,0 +1,618 @@
+import { describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import {
+ CHALLENGE_MAX_ATTEMPTS,
+ CHALLENGE_TTL_MS,
+ UNCLAIM_GRACE_MS,
+ claimViaDiscordLink,
+ claimViaToken,
+ createDescriptionChallenge,
+ currentOwner,
+ discoverLinkedSystems,
+ ensureSystemRow,
+ systemsForAccount,
+ unclaimSystem,
+ verifyDescriptionChallenge,
+} from "../src/claims/index.ts";
+import { openDb, type Db } from "../src/db/index.ts";
+import { migrate } from "../src/db/migrate.ts";
+import { PkClient } from "../src/pk/client.ts";
+import { MemorySnapshotStore } from "../src/pk/snapshots.ts";
+import {
+ RESERVATION_MS,
+ effectiveState,
+ findSlug,
+ reclaimSlug,
+ releaseSlug,
+ slugsForSubject,
+} from "../src/slugs/lifecycle.ts";
+
+const SYS_A = { id: "tythty", uuid: "uuid-a", name: "System A", description: null };
+const SYS_B = { id: "abcdef", uuid: "uuid-b", name: "System B", description: null };
+
+function freshDb(): Db {
+ const db = openDb(":memory:");
+ migrate(db);
+ return db;
+}
+
+function account(db: Db, now = Date.now()): string {
+ const id = randomUUID();
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run(id, now);
+ return id;
+}
+
+/** A PkClient wired to a scripted map of ref -> system (or a thrown status). */
+function pkStub(routes: Record<string, unknown>, ownSystem?: unknown) {
+ const calls: string[] = [];
+ const impl = (async (input: string | URL) => {
+ const url = String(input);
+ calls.push(url);
+ const path = url.replace("https://api.pluralkit.me/v2", "");
+ if (path === "/systems/@me") {
+ if (!ownSystem) return new Response("", { status: 401 });
+ return Response.json(ownSystem);
+ }
+ const ref = decodeURIComponent(path.replace("/systems/", ""));
+ const found = routes[ref];
+ if (!found) return new Response("", { status: 404 });
+ return Response.json(found);
+ }) as unknown as typeof fetch;
+
+ const pk = new PkClient({
+ apiBase: "https://api.pluralkit.me/v2",
+ userAgent: "pkviewer/test (+https://github.com/owner/pkviewer)",
+ readRps: 1000,
+ writeRps: 1000,
+ fetchImpl: impl,
+ snapshots: new MemorySnapshotStore(),
+ sleep: async () => {},
+ maxRetries: 0,
+ });
+ return { pk, calls };
+}
+
+describe("tier 1 — Discord link proof", () => {
+ test("claims a system linked to the caller's Discord account", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const { pk } = pkStub({ "999888777": SYS_A, tythty: SYS_A, "uuid-a": SYS_A });
+
+ const result = await claimViaDiscordLink(
+ { db, pk },
+ { accountId: acct, discordIds: ["999888777"], pkSystemRef: "tythty" },
+ );
+
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(currentOwner(db, result.systemId)).toBe(acct);
+ db.close();
+ });
+
+ // The Discord ids come from the session. A caller must not be able to claim a
+ // system merely by naming someone else's Discord account.
+ test("refuses when the system is not linked to the caller", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const { pk } = pkStub({ "999888777": SYS_A, abcdef: SYS_B });
+
+ const result = await claimViaDiscordLink(
+ { db, pk },
+ { accountId: acct, discordIds: ["999888777"], pkSystemRef: "abcdef" },
+ );
+
+ expect(result).toEqual({ ok: false, reason: "not_verified" });
+ db.close();
+ });
+
+ test("discovery tolerates a Discord account with no linked system", async () => {
+ const db = freshDb();
+ const { pk } = pkStub({ "111": SYS_A });
+ const found = await discoverLinkedSystems({ db, pk }, ["111", "222"]);
+ expect(found.map((s) => s.uuid)).toEqual(["uuid-a"]);
+ db.close();
+ });
+
+ test("an unknown system is not found", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const { pk } = pkStub({});
+ const result = await claimViaDiscordLink(
+ { db, pk },
+ { accountId: acct, discordIds: ["111"], pkSystemRef: "nope" },
+ );
+ expect(result).toEqual({ ok: false, reason: "not_found" });
+ db.close();
+ });
+});
+
+describe("contested claims", () => {
+ // Decision 7: block automatically, never take over, never say who holds it.
+ test("a second account cannot claim an owned system", async () => {
+ const db = freshDb();
+ const first = account(db);
+ const second = account(db);
+ const { pk } = pkStub({ "111": SYS_A, "222": SYS_A, tythty: SYS_A });
+
+ const a = await claimViaDiscordLink(
+ { db, pk },
+ { accountId: first, discordIds: ["111"], pkSystemRef: "tythty" },
+ );
+ expect(a.ok).toBe(true);
+
+ const b = await claimViaDiscordLink(
+ { db, pk },
+ { accountId: second, discordIds: ["222"], pkSystemRef: "tythty" },
+ );
+ expect(b).toEqual({ ok: false, reason: "already_claimed" });
+ if (a.ok) expect(currentOwner(db, a.systemId)).toBe(first);
+ db.close();
+ });
+
+ test("re-claiming by the existing owner is idempotent", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const { pk } = pkStub({ "111": SYS_A, tythty: SYS_A });
+
+ const a = await claimViaDiscordLink(
+ { db, pk },
+ { accountId: acct, discordIds: ["111"], pkSystemRef: "tythty" },
+ );
+ const b = await claimViaDiscordLink(
+ { db, pk },
+ { accountId: acct, discordIds: ["111"], pkSystemRef: "tythty" },
+ );
+ expect(a.ok && b.ok).toBe(true);
+ if (a.ok && b.ok) expect(a.systemId).toBe(b.systemId);
+ expect(systemsForAccount(db, acct)).toHaveLength(1);
+ db.close();
+ });
+
+ // The database, not application logic, is what makes two claimants safe.
+ test("the single-owner index blocks a second owner row outright", () => {
+ const db = freshDb();
+ const a = account(db);
+ const b = account(db);
+ const systemId = ensureSystemRow(db, SYS_A as never, Date.now());
+
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(a, systemId, Date.now());
+
+ expect(() =>
+ db
+ .query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ )
+ .run(b, systemId, Date.now()),
+ ).toThrow(/UNIQUE/i);
+ db.close();
+ });
+
+ test("a manager alongside an owner is still allowed", () => {
+ const db = freshDb();
+ const a = account(db);
+ const b = account(db);
+ const systemId = ensureSystemRow(db, SYS_A as never, Date.now());
+ const now = Date.now();
+
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(a, systemId, now);
+ expect(() =>
+ db
+ .query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'manager',?)",
+ )
+ .run(b, systemId, now),
+ ).not.toThrow();
+ db.close();
+ });
+});
+
+describe("tier 2 — description challenge", () => {
+ test("verifies when the nonce appears in the description", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const state = { ...SYS_A, description: "just a system" };
+ const { pk } = pkStub({ tythty: state, "uuid-a": state });
+
+ const created = await createDescriptionChallenge(
+ { db, pk },
+ { accountId: acct, pkSystemRef: "tythty" },
+ );
+ expect(created.ok).toBe(true);
+ if (!created.ok) return;
+
+ // Before the user edits their description, verification fails.
+ const early = await verifyDescriptionChallenge(
+ { db, pk },
+ { accountId: acct, challengeId: created.challenge.id },
+ );
+ expect(early).toEqual({ ok: false, reason: "not_verified" });
+
+ state.description = `hello ${created.challenge.nonce} world`;
+ const done = await verifyDescriptionChallenge(
+ { db, pk },
+ { accountId: acct, challengeId: created.challenge.id },
+ );
+ expect(done.ok).toBe(true);
+ db.close();
+ });
+
+ // Verifying against a cached description would let a stale copy prove
+ // ownership the user may no longer have.
+ test("verification reads the description fresh, bypassing the cache", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const state = { ...SYS_A, description: "before" };
+ const { pk, calls } = pkStub({ tythty: state, "uuid-a": state });
+
+ const created = await createDescriptionChallenge(
+ { db, pk },
+ { accountId: acct, pkSystemRef: "tythty" },
+ );
+ if (!created.ok) throw new Error("setup failed");
+
+ const before = calls.length;
+ state.description = created.challenge.nonce;
+ const done = await verifyDescriptionChallenge(
+ { db, pk },
+ { accountId: acct, challengeId: created.challenge.id },
+ );
+ expect(calls.length).toBeGreaterThan(before);
+ expect(done.ok).toBe(true);
+ db.close();
+ });
+
+ test("a private description cannot complete the challenge", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const state: { id: string; uuid: string; name: string; description: string | null } =
+ { ...SYS_A, description: null };
+ const { pk } = pkStub({ tythty: state, "uuid-a": state });
+
+ const created = await createDescriptionChallenge(
+ { db, pk },
+ { accountId: acct, pkSystemRef: "tythty" },
+ );
+ if (!created.ok) throw new Error("setup failed");
+
+ const result = await verifyDescriptionChallenge(
+ { db, pk },
+ { accountId: acct, challengeId: created.challenge.id },
+ );
+ expect(result).toEqual({ ok: false, reason: "description_unavailable" });
+ db.close();
+ });
+
+ test("expires", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ let now = 1_000_000;
+ const state: { id: string; uuid: string; name: string; description: string | null } =
+ { ...SYS_A, description: null };
+ const { pk } = pkStub({ tythty: state, "uuid-a": state });
+ const deps = { db, pk, now: () => now };
+
+ const created = await createDescriptionChallenge(deps, {
+ accountId: acct,
+ pkSystemRef: "tythty",
+ });
+ if (!created.ok) throw new Error("setup failed");
+
+ now += CHALLENGE_TTL_MS + 1;
+ const result = await verifyDescriptionChallenge(deps, {
+ accountId: acct,
+ challengeId: created.challenge.id,
+ });
+ expect(result).toEqual({ ok: false, reason: "challenge_expired" });
+ db.close();
+ });
+
+ test("attempts are rate limited", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const state = { ...SYS_A, description: "nothing here" };
+ const { pk } = pkStub({ tythty: state, "uuid-a": state });
+
+ const created = await createDescriptionChallenge(
+ { db, pk },
+ { accountId: acct, pkSystemRef: "tythty" },
+ );
+ if (!created.ok) throw new Error("setup failed");
+
+ for (let i = 0; i < CHALLENGE_MAX_ATTEMPTS; i++) {
+ await verifyDescriptionChallenge({ db, pk }, { accountId: acct, challengeId: created.challenge.id });
+ }
+ const result = await verifyDescriptionChallenge(
+ { db, pk },
+ { accountId: acct, challengeId: created.challenge.id },
+ );
+ expect(result).toEqual({ ok: false, reason: "too_many_attempts" });
+ db.close();
+ });
+
+ test("another account cannot verify someone else's challenge", async () => {
+ const db = freshDb();
+ const owner = account(db);
+ const stranger = account(db);
+ const state: { id: string; uuid: string; name: string; description: string | null } =
+ { ...SYS_A, description: null };
+ const { pk } = pkStub({ tythty: state, "uuid-a": state });
+
+ const created = await createDescriptionChallenge(
+ { db, pk },
+ { accountId: owner, pkSystemRef: "tythty" },
+ );
+ if (!created.ok) throw new Error("setup failed");
+ state.description = created.challenge.nonce;
+
+ const result = await verifyDescriptionChallenge(
+ { db, pk },
+ { accountId: stranger, challengeId: created.challenge.id },
+ );
+ expect(result).toEqual({ ok: false, reason: "challenge_not_found" });
+ db.close();
+ });
+});
+
+describe("tier 3 — transient PluralKit token", () => {
+ test("claims when the token's own system matches the target", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const { pk } = pkStub({ tythty: SYS_A }, SYS_A);
+
+ const result = await claimViaToken(
+ { db, pk },
+ { accountId: acct, pkSystemRef: "tythty", token: "pk-token" },
+ );
+ expect(result.ok).toBe(true);
+ db.close();
+ });
+
+ test("refuses when the token belongs to a different system", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const { pk } = pkStub({ abcdef: SYS_B }, SYS_A);
+
+ const result = await claimViaToken(
+ { db, pk },
+ { accountId: acct, pkSystemRef: "abcdef", token: "pk-token" },
+ );
+ expect(result).toEqual({ ok: false, reason: "not_verified" });
+ db.close();
+ });
+
+ test("an invalid token verifies nothing", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const { pk } = pkStub({ tythty: SYS_A }); // no @me
+ const result = await claimViaToken(
+ { db, pk },
+ { accountId: acct, pkSystemRef: "tythty", token: "bad" },
+ );
+ expect(result).toEqual({ ok: false, reason: "not_verified" });
+ db.close();
+ });
+
+ // C1: the token is used inside the request and never written anywhere.
+ test("the token is never persisted", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const { pk } = pkStub({ tythty: SYS_A }, SYS_A);
+ await claimViaToken({ db, pk }, { accountId: acct, pkSystemRef: "tythty", token: "s3cret-pk-token" });
+
+ const tables = db
+ .query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE type='table'")
+ .all()
+ .map((r) => r.name);
+ for (const table of tables) {
+ const rows = db.query(`SELECT * FROM ${table}`).all() as Record<string, unknown>[];
+ const dump = JSON.stringify(rows);
+ expect(dump).not.toContain("s3cret-pk-token");
+ }
+ db.close();
+ });
+});
+
+describe("unclaiming", () => {
+ function claimedSystem(db: Db, now: number) {
+ const acct = account(db, now);
+ const systemId = ensureSystemRow(db, SYS_A as never, now);
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(acct, systemId, now);
+ db.query("UPDATE systems SET claimed_at = ? WHERE id = ?").run(now, systemId);
+ db.query(
+ "INSERT INTO slugs (scope, scope_key, slug_normalized, slug_display, state, subject_id, claimed_at) VALUES ('system','','mysystem','mysystem','active',?,?)",
+ ).run(systemId, now);
+ db.query(
+ "INSERT INTO themes (owner_type, owner_id, schema_version, tokens, updated_at) VALUES ('system',?,1,'{\"accent\":\"pink\"}',?)",
+ ).run(systemId, now);
+ return { acct, systemId };
+ }
+
+ test("releases slugs into reservation and soft-deletes configuration", () => {
+ const db = freshDb();
+ const now = 1_000_000;
+ const { acct, systemId } = claimedSystem(db, now);
+
+ const result = unclaimSystem({ db, pk: null as never, now: () => now }, { accountId: acct, systemId });
+ expect(result).toEqual({ ok: true, slugsReleased: 1 });
+
+ const slug = findSlug(db, "system", "", "mysystem");
+ expect(slug?.state).toBe("reserved");
+ expect(slug?.reserved_until).toBe(now + RESERVATION_MS);
+ // Reservation follows the SUBJECT, not the account (decision 6).
+ expect(slug?.reserved_principal_id).toBe(systemId);
+ expect(slug?.reserved_principal_type).toBe("system");
+
+ const theme = db
+ .query<{ deleted_at: number | null }, [string]>(
+ "SELECT deleted_at FROM themes WHERE owner_type='system' AND owner_id = ?",
+ )
+ .get(systemId);
+ expect(theme?.deleted_at).toBe(now);
+
+ expect(currentOwner(db, systemId)).toBeNull();
+ db.close();
+ });
+
+ test("only the owner may unclaim", () => {
+ const db = freshDb();
+ const now = 1_000_000;
+ const { systemId } = claimedSystem(db, now);
+ const stranger = account(db, now);
+
+ const result = unclaimSystem(
+ { db, pk: null as never, now: () => now },
+ { accountId: stranger, systemId },
+ );
+ expect(result).toEqual({ ok: false, reason: "not_owner" });
+ db.close();
+ });
+
+ test("re-claiming inside the grace window restores configuration and slug", async () => {
+ const db = freshDb();
+ let now = 1_000_000;
+ const { acct, systemId } = claimedSystem(db, now);
+ const { pk } = pkStub({ "111": SYS_A, tythty: SYS_A });
+
+ unclaimSystem({ db, pk, now: () => now }, { accountId: acct, systemId });
+
+ now += 3 * 24 * 60 * 60 * 1000; // well inside both windows
+ const result = await claimViaDiscordLink(
+ { db, pk, now: () => now },
+ { accountId: acct, discordIds: ["111"], pkSystemRef: "tythty" },
+ );
+
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.restored).toBe(true);
+
+ const theme = db
+ .query<{ deleted_at: number | null }, [string]>(
+ "SELECT deleted_at FROM themes WHERE owner_type='system' AND owner_id = ?",
+ )
+ .get(systemId);
+ expect(theme?.deleted_at).toBeNull();
+ expect(slugsForSubject(db, "system", systemId)).toHaveLength(1);
+ db.close();
+ });
+
+ test("past the grace window, configuration is not restored", async () => {
+ const db = freshDb();
+ let now = 1_000_000;
+ const { acct, systemId } = claimedSystem(db, now);
+ const { pk } = pkStub({ "111": SYS_A, tythty: SYS_A });
+
+ unclaimSystem({ db, pk, now: () => now }, { accountId: acct, systemId });
+ now += UNCLAIM_GRACE_MS + 1;
+
+ const result = await claimViaDiscordLink(
+ { db, pk, now: () => now },
+ { accountId: acct, discordIds: ["111"], pkSystemRef: "tythty" },
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.restored).toBe(false);
+ db.close();
+ });
+});
+
+describe("slug reservation lifecycle", () => {
+ function activeSlug(db: Db, subjectId: string, now: number) {
+ db.query(
+ "INSERT INTO slugs (scope, scope_key, slug_normalized, slug_display, state, subject_id, claimed_at) VALUES ('system','','name','name','active',?,?)",
+ ).run(subjectId, now);
+ return findSlug(db, "system", "", "name")!;
+ }
+
+ test("release moves an active slug into a 7-day reservation", () => {
+ const db = freshDb();
+ const now = 1_000_000;
+ const slug = activeSlug(db, "sys-1", now);
+ expect(releaseSlug(db, slug, now)).toBe(true);
+
+ const after = findSlug(db, "system", "", "name")!;
+ expect(effectiveState(after, now)).toEqual({
+ kind: "reserved",
+ principalType: "system",
+ principalId: "sys-1",
+ until: now + RESERVATION_MS,
+ });
+ db.close();
+ });
+
+ // Expiry is derived at read time, so no scheduled job can get it wrong.
+ test("a reservation reads as free once it lapses, with no job running", () => {
+ const db = freshDb();
+ const now = 1_000_000;
+ const slug = activeSlug(db, "sys-1", now);
+ releaseSlug(db, slug, now);
+
+ const after = findSlug(db, "system", "", "name")!;
+ expect(effectiveState(after, now + RESERVATION_MS - 1).kind).toBe("reserved");
+ expect(effectiveState(after, now + RESERVATION_MS).kind).toBe("free");
+ db.close();
+ });
+
+ test("the previous subject can reclaim inside the window", () => {
+ const db = freshDb();
+ const now = 1_000_000;
+ releaseSlug(db, activeSlug(db, "sys-1", now), now);
+
+ const reserved = findSlug(db, "system", "", "name")!;
+ expect(reclaimSlug(db, reserved, "sys-1", now + 1000)).toEqual({ ok: true });
+ expect(findSlug(db, "system", "", "name")?.state).toBe("active");
+ db.close();
+ });
+
+ test("a different subject cannot reclaim during the reservation", () => {
+ const db = freshDb();
+ const now = 1_000_000;
+ releaseSlug(db, activeSlug(db, "sys-1", now), now);
+
+ const reserved = findSlug(db, "system", "", "name")!;
+ expect(reclaimSlug(db, reserved, "sys-2", now + 1000)).toEqual({
+ ok: false,
+ reason: "reserved_for_someone_else",
+ });
+ db.close();
+ });
+
+ test("reclaim fails once the reservation has lapsed", () => {
+ const db = freshDb();
+ const now = 1_000_000;
+ releaseSlug(db, activeSlug(db, "sys-1", now), now);
+
+ const reserved = findSlug(db, "system", "", "name")!;
+ expect(reclaimSlug(db, reserved, "sys-1", now + RESERVATION_MS)).toEqual({
+ ok: false,
+ reason: "expired",
+ });
+ db.close();
+ });
+
+ test("releasing twice does not reset the reservation clock", () => {
+ const db = freshDb();
+ const now = 1_000_000;
+ const slug = activeSlug(db, "sys-1", now);
+ releaseSlug(db, slug, now);
+
+ // A stale copy of the row attempting a second release must not extend it.
+ expect(releaseSlug(db, slug, now + 5000)).toBe(false);
+ expect(findSlug(db, "system", "", "name")?.reserved_until).toBe(now + RESERVATION_MS);
+ db.close();
+ });
+
+ test("every release is recorded in history", () => {
+ const db = freshDb();
+ const now = 1_000_000;
+ releaseSlug(db, activeSlug(db, "sys-1", now), now, "acct-1");
+ const rows = db
+ .query<{ event: string }, []>("SELECT event FROM slug_history")
+ .all()
+ .map((r) => r.event);
+ expect(rows).toContain("released");
+ db.close();
+ });
+});
diff --git a/apps/api/test/config.test.ts b/apps/api/test/config.test.ts
new file mode 100644
index 0000000..9296e79
--- /dev/null
+++ b/apps/api/test/config.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, test } from "bun:test";
+import { buildUserAgent, ConfigError, loadConfig } from "../src/config/index.ts";
+import { PKVIEWER_VERSION } from "../src/config/version.ts";
+
+const base = {
+ NODE_ENV: "development",
+ PUBLIC_APP_ORIGIN: "http://localhost:3000",
+ PUBLIC_USERCONTENT_ORIGIN: "http://localhost:3002",
+ PUBLIC_ASSET_ORIGIN: "http://localhost:3002",
+ INTERNAL_API_ORIGIN: "http://127.0.0.1:3001",
+ PK_USER_AGENT_CONTACT: "https://github.com/owner/pkviewer",
+};
+
+describe("config", () => {
+ test("parses a valid development environment", () => {
+ const cfg = loadConfig(base);
+ expect(cfg.appOrigin).toBe("http://localhost:3000");
+ expect(cfg.beta.enabled).toBe(false);
+ expect(cfg.pk.readRps).toBe(6);
+ });
+
+ test("normalises origins by stripping trailing slashes", () => {
+ const cfg = loadConfig({ ...base, PUBLIC_APP_ORIGIN: "http://localhost:3000/" });
+ expect(cfg.appOrigin).toBe("http://localhost:3000");
+ });
+
+ test("rejects an origin carrying a path", () => {
+ expect(() => loadConfig({ ...base, PUBLIC_APP_ORIGIN: "http://localhost:3000/app" })).toThrow(
+ ConfigError,
+ );
+ });
+
+ // The user-content origin is the boundary keeping user-authored presentation
+ // away from __Host- session cookies. Collapsing it into the app origin would
+ // void that silently, so it must be fatal everywhere including development.
+ test("refuses to boot when user content shares the app origin", () => {
+ expect(() =>
+ loadConfig({ ...base, PUBLIC_USERCONTENT_ORIGIN: "http://localhost:3000" }),
+ ).toThrow(/must not equal PUBLIC_APP_ORIGIN/);
+ });
+
+ test("requires https origins in production", () => {
+ expect(() =>
+ loadConfig({
+ ...base,
+ NODE_ENV: "production",
+ DISCORD_REDIRECT_URIS: "https://example.test/cb",
+ SESSION_SECRET: "x".repeat(32),
+ }),
+ ).toThrow(/must be https in production/);
+ });
+
+ test("requires a session secret in production", () => {
+ expect(() =>
+ loadConfig({
+ NODE_ENV: "production",
+ PUBLIC_APP_ORIGIN: "https://app.example",
+ PUBLIC_USERCONTENT_ORIGIN: "https://usercontent.example",
+ PUBLIC_ASSET_ORIGIN: "https://usercontent.example",
+ INTERNAL_API_ORIGIN: "http://127.0.0.1:3001",
+ PK_USER_AGENT_CONTACT: "https://github.com/owner/pkviewer",
+ DISCORD_REDIRECT_URIS: "https://app.example/cb",
+ SESSION_SECRET: "short",
+ }),
+ ).toThrow(/SESSION_SECRET/);
+ });
+
+ test("accepts several Discord redirect URIs so a domain move needs no flag day", () => {
+ const cfg = loadConfig({
+ ...base,
+ DISCORD_REDIRECT_URIS:
+ "https://beta.example/auth/discord/callback, https://prod.example/auth/discord/callback",
+ });
+ expect(cfg.discord.redirectUris).toHaveLength(2);
+ });
+
+ test("rejects a non-URL redirect URI", () => {
+ expect(() => loadConfig({ ...base, DISCORD_REDIRECT_URIS: "not-a-url" })).toThrow(ConfigError);
+ });
+});
+
+describe("user agent", () => {
+ test("identifies pkviewer and carries a contact URL", () => {
+ expect(buildUserAgent("https://github.com/owner/pkviewer")).toBe(
+ `pkviewer/${PKVIEWER_VERSION} (+https://github.com/owner/pkviewer)`,
+ );
+ });
+
+ // The UA must be identical across instances and over time. Deriving it from
+ // the deployment origin would change it on the beta -> production move, which
+ // is the thing PluralKit uses it to avoid.
+ test("does not depend on the deployment origin", () => {
+ const a = loadConfig({ ...base, PUBLIC_APP_ORIGIN: "https://beta.example" });
+ const b = loadConfig({ ...base, PUBLIC_APP_ORIGIN: "https://production.example" });
+ expect(a.pk.userAgent).toBe(b.pk.userAgent);
+ });
+});
+
+describe("beta readiness", () => {
+ // An empty HMAC key would still "work", which is exactly the problem.
+ test("an absent session secret becomes a random one outside production", () => {
+ const a = loadConfig(base);
+ const b = loadConfig(base);
+ expect(a.sessionSecret.length).toBeGreaterThanOrEqual(32);
+ expect(a.sessionSecret).not.toBe(b.sessionSecret);
+ });
+
+ test("a provided session secret is used as-is", () => {
+ const cfg = loadConfig({ ...base, SESSION_SECRET: "y".repeat(40) });
+ expect(cfg.sessionSecret).toBe("y".repeat(40));
+ });
+
+ const prodBase = {
+ NODE_ENV: "production",
+ PUBLIC_APP_ORIGIN: "https://app.example",
+ PUBLIC_USERCONTENT_ORIGIN: "https://public.example",
+ PUBLIC_ASSET_ORIGIN: "https://public.example",
+ INTERNAL_API_ORIGIN: "http://127.0.0.1:3001",
+ PK_USER_AGENT_CONTACT: "https://github.com/owner/pkviewer",
+ DISCORD_REDIRECT_URIS: "https://app.example/auth/discord/callback",
+ DISCORD_CLIENT_ID: "id",
+ DISCORD_CLIENT_SECRET: "secret",
+ SESSION_SECRET: "z".repeat(40),
+ };
+
+ test("a complete production environment loads", () => {
+ expect(() => loadConfig(prodBase)).not.toThrow();
+ });
+
+ // Production must never fall back to a generated secret: that would make
+ // every restart silently invalidate in-flight logins, and hide a missing var.
+ test("production refuses a missing session secret rather than generating one", () => {
+ const { SESSION_SECRET: _omitted, ...withoutSecret } = prodBase;
+ expect(() => loadConfig(withoutSecret)).toThrow(/SESSION_SECRET/);
+ });
+
+ test("production refuses to start without Discord credentials", () => {
+ const { DISCORD_CLIENT_SECRET: _omitted, ...withoutDiscord } = prodBase;
+ expect(() => loadConfig(withoutDiscord)).toThrow(/DISCORD_CLIENT/);
+ });
+
+ test("the error names the missing variable so it can be fixed", () => {
+ try {
+ loadConfig({ ...base, PK_USER_AGENT_CONTACT: "" });
+ throw new Error("expected a failure");
+ } catch (err) {
+ expect(String(err)).toContain("PK_USER_AGENT_CONTACT");
+ }
+ });
+});
diff --git a/apps/api/test/db.test.ts b/apps/api/test/db.test.ts
new file mode 100644
index 0000000..e742ad3
--- /dev/null
+++ b/apps/api/test/db.test.ts
@@ -0,0 +1,243 @@
+import { describe, expect, test } from "bun:test";
+import { openDb, writeTx } from "../src/db/index.ts";
+import { migrate } from "../src/db/migrate.ts";
+
+function freshDb() {
+ const db = openDb(":memory:");
+ migrate(db);
+ return db;
+}
+
+describe("migrations", () => {
+ test("apply cleanly and are idempotent", () => {
+ const db = openDb(":memory:");
+ const first = migrate(db);
+ expect(first.applied).toContain("001_init.sql");
+
+ const second = migrate(db);
+ expect(second.applied).toHaveLength(0);
+ expect(second.alreadyApplied).toContain("001_init.sql");
+ db.close();
+ });
+
+ test("create the expected tables", () => {
+ const db = freshDb();
+ const names = db
+ .query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE type='table'")
+ .all()
+ .map((r) => r.name);
+ for (const t of [
+ "accounts",
+ "discord_identities",
+ "sessions",
+ "systems",
+ "members",
+ "grants",
+ "slugs",
+ "slug_history",
+ "themes",
+ "social_links",
+ "pk_snapshots",
+ "audit_events",
+ ]) {
+ expect(names).toContain(t);
+ }
+ db.close();
+ });
+});
+
+describe("pragmas", () => {
+ // foreign_keys is off by default and per-connection. If this regresses, every
+ // ON DELETE CASCADE in the schema silently stops working.
+ test("foreign keys are enforced", () => {
+ const db = freshDb();
+ expect(() =>
+ db
+ .query("INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,?,?,?,?)")
+ .run("no-such-account", "system", "sys-1", "owner", Date.now()),
+ ).toThrow(/FOREIGN KEY/i);
+ db.close();
+ });
+
+ test("cascade deletes reach dependent rows", () => {
+ const db = freshDb();
+ const now = Date.now();
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run("acct-1", now);
+ db.query("INSERT INTO systems (id, pk_system_uuid, pk_system_hid, created_at) VALUES (?,?,?,?)")
+ .run("sys-1", "uuid-1", "tythty", now);
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,?,?,?,?)",
+ ).run("acct-1", "system", "sys-1", "owner", now);
+
+ db.query("DELETE FROM accounts WHERE id = ?").run("acct-1");
+ const left = db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM grants").get();
+ expect(left?.n).toBe(0);
+ db.close();
+ });
+});
+
+describe("slug state constraints", () => {
+ // The slug state machine is enforced by CHECK constraints, not convention: an
+ // inconsistent row cannot be written at all.
+ test("an active slug cannot carry a reservation", () => {
+ const db = freshDb();
+ expect(() =>
+ db
+ .query(
+ `INSERT INTO slugs
+ (scope, scope_key, slug_normalized, slug_display, state, subject_id,
+ reserved_principal_type, reserved_principal_id, reserved_until, claimed_at)
+ VALUES ('system','','example-system','example-system','active','sys-1',
+ 'system','sys-1',?,?)`,
+ )
+ .run(Date.now() + 1000, Date.now()),
+ ).toThrow(/CHECK/i);
+ db.close();
+ });
+
+ test("a reserved slug must have an expiry and a principal", () => {
+ const db = freshDb();
+ expect(() =>
+ db
+ .query(
+ `INSERT INTO slugs
+ (scope, scope_key, slug_normalized, slug_display, state, released_at)
+ VALUES ('system','','example-system','example-system','reserved',?)`,
+ )
+ .run(Date.now()),
+ ).toThrow(/CHECK/i);
+ db.close();
+ });
+
+ test("a slug is unique within its namespace", () => {
+ const db = freshDb();
+ const now = Date.now();
+ const insert = (subject: string) =>
+ db
+ .query(
+ `INSERT INTO slugs (scope, scope_key, slug_normalized, slug_display, state, subject_id, claimed_at)
+ VALUES ('system','','example-system','example-system','active',?,?)`,
+ )
+ .run(subject, now);
+ insert("sys-1");
+ expect(() => insert("sys-2")).toThrow(/UNIQUE/i);
+ db.close();
+ });
+
+ // Member slugs are scoped to their system, so two systems may each have a
+ // member called "clove".
+ test("member slugs are scoped per system", () => {
+ const db = freshDb();
+ const now = Date.now();
+ const insert = (systemId: string, subject: string) =>
+ db
+ .query(
+ `INSERT INTO slugs (scope, scope_key, slug_normalized, slug_display, state, subject_id, claimed_at)
+ VALUES ('member',?,'clove','clove','active',?,?)`,
+ )
+ .run(systemId, subject, now);
+ insert("sys-1", "mem-1");
+ expect(() => insert("sys-2", "mem-2")).not.toThrow();
+ expect(() => insert("sys-1", "mem-3")).toThrow(/UNIQUE/i);
+ db.close();
+ });
+});
+
+describe("transactions", () => {
+ test("writeTx rolls back on failure", () => {
+ const db = freshDb();
+ const now = Date.now();
+ expect(() =>
+ writeTx(db, (tx) => {
+ tx.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run("acct-x", now);
+ throw new Error("boom");
+ }),
+ ).toThrow("boom");
+ const row = db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM accounts").get();
+ expect(row?.n).toBe(0);
+ db.close();
+ });
+});
+
+describe("account deletion", () => {
+ /**
+ * granted_by and updated_by are audit breadcrumbs, not ownership. Declared
+ * without an ON DELETE rule they default to RESTRICT, which made deleting an
+ * account that had ever granted a role or saved a theme fail outright.
+ */
+ test("an account that has granted a role and saved a theme can be deleted", () => {
+ const db = freshDb();
+ const now = Date.now();
+
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run("acct-1", now);
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run("acct-2", now);
+ db.query("INSERT INTO systems (id, pk_system_uuid, pk_system_hid, created_at) VALUES (?,?,?,?)")
+ .run("sys-1", "uuid-1", "tythty", now);
+
+ // acct-1 grants acct-2 a role, and saves a theme.
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at, granted_by) VALUES (?,'system',?,'manager',?,?)",
+ ).run("acct-2", "sys-1", now, "acct-1");
+ db.query(
+ "INSERT INTO themes (owner_type, owner_id, schema_version, tokens, updated_at, updated_by) VALUES ('system',?,1,'{}',?,?)",
+ ).run("sys-1", now, "acct-1");
+
+ expect(() => db.query("DELETE FROM accounts WHERE id = ?").run("acct-1")).not.toThrow();
+
+ // The breadcrumbs become null; the records they annotate survive.
+ const grant = db
+ .query<{ granted_by: string | null; account_id: string }, []>(
+ "SELECT granted_by, account_id FROM grants",
+ )
+ .get();
+ expect(grant?.granted_by).toBeNull();
+ expect(grant?.account_id).toBe("acct-2");
+
+ const theme = db
+ .query<{ updated_by: string | null }, []>("SELECT updated_by FROM themes")
+ .get();
+ expect(theme?.updated_by).toBeNull();
+ db.close();
+ });
+
+ test("deleting an account still removes its own grants and sessions", () => {
+ const db = freshDb();
+ const now = Date.now();
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run("acct-1", now);
+ db.query("INSERT INTO systems (id, pk_system_uuid, pk_system_hid, created_at) VALUES (?,?,?,?)")
+ .run("sys-1", "uuid-1", "tythty", now);
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run("acct-1", "sys-1", now);
+ db.query(
+ "INSERT INTO sessions (id, account_id, created_at, idle_expires_at, abs_expires_at) VALUES (?,?,?,?,?)",
+ ).run("sess-1", "acct-1", now, now + 1000, now + 2000);
+
+ db.query("DELETE FROM accounts WHERE id = ?").run("acct-1");
+ expect(db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM grants").get()?.n).toBe(0);
+ expect(db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM sessions").get()?.n).toBe(0);
+ db.close();
+ });
+
+ // The rebuild must not lose the constraint that blocks a contested takeover.
+ test("the single-owner constraint survives the table rebuild", () => {
+ const db = freshDb();
+ const now = Date.now();
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run("a", now);
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run("b", now);
+ db.query("INSERT INTO systems (id, pk_system_uuid, pk_system_hid, created_at) VALUES (?,?,?,?)")
+ .run("sys-1", "uuid-1", "tythty", now);
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run("a", "sys-1", now);
+
+ expect(() =>
+ db
+ .query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ )
+ .run("b", "sys-1", now),
+ ).toThrow(/UNIQUE/i);
+ db.close();
+ });
+});
diff --git a/apps/api/test/manage.test.ts b/apps/api/test/manage.test.ts
new file mode 100644
index 0000000..66a591e
--- /dev/null
+++ b/apps/api/test/manage.test.ts
@@ -0,0 +1,581 @@
+import { describe, expect, test } from "bun:test";
+import { Hono } from "hono";
+import { randomUUID } from "node:crypto";
+import { resolveTheme } from "@pkviewer/shared";
+import { createSession } from "../src/auth/sessions.ts";
+import { ensureSystemRow } from "../src/claims/index.ts";
+import { loadConfig } from "../src/config/index.ts";
+import { openDb, type Db } from "../src/db/index.ts";
+import { migrate } from "../src/db/migrate.ts";
+import { requireKnownOrigin } from "../src/http/middleware.ts";
+import { manageRoutes } from "../src/http/routes/manage.ts";
+import {
+ authorizeSystem,
+ listManagedSystems,
+ listSocialLinks,
+ readTheme,
+ saveSocialLinks,
+ saveTheme,
+} from "../src/manage/index.ts";
+import { PkClient } from "../src/pk/client.ts";
+import { MemorySnapshotStore } from "../src/pk/snapshots.ts";
+
+const SYS = { id: "tythty", uuid: "uuid-a", name: "Doughmination", description: "hi" };
+const MEMBERS = [
+ { id: "kzsbyo", uuid: "mu-1", name: "Clove", display_name: null, pronouns: "she/her", avatar_url: null },
+ { id: "abcdef", uuid: "mu-2", name: "Ash", display_name: null, pronouns: null, avatar_url: null },
+];
+
+const cfg = loadConfig({
+ PUBLIC_APP_ORIGIN: "http://app.localhost:3000",
+ PUBLIC_USERCONTENT_ORIGIN: "http://system.localhost:3000",
+ PUBLIC_ASSET_ORIGIN: "http://system.localhost:3000",
+ INTERNAL_API_ORIGIN: "http://127.0.0.1:3001",
+ PK_USER_AGENT_CONTACT: "https://github.com/owner/pkviewer",
+ SESSION_SECRET: "x".repeat(40),
+});
+
+function freshDb(): Db {
+ const db = openDb(":memory:");
+ migrate(db);
+ return db;
+}
+
+function pkStub(members = MEMBERS) {
+ const impl = (async (input: string | URL) => {
+ const path = String(input).replace("https://api.pluralkit.me/v2", "");
+ if (path.endsWith("/members")) return Response.json(members);
+ const ref = decodeURIComponent(path.replace("/systems/", ""));
+ if (ref === SYS.uuid || ref === SYS.id) return Response.json(SYS);
+ return new Response("", { status: 404 });
+ }) as unknown as typeof fetch;
+
+ return new PkClient({
+ apiBase: "https://api.pluralkit.me/v2",
+ userAgent: "pkviewer/test (+https://github.com/owner/pkviewer)",
+ readRps: 1000,
+ writeRps: 1000,
+ fetchImpl: impl,
+ snapshots: new MemorySnapshotStore(),
+ sleep: async () => {},
+ maxRetries: 0,
+ });
+}
+
+function seedAccount(db: Db): string {
+ const id = randomUUID();
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run(id, Date.now());
+ return id;
+}
+
+function seedOwnedSystem(db: Db, accountId: string): string {
+ const systemId = ensureSystemRow(db, SYS as never, Date.now());
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(accountId, systemId, Date.now());
+ return systemId;
+}
+
+/** Builds a request carrying a real session cookie, as the browser would. */
+function requestFor(db: Db, accountId: string | null, path: string, init: RequestInit = {}) {
+ const headers = new Headers(init.headers);
+ headers.set("origin", cfg.appOrigin);
+ if (init.body) headers.set("content-type", "application/json");
+ if (accountId) {
+ const { token } = createSession(db, accountId, Date.now());
+ headers.set("cookie", `__Host-pkv_session=${token}`);
+ }
+ return new Request(`http://app.localhost${path}`, { ...init, headers });
+}
+
+function app(db: Db, pk = pkStub()) {
+ return manageRoutes({ cfg, db, pk });
+}
+
+describe("authorization", () => {
+ test("unauthenticated requests are refused", async () => {
+ const db = freshDb();
+ const res = await app(db).fetch(requestFor(db, null, "/systems"));
+ expect(res.status).toBe(401);
+ db.close();
+ });
+
+ test("an account sees only systems it has a grant for", async () => {
+ const db = freshDb();
+ const owner = seedAccount(db);
+ const stranger = seedAccount(db);
+ seedOwnedSystem(db, owner);
+
+ const mine = await listManagedSystems({ db, pk: pkStub() }, owner);
+ const theirs = await listManagedSystems({ db, pk: pkStub() }, stranger);
+ expect(mine).toHaveLength(1);
+ expect(theirs).toHaveLength(0);
+ db.close();
+ });
+
+ test("an account with no systems gets an empty list, not an error", async () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const res = await app(db).fetch(requestFor(db, accountId, "/systems"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ systems: [] });
+ db.close();
+ });
+
+ // 403 would confirm the system exists on pkviewer. An unauthorised caller
+ // learns nothing.
+ test("a system the caller cannot manage is reported as not found", async () => {
+ const db = freshDb();
+ const owner = seedAccount(db);
+ const stranger = seedAccount(db);
+ const systemId = seedOwnedSystem(db, owner);
+
+ const res = await app(db).fetch(requestFor(db, stranger, `/systems/${systemId}`));
+ expect(res.status).toBe(404);
+ db.close();
+ });
+
+ test("authorizeSystem refuses an account without a grant", () => {
+ const db = freshDb();
+ const owner = seedAccount(db);
+ const stranger = seedAccount(db);
+ const systemId = seedOwnedSystem(db, owner);
+
+ expect(authorizeSystem(db, owner, systemId)).not.toBeNull();
+ expect(authorizeSystem(db, stranger, systemId)).toBeNull();
+ db.close();
+ });
+
+ test("a manager may manage, not only the owner", () => {
+ const db = freshDb();
+ const owner = seedAccount(db);
+ const manager = seedAccount(db);
+ const systemId = seedOwnedSystem(db, owner);
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'manager',?)",
+ ).run(manager, systemId, Date.now());
+
+ expect(authorizeSystem(db, manager, systemId)).not.toBeNull();
+ db.close();
+ });
+
+ // CSRF: a cross-site form post carries no Origin we recognise. The check
+ // lives in middleware, so it is exercised here through a mounted app rather
+ // than asserted loosely at the route.
+ test("a state-changing request without a known Origin is refused", async () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+ const { token } = createSession(db, accountId, Date.now());
+
+ const guarded = new Hono();
+ guarded.use("*", requireKnownOrigin(cfg));
+ guarded.route("/", app(db));
+
+ const send = (origin: string | null) =>
+ guarded.fetch(
+ new Request(`http://app.localhost/systems/${systemId}/theme`, {
+ method: "PUT",
+ headers: {
+ cookie: `__Host-pkv_session=${token}`,
+ "content-type": "application/json",
+ ...(origin ? { origin } : {}),
+ },
+ body: JSON.stringify({ tokens: { density: "compact" } }),
+ }),
+ );
+
+ expect((await send(null)).status).toBe(403);
+ expect((await send("https://evil.test")).status).toBe(403);
+ expect((await send(cfg.appOrigin)).status).toBe(200);
+
+ // Only the legitimate request should have written anything.
+ expect(readTheme(db, "system", systemId).tokens).toEqual({ density: "compact" });
+ db.close();
+ });
+});
+
+describe("theme saving", () => {
+ test("saves and reads back valid tokens", async () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+
+ const res = await app(db).fetch(
+ requestFor(db, accountId, `/systems/${systemId}/theme`, {
+ method: "PUT",
+ body: JSON.stringify({ tokens: { "color.accent": "#112233", density: "relaxed" } }),
+ }),
+ );
+ expect(res.status).toBe(200);
+
+ const stored = readTheme(db, "system", systemId);
+ expect(stored.tokens).toEqual({ "color.accent": "#112233", density: "relaxed" });
+ db.close();
+ });
+
+ test("rejects invalid values with a reportable error", async () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+
+ const res = await app(db).fetch(
+ requestFor(db, accountId, `/systems/${systemId}/theme`, {
+ method: "PUT",
+ body: JSON.stringify({ tokens: { "color.accent": "red", density: "spacious" } }),
+ }),
+ );
+ expect(res.status).toBe(422);
+ const body = (await res.json()) as { rejected: Array<{ key: string }> };
+ expect(body.rejected.map((r) => r.key).sort()).toEqual(["color.accent", "density"]);
+ db.close();
+ });
+
+ // A rejected save must not have written anything. Dropping the invalid keys
+ // and saving the rest would silently discard settings the user already had —
+ // a destructive save wearing the costume of a validation error.
+ test("a rejected save leaves existing settings untouched", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+
+ saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId,
+ now: 1,
+ tokens: { "color.accent": "#2E7D5B", density: "relaxed" },
+ });
+
+ const result = saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId,
+ now: 2,
+ tokens: { "color.accent": "red", density: "compact" },
+ });
+
+ expect(result.ok).toBe(false);
+ // Both the invalid value AND the valid one alongside it are discarded.
+ expect(readTheme(db, "system", systemId).tokens).toEqual({
+ "color.accent": "#2E7D5B",
+ density: "relaxed",
+ });
+ db.close();
+ });
+
+ // Saving appearance must never wipe directory settings.
+ test("saving one layer leaves the other untouched", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+
+ saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId,
+ now: 1,
+ composition: { "directory.columns": "two" },
+ });
+ saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId,
+ now: 2,
+ tokens: { density: "compact" },
+ });
+
+ const stored = readTheme(db, "system", systemId);
+ expect(stored.composition).toEqual({ "directory.columns": "two" });
+ expect(stored.tokens).toEqual({ density: "compact" });
+ db.close();
+ });
+
+ test("a member reset is stored as an explicit null, preserving the third state", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+ const memberId = randomUUID();
+ db.query(
+ "INSERT INTO members (id, system_id, pk_member_uuid, pk_member_hid, first_seen_at) VALUES (?,?,?,?,?)",
+ ).run(memberId, systemId, "mu-1", "kzsbyo", Date.now());
+
+ saveTheme(db, {
+ ownerType: "member",
+ ownerId: memberId,
+ accountId,
+ now: 1,
+ tokens: { "color.accent": null, density: "compact" },
+ });
+
+ const stored = readTheme(db, "member", memberId) as { tokens: Record<string, unknown> };
+ expect(stored.tokens["color.accent"]).toBeNull();
+ expect(stored.tokens["density"]).toBe("compact");
+ db.close();
+ });
+
+ test("a member cannot store a system-only token", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+ const memberId = randomUUID();
+ db.query(
+ "INSERT INTO members (id, system_id, pk_member_uuid, pk_member_hid, first_seen_at) VALUES (?,?,?,?,?)",
+ ).run(memberId, systemId, "mu-1", "kzsbyo", Date.now());
+
+ const result = saveTheme(db, {
+ ownerType: "member",
+ ownerId: memberId,
+ accountId,
+ now: 1,
+ tokens: { "color.scheme": "dark" },
+ });
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.rejected[0]?.reason).toBe("not_member_overridable");
+ expect(readTheme(db, "member", memberId).tokens).toEqual({});
+ db.close();
+ });
+
+ test("member inheritance resolves through the saved layers", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+ const memberId = randomUUID();
+ db.query(
+ "INSERT INTO members (id, system_id, pk_member_uuid, pk_member_hid, first_seen_at) VALUES (?,?,?,?,?)",
+ ).run(memberId, systemId, "mu-1", "kzsbyo", Date.now());
+
+ saveTheme(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ accountId,
+ now: 1,
+ tokens: { "color.accent": "#111111", density: "relaxed" },
+ });
+ saveTheme(db, {
+ ownerType: "member",
+ ownerId: memberId,
+ accountId,
+ now: 2,
+ tokens: { "color.accent": "#222222", density: null },
+ });
+
+ const resolved = resolveTheme(
+ readTheme(db, "system", systemId).tokens,
+ readTheme(db, "member", memberId).tokens,
+ );
+ expect(resolved.light["color.accent"]).toBe("#222222"); // member override
+ expect(resolved.light["density"]).toBe("normal"); // explicit reset to platform
+ db.close();
+ });
+});
+
+describe("members", () => {
+ test("lists the members PluralKit returns publicly", async () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+
+ const res = await app(db).fetch(requestFor(db, accountId, `/systems/${systemId}/members`));
+ const body = (await res.json()) as { members: Array<{ pkMemberHid: string }> };
+ expect(body.members.map((m) => m.pkMemberHid)).toEqual(["kzsbyo", "abcdef"]);
+ db.close();
+ });
+
+ // Being signed in as the owner does not change what the public API returns,
+ // and pkviewer does not ask for more.
+ test("a member PluralKit withholds is absent, and 404s individually", async () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+ const pk = pkStub([MEMBERS[0]!]); // second member is private
+
+ const list = await app(db, pk).fetch(
+ requestFor(db, accountId, `/systems/${systemId}/members`),
+ );
+ const body = (await list.json()) as { members: Array<{ pkMemberHid: string }> };
+ expect(body.members.map((m) => m.pkMemberHid)).toEqual(["kzsbyo"]);
+
+ const direct = await app(db, pk).fetch(
+ requestFor(db, accountId, `/systems/${systemId}/members/abcdef`),
+ );
+ expect(direct.status).toBe(404);
+ db.close();
+ });
+
+ test("a member row is created lazily on first access", async () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+
+ expect(db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM members").get()?.n).toBe(0);
+ await app(db).fetch(requestFor(db, accountId, `/systems/${systemId}/members/kzsbyo`));
+ expect(db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM members").get()?.n).toBe(1);
+ db.close();
+ });
+});
+
+describe("social links", () => {
+ test("saves an ordered list", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+
+ const result = saveSocialLinks(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ links: [
+ { platform: "github", label: "Code", url: "https://github.com/example" },
+ { platform: "website", label: "", url: "https://example.com" },
+ ],
+ });
+ expect(result.ok).toBe(true);
+
+ const stored = listSocialLinks(db, "system", systemId);
+ expect(stored.map((l) => l.platform)).toEqual(["github", "website"]);
+ expect(stored[0]?.sortOrder).toBe(0);
+ expect(stored[1]?.label).toBeNull();
+ db.close();
+ });
+
+ test("reordering is a whole-list replacement", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+ const links = [
+ { platform: "github", label: "", url: "https://github.com/a" },
+ { platform: "website", label: "", url: "https://example.com" },
+ ];
+
+ saveSocialLinks(db, { ownerType: "system", ownerId: systemId, links });
+ saveSocialLinks(db, { ownerType: "system", ownerId: systemId, links: [...links].reverse() });
+
+ expect(listSocialLinks(db, "system", systemId).map((l) => l.platform)).toEqual([
+ "website",
+ "github",
+ ]);
+ db.close();
+ });
+
+ test("removing a link deletes it", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+ saveSocialLinks(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ links: [{ platform: "github", label: "", url: "https://github.com/a" }],
+ });
+ saveSocialLinks(db, { ownerType: "system", ownerId: systemId, links: [] });
+ expect(listSocialLinks(db, "system", systemId)).toHaveLength(0);
+ db.close();
+ });
+
+ // A link is rendered into an href. Any scheme but http(s) is an XSS vector.
+ test("rejects dangerous URL schemes", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+
+ for (const url of [
+ "javascript:alert(1)",
+ "data:text/html,<script>alert(1)</script>",
+ "file:///etc/passwd",
+ "not a url",
+ ]) {
+ const result = saveSocialLinks(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ links: [{ platform: "website", label: "", url }],
+ });
+ expect(result.ok, url).toBe(false);
+ }
+ expect(listSocialLinks(db, "system", systemId)).toHaveLength(0);
+ db.close();
+ });
+
+ test("rejects an unknown platform", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+ const result = saveSocialLinks(db, {
+ ownerType: "system",
+ ownerId: systemId,
+ links: [{ platform: "myspace", label: "", url: "https://example.com" }],
+ });
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.errors[0]?.field).toBe("platform");
+ db.close();
+ });
+
+ test("caps the number of links", () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+ const many = Array.from({ length: 20 }, () => ({
+ platform: "website",
+ label: "",
+ url: "https://example.com",
+ }));
+ expect(saveSocialLinks(db, { ownerType: "system", ownerId: systemId, links: many }).ok).toBe(
+ false,
+ );
+ db.close();
+ });
+
+ test("a stranger cannot write links through the API", async () => {
+ const db = freshDb();
+ const owner = seedAccount(db);
+ const stranger = seedAccount(db);
+ const systemId = seedOwnedSystem(db, owner);
+
+ const res = await app(db).fetch(
+ requestFor(db, stranger, `/systems/${systemId}/socials`, {
+ method: "PUT",
+ body: JSON.stringify({ links: [{ platform: "website", url: "https://evil.test" }] }),
+ }),
+ );
+ expect(res.status).toBe(404);
+ expect(listSocialLinks(db, "system", systemId)).toHaveLength(0);
+ db.close();
+ });
+});
+
+describe("overview", () => {
+ test("reports the public path and cache age", async () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+
+ const res = await app(db).fetch(requestFor(db, accountId, `/systems/${systemId}`));
+ const body = (await res.json()) as { publicPath: string; name: string; reachable: boolean };
+ expect(body.publicPath).toBe("/s/tythty");
+ expect(body.name).toBe("Doughmination");
+ expect(body.reachable).toBe(true);
+ db.close();
+ });
+
+ test("survives PluralKit being unreachable", async () => {
+ const db = freshDb();
+ const accountId = seedAccount(db);
+ const systemId = seedOwnedSystem(db, accountId);
+
+ const down = new PkClient({
+ apiBase: "https://api.pluralkit.me/v2",
+ userAgent: "pkviewer/test (+https://github.com/owner/pkviewer)",
+ readRps: 1000,
+ writeRps: 1000,
+ fetchImpl: (async () => new Response("", { status: 502 })) as unknown as typeof fetch,
+ snapshots: new MemorySnapshotStore(),
+ sleep: async () => {},
+ maxRetries: 0,
+ });
+
+ const res = await app(db, down).fetch(requestFor(db, accountId, `/systems/${systemId}`));
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { reachable: boolean };
+ expect(body.reachable).toBe(false);
+ db.close();
+ });
+});
diff --git a/apps/api/test/pk-client.test.ts b/apps/api/test/pk-client.test.ts
new file mode 100644
index 0000000..30964e4
--- /dev/null
+++ b/apps/api/test/pk-client.test.ts
@@ -0,0 +1,250 @@
+import { describe, expect, test } from "bun:test";
+import { PkClient } from "../src/pk/client.ts";
+import { PkNotFound, PkRateLimited, PkUpstreamDown } from "../src/pk/errors.ts";
+import { MemorySnapshotStore } from "../src/pk/snapshots.ts";
+
+const UA = "pkviewer/0.1.0 (+https://github.com/owner/pkviewer)";
+
+type Call = { url: string; headers: Headers; method: string };
+
+function stubFetch(handler: (call: Call, n: number) => Response | Promise<Response>) {
+ const calls: Call[] = [];
+ const impl = (async (input: string | URL | Request, init?: RequestInit) => {
+ const call: Call = {
+ url: String(input),
+ headers: new Headers(init?.headers),
+ method: init?.method ?? "GET",
+ };
+ calls.push(call);
+ return handler(call, calls.length);
+ }) as unknown as typeof fetch;
+ return { impl, calls };
+}
+
+function json(body: unknown, init: ResponseInit = {}): Response {
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ ...init,
+ });
+}
+
+function makeClient(fetchImpl: typeof fetch, extra: Partial<Record<string, unknown>> = {}) {
+ return new PkClient({
+ apiBase: "https://api.pluralkit.me/v2",
+ userAgent: UA,
+ readRps: 1000,
+ writeRps: 1000,
+ fetchImpl,
+ snapshots: new MemorySnapshotStore(),
+ sleep: async () => {},
+ ...extra,
+ });
+}
+
+describe("user agent", () => {
+ // PluralKit rejects a missing User-Agent with 400. This is the guard that
+ // keeps every outbound request carrying it.
+ test("is sent on every request", async () => {
+ const { impl, calls } = stubFetch(() => json({ id: "tythty", uuid: "u" }));
+ const client = makeClient(impl);
+ await client.getSystem("tythty");
+ await client.getMembers("tythty");
+ await client.getMember("kzsbyo");
+ expect(calls).toHaveLength(3);
+ for (const c of calls) expect(c.headers.get("user-agent")).toBe(UA);
+ });
+
+ test("cannot be constructed empty", () => {
+ expect(() => makeClient(stubFetch(() => json({})).impl, { userAgent: "" })).toThrow(
+ /User-Agent/,
+ );
+ });
+});
+
+describe("credentials", () => {
+ test("are sent only when explicitly passed at the call site", async () => {
+ const { impl, calls } = stubFetch(() => json({ id: "tythty", uuid: "u" }));
+ const client = makeClient(impl);
+
+ await client.getSystem("tythty");
+ expect(calls[0]?.headers.get("authorization")).toBeNull();
+
+ await client.getSystem("tythty", { as: { token: "secret-token" }, maxAgeMs: 0 });
+ expect(calls[1]?.headers.get("authorization")).toBe("secret-token");
+ });
+
+ // An authenticated response with no account to scope it to must never be
+ // written to a shared cache, or it becomes reachable from the public scope.
+ test("an unscoped authenticated response is not cached", async () => {
+ const snapshots = new MemorySnapshotStore();
+ const { impl } = stubFetch(() => json({ id: "tythty", uuid: "private-data" }));
+ const client = makeClient(impl, { snapshots });
+
+ await client.getSystem("tythty", { as: { token: "secret" } });
+ expect(snapshots.read("system", "tythty", "public")).toBeUndefined();
+ });
+
+ test("an account-scoped response is never readable from the public scope", async () => {
+ const snapshots = new MemorySnapshotStore();
+ const { impl } = stubFetch(() => json({ id: "tythty", uuid: "private-data" }));
+ const client = makeClient(impl, { snapshots });
+
+ await client.getSystem("tythty", { as: { token: "secret", accountId: "acct-1" } });
+ expect(snapshots.read("system", "tythty", "acct-1")).toBeDefined();
+ expect(snapshots.read("system", "tythty", "public")).toBeUndefined();
+ });
+
+ test("log entries never carry the token", async () => {
+ const entries: string[] = [];
+ const { impl } = stubFetch(() => json({ id: "tythty", uuid: "u" }));
+ const client = makeClient(impl, {
+ onLog: (e: unknown) => entries.push(JSON.stringify(e)),
+ });
+ await client.getSystem("tythty", { as: { token: "super-secret-token" } });
+ expect(entries.join("\n")).not.toContain("super-secret-token");
+ expect(entries.join("\n")).toContain('"authenticated":true');
+ });
+});
+
+describe("caching", () => {
+ test("serves a fresh snapshot without hitting the network", async () => {
+ const { impl, calls } = stubFetch(() => json({ id: "tythty", uuid: "u" }));
+ const client = makeClient(impl);
+ await client.getSystem("tythty");
+ await client.getSystem("tythty");
+ expect(calls).toHaveLength(1);
+ });
+
+ test("refetches once the freshness window passes", async () => {
+ let now = 1_000_000;
+ const { impl, calls } = stubFetch(() => json({ id: "tythty", uuid: "u" }));
+ const client = makeClient(impl, { clock: () => now, defaultMaxAgeMs: 1000 });
+ await client.getSystem("tythty");
+ now += 2000;
+ await client.getSystem("tythty");
+ expect(calls).toHaveLength(2);
+ });
+
+ // Fifty concurrent visitors to one popular page must produce one upstream call.
+ test("coalesces concurrent requests for the same reference", async () => {
+ const { impl, calls } = stubFetch(async () => {
+ await new Promise((r) => setTimeout(r, 5));
+ return json({ id: "tythty", uuid: "u" });
+ });
+ const client = makeClient(impl);
+ await Promise.all(Array.from({ length: 25 }, () => client.getSystem("tythty")));
+ expect(calls).toHaveLength(1);
+ });
+});
+
+describe("failure handling", () => {
+ test("maps 404 to PkNotFound, which does not distinguish private from absent", async () => {
+ const { impl } = stubFetch(() => new Response("", { status: 404 }));
+ const client = makeClient(impl);
+ await expect(client.getSystem("nope")).rejects.toBeInstanceOf(PkNotFound);
+ });
+
+ test("retries a 5xx and succeeds", async () => {
+ const { impl, calls } = stubFetch((_c, n) =>
+ n < 3 ? new Response("", { status: 503 }) : json({ id: "tythty", uuid: "u" }),
+ );
+ const client = makeClient(impl);
+ await expect(client.getSystem("tythty")).resolves.toMatchObject({ id: "tythty" });
+ expect(calls).toHaveLength(3);
+ });
+
+ test("surfaces a rate limit with its Retry-After once retries are exhausted", async () => {
+ const { impl } = stubFetch(
+ () => new Response("", { status: 429, headers: { "retry-after": "2" } }),
+ );
+ const client = makeClient(impl, { maxRetries: 1 });
+ const err = await client.getSystem("tythty").catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(PkRateLimited);
+ expect((err as PkRateLimited).retryAfterMs).toBe(2000);
+ });
+
+ // A presentation layer that inherits its upstream's downtime is not much of a
+ // presentation layer: pages fall back to the last good snapshot.
+ test("falls back to a stale snapshot when PluralKit is down", async () => {
+ let up = true;
+ const { impl } = stubFetch(() =>
+ up ? json({ id: "tythty", uuid: "u", name: "Example System" }) : new Response("", { status: 502 }),
+ );
+ let now = 1_000_000;
+ const client = makeClient(impl, { clock: () => now, defaultMaxAgeMs: 1000 });
+
+ await client.getSystem("tythty");
+ up = false;
+ now += 60_000;
+
+ const result = await client.getSystem("tythty");
+ expect(result).toMatchObject({ name: "Example System" });
+ expect(client.snapshotAge("system", "tythty")).toBe(60_000);
+ });
+
+ test("propagates upstream failure when no snapshot exists", async () => {
+ const { impl } = stubFetch(() => new Response("", { status: 502 }));
+ const client = makeClient(impl, { maxRetries: 0 });
+ await expect(client.getSystem("tythty")).rejects.toBeInstanceOf(PkUpstreamDown);
+ });
+
+ test("honours allowStale:false", async () => {
+ let up = true;
+ const { impl } = stubFetch(() => (up ? json({ id: "t", uuid: "u" }) : new Response("", { status: 502 })));
+ let now = 1_000;
+ const client = makeClient(impl, { clock: () => now, defaultMaxAgeMs: 10, maxRetries: 0 });
+ await client.getSystem("t");
+ up = false;
+ now += 1000;
+ await expect(client.getSystem("t", { allowStale: false })).rejects.toBeInstanceOf(
+ PkUpstreamDown,
+ );
+ });
+});
+
+describe("claim verification support", () => {
+ // Tier 1: Discord asserts identity, PluralKit asserts the link. No credential.
+ test("resolves a system from a Discord account id", async () => {
+ const { impl, calls } = stubFetch(() => json({ id: "tythty", uuid: "sys-uuid" }));
+ const client = makeClient(impl);
+ const system = await client.getSystem("123456789012345678");
+ expect(calls[0]?.url).toBe("https://api.pluralkit.me/v2/systems/123456789012345678");
+ expect(system.uuid).toBe("sys-uuid");
+ });
+
+ // Tier 3: the token is used within one request and never persisted or cached.
+ test("getOwnSystem sends the token and caches nothing", async () => {
+ const snapshots = new MemorySnapshotStore();
+ const { impl, calls } = stubFetch(() => json({ id: "tythty", uuid: "sys-uuid" }));
+ const client = makeClient(impl, { snapshots });
+ await client.getOwnSystem("transient-token");
+ expect(calls[0]?.headers.get("authorization")).toBe("transient-token");
+ expect(snapshots.read("system", "@me", "public")).toBeUndefined();
+ });
+});
+
+describe("cache bypass", () => {
+ // maxAgeMs: 0 must mean "never serve from cache", not "fresh within 0ms".
+ // Claim verification relies on this to re-read a system description.
+ test("maxAgeMs 0 always refetches, even within the same millisecond", async () => {
+ const frozen = 1_000_000;
+ const { impl, calls } = stubFetch(() => json({ id: "tythty", uuid: "u" }));
+ const client = makeClient(impl, { clock: () => frozen });
+
+ await client.getSystem("tythty", { maxAgeMs: 0 });
+ await client.getSystem("tythty", { maxAgeMs: 0 });
+ await client.getSystem("tythty", { maxAgeMs: 0 });
+ expect(calls).toHaveLength(3);
+ });
+
+ test("a positive maxAge still serves from cache", async () => {
+ const frozen = 1_000_000;
+ const { impl, calls } = stubFetch(() => json({ id: "tythty", uuid: "u" }));
+ const client = makeClient(impl, { clock: () => frozen });
+
+ await client.getSystem("tythty", { maxAgeMs: 60_000 });
+ await client.getSystem("tythty", { maxAgeMs: 60_000 });
+ expect(calls).toHaveLength(1);
+ });
+});
diff --git a/apps/api/test/slug-management.test.ts b/apps/api/test/slug-management.test.ts
new file mode 100644
index 0000000..f0368f2
--- /dev/null
+++ b/apps/api/test/slug-management.test.ts
@@ -0,0 +1,544 @@
+import { describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import { Hono } from "hono";
+import { createSession } from "../src/auth/sessions.ts";
+import { ensureSystemRow } from "../src/claims/index.ts";
+import { loadConfig } from "../src/config/index.ts";
+import { openDb, type Db } from "../src/db/index.ts";
+import { migrate } from "../src/db/migrate.ts";
+import { requireKnownOrigin } from "../src/http/middleware.ts";
+import { slugRoutes } from "../src/http/routes/slugs.ts";
+import { PkClient } from "../src/pk/client.ts";
+import { MemorySnapshotStore } from "../src/pk/snapshots.ts";
+import { activeSlugFor } from "../src/slugs/claim.ts";
+import { RESERVATION_MS, reservationsForSubject } from "../src/slugs/lifecycle.ts";
+import { memberPath, resolveMemberRef, resolveSystemRef, systemPath } from "../src/slugs/resolve.ts";
+
+const SYS = { id: "tythty", uuid: "uuid-a", name: "Doughmination", description: null };
+const MEMBERS = [
+ { id: "kzsbyo", uuid: "mu-1", name: "Clove", display_name: null, pronouns: null, avatar_url: null },
+ { id: "wrenxy", uuid: "mu-2", name: "Wren", display_name: null, pronouns: null, avatar_url: null },
+];
+
+const cfg = loadConfig({
+ PUBLIC_APP_ORIGIN: "http://app.localhost:3000",
+ PUBLIC_USERCONTENT_ORIGIN: "http://system.localhost:3000",
+ PUBLIC_ASSET_ORIGIN: "http://system.localhost:3000",
+ INTERNAL_API_ORIGIN: "http://127.0.0.1:3001",
+ PK_USER_AGENT_CONTACT: "https://github.com/owner/pkviewer",
+ SESSION_SECRET: "x".repeat(40),
+});
+
+function freshDb(): Db {
+ const db = openDb(":memory:");
+ migrate(db);
+ return db;
+}
+
+function pk(members = MEMBERS) {
+ const impl = (async (input: string | URL) => {
+ const path = String(input).replace("https://api.pluralkit.me/v2", "");
+ if (path.endsWith("/members")) return Response.json(members);
+ const ref = decodeURIComponent(path.replace("/systems/", ""));
+ return ref === SYS.uuid || ref === SYS.id
+ ? Response.json(SYS)
+ : new Response("", { status: 404 });
+ }) as unknown as typeof fetch;
+
+ return new PkClient({
+ apiBase: "https://api.pluralkit.me/v2",
+ userAgent: "pkviewer/test (+https://github.com/owner/pkviewer)",
+ readRps: 1000,
+ writeRps: 1000,
+ fetchImpl: impl,
+ snapshots: new MemorySnapshotStore(),
+ sleep: async () => {},
+ maxRetries: 0,
+ });
+}
+
+function account(db: Db): string {
+ const id = randomUUID();
+ db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run(id, Date.now());
+ return id;
+}
+
+function ownedSystem(db: Db, accountId: string): string {
+ const systemId = ensureSystemRow(db, SYS as never, Date.now());
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(accountId, systemId, Date.now());
+ return systemId;
+}
+
+function memberRow(db: Db, systemId: string, uuid: string, hid: string): string {
+ const id = randomUUID();
+ db.query(
+ "INSERT INTO members (id, system_id, pk_member_uuid, pk_member_hid, first_seen_at) VALUES (?,?,?,?,?)",
+ ).run(id, systemId, uuid, hid, Date.now());
+ return id;
+}
+
+function app(db: Db, now?: () => number) {
+ const guarded = new Hono();
+ guarded.use("*", requireKnownOrigin(cfg));
+ guarded.route("/", slugRoutes({ cfg, db, pk: pk(), ...(now ? { now } : {}) }));
+ return guarded;
+}
+
+function req(db: Db, accountId: string | null, path: string, init: RequestInit = {}) {
+ const headers = new Headers(init.headers);
+ headers.set("origin", cfg.appOrigin);
+ if (init.body) headers.set("content-type", "application/json");
+ if (accountId) {
+ const { token } = createSession(db, accountId, Date.now());
+ headers.set("cookie", `__Host-pkv_session=${token}`);
+ }
+ return new Request(`http://app.localhost${path}`, { ...init, headers });
+}
+
+const claimBody = (subjectId: string, slug: string, scope = "system") =>
+ JSON.stringify({ scope, subjectId, slug });
+
+describe("setting a system address", () => {
+ test("accepts a valid address", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+
+ const res = await app(db).fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "doughmination") }),
+ );
+ expect(res.status).toBe(200);
+ expect(activeSlugFor(db, "system", systemId)?.slug_display).toBe("doughmination");
+ db.close();
+ });
+
+ test("normalises case rather than rejecting it", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ await app(db).fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "DoughMination") }),
+ );
+ expect(activeSlugFor(db, "system", systemId)?.slug_display).toBe("doughmination");
+ db.close();
+ });
+
+ test.each([
+ ["too short", "ab", "too_short"],
+ ["reserved word", "docs", "reserved"],
+ ["consecutive hyphens", "xn--evil", "double_hyphen"],
+ ["leading hyphen", "-nope", "edge_hyphen"],
+ ["over maximum length", "a".repeat(33), "too_long"],
+ ["invalid characters", "dough mination", "invalid_characters"],
+ ["id shaped", "clove", "id_shaped"],
+ ])("rejects %s", async (_label, slug, reason) => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+
+ const res = await app(db).fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, slug) }),
+ );
+ expect(res.status).toBe(400);
+ expect(((await res.json()) as { detail: string }).detail).toBe(reason);
+ expect(activeSlugFor(db, "system", systemId)).toBeNull();
+ db.close();
+ });
+});
+
+describe("address lifecycle", () => {
+ test("changing the address holds the previous one for 7 days", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ let now = 1_000_000;
+ const client = app(db, () => now);
+
+ await client.fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "first-name") }));
+ await client.fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "second-name") }));
+
+ const held = reservationsForSubject(db, "system", systemId, now);
+ expect(held).toEqual([{ slug: "first-name", until: now + RESERVATION_MS }]);
+ expect(activeSlugFor(db, "system", systemId)?.slug_display).toBe("second-name");
+ db.close();
+ });
+
+ test("another subject cannot take a held address, and is not told who holds it", async () => {
+ const db = freshDb();
+ const ownerA = account(db);
+ const systemA = ownedSystem(db, ownerA);
+
+ const ownerB = account(db);
+ const systemB = randomUUID();
+ db.query(
+ "INSERT INTO systems (id, pk_system_uuid, pk_system_hid, created_at) VALUES (?,?,?,?)",
+ ).run(systemB, "uuid-b", "bbbbbb", Date.now());
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(ownerB, systemB, Date.now());
+
+ let now = 1_000_000;
+ const client = app(db, () => now);
+
+ await client.fetch(req(db, ownerA, "/claim", { method: "POST", body: claimBody(systemA, "wanted-name") }));
+ await client.fetch(req(db, ownerA, "/claim", { method: "POST", body: claimBody(systemA, "other-name") }));
+
+ const res = await client.fetch(
+ req(db, ownerB, "/claim", { method: "POST", body: claimBody(systemB, "wanted-name") }),
+ );
+ expect(res.status).toBe(409);
+ const body = await res.text();
+ expect(body).toContain("reserved");
+ // Nothing identifies the holder.
+ expect(body).not.toContain(systemA);
+ expect(body).not.toContain(ownerA);
+ db.close();
+ });
+
+ test("the previous holder can take it back during the hold", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ let now = 1_000_000;
+ const client = app(db, () => now);
+
+ await client.fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "wanted-name") }));
+ await client.fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "other-name") }));
+
+ now += 3 * 86_400_000;
+ const res = await client.fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "wanted-name") }),
+ );
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as { kind: string }).kind).toBe("reclaimed");
+ db.close();
+ });
+
+ test("after the hold lapses anyone may take it", async () => {
+ const db = freshDb();
+ const ownerA = account(db);
+ const systemA = ownedSystem(db, ownerA);
+ const ownerB = account(db);
+ const systemB = randomUUID();
+ db.query(
+ "INSERT INTO systems (id, pk_system_uuid, pk_system_hid, created_at) VALUES (?,?,?,?)",
+ ).run(systemB, "uuid-b", "bbbbbb", Date.now());
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(ownerB, systemB, Date.now());
+
+ let now = 1_000_000;
+ const client = app(db, () => now);
+ await client.fetch(req(db, ownerA, "/claim", { method: "POST", body: claimBody(systemA, "wanted-name") }));
+ await client.fetch(req(db, ownerA, "/claim", { method: "POST", body: claimBody(systemA, "other-name") }));
+
+ now += RESERVATION_MS;
+ const res = await client.fetch(
+ req(db, ownerB, "/claim", { method: "POST", body: claimBody(systemB, "wanted-name") }),
+ );
+ expect(res.status).toBe(200);
+ db.close();
+ });
+
+ test("release requires confirmation and reports the hold expiry", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ const now = 1_000_000;
+ const client = app(db, () => now);
+
+ await client.fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "released-name") }));
+
+ const unconfirmed = await client.fetch(
+ req(db, acct, "/release", {
+ method: "POST",
+ body: JSON.stringify({ scope: "system", subjectId: systemId }),
+ }),
+ );
+ expect(unconfirmed.status).toBe(400);
+ expect(activeSlugFor(db, "system", systemId)).not.toBeNull();
+
+ const confirmed = await client.fetch(
+ req(db, acct, "/release", {
+ method: "POST",
+ body: JSON.stringify({ scope: "system", subjectId: systemId, confirm: true }),
+ }),
+ );
+ expect(confirmed.status).toBe(200);
+ expect(((await confirmed.json()) as { reservedUntil: number }).reservedUntil).toBe(
+ now + RESERVATION_MS,
+ );
+ expect(activeSlugFor(db, "system", systemId)).toBeNull();
+ db.close();
+ });
+
+ test("status reports the current address and what is held", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ const now = 1_000_000;
+ const client = app(db, () => now);
+
+ await client.fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "first-name") }));
+ await client.fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "second-name") }));
+
+ const res = await client.fetch(req(db, acct, `/status?scope=system&subjectId=${systemId}`));
+ const body = (await res.json()) as {
+ current: { slug: string };
+ reservations: Array<{ slug: string }>;
+ reservationDays: number;
+ };
+ expect(body.current.slug).toBe("second-name");
+ expect(body.reservations.map((r) => r.slug)).toEqual(["first-name"]);
+ expect(body.reservationDays).toBe(7);
+ db.close();
+ });
+});
+
+describe("member addresses", () => {
+ test("accepts a two character address and an id-shaped one", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ const memberId = memberRow(db, systemId, "mu-1", "kzsbyo");
+
+ const short = await app(db).fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(memberId, "jo", "member") }),
+ );
+ expect(short.status).toBe(200);
+
+ // Member namespaces are per system, so id-shaped names stay available.
+ const idShaped = await app(db).fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(memberId, "clove", "member") }),
+ );
+ expect(idShaped.status).toBe(200);
+ db.close();
+ });
+
+ test("system reserved words are not reserved for members", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ const memberId = memberRow(db, systemId, "mu-1", "kzsbyo");
+
+ const res = await app(db).fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(memberId, "docs", "member") }),
+ );
+ expect(res.status).toBe(200);
+ db.close();
+ });
+
+ test("warns without blocking when an address shadows a sibling's id", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ const memberId = memberRow(db, systemId, "mu-1", "kzsbyo");
+
+ const res = await app(db).fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(memberId, "wrenxy", "member") }),
+ );
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { warnings: Array<{ code: string; memberHid: string }> };
+ expect(body.warnings).toContainEqual({ code: "shadows_member_id", memberHid: "wrenxy" });
+ db.close();
+ });
+
+ test("the same member address may exist in two different systems", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemA = ownedSystem(db, acct);
+ const systemB = randomUUID();
+ db.query(
+ "INSERT INTO systems (id, pk_system_uuid, pk_system_hid, created_at) VALUES (?,?,?,?)",
+ ).run(systemB, "uuid-b", "bbbbbb", Date.now());
+ db.query(
+ "INSERT INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+ ).run(acct, systemB, Date.now());
+
+ const m1 = memberRow(db, systemA, "mu-1", "kzsbyo");
+ const m2 = memberRow(db, systemB, "mu-9", "zzzzzz");
+
+ expect(
+ (await app(db).fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(m1, "ash", "member") }))).status,
+ ).toBe(200);
+ expect(
+ (await app(db).fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(m2, "ash", "member") }))).status,
+ ).toBe(200);
+ db.close();
+ });
+
+ test("rejects a one character member address", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ const memberId = memberRow(db, systemId, "mu-1", "kzsbyo");
+
+ const res = await app(db).fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(memberId, "a", "member") }),
+ );
+ expect(res.status).toBe(400);
+ db.close();
+ });
+});
+
+describe("authorization", () => {
+ test("an unauthenticated caller cannot change an address", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+
+ const res = await app(db).fetch(
+ req(db, null, "/claim", { method: "POST", body: claimBody(systemId, "taken-name") }),
+ );
+ expect(res.status).toBe(401);
+ expect(activeSlugFor(db, "system", systemId)).toBeNull();
+ db.close();
+ });
+
+ test("an account without a grant cannot change an address", async () => {
+ const db = freshDb();
+ const owner = account(db);
+ const stranger = account(db);
+ const systemId = ownedSystem(db, owner);
+
+ const res = await app(db).fetch(
+ req(db, stranger, "/claim", { method: "POST", body: claimBody(systemId, "stolen-name") }),
+ );
+ expect(res.status).toBe(403);
+ expect(activeSlugFor(db, "system", systemId)).toBeNull();
+ db.close();
+ });
+
+ test("a cross-site request without a known Origin is refused", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ const { token } = createSession(db, acct, Date.now());
+
+ const res = await app(db).fetch(
+ new Request("http://app.localhost/claim", {
+ method: "POST",
+ headers: { cookie: `__Host-pkv_session=${token}`, "content-type": "application/json" },
+ body: claimBody(systemId, "csrf-name"),
+ }),
+ );
+ expect(res.status).toBe(403);
+ expect(activeSlugFor(db, "system", systemId)).toBeNull();
+ db.close();
+ });
+
+ test("availability checks require a session", async () => {
+ const db = freshDb();
+ const res = await app(db).fetch(req(db, null, "/check?slug=anything"));
+ expect(res.status).toBe(401);
+ db.close();
+ });
+});
+
+describe("canonical public URLs", () => {
+ test("the address is canonical, and the id address still resolves", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ await app(db).fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "doughmination") }),
+ );
+
+ const client = pk();
+ const bySlug = await resolveSystemRef({ db, pk: client }, "doughmination");
+ const byId = await resolveSystemRef({ db, pk: client }, "tythty");
+
+ expect(bySlug.ok && bySlug.value.canonicalPath).toBe("/s/doughmination");
+ // The raw id page advertises the address as canonical.
+ expect(byId.ok && byId.value.canonicalPath).toBe("/s/doughmination");
+ expect(byId.ok && byId.value.matchedBy).toBe("id");
+ db.close();
+ });
+
+ test("with no address, the id URL is canonical", async () => {
+ const db = freshDb();
+ const result = await resolveSystemRef({ db, pk: pk() }, "tythty");
+ expect(result.ok && result.value.canonicalPath).toBe("/s/tythty");
+ expect(result.ok && result.value.slug).toBeNull();
+ db.close();
+ });
+
+ test("member pages behave equivalently", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ const memberId = memberRow(db, systemId, "mu-1", "kzsbyo");
+
+ await app(db).fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "doughmination") }));
+ await app(db).fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(memberId, "clove", "member") }));
+
+ const client = pk();
+ const system = await resolveSystemRef({ db, pk: client }, "doughmination");
+ if (!system.ok) throw new Error("system did not resolve");
+
+ const bySlug = await resolveMemberRef({ db, pk: client }, system.value, "clove");
+ const byId = await resolveMemberRef({ db, pk: client }, system.value, "kzsbyo");
+
+ expect(bySlug.ok && bySlug.value.canonicalPath).toBe("/s/doughmination/clove");
+ expect(byId.ok && byId.value.canonicalPath).toBe("/s/doughmination/clove");
+ db.close();
+ });
+
+ // Canonical URLs are composed from configured origins at render time. No
+ // absolute pkviewer URL is ever stored.
+ test("paths carry no origin, and no absolute URL is persisted", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ await app(db).fetch(
+ req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "doughmination") }),
+ );
+
+ expect(systemPath("tythty", "doughmination")).toBe("/s/doughmination");
+ expect(memberPath("tythty", "doughmination", "kzsbyo", "clove")).toBe("/s/doughmination/clove");
+
+ const tables = db
+ .query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE type='table'")
+ .all()
+ .map((r) => r.name);
+ for (const table of tables) {
+ const dump = JSON.stringify(db.query(`SELECT * FROM ${table}`).all());
+ expect(dump, table).not.toContain("http://");
+ expect(dump, table).not.toContain("https://system.");
+ }
+ db.close();
+ });
+
+ test("a Discord snowflake never resolves as a public address", async () => {
+ const db = freshDb();
+ const result = await resolveSystemRef({ db, pk: pk() }, "123456789012345678");
+ expect(result).toEqual({ ok: false, reason: "unsupported_reference" });
+ db.close();
+ });
+
+ test("a released address stops resolving to its old system", async () => {
+ const db = freshDb();
+ const acct = account(db);
+ const systemId = ownedSystem(db, acct);
+ const now = 1_000_000;
+ const client = app(db, () => now);
+
+ await client.fetch(req(db, acct, "/claim", { method: "POST", body: claimBody(systemId, "oldname") }));
+ await client.fetch(
+ req(db, acct, "/release", {
+ method: "POST",
+ body: JSON.stringify({ scope: "system", subjectId: systemId, confirm: true }),
+ }),
+ );
+
+ const resolved = await resolveSystemRef({ db, pk: pk(), now: () => now + 1 }, "oldname");
+ expect(resolved.ok).toBe(false);
+
+ // The system remains public at its id address throughout.
+ const byId = await resolveSystemRef({ db, pk: pk(), now: () => now + 1 }, "tythty");
+ expect(byId.ok && byId.value.canonicalPath).toBe("/s/tythty");
+ db.close();
+ });
+});
diff --git a/apps/api/test/slugs.test.ts b/apps/api/test/slugs.test.ts
new file mode 100644
index 0000000..1410427
--- /dev/null
+++ b/apps/api/test/slugs.test.ts
@@ -0,0 +1,437 @@
+import { describe, expect, test } from "bun:test";
+import { openDb, type Db } from "../src/db/index.ts";
+import { migrate } from "../src/db/migrate.ts";
+import { PkClient } from "../src/pk/client.ts";
+import { MemorySnapshotStore } from "../src/pk/snapshots.ts";
+import { activeSlugFor, checkSlugAvailability, claimSlug } from "../src/slugs/claim.ts";
+import { RESERVATION_MS, effectiveState, findSlug } from "../src/slugs/lifecycle.ts";
+import {
+ SLUG_MAX_LENGTH,
+ looksLikeHid,
+ looksLikeSnowflake,
+ normalizeSlug,
+ validateSlug,
+} from "../src/slugs/normalize.ts";
+import { memberPath, resolveMemberRef, resolveSystemRef, systemPath } from "../src/slugs/resolve.ts";
+
+function freshDb(): Db {
+ const db = openDb(":memory:");
+ migrate(db);
+ return db;
+}
+
+function seedSystem(db: Db, uuid: string, hid: string, id = `sys-${uuid}`): string {
+ db.query(
+ "INSERT INTO systems (id, pk_system_uuid, pk_system_hid, created_at) VALUES (?,?,?,?)",
+ ).run(id, uuid, hid, Date.now());
+ return id;
+}
+
+function seedMember(db: Db, systemId: string, uuid: string, hid: string, id = `mem-${uuid}`): string {
+ db.query(
+ "INSERT INTO members (id, system_id, pk_member_uuid, pk_member_hid, first_seen_at) VALUES (?,?,?,?,?)",
+ ).run(id, systemId, uuid, hid, Date.now());
+ return id;
+}
+
+function pkStub(systems: Record<string, unknown>, members: Record<string, unknown[]> = {}) {
+ const impl = (async (input: string | URL) => {
+ const path = String(input).replace("https://api.pluralkit.me/v2", "");
+ const memberMatch = path.match(/^\/systems\/([^/]+)\/members$/);
+ if (memberMatch) {
+ const list = members[decodeURIComponent(memberMatch[1]!)];
+ return list ? Response.json(list) : new Response("", { status: 404 });
+ }
+ const ref = decodeURIComponent(path.replace("/systems/", ""));
+ const found = systems[ref];
+ return found ? Response.json(found) : new Response("", { status: 404 });
+ }) as unknown as typeof fetch;
+
+ return new PkClient({
+ apiBase: "https://api.pluralkit.me/v2",
+ userAgent: "pkviewer/test (+https://github.com/owner/pkviewer)",
+ readRps: 1000,
+ writeRps: 1000,
+ fetchImpl: impl,
+ snapshots: new MemorySnapshotStore(),
+ sleep: async () => {},
+ maxRetries: 0,
+ });
+}
+
+describe("normalisation and validation", () => {
+ test("casefolds and trims", () => {
+ expect(normalizeSlug(" DoughMination ")).toBe("doughmination");
+ });
+
+ test("accepts lowercase letters, numbers and hyphens", () => {
+ expect(validateSlug("dough-mination-2", "system").ok).toBe(true);
+ });
+
+ test("rejects characters outside the allowed set rather than transliterating", () => {
+ // Silently rewriting someone's input into a different slug is worse than
+ // refusing it.
+ for (const bad of ["Доughmination", "dough mination", "dough_mination", "dough.mination", "café"]) {
+ const result = validateSlug(bad, "system");
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.reason).toBe("invalid_characters");
+ }
+ });
+
+ test("rejects edge and doubled hyphens", () => {
+ expect(validateSlug("-nope", "system")).toEqual({ ok: false, reason: "edge_hyphen" });
+ expect(validateSlug("nope-", "system")).toEqual({ ok: false, reason: "edge_hyphen" });
+ expect(validateSlug("xn--nope", "system")).toEqual({ ok: false, reason: "double_hyphen" });
+ });
+
+ test("enforces length bounds", () => {
+ expect(validateSlug("ab", "system")).toEqual({ ok: false, reason: "too_short" });
+ expect(validateSlug("ab", "member").ok).toBe(true);
+ expect(validateSlug("a".repeat(SLUG_MAX_LENGTH + 1), "system")).toEqual({
+ ok: false,
+ reason: "too_long",
+ });
+ });
+
+ // The max length is below a UUID's 36 characters, so /s/<uuid> can never be
+ // shadowed by any slug.
+ test("no valid slug can be as long as a UUID", () => {
+ const uuid = "0192f0a1-2b3c-4d5e-8f90-1a2b3c4d5e6f";
+ expect(uuid.length).toBeGreaterThan(SLUG_MAX_LENGTH);
+ expect(validateSlug(uuid, "system").ok).toBe(false);
+ });
+
+ test("reserves application names at system level only", () => {
+ expect(validateSlug("docs", "system")).toEqual({ ok: false, reason: "reserved" });
+ // Member slugs live under their system and cannot collide with app routes.
+ expect(validateSlug("docs", "member").ok).toBe(true);
+ });
+});
+
+describe("id-shaped slugs", () => {
+ // System slugs and system ids share one global namespace, so a slug shaped
+ // like an id could shadow another system's id URL. That is cross-tenant
+ // hijacking, so the shape is removed from the namespace.
+ test("a system slug may not look like a PluralKit id", () => {
+ expect(validateSlug("clove", "system")).toEqual({ ok: false, reason: "id_shaped" });
+ expect(validateSlug("tythty", "system")).toEqual({ ok: false, reason: "id_shaped" });
+ });
+
+ test("adding a digit or hyphen makes it claimable", () => {
+ expect(validateSlug("clove1", "system").ok).toBe(true);
+ expect(validateSlug("clove-", "system").ok).toBe(false); // still an edge hyphen
+ expect(validateSlug("cl-ove", "system").ok).toBe(true);
+ expect(validateSlug("doughmination", "system").ok).toBe(true);
+ });
+
+ test("4 and 7 letter names are unaffected", () => {
+ expect(validateSlug("dawn", "system").ok).toBe(true);
+ expect(validateSlug("cloveee", "system").ok).toBe(true);
+ });
+
+ // Member namespaces are per-system, so a collision only ever shadows a member
+ // of a system the claimant already controls.
+ test("a member slug MAY look like an id", () => {
+ expect(validateSlug("clove", "member").ok).toBe(true);
+ });
+
+ test("looksLikeHid matches only 5-6 lowercase letters", () => {
+ expect(looksLikeHid("clove")).toBe(true);
+ expect(looksLikeHid("tythty")).toBe(true);
+ expect(looksLikeHid("dawn")).toBe(false);
+ expect(looksLikeHid("clove1")).toBe(false);
+ expect(looksLikeHid("cloveee")).toBe(false);
+ });
+});
+
+describe("claiming", () => {
+ test("claims a free slug", () => {
+ const db = freshDb();
+ const sys = seedSystem(db, "uuid-a", "tythty");
+ const result = claimSlug(db, {
+ scope: "system",
+ scopeKey: "",
+ subjectId: sys,
+ requested: "Doughmination",
+ accountId: "acct-1",
+ now: 1000,
+ });
+ expect(result.ok && result.kind).toBe("claimed");
+ expect(activeSlugFor(db, "system", sys)?.slug_display).toBe("doughmination");
+ db.close();
+ });
+
+ test("a second subject cannot take an active slug", () => {
+ const db = freshDb();
+ const a = seedSystem(db, "uuid-a", "aaaaaa", "sys-a");
+ const b = seedSystem(db, "uuid-b", "bbbbbb", "sys-b");
+ const params = { scope: "system" as const, scopeKey: "", requested: "shared-name", accountId: null, now: 1000 };
+
+ expect(claimSlug(db, { ...params, subjectId: a }).ok).toBe(true);
+ expect(claimSlug(db, { ...params, subjectId: b })).toEqual({ ok: false, kind: "taken" });
+ db.close();
+ });
+
+ test("re-claiming your own active slug is a no-op", () => {
+ const db = freshDb();
+ const sys = seedSystem(db, "uuid-a", "tythty");
+ const params = { scope: "system" as const, scopeKey: "", subjectId: sys, requested: "mine", accountId: null, now: 1000 };
+ claimSlug(db, params);
+ const again = claimSlug(db, params);
+ expect(again.ok && again.kind).toBe("unchanged");
+ db.close();
+ });
+
+ // Renaming must not free the old URL for immediate sniping.
+ test("changing slug releases the previous one into its reservation", () => {
+ const db = freshDb();
+ const sys = seedSystem(db, "uuid-a", "tythty");
+ const now = 1_000_000;
+
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "first-name", accountId: null, now });
+ const second = claimSlug(db, {
+ scope: "system", scopeKey: "", subjectId: sys, requested: "second-name", accountId: null, now,
+ });
+
+ expect(second.ok && second.previousSlug).toBe("first-name");
+ const old = findSlug(db, "system", "", "first-name")!;
+ expect(effectiveState(old, now).kind).toBe("reserved");
+ expect(old.reserved_principal_id).toBe(sys);
+ expect(activeSlugFor(db, "system", sys)?.slug_display).toBe("second-name");
+ db.close();
+ });
+
+ test("a reserved slug is refused to others, without naming the holder", () => {
+ const db = freshDb();
+ const a = seedSystem(db, "uuid-a", "aaaaaa", "sys-a");
+ const b = seedSystem(db, "uuid-b", "bbbbbb", "sys-b");
+ const now = 1_000_000;
+
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: a, requested: "wanted-name", accountId: null, now });
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: a, requested: "other-name", accountId: null, now });
+
+ const attempt = claimSlug(db, {
+ scope: "system", scopeKey: "", subjectId: b, requested: "wanted-name", accountId: null, now: now + 1000,
+ });
+ expect(attempt.ok).toBe(false);
+ if (!attempt.ok && attempt.kind === "reserved") {
+ expect(attempt.until).toBe(now + RESERVATION_MS);
+ expect(JSON.stringify(attempt)).not.toContain("sys-a");
+ } else {
+ throw new Error("expected a reservation refusal");
+ }
+ db.close();
+ });
+
+ // Reservation follows the SUBJECT, not the account (decision 6).
+ test("the previous subject reclaims its own reserved slug", () => {
+ const db = freshDb();
+ const sys = seedSystem(db, "uuid-a", "tythty");
+ const now = 1_000_000;
+
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "wanted-name", accountId: "acct-1", now });
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "other-name", accountId: "acct-1", now });
+
+ // A different account, managing the same system, still reclaims it.
+ const back = claimSlug(db, {
+ scope: "system", scopeKey: "", subjectId: sys, requested: "wanted-name", accountId: "acct-2", now: now + 5000,
+ });
+ expect(back.ok && back.kind).toBe("reclaimed");
+ db.close();
+ });
+
+ test("once a reservation lapses anyone may claim it", () => {
+ const db = freshDb();
+ const a = seedSystem(db, "uuid-a", "aaaaaa", "sys-a");
+ const b = seedSystem(db, "uuid-b", "bbbbbb", "sys-b");
+ const now = 1_000_000;
+
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: a, requested: "wanted-name", accountId: null, now });
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: a, requested: "other-name", accountId: null, now });
+
+ const early = claimSlug(db, {
+ scope: "system", scopeKey: "", subjectId: b, requested: "wanted-name", accountId: null,
+ now: now + RESERVATION_MS - 1,
+ });
+ expect(early.ok).toBe(false);
+
+ const late = claimSlug(db, {
+ scope: "system", scopeKey: "", subjectId: b, requested: "wanted-name", accountId: null,
+ now: now + RESERVATION_MS,
+ });
+ expect(late.ok && late.kind).toBe("claimed");
+ db.close();
+ });
+
+ test("member slugs are scoped per system", () => {
+ const db = freshDb();
+ const s1 = seedSystem(db, "uuid-a", "aaaaaa", "sys-a");
+ const s2 = seedSystem(db, "uuid-b", "bbbbbb", "sys-b");
+ const m1 = seedMember(db, s1, "mu-1", "aaaaa", "mem-1");
+ const m2 = seedMember(db, s2, "mu-2", "bbbbb", "mem-2");
+
+ expect(claimSlug(db, { scope: "member", scopeKey: s1, subjectId: m1, requested: "clove", accountId: null, now: 1000 }).ok).toBe(true);
+ // Same name, different system: allowed.
+ expect(claimSlug(db, { scope: "member", scopeKey: s2, subjectId: m2, requested: "clove", accountId: null, now: 1000 }).ok).toBe(true);
+ db.close();
+ });
+
+ test("a member slug shadowing a sibling id warns but does not block", () => {
+ const db = freshDb();
+ const sys = seedSystem(db, "uuid-a", "tythty");
+ const mem = seedMember(db, sys, "mu-1", "abcde", "mem-1");
+
+ const result = claimSlug(db, {
+ scope: "member", scopeKey: sys, subjectId: mem, requested: "kzsbyo",
+ accountId: null, now: 1000, siblingHids: ["kzsbyo", "qqqqq"],
+ });
+
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.warnings).toContainEqual({ code: "shadows_member_id", memberHid: "kzsbyo" });
+ }
+ db.close();
+ });
+
+ test("history records every transition", () => {
+ const db = freshDb();
+ const sys = seedSystem(db, "uuid-a", "tythty");
+ const now = 1_000_000;
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "one", accountId: null, now });
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "two", accountId: null, now });
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "one", accountId: null, now: now + 10 });
+
+ const events = db
+ .query<{ event: string }, []>("SELECT event FROM slug_history ORDER BY id")
+ .all()
+ .map((r) => r.event);
+ expect(events).toEqual(["claimed", "released", "claimed", "released", "reclaimed"]);
+ db.close();
+ });
+});
+
+describe("availability checks", () => {
+ test("reports invalid, taken, reserved and free", () => {
+ const db = freshDb();
+ const a = seedSystem(db, "uuid-a", "aaaaaa", "sys-a");
+ const now = 1_000_000;
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: a, requested: "taken-name", accountId: null, now });
+
+ expect(checkSlugAvailability(db, { scope: "system", scopeKey: "", requested: "free-one", now })).toEqual({ available: true });
+ expect(checkSlugAvailability(db, { scope: "system", scopeKey: "", requested: "taken-name", now })).toEqual({ available: false, reason: "taken" });
+ expect(checkSlugAvailability(db, { scope: "system", scopeKey: "", requested: "docs", now })).toEqual({ available: false, reason: "invalid", detail: "reserved" });
+ expect(checkSlugAvailability(db, { scope: "system", scopeKey: "", subjectId: a, requested: "taken-name", now })).toEqual({ available: true, reason: "yours" });
+ db.close();
+ });
+});
+
+describe("resolution and canonical URLs", () => {
+ const SYS = { id: "tythty", uuid: "uuid-a", name: "Doughmination", description: null };
+
+ test("resolves by slug and by id to the same system", async () => {
+ const db = freshDb();
+ const sys = seedSystem(db, "uuid-a", "tythty");
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "doughmination", accountId: null, now: 1000 });
+ const pk = pkStub({ tythty: SYS, "uuid-a": SYS });
+
+ const bySlug = await resolveSystemRef({ db, pk }, "doughmination");
+ const byId = await resolveSystemRef({ db, pk }, "tythty");
+
+ expect(bySlug.ok && bySlug.value.matchedBy).toBe("slug");
+ expect(byId.ok && byId.value.matchedBy).toBe("id");
+ if (bySlug.ok && byId.ok) {
+ expect(bySlug.value.system.uuid).toBe(byId.value.system.uuid);
+ // Both advertise the slug as canonical.
+ expect(bySlug.value.canonicalPath).toBe("/s/doughmination");
+ expect(byId.value.canonicalPath).toBe("/s/doughmination");
+ }
+ db.close();
+ });
+
+ test("an unclaimed system is canonical at its id", async () => {
+ const db = freshDb();
+ const pk = pkStub({ tythty: SYS });
+ const result = await resolveSystemRef({ db, pk }, "tythty");
+ expect(result.ok && result.value.canonicalPath).toBe("/s/tythty");
+ expect(result.ok && result.value.slug).toBeNull();
+ db.close();
+ });
+
+ // PluralKit resolves a linked Discord id to its system. Exposing that as a
+ // public URL would make the account-to-system mapping browsable.
+ test("a Discord snowflake is refused as a public reference", async () => {
+ const db = freshDb();
+ const pk = pkStub({ "123456789012345678": SYS });
+ const result = await resolveSystemRef({ db, pk }, "123456789012345678");
+ expect(result).toEqual({ ok: false, reason: "unsupported_reference" });
+ db.close();
+ });
+
+ test("a released slug stops resolving to its old system", async () => {
+ const db = freshDb();
+ const sys = seedSystem(db, "uuid-a", "tythty");
+ const now = 1_000_000;
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "oldname", accountId: null, now });
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "newname", accountId: null, now });
+
+ const pk = pkStub({ tythty: SYS, "uuid-a": SYS });
+ const old = await resolveSystemRef({ db, pk, now: () => now + 1 }, "oldname");
+ expect(old.ok).toBe(false);
+
+ const current = await resolveSystemRef({ db, pk, now: () => now + 1 }, "newname");
+ expect(current.ok && current.value.canonicalPath).toBe("/s/newname");
+ db.close();
+ });
+
+ test("resolves a member by slug and by id", async () => {
+ const db = freshDb();
+ const sys = seedSystem(db, "uuid-a", "tythty");
+ const mem = seedMember(db, sys, "mu-1", "kzsbyo", "mem-1");
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "doughmination", accountId: null, now: 1000 });
+ claimSlug(db, { scope: "member", scopeKey: sys, subjectId: mem, requested: "clove", accountId: null, now: 1000 });
+
+ const members = [{ id: "kzsbyo", uuid: "mu-1", name: "Clove", description: null }];
+ const pk = pkStub({ tythty: SYS, "uuid-a": SYS }, { "uuid-a": members });
+
+ const system = await resolveSystemRef({ db, pk }, "doughmination");
+ if (!system.ok) throw new Error("system did not resolve");
+
+ const bySlug = await resolveMemberRef({ db, pk }, system.value, "clove");
+ const byId = await resolveMemberRef({ db, pk }, system.value, "kzsbyo");
+
+ expect(bySlug.ok && bySlug.value.canonicalPath).toBe("/s/doughmination/clove");
+ expect(byId.ok && byId.value.canonicalPath).toBe("/s/doughmination/clove");
+ db.close();
+ });
+
+ // Decision 5: a member PluralKit does not return publicly is indistinguishable
+ // from one that never existed, even when a slug points at it.
+ test("a slug pointing at a non-public member resolves to nothing", async () => {
+ const db = freshDb();
+ const sys = seedSystem(db, "uuid-a", "tythty");
+ const mem = seedMember(db, sys, "mu-private", "prvte", "mem-1");
+ claimSlug(db, { scope: "system", scopeKey: "", subjectId: sys, requested: "doughmination", accountId: null, now: 1000 });
+ claimSlug(db, { scope: "member", scopeKey: sys, subjectId: mem, requested: "secret", accountId: null, now: 1000 });
+
+ const pk = pkStub({ tythty: SYS, "uuid-a": SYS }, { "uuid-a": [] });
+ const system = await resolveSystemRef({ db, pk }, "doughmination");
+ if (!system.ok) throw new Error("system did not resolve");
+
+ const result = await resolveMemberRef({ db, pk }, system.value, "secret");
+ expect(result).toEqual({ ok: false, reason: "not_found" });
+ db.close();
+ });
+
+ test("path helpers prefer slugs and fall back to ids", () => {
+ expect(systemPath("tythty", "doughmination")).toBe("/s/doughmination");
+ expect(systemPath("tythty", null)).toBe("/s/tythty");
+ expect(memberPath("tythty", "doughmination", "kzsbyo", "clove")).toBe("/s/doughmination/clove");
+ expect(memberPath("tythty", null, "kzsbyo", null)).toBe("/s/tythty/kzsbyo");
+ });
+
+ test("looksLikeSnowflake matches Discord ids only", () => {
+ expect(looksLikeSnowflake("123456789012345678")).toBe(true);
+ expect(looksLikeSnowflake("tythty")).toBe(false);
+ expect(looksLikeSnowflake("12345")).toBe(false);
+ });
+});
diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json
new file mode 100644
index 0000000..04a9293
--- /dev/null
+++ b/apps/api/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "paths": { "@pkviewer/shared": ["../../packages/shared/src/index.ts"] }
+ },
+ "include": ["src/**/*.ts", "test/**/*.ts"]
+}
diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts
new file mode 100644
index 0000000..830fb59
--- /dev/null
+++ b/apps/web/next-env.d.ts
@@ -0,0 +1,6 @@
+/// <reference types="next" />
+/// <reference types="next/image-types/global" />
+/// <reference path="./.next/types/routes.d.ts" />
+
+// NOTE: This file should not be edited
+// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
new file mode 100644
index 0000000..199e821
--- /dev/null
+++ b/apps/web/next.config.ts
@@ -0,0 +1,124 @@
+import type { NextConfig } from "next";
+
+/**
+ * Security headers.
+ *
+ * These live here rather than in the API because the browser never talks to the
+ * API directly — every header a visitor actually receives comes from this tier.
+ * The API's own headers protect nothing on their own.
+ *
+ * Two deliberate exceptions, both documented because they are real weakenings:
+ *
+ * 1. `script-src` allows 'unsafe-inline'. Next's App Router bootstraps and
+ * hydrates through inline scripts, and tightening this properly needs a
+ * per-request nonce threaded through middleware. The exception is survivable
+ * because pkviewer accepts no user HTML and no user JavaScript anywhere:
+ * themes are a fixed vocabulary of validated values, and social links are
+ * rendered as links. Worth revisiting with nonces.
+ *
+ * 2. `img-src` allows any https host. Avatars and banners are hosted wherever
+ * each system chose, and PluralKit hands us those URLs. Restricting this
+ * would break most systems' pages. The URLs are only ever placed in `src`,
+ * never fetched by us.
+ *
+ * `frame-ancestors 'none'` is the one that matters most: the management UI
+ * changes addresses and appearance, so it must not be framable.
+ */
+const isProduction = process.env["NODE_ENV"] === "production";
+
+/**
+ * Development needs `'unsafe-eval'` and a WebSocket connection.
+ *
+ * Next's development bundles evaluate modules through `eval()`, and hot reload
+ * runs over a WebSocket. Without these the browser blocks hydration outright:
+ * pages still render, because they are server-rendered, but nothing is
+ * interactive — every button silently does nothing.
+ *
+ * That failure is invisible to any check that does not execute JavaScript,
+ * which is exactly how it shipped. Production keeps the strict policy.
+ */
+const scriptSrc = isProduction
+ ? "script-src 'self' 'unsafe-inline'"
+ : "script-src 'self' 'unsafe-inline' 'unsafe-eval'";
+
+const connectSrc = isProduction
+ ? "connect-src 'self'"
+ : "connect-src 'self' ws: wss:";
+
+const CSP = [
+ "default-src 'self'",
+ "base-uri 'self'",
+ "form-action 'self'",
+ "frame-ancestors 'none'",
+ "object-src 'none'",
+ scriptSrc,
+ // Theme tokens are emitted as a scoped <style> element, and Google Fonts
+ // serves the allow-listed families.
+ "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
+ "font-src 'self' https://fonts.gstatic.com",
+ "img-src 'self' https: data:",
+ connectSrc,
+ "manifest-src 'self'",
+].join("; ");
+
+const BASE_HEADERS = [
+ { key: "Content-Security-Policy", value: CSP },
+ { key: "X-Content-Type-Options", value: "nosniff" },
+ { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
+ // Redundant with frame-ancestors for modern browsers, kept for older ones.
+ { key: "X-Frame-Options", value: "DENY" },
+ // Nothing in pkviewer needs any of these.
+ {
+ key: "Permissions-Policy",
+ value: "camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()",
+ },
+ { key: "Cross-Origin-Opener-Policy", value: "same-origin" },
+];
+
+const isBeta = process.env["BETA_MODE"] !== "false";
+
+const config: NextConfig = {
+ reactStrictMode: true,
+
+ /**
+ * Production builds get their own output directory.
+ *
+ * `next dev` and `next build` otherwise share `.next`, and a build run while
+ * the dev server is up leaves it loading chunks from an output that no longer
+ * matches — pages go blank with "Cannot find module './530.js'". Since the dev
+ * server is expected to stay running, they are simply kept apart.
+ */
+ distDir: process.env["NEXT_DIST_DIR"] ?? ".next",
+ // The web tier renders and nothing else. It has no database driver and no
+ // PluralKit client: everything comes from the API over HTTP (A1).
+ transpilePackages: ["@pkviewer/shared"],
+ poweredByHeader: false,
+
+ async headers() {
+ const headers = [...BASE_HEADERS];
+
+ if (isProduction) {
+ headers.push({
+ key: "Strict-Transport-Security",
+ value: "max-age=31536000; includeSubDomains",
+ });
+ // Production only: on an http development origin this would try to
+ // upgrade local subresources and is at best pointless, at worst
+ // confusing to debug.
+ headers[0] = {
+ key: "Content-Security-Policy",
+ value: `${CSP}; upgrade-insecure-requests`,
+ };
+ }
+
+ // Belt and braces with the robots metadata: this also covers responses that
+ // are not HTML, which a <meta> tag cannot reach.
+ if (isBeta) {
+ headers.push({ key: "X-Robots-Tag", value: "noindex, nofollow" });
+ }
+
+ return [{ source: "/:path*", headers }];
+ },
+};
+
+export default config;
diff --git a/apps/web/package.json b/apps/web/package.json
new file mode 100644
index 0000000..2b5be2b
--- /dev/null
+++ b/apps/web/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@pkviewer/web",
+ "version": "0.1.0",
+ "private": true,
+ "scripts": {
+ "dev": "next dev -p ${WEB_PORT:-3000}",
+ "build": "NEXT_DIST_DIR=.next-prod next build",
+ "start": "NEXT_DIST_DIR=.next-prod next start -p ${WEB_PORT:-3000}",
+ "typecheck": "tsc -p tsconfig.json"
+ },
+ "dependencies": {
+ "@pkviewer/shared": "workspace:*",
+ "next": "^15.1.0",
+ "react": "^19.0.0",
+ "react-bootstrap-icons": "^1.11.6",
+ "react-dom": "^19.0.0",
+ "server-only": "^0.0.1"
+ },
+ "devDependencies": {
+ "@types/react": "^19.0.0",
+ "@types/react-dom": "^19.0.0",
+ "typescript": "^5.6.0",
+ "@types/node": "^22.0.0"
+ }
+}
diff --git a/apps/web/src/app/auth/[...segments]/route.ts b/apps/web/src/app/auth/[...segments]/route.ts
new file mode 100644
index 0000000..d6a1812
--- /dev/null
+++ b/apps/web/src/app/auth/[...segments]/route.ts
@@ -0,0 +1,77 @@
+import { cookies } from "next/headers";
+import type { NextRequest } from "next/server";
+import { webConfig } from "@/lib/config.ts";
+
+/**
+ * Proxies the Discord OAuth endpoints to the API.
+ *
+ * The browser never talks to the API directly — that is what keeps
+ * INTERNAL_API_ORIGIN internal and the __Host- session cookie pinned to one
+ * host. But the OAuth handshake is a browser redirect flow: the user's browser
+ * must be sent to Discord and must receive the cookies the API sets. So these
+ * routes exist to carry that traffic through the web tier.
+ *
+ * Scope is deliberately narrow. Being mounted under /auth means only the auth
+ * endpoints are reachable, so this cannot become a general proxy to the API.
+ */
+
+const ALLOWED = new Set(["discord/start", "discord/callback", "logout", "logout-all", "me"]);
+
+async function proxy(request: NextRequest, segments: string[], method: "GET" | "POST") {
+ const path = segments.join("/");
+ if (!ALLOWED.has(path)) {
+ return new Response("Not found", { status: 404 });
+ }
+
+ const target = `${webConfig.apiOrigin}/auth/${path}${request.nextUrl.search}`;
+ const cookieHeader = (await cookies()).toString();
+
+ let upstream: Response;
+ try {
+ upstream = await fetch(target, {
+ method,
+ headers: {
+ cookie: cookieHeader,
+ // The API rejects state-changing requests without a recognised Origin.
+ origin: webConfig.appOrigin,
+ accept: "application/json",
+ },
+ // The API's redirect goes to Discord and must reach the browser, not be
+ // followed here.
+ redirect: "manual",
+ cache: "no-store",
+ });
+ } catch {
+ return Response.redirect(`${webConfig.appOrigin}/login?error=unavailable`, 302);
+ }
+
+ const headers = new Headers();
+
+ // Every Set-Cookie must survive: the handshake cookie on the way out and the
+ // session cookie on the way back are the whole point of this proxy.
+ for (const cookie of upstream.headers.getSetCookie()) {
+ headers.append("set-cookie", cookie);
+ }
+
+ const location = upstream.headers.get("location");
+ if (location) {
+ headers.set("location", location);
+ return new Response(null, { status: upstream.status, headers });
+ }
+
+ const contentType = upstream.headers.get("content-type");
+ if (contentType) headers.set("content-type", contentType);
+ headers.set("cache-control", "no-store");
+
+ return new Response(await upstream.text(), { status: upstream.status, headers });
+}
+
+type RouteContext = { params: Promise<{ segments?: string[] }> };
+
+export async function GET(request: NextRequest, context: RouteContext) {
+ return proxy(request, (await context.params).segments ?? [], "GET");
+}
+
+export async function POST(request: NextRequest, context: RouteContext) {
+ return proxy(request, (await context.params).segments ?? [], "POST");
+}
diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css
new file mode 100644
index 0000000..af928fc
--- /dev/null
+++ b/apps/web/src/app/globals.css
@@ -0,0 +1,521 @@
+/*
+ * pkviewer's one stylesheet.
+ *
+ * Loaded once at the root and used by every page. There is no second sheet and
+ * no per-page import, so "which styles does this page get" is never a question.
+ *
+ * It contains two visual languages that deliberately do not mix:
+ *
+ * PUBLIC pages (/, /s/...) are drawn from the system's own theme, through
+ * `--pkv-*` properties the theme vocabulary emits.
+ * Every value here is a fallback matching the
+ * platform default, so an unthemed page is still
+ * correct.
+ *
+ * APP pages (/login, /manage/...) are drawn from pkviewer's own fixed
+ * palette, through `--mg-*`, scoped under `.mg`.
+ * The control plane must look the same whichever
+ * system you are editing, so it never inherits a
+ * user's theme (M6).
+ *
+ * The two prefixes are what keep them apart: a theme can never reach `--mg-*`,
+ * and the app UI never reads `--pkv-*`.
+ */
+
+:root {
+ /* Platform defaults, duplicated as fallbacks only. The authoritative copy is
+ * the vocabulary; these keep an unthemed page correct. */
+ --pkv-color-page: #FAF8FB;
+ --pkv-color-surface: #FFFFFF;
+ --pkv-color-text: #1C1721;
+ --pkv-color-muted: #6B6478;
+ --pkv-color-accent: #A23B72;
+ --pkv-color-border: #E6E1EC;
+ --pkv-font-body: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ --pkv-font-heading: "Newsreader", Georgia, serif;
+ --pkv-font-size: 16.5px;
+ --pkv-radius: 10px;
+ --pkv-density: 1;
+ --pkv-avatar-radius: var(--pkv-radius);
+ --pkv-avatar-size: 88px;
+ --pkv-surface-bg: var(--pkv-color-surface);
+ --pkv-surface-border: var(--pkv-color-border);
+ --pkv-surface-pad: 1;
+ --pkv-directory-columns: repeat(auto-fill, minmax(min(100%, 15rem), 1fr));
+
+ color-scheme: light dark;
+}
+
+@media (prefers-color-scheme: dark) {
+ :root {
+ --pkv-color-page: #151219;
+ --pkv-color-surface: #1E1A24;
+ --pkv-color-text: #EEEAF2;
+ --pkv-color-muted: #9A93A6;
+ --pkv-color-accent: #F58FC2;
+ --pkv-color-border: #302938;
+ }
+}
+
+/* Spacing scale. Density multiplies the whole scale, so one choice retunes the
+ * page coherently rather than leaving the user to nudge individual gaps. */
+:root {
+ --sp-1: calc(0.25rem * var(--pkv-density));
+ --sp-2: calc(0.5rem * var(--pkv-density));
+ --sp-3: calc(0.75rem * var(--pkv-density));
+ --sp-4: calc(1rem * var(--pkv-density));
+ --sp-6: calc(1.5rem * var(--pkv-density));
+ --sp-8: calc(2rem * var(--pkv-density));
+ --sp-12: calc(3rem * var(--pkv-density));
+ --measure: 68ch;
+ --page-width: 60rem;
+}
+
+* { box-sizing: border-box; }
+
+body {
+ margin: 0;
+ background: var(--pkv-color-page);
+ color: var(--pkv-color-text);
+ font-family: var(--pkv-font-body);
+ font-size: var(--pkv-font-size);
+ line-height: 1.6;
+ -webkit-font-smoothing: antialiased;
+}
+
+h1, h2, h3 {
+ font-family: var(--pkv-font-heading);
+ font-weight: 600;
+ line-height: 1.18;
+ text-wrap: balance;
+ margin: 0;
+}
+h1 { font-size: 1.95em; letter-spacing: -0.015em; }
+h2 { font-size: 1.3em; }
+
+a { color: var(--pkv-color-accent); text-underline-offset: 2px; }
+a:focus-visible, button:focus-visible {
+ outline: 2px solid var(--pkv-color-accent);
+ outline-offset: 2px;
+}
+
+img { max-width: 100%; height: auto; display: block; }
+code { font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size: 0.88em; }
+
+.page {
+ max-width: var(--page-width);
+ margin: 0 auto;
+ padding: var(--sp-8) var(--sp-4) var(--sp-12);
+}
+
+.stack > * + * { margin-top: var(--sp-6); }
+.stack-tight > * + * { margin-top: var(--sp-2); }
+.prose { max-width: var(--measure); }
+.muted { color: var(--pkv-color-muted); }
+
+/* Card treatment is one token expanding into three properties, so `plain`
+ * genuinely removes the card rather than making it invisible-but-padded. */
+.surface {
+ background: var(--pkv-surface-bg);
+ border: 1px solid var(--pkv-surface-border);
+ border-radius: var(--pkv-radius);
+ padding: calc(var(--sp-4) * var(--pkv-surface-pad));
+}
+
+.notice {
+ display: flex;
+ gap: var(--sp-3);
+ align-items: flex-start;
+ border: 1px solid var(--pkv-color-border);
+ border-radius: var(--pkv-radius);
+ padding: var(--sp-3) var(--sp-4);
+ font-size: 0.875em;
+}
+.notice svg { flex: none; margin-top: 0.2em; }
+
+.identity { display: flex; gap: var(--sp-4); align-items: center; flex-wrap: wrap; }
+
+.avatar {
+ width: var(--pkv-avatar-size);
+ height: var(--pkv-avatar-size);
+ border-radius: var(--pkv-avatar-radius);
+ object-fit: cover;
+ border: 1px solid var(--pkv-color-border);
+ flex: none;
+}
+.avatar-sm {
+ width: calc(var(--pkv-avatar-size) * 0.5);
+ height: calc(var(--pkv-avatar-size) * 0.5);
+}
+
+.banner {
+ width: 100%;
+ max-height: 220px;
+ object-fit: cover;
+ border-radius: var(--pkv-radius);
+ border: 1px solid var(--pkv-color-border);
+}
+
+.meta-list {
+ display: flex; flex-wrap: wrap;
+ gap: var(--sp-2) var(--sp-4);
+ padding: 0; margin: 0; list-style: none;
+ font-size: 0.9em;
+}
+.meta-list li { display: inline-flex; align-items: center; gap: var(--sp-2); }
+
+.directory {
+ display: grid;
+ grid-template-columns: var(--pkv-directory-columns);
+ gap: var(--sp-3);
+ padding: 0; margin: 0; list-style: none;
+}
+
+.member-card {
+ display: flex;
+ gap: var(--sp-3);
+ align-items: center;
+ background: var(--pkv-surface-bg);
+ border: 1px solid var(--pkv-surface-border);
+ border-radius: var(--pkv-radius);
+ padding: calc(var(--sp-3) * var(--pkv-surface-pad) + var(--sp-1));
+ text-decoration: none;
+ color: inherit;
+ min-width: 0;
+}
+.member-card:hover { border-color: var(--pkv-color-accent); }
+.member-card .name { font-weight: 600; overflow-wrap: anywhere; }
+
+.socials { display: flex; flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); padding: 0; margin: 0; list-style: none; }
+.socials a { display: inline-flex; align-items: center; gap: var(--sp-2); }
+
+.site-footer {
+ margin-top: var(--sp-12);
+ padding-top: var(--sp-4);
+ border-top: 1px solid var(--pkv-color-border);
+ font-size: 0.875em;
+}
+
+.breadcrumb { display: inline-flex; align-items: center; gap: var(--sp-2); font-size: 0.9em; text-decoration: none; }
+
+@media (prefers-reduced-motion: reduce) {
+ * { transition: none !important; animation: none !important; }
+}
+
+/* Detailed member cards carry a description line, clamped so one long entry
+ * cannot set the height of an entire row. */
+.member-card .card-blurb {
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ font-size: 0.85em;
+ margin-top: var(--sp-1);
+}
+
+/* ==========================================================================
+ Application UI — /login and /manage. Scoped under .mg so it cannot touch
+ public pages, and so a user's theme cannot touch it.
+ ========================================================================== */
+
+.mg {
+ --mg-bg: #F7F7F9;
+ --mg-panel: #FFFFFF;
+ --mg-ink: #1A1A1F;
+ --mg-ink-soft: #4C4C57;
+ --mg-muted: #6E6E7B;
+ --mg-line: #E2E2E8;
+ --mg-line-strong: #C9C9D3;
+ --mg-accent: #4A3AB5;
+ --mg-accent-soft: #EEEBFA;
+ --mg-danger: #B3261E;
+ --mg-ok: #1F7A4D;
+ --mg-warn: #8A5B00;
+ --mg-radius: 8px;
+ --mg-shadow: 0 1px 2px rgba(20, 20, 30, 0.06), 0 6px 20px -14px rgba(20, 20, 30, 0.25);
+
+ color-scheme: light;
+ background: var(--mg-bg);
+ color: var(--mg-ink);
+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ font-size: 15px;
+ line-height: 1.5;
+ min-height: 100vh;
+}
+
+@media (prefers-color-scheme: dark) {
+ .mg {
+ --mg-bg: #131317;
+ --mg-panel: #1B1B21;
+ --mg-ink: #ECECF1;
+ --mg-ink-soft: #C3C3CE;
+ --mg-muted: #9494A2;
+ --mg-line: #2C2C35;
+ --mg-line-strong: #3D3D49;
+ --mg-accent: #A99BFF;
+ --mg-accent-soft: #232035;
+ --mg-danger: #FF8A80;
+ --mg-ok: #6FD3A0;
+ --mg-warn: #E3B341;
+ color-scheme: dark;
+ }
+}
+
+.mg * { box-sizing: border-box; }
+.mg a { color: var(--mg-accent); }
+.mg :focus-visible { outline: 2px solid var(--mg-accent); outline-offset: 2px; border-radius: 4px; }
+
+/* ------------------------------------------------------------------ chrome */
+
+.mg-bar {
+ display: flex; align-items: center; gap: 12px;
+ padding: 10px 16px;
+ background: var(--mg-panel);
+ border-bottom: 1px solid var(--mg-line);
+ position: sticky; top: 0; z-index: 30;
+ flex-wrap: wrap;
+}
+.mg-brand { font-weight: 650; letter-spacing: -0.01em; text-decoration: none; color: var(--mg-ink); }
+.mg-bar .spacer { flex: 1; }
+.mg-bar-note { font-size: 12.5px; color: var(--mg-muted); }
+
+.mg-shell { max-width: 1100px; margin: 0 auto; padding: 20px 16px 64px; }
+
+.mg-layout { display: grid; grid-template-columns: 1fr; gap: 20px; }
+@media (min-width: 900px) {
+ .mg-layout { grid-template-columns: 210px minmax(0, 1fr); gap: 28px; align-items: start; }
+}
+
+/* On narrow screens the section nav becomes a horizontal scroller rather than a
+ * squeezed sidebar: shrinking a sidebar until it is unusable is worse than
+ * changing its shape. */
+.mg-nav { display: flex; gap: 4px; overflow-x: auto; padding-bottom: 4px; }
+.mg-nav a {
+ display: flex; align-items: center; gap: 8px;
+ padding: 8px 12px; border-radius: var(--mg-radius);
+ text-decoration: none; color: var(--mg-ink-soft);
+ white-space: nowrap; font-size: 14px;
+}
+.mg-nav a:hover { background: var(--mg-panel); }
+.mg-nav a[aria-current="page"] { background: var(--mg-accent-soft); color: var(--mg-accent); font-weight: 600; }
+@media (min-width: 900px) {
+ .mg-nav { flex-direction: column; overflow: visible; position: sticky; top: 68px; }
+}
+
+/* ------------------------------------------------------------------ panels */
+
+.mg-panel {
+ background: var(--mg-panel);
+ border: 1px solid var(--mg-line);
+ border-radius: var(--mg-radius);
+ padding: 18px;
+ box-shadow: var(--mg-shadow);
+}
+.mg-panel + .mg-panel { margin-top: 16px; }
+.mg-panel h2 { font-size: 15px; margin: 0 0 4px; letter-spacing: -0.005em; }
+.mg-panel .hint { color: var(--mg-muted); font-size: 13px; margin: 0 0 14px; }
+
+.mg-head { margin-bottom: 18px; }
+.mg-head h1 { font-size: 22px; margin: 0 0 4px; letter-spacing: -0.015em; }
+.mg-head p { margin: 0; color: var(--mg-muted); font-size: 13.5px; }
+
+/* ------------------------------------------------------------------- forms */
+
+.mg-field { display: grid; gap: 6px; margin-bottom: 16px; }
+.mg-field:last-child { margin-bottom: 0; }
+.mg-field label { font-size: 13.5px; font-weight: 600; }
+.mg-field .desc { font-size: 12.5px; color: var(--mg-muted); }
+.mg-field .err { font-size: 12.5px; color: var(--mg-danger); font-weight: 500; }
+
+.mg-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(min(100%, 230px), 1fr)); }
+
+.mg input[type="text"], .mg input[type="url"], .mg select {
+ font: inherit;
+ padding: 8px 10px;
+ border: 1px solid var(--mg-line-strong);
+ border-radius: 6px;
+ background: var(--mg-panel);
+ color: var(--mg-ink);
+ width: 100%;
+ min-width: 0;
+}
+.mg input[aria-invalid="true"] { border-color: var(--mg-danger); }
+
+.mg-colour { display: flex; align-items: center; gap: 8px; }
+.mg-colour input[type="color"] {
+ inline-size: 38px; block-size: 34px; padding: 2px;
+ border: 1px solid var(--mg-line-strong); border-radius: 6px;
+ background: var(--mg-panel); cursor: pointer; flex: none;
+}
+.mg-colour input[type="text"] { font-family: ui-monospace, Menlo, monospace; font-size: 13px; }
+
+/* -------------------------------------------------------------- inheritance */
+
+/* Inherited vs overridden is shown by a word and a border, never by colour
+ * alone: state must survive both colour blindness and a greyscale print. */
+.mg-inherit {
+ display: inline-flex; align-items: center; gap: 6px;
+ font-size: 11.5px; font-weight: 600;
+ padding: 2px 8px; border-radius: 999px;
+ border: 1px solid var(--mg-line-strong);
+ color: var(--mg-muted);
+ background: transparent;
+}
+.mg-inherit[data-state="override"] {
+ border-color: var(--mg-accent);
+ color: var(--mg-accent);
+ background: var(--mg-accent-soft);
+}
+.mg-field[data-state="override"] {
+ border-left: 3px solid var(--mg-accent);
+ padding-left: 12px;
+ margin-left: -15px;
+}
+.mg-field-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.mg-field-head .spacer { flex: 1; }
+
+/* ----------------------------------------------------------------- buttons */
+
+.mg button, .mg .btn {
+ font: inherit; font-size: 13.5px; font-weight: 500;
+ padding: 7px 13px; border-radius: 6px;
+ border: 1px solid var(--mg-line-strong);
+ background: var(--mg-panel); color: var(--mg-ink);
+ cursor: pointer; text-decoration: none;
+ display: inline-flex; align-items: center; gap: 7px;
+}
+.mg button:hover:not(:disabled), .mg .btn:hover { border-color: var(--mg-accent); color: var(--mg-accent); }
+.mg button:disabled { opacity: 0.55; cursor: not-allowed; }
+.mg button.primary {
+ background: var(--mg-accent); border-color: var(--mg-accent); color: #fff;
+}
+.mg button.primary:hover:not(:disabled) { filter: brightness(1.08); color: #fff; }
+.mg button.ghost { border-color: transparent; background: transparent; color: var(--mg-muted); }
+.mg button.ghost:hover:not(:disabled) { background: var(--mg-bg); }
+.mg button.danger { color: var(--mg-danger); }
+.mg button.danger:hover:not(:disabled) { border-color: var(--mg-danger); }
+.mg button.icon { padding: 6px; }
+
+/* ---------------------------------------------------------------- save bar */
+
+.mg-savebar {
+ position: sticky; bottom: 0; z-index: 20;
+ display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
+ margin-top: 18px; padding: 12px 16px;
+ background: var(--mg-panel);
+ border: 1px solid var(--mg-line);
+ border-radius: var(--mg-radius);
+ box-shadow: var(--mg-shadow);
+}
+.mg-savebar .spacer { flex: 1; }
+.mg-status { font-size: 13px; display: inline-flex; align-items: center; gap: 7px; }
+.mg-status[data-tone="dirty"] { color: var(--mg-warn); }
+.mg-status[data-tone="ok"] { color: var(--mg-ok); }
+.mg-status[data-tone="error"] { color: var(--mg-danger); }
+
+/* ------------------------------------------------------------------- lists */
+
+.mg-list { list-style: none; padding: 0; margin: 0; display: grid; gap: 10px; }
+.mg-card {
+ display: flex; align-items: center; gap: 12px;
+ padding: 12px 14px;
+ background: var(--mg-panel);
+ border: 1px solid var(--mg-line);
+ border-radius: var(--mg-radius);
+ text-decoration: none; color: inherit;
+ min-width: 0;
+}
+a.mg-card:hover { border-color: var(--mg-accent); }
+.mg-card .grow { flex: 1; min-width: 0; }
+.mg-card .title { font-weight: 600; overflow-wrap: anywhere; }
+.mg-card .sub { font-size: 12.5px; color: var(--mg-muted); overflow-wrap: anywhere; }
+.mg-thumb { width: 40px; height: 40px; border-radius: 8px; object-fit: cover; border: 1px solid var(--mg-line); flex: none; }
+
+.mg-tag {
+ font-size: 11.5px; font-weight: 600;
+ padding: 2px 8px; border-radius: 999px;
+ border: 1px solid var(--mg-line-strong); color: var(--mg-muted);
+ white-space: nowrap;
+}
+.mg-tag[data-tone="ok"] { color: var(--mg-ok); border-color: currentColor; }
+.mg-tag[data-tone="warn"] { color: var(--mg-warn); border-color: currentColor; }
+
+.mg-note {
+ display: flex; gap: 10px; align-items: flex-start;
+ padding: 11px 14px; border-radius: var(--mg-radius);
+ border: 1px solid var(--mg-line-strong);
+ font-size: 13px; color: var(--mg-ink-soft);
+}
+.mg-note svg { flex: none; margin-top: 2px; }
+.mg-note[data-tone="warn"] { border-color: var(--mg-warn); color: var(--mg-warn); }
+
+.mg-empty { text-align: left; max-width: 52ch; margin: 8px auto 0; }
+.mg-empty h1 { font-size: 20px; margin: 0 0 8px; }
+.mg-empty p { color: var(--mg-ink-soft); margin: 0 0 12px; }
+.mg-empty ol { color: var(--mg-ink-soft); padding-left: 20px; margin: 0 0 16px; }
+.mg-empty li { margin-bottom: 6px; }
+
+/* --------------------------------------------------------------- presets */
+
+.mg-presets { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr)); }
+.mg-preset {
+ display: grid; gap: 8px; text-align: left;
+ padding: 12px; border-radius: var(--mg-radius);
+ border: 1px solid var(--mg-line-strong); background: var(--mg-panel);
+ cursor: pointer;
+}
+.mg-preset:hover { border-color: var(--mg-accent); }
+.mg-preset .pname { font-weight: 650; font-size: 14px; }
+.mg-preset .pchar { font-size: 12px; color: var(--mg-muted); line-height: 1.45; }
+.mg-swatches { display: flex; gap: 4px; }
+.mg-swatch { width: 22px; height: 22px; border-radius: 5px; border: 1px solid rgba(0,0,0,0.12); flex: none; }
+
+@media (prefers-reduced-motion: reduce) {
+ .mg * { transition: none !important; animation: none !important; }
+}
+
+.visually-hidden {
+ position: absolute; width: 1px; height: 1px;
+ padding: 0; margin: -1px; overflow: hidden;
+ clip: rect(0 0 0 0); white-space: nowrap; border: 0;
+}
+
+/* Skeletons: a stable shape while data loads, not a spinner. The pulse is
+ * suppressed under reduced-motion by the rule further up. */
+.mg-skel {
+ display: block;
+ background: var(--mg-line);
+ border-radius: 6px;
+ animation: mg-pulse 1.4s ease-in-out infinite;
+}
+@keyframes mg-pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.55; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .mg-skel { animation: none; opacity: 0.8; }
+}
+
+/* The override marker must not push a field outside its grid column on narrow
+ * screens, so it is drawn inside the field's own box. */
+.mg-field[data-state="override"] {
+ border-left: 3px solid var(--mg-accent);
+ padding-left: 10px;
+ margin-left: 0;
+}
+
+/* Claim flow: numbered steps and the code the user copies into PluralKit. */
+.mg-steps { padding-left: 20px; margin: 0 0 12px; color: var(--mg-ink-soft); }
+.mg-steps li { margin-bottom: 10px; }
+.mg-code {
+ display: block;
+ margin-top: 8px;
+ padding: 10px 12px;
+ border: 1px solid var(--mg-line-strong);
+ border-radius: 6px;
+ background: var(--mg-bg);
+ font-family: ui-monospace, Menlo, monospace;
+ font-size: 14px;
+ user-select: all;
+ overflow-wrap: anywhere;
+}
diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx
new file mode 100644
index 0000000..ae96fcd
--- /dev/null
+++ b/apps/web/src/app/layout.tsx
@@ -0,0 +1,19 @@
+import type { Metadata } from "next";
+import "./globals.css";
+
+export const metadata: Metadata = {
+ title: { default: "pkviewer", template: "%s · pkviewer" },
+ description: "Websites for PluralKit systems.",
+ // The beta deployment must stay out of search indexes: testers' pages would
+ // be indexed before they intended, and the eventual domain move would leave
+ // stale results pointing at a dead host.
+ robots: process.env["BETA_MODE"] === "true" ? { index: false, follow: false } : undefined,
+};
+
+export default function RootLayout({ children }: { children: React.ReactNode }) {
+ return (
+ <html lang="en">
+ <body>{children}</body>
+ </html>
+ );
+}
diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsx
new file mode 100644
index 0000000..c8861ed
--- /dev/null
+++ b/apps/web/src/app/login/page.tsx
@@ -0,0 +1,90 @@
+import type { Metadata } from "next";
+import { Discord, ExclamationTriangle } from "react-bootstrap-icons";
+import { webConfig } from "@/lib/config.ts";
+
+export const metadata: Metadata = { title: "Sign in", robots: { index: false, follow: false } };
+
+/**
+ * Sign-in lives on the APP origin, never the public one: it is session-bearing
+ * by definition (O1).
+ *
+ * It uses the application visual language rather than the public one, because
+ * it is the first screen of the control plane. Rendering it with the public
+ * theme made the app origin look like two different products.
+ */
+
+const ERRORS: Record<string, string> = {
+ missing_handshake: "That sign-in attempt expired. Please try again.",
+ invalid_handshake: "That sign-in attempt could not be verified. Please try again.",
+ handshake_expired: "That sign-in attempt took too long. Please try again.",
+ state_mismatch: "That sign-in attempt could not be verified. Please try again.",
+ discord_denied: "Sign-in was cancelled.",
+ missing_code: "Discord did not complete the sign-in. Please try again.",
+ discord_error: "Discord could not be reached. Please try again shortly.",
+ signup_disabled: "New accounts are closed at the moment.",
+ unavailable: "Sign-in is unavailable right now. Please try again shortly.",
+};
+
+export default async function LoginPage({
+ searchParams,
+}: {
+ searchParams: Promise<{ error?: string; return_to?: string }>;
+}) {
+ const { error, return_to: returnTo } = await searchParams;
+
+ // Only same-origin paths, so the sign-in link cannot become an open redirect.
+ const destination = returnTo && returnTo.startsWith("/") && !returnTo.startsWith("//")
+ ? returnTo
+ : "/manage";
+
+ return (
+ <div className="mg">
+ <header className="mg-bar">
+ <span className="mg-brand">pkviewer</span>
+ <span className="mg-bar-note">Sign in</span>
+ <span className="spacer" />
+ <a className="btn" href={webConfig.publicOrigin}>Public site</a>
+ </header>
+
+ <div className="mg-shell" style={{ maxWidth: "34rem" }}>
+ <div className="mg-head">
+ <h1>Sign in to pkviewer</h1>
+ <p>Manage and customise a system you already have on PluralKit.</p>
+ </div>
+
+ {error ? (
+ <p className="mg-note" data-tone="warn" role="alert">
+ <ExclamationTriangle aria-hidden="true" />
+ <span>{ERRORS[error] ?? "Sign-in did not complete. Please try again."}</span>
+ </p>
+ ) : null}
+
+ <section className="mg-panel">
+ <h2>Continue with Discord</h2>
+ <p className="hint">
+ pkviewer asks Discord only for your account ID and username. Not your
+ servers, not your messages, not your email.
+ </p>
+ <p style={{ marginBottom: 0 }}>
+ <a
+ className="btn"
+ href={`/auth/discord/start?return_to=${encodeURIComponent(destination)}`}
+ style={{ fontWeight: 600 }}
+ >
+ <Discord aria-hidden="true" /> Continue with Discord
+ </a>
+ </p>
+ </section>
+
+ <section className="mg-panel">
+ <h2>You may not need an account</h2>
+ <p className="hint" style={{ marginBottom: 0 }}>
+ Public system and member pages are open to everyone, with no sign-in.
+ An account is only for managing and customising a system — and
+ pkviewer never asks for a PluralKit token in order to claim one.
+ </p>
+ </section>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/manage/[systemId]/address/page.tsx b/apps/web/src/app/manage/[systemId]/address/page.tsx
new file mode 100644
index 0000000..1b060e4
--- /dev/null
+++ b/apps/web/src/app/manage/[systemId]/address/page.tsx
@@ -0,0 +1,55 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { SlugEditor, type SlugStatus } from "@/components/manage/SlugEditor.tsx";
+import { manageApi, type SystemOverview } from "@/lib/manage-api.ts";
+import { webConfig } from "@/lib/config.ts";
+import { checkSlug, claimSlugAction, releaseSlugAction } from "../../actions.ts";
+
+export const metadata: Metadata = { title: "Public address" };
+
+/**
+ * System address management.
+ *
+ * The address is a product feature, not an implementation detail: this page is
+ * where a manager sees the URL people will share, and changes it.
+ */
+export default async function AddressPage({
+ params,
+}: {
+ params: Promise<{ systemId: string }>;
+}) {
+ const { systemId } = await params;
+
+ const [overview, status] = await Promise.all([
+ manageApi.get<SystemOverview>(`/manage/systems/${systemId}`),
+ manageApi.get<SlugStatus>(
+ `/manage/slugs/status?scope=system&subjectId=${encodeURIComponent(systemId)}`,
+ ),
+ ]);
+ if (!overview.ok || !status.ok) notFound();
+
+ async function check(slug: string) {
+ "use server";
+ return checkSlug("system", systemId, systemId, slug);
+ }
+ async function claim(slug: string) {
+ "use server";
+ return claimSlugAction("system", systemId, slug);
+ }
+ async function release() {
+ "use server";
+ return releaseSlugAction("system", systemId);
+ }
+
+ return (
+ <SlugEditor
+ scope="system"
+ status={status.value}
+ actions={{ check, claim, release }}
+ publicOrigin={webConfig.publicOrigin}
+ basePath="/s"
+ idPath={`/s/${overview.value.pkSystemHid}`}
+ idLabel="PluralKit ID"
+ />
+ );
+}
diff --git a/apps/web/src/app/manage/[systemId]/appearance/page.tsx b/apps/web/src/app/manage/[systemId]/appearance/page.tsx
new file mode 100644
index 0000000..ba10d14
--- /dev/null
+++ b/apps/web/src/app/manage/[systemId]/appearance/page.tsx
@@ -0,0 +1,49 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { resolveTheme, THEME_TOKENS } from "@pkviewer/shared";
+import { ThemeEditor } from "@/components/manage/ThemeEditor.tsx";
+import { manageApi, type SystemOverview } from "@/lib/manage-api.ts";
+import { saveSystemTheme } from "../../actions.ts";
+
+export const metadata: Metadata = { title: "Appearance" };
+
+export default async function AppearancePage({
+ params,
+}: {
+ params: Promise<{ systemId: string }>;
+}) {
+ const { systemId } = await params;
+
+ const [theme, overview] = await Promise.all([
+ manageApi.get<{ tokens: Record<string, string | null> }>(`/manage/systems/${systemId}/theme`),
+ manageApi.get<SystemOverview>(`/manage/systems/${systemId}`),
+ ]);
+ if (!theme.ok || !overview.ok) notFound();
+
+ // At system level the layer beneath is the platform default, so that is what
+ // "inherited" shows.
+ const platform = resolveTheme({}, {}).light;
+ const inherited: Record<string, string> = {};
+ for (const def of THEME_TOKENS) inherited[def.key] = platform[def.key] ?? "";
+
+ async function save(values: Record<string, string | null>) {
+ "use server";
+ return saveSystemTheme(systemId, values);
+ }
+
+ return (
+ <>
+ <p className="mg-note">
+ These settings define the default appearance for this system and every
+ member page under it. A member can override any of it on their own page.
+ </p>
+ <ThemeEditor
+ level="system"
+ initialValues={theme.value.tokens ?? {}}
+ inheritedFrom={inherited}
+ saveAction={save}
+ previewName={overview.value.name ?? overview.value.pkSystemHid}
+ />
+ </>
+ );
+}
diff --git a/apps/web/src/app/manage/[systemId]/directory/page.tsx b/apps/web/src/app/manage/[systemId]/directory/page.tsx
new file mode 100644
index 0000000..fd17c71
--- /dev/null
+++ b/apps/web/src/app/manage/[systemId]/directory/page.tsx
@@ -0,0 +1,44 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { resolveComposition } from "@pkviewer/shared";
+import { CompositionEditor } from "@/components/manage/CompositionEditor.tsx";
+import { manageApi } from "@/lib/manage-api.ts";
+import { saveSystemComposition } from "../../actions.ts";
+
+export const metadata: Metadata = { title: "Layout" };
+
+/**
+ * Composition settings.
+ *
+ * Kept in its own section rather than mixed into Appearance, because it answers
+ * a different question: what is on the page and how it is arranged, rather than
+ * how it looks.
+ */
+export default async function DirectoryPage({
+ params,
+}: {
+ params: Promise<{ systemId: string }>;
+}) {
+ const { systemId } = await params;
+ const stored = await manageApi.get<{ composition: Record<string, string> }>(
+ `/manage/systems/${systemId}/theme`,
+ );
+ if (!stored.ok) notFound();
+
+ const resolved = resolveComposition(stored.value.composition ?? {}, {});
+
+ async function save(values: Record<string, string>) {
+ "use server";
+ return saveSystemComposition(systemId, values);
+ }
+
+ return (
+ <>
+ <p className="mg-note">
+ These control what appears on your pages and how it is arranged. They are
+ separate from Appearance, which controls how things look.
+ </p>
+ <CompositionEditor initialValues={resolved} saveAction={save} />
+ </>
+ );
+}
diff --git a/apps/web/src/app/manage/[systemId]/layout.tsx b/apps/web/src/app/manage/[systemId]/layout.tsx
new file mode 100644
index 0000000..fc50aef
--- /dev/null
+++ b/apps/web/src/app/manage/[systemId]/layout.tsx
@@ -0,0 +1,42 @@
+import { notFound } from "next/navigation";
+import { manageApi, type SystemOverview } from "@/lib/manage-api.ts";
+import { SystemNav } from "@/components/manage/SystemNav.tsx";
+
+/**
+ * The per-system shell.
+ *
+ * Loading the system here doubles as the authorization check: the API returns
+ * 404 for any system this account does not manage, so an unauthorised id never
+ * renders a shell at all.
+ */
+export default async function SystemLayout({
+ children,
+ params,
+}: {
+ children: React.ReactNode;
+ params: Promise<{ systemId: string }>;
+}) {
+ const { systemId } = await params;
+ const result = await manageApi.get<SystemOverview>(`/manage/systems/${systemId}`);
+
+ // Deliberately does NOT call notFound() here. Next renders the not-found
+ // boundary for a layout without setting a 404 status, so the page looks right
+ // and the response lies. Every page under this layout does its own check, so
+ // the 404 comes from there with the correct status.
+ if (!result.ok) return <>{children}</>;
+
+ const system = result.value;
+
+ return (
+ <div className="mg-shell">
+ <div className="mg-head">
+ <h1>{system.name ?? system.pkSystemHid}</h1>
+ <p>Editing how this system appears on the public site.</p>
+ </div>
+ <div className="mg-layout">
+ <SystemNav systemId={systemId} />
+ <div>{children}</div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/manage/[systemId]/links/page.tsx b/apps/web/src/app/manage/[systemId]/links/page.tsx
new file mode 100644
index 0000000..cbf6f99
--- /dev/null
+++ b/apps/web/src/app/manage/[systemId]/links/page.tsx
@@ -0,0 +1,36 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { SocialLinksEditor } from "@/components/manage/SocialLinksEditor.tsx";
+import { manageApi, type StoredSocial } from "@/lib/manage-api.ts";
+import { saveSystemSocials } from "../../actions.ts";
+
+export const metadata: Metadata = { title: "Social links" };
+
+export default async function LinksPage({
+ params,
+}: {
+ params: Promise<{ systemId: string }>;
+}) {
+ const { systemId } = await params;
+ const stored = await manageApi.get<{ links: StoredSocial[] }>(
+ `/manage/systems/${systemId}/socials`,
+ );
+ if (!stored.ok) notFound();
+
+ async function save(links: Array<{ platform: string; label: string; url: string }>) {
+ "use server";
+ return saveSystemSocials(systemId, links);
+ }
+
+ return (
+ <SocialLinksEditor
+ ownerLabel="your system page"
+ initialLinks={stored.value.links.map((l) => ({
+ platform: l.platform,
+ label: l.label ?? "",
+ url: l.url,
+ }))}
+ saveAction={save}
+ />
+ );
+}
diff --git a/apps/web/src/app/manage/[systemId]/loading.tsx b/apps/web/src/app/manage/[systemId]/loading.tsx
new file mode 100644
index 0000000..74c74f1
--- /dev/null
+++ b/apps/web/src/app/manage/[systemId]/loading.tsx
@@ -0,0 +1,19 @@
+/** Section skeleton. Keeps the panel rhythm so the page does not reflow. */
+export default function SectionLoading() {
+ return (
+ <div aria-busy="true">
+ <p className="visually-hidden" role="status">Loading settings…</p>
+ {[0, 1].map((i) => (
+ <section className="mg-panel" key={i}>
+ <span className="mg-skel" style={{ width: "8rem", height: "1rem" }} />
+ <span className="mg-skel" style={{ width: "16rem", height: "0.8rem", marginTop: 8 }} />
+ <div className="mg-grid" style={{ marginTop: 18 }}>
+ {[0, 1, 2].map((j) => (
+ <span className="mg-skel" key={j} style={{ height: "3.2rem" }} />
+ ))}
+ </div>
+ </section>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/src/app/manage/[systemId]/members/[memberRef]/page.tsx b/apps/web/src/app/manage/[systemId]/members/[memberRef]/page.tsx
new file mode 100644
index 0000000..e4594be
--- /dev/null
+++ b/apps/web/src/app/manage/[systemId]/members/[memberRef]/page.tsx
@@ -0,0 +1,150 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { ArrowLeft, BoxArrowUpRight } from "react-bootstrap-icons";
+import { resolveTheme, THEME_TOKENS } from "@pkviewer/shared";
+import { SlugEditor, type SlugStatus } from "@/components/manage/SlugEditor.tsx";
+import { SocialLinksEditor } from "@/components/manage/SocialLinksEditor.tsx";
+import { ThemeEditor } from "@/components/manage/ThemeEditor.tsx";
+import { manageApi, type StoredSocial, type SystemOverview } from "@/lib/manage-api.ts";
+import { webConfig } from "@/lib/config.ts";
+import {
+ checkSlug,
+ claimSlugAction,
+ releaseSlugAction,
+ saveMemberSocials,
+ saveMemberTheme,
+} from "../../../actions.ts";
+
+export const metadata: Metadata = { title: "Member" };
+
+type MemberDetail = {
+ memberId: string;
+ pkMemberHid: string;
+ name: string | null;
+ displayName: string | null;
+ avatarUrl: string | null;
+ pronouns: string | null;
+ slug: string | null;
+ tokens: Record<string, string | null>;
+ socials: StoredSocial[];
+ systemTokens: Record<string, string | null>;
+};
+
+export default async function MemberPage({
+ params,
+}: {
+ params: Promise<{ systemId: string; memberRef: string }>;
+}) {
+ const { systemId, memberRef } = await params;
+
+ const [detail, overview] = await Promise.all([
+ manageApi.get<MemberDetail>(
+ `/manage/systems/${systemId}/members/${encodeURIComponent(memberRef)}`,
+ ),
+ manageApi.get<SystemOverview>(`/manage/systems/${systemId}`),
+ ]);
+ // A member PluralKit does not list publicly 404s here exactly as it does on
+ // the public site.
+ if (!detail.ok || !overview.ok) notFound();
+
+ const member = detail.value;
+ const name = member.displayName ?? member.name ?? member.pkMemberHid;
+
+ // What this member inherits is the SYSTEM's resolved appearance, so the
+ // editor shows the real inherited value rather than the platform default.
+ const systemResolved = resolveTheme(member.systemTokens ?? {}, {}).light;
+ const inherited: Record<string, string> = {};
+ for (const def of THEME_TOKENS) inherited[def.key] = systemResolved[def.key] ?? "";
+
+ const publicUrl = `${webConfig.publicOrigin}${overview.value.publicPath}/${member.slug ?? member.pkMemberHid}`;
+
+ // Member addresses are scoped to their system, so the system's own address
+ // forms the prefix. A member row exists by now: loading this page created it.
+ const slugStatus = await manageApi.get<SlugStatus>(
+ `/manage/slugs/status?scope=member&subjectId=${encodeURIComponent(member.memberId)}`,
+ );
+
+ async function saveTheme(values: Record<string, string | null>) {
+ "use server";
+ return saveMemberTheme(systemId, memberRef, values);
+ }
+
+ async function saveLinks(links: Array<{ platform: string; label: string; url: string }>) {
+ "use server";
+ return saveMemberSocials(systemId, memberRef, links);
+ }
+
+ const memberId = member.memberId;
+ async function checkMemberSlug(slug: string) {
+ "use server";
+ return checkSlug("member", memberId, systemId, slug);
+ }
+ async function claimMemberSlug(slug: string) {
+ "use server";
+ return claimSlugAction("member", memberId, slug);
+ }
+ async function releaseMemberSlug() {
+ "use server";
+ return releaseSlugAction("member", memberId);
+ }
+
+ return (
+ <>
+ <p style={{ marginTop: 0 }}>
+ <a className="btn" href={`/manage/${systemId}/members`}>
+ <ArrowLeft aria-hidden="true" /> All members
+ </a>{" "}
+ <a className="btn" href={publicUrl} target="_blank" rel="noopener">
+ Open public page <BoxArrowUpRight aria-hidden="true" />
+ </a>
+ </p>
+
+ <div className="mg-head">
+ <h1>{name}</h1>
+ <p>
+ {member.pronouns ? `${member.pronouns} · ` : ""}
+ PluralKit ID {member.pkMemberHid}
+ </p>
+ </div>
+
+ <p className="mg-note">
+ Every setting here starts out following your system appearance. Override
+ only what you want different on this member's page.
+ </p>
+
+ {slugStatus.ok ? (
+ <SlugEditor
+ scope="member"
+ status={slugStatus.value}
+ actions={{
+ check: checkMemberSlug,
+ claim: claimMemberSlug,
+ release: releaseMemberSlug,
+ }}
+ publicOrigin={webConfig.publicOrigin}
+ basePath={overview.value.publicPath}
+ idPath={`${overview.value.publicPath}/${member.pkMemberHid}`}
+ idLabel="PluralKit ID"
+ />
+ ) : null}
+
+ <ThemeEditor
+ level="member"
+ initialValues={member.tokens ?? {}}
+ inheritedFrom={inherited}
+ saveAction={saveTheme}
+ previewName={name}
+ />
+
+ <SocialLinksEditor
+ ownerLabel={`${name}'s page`}
+ initialLinks={member.socials.map((l) => ({
+ platform: l.platform,
+ label: l.label ?? "",
+ url: l.url,
+ }))}
+ saveAction={saveLinks}
+ />
+ </>
+ );
+}
diff --git a/apps/web/src/app/manage/[systemId]/members/page.tsx b/apps/web/src/app/manage/[systemId]/members/page.tsx
new file mode 100644
index 0000000..920c793
--- /dev/null
+++ b/apps/web/src/app/manage/[systemId]/members/page.tsx
@@ -0,0 +1,83 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { ExclamationTriangle, PersonCircle } from "react-bootstrap-icons";
+import { manageApi, type ManagedMemberSummary } from "@/lib/manage-api.ts";
+
+export const metadata: Metadata = { title: "Members" };
+
+/**
+ * The member list.
+ *
+ * These are the members PluralKit returns publicly. Signing in as the owner
+ * does not change what the public API returns and pkviewer does not ask for
+ * more, so a member kept private in PluralKit is absent here — the management
+ * UI must not become a way to confirm one exists.
+ */
+export default async function MembersPage({
+ params,
+}: {
+ params: Promise<{ systemId: string }>;
+}) {
+ const { systemId } = await params;
+ const result = await manageApi.get<{ members: ManagedMemberSummary[]; reachable: boolean }>(
+ `/manage/systems/${systemId}/members`,
+ );
+ if (!result.ok) notFound();
+
+ const { members, reachable } = result.value;
+
+ return (
+ <>
+ <p className="mg-note">
+ These are the members PluralKit lists publicly. Anything you keep private
+ in PluralKit stays private and does not appear here.
+ </p>
+
+ {!reachable ? (
+ <p className="mg-note" data-tone="warn" role="status">
+ <ExclamationTriangle aria-hidden="true" />
+ PluralKit could not be reached, so the member list is unavailable right
+ now. Try again shortly.
+ </p>
+ ) : members.length === 0 ? (
+ <section className="mg-panel">
+ <h2>No public members</h2>
+ <p className="hint">
+ This system has no publicly listed members, so its page shows no
+ directory.
+ </p>
+ </section>
+ ) : (
+ <section className="mg-panel">
+ <h2>{members.length} public {members.length === 1 ? "member" : "members"}</h2>
+ <p className="hint">Choose a member to give their page its own look.</p>
+ <ul className="mg-list">
+ {members.map((member) => (
+ <li key={member.pkMemberUuid}>
+ <a className="mg-card" href={`/manage/${systemId}/members/${member.pkMemberHid}`}>
+ {member.avatarUrl ? (
+ <img className="mg-thumb" src={member.avatarUrl} alt="" />
+ ) : (
+ <PersonCircle className="mg-thumb" aria-hidden="true" />
+ )}
+ <span className="grow">
+ <span className="title">
+ {member.displayName ?? member.name ?? member.pkMemberHid}
+ </span>
+ <span className="sub">
+ {member.pronouns ? `${member.pronouns} · ` : ""}
+ {member.slug ?? member.pkMemberHid}
+ </span>
+ </span>
+ <span className="mg-tag" data-tone={member.hasThemeOverrides ? "ok" : undefined}>
+ {member.hasThemeOverrides ? "Custom look" : "System appearance"}
+ </span>
+ </a>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+ </>
+ );
+}
diff --git a/apps/web/src/app/manage/[systemId]/page.tsx b/apps/web/src/app/manage/[systemId]/page.tsx
new file mode 100644
index 0000000..8f815ed
--- /dev/null
+++ b/apps/web/src/app/manage/[systemId]/page.tsx
@@ -0,0 +1,120 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { ClockHistory, ExclamationTriangle, InfoCircle } from "react-bootstrap-icons";
+import { PublicUrl } from "@/components/manage/PublicUrl.tsx";
+import { manageApi, type SystemOverview } from "@/lib/manage-api.ts";
+import { webConfig } from "@/lib/config.ts";
+
+export const metadata: Metadata = { title: "Overview" };
+
+export default async function OverviewPage({
+ params,
+}: {
+ params: Promise<{ systemId: string }>;
+}) {
+ const { systemId } = await params;
+ const result = await manageApi.get<SystemOverview>(`/manage/systems/${systemId}`);
+ if (!result.ok) notFound();
+ const system = result.value;
+
+ const publicUrl = `${webConfig.publicOrigin}${system.publicPath}`;
+
+ return (
+ <>
+ {!system.reachable ? (
+ <p className="mg-note" data-tone="warn" role="status">
+ <ExclamationTriangle aria-hidden="true" />
+ PluralKit could not be reached, so some details may be out of date.
+ Your settings are unaffected and still save normally.
+ </p>
+ ) : null}
+
+ <section className="mg-panel">
+ <h2>Public page</h2>
+ <p className="hint">Where this system appears on the web.</p>
+
+ {system.slug ? (
+ <PublicUrl
+ url={publicUrl}
+ secondary={{
+ url: `${webConfig.publicOrigin}/s/${system.pkSystemHid}`,
+ note: "Its PluralKit ID address also works and always will:",
+ }}
+ />
+ ) : (
+ <>
+ <PublicUrl url={publicUrl} label="Current address" />
+ <p className="mg-note">
+ <InfoCircle aria-hidden="true" />
+ <span>
+ This system is public already. It has no chosen address yet, so
+ it uses its PluralKit ID. Choosing one makes the link friendlier
+ to share, and the ID address keeps working either way.
+ </span>
+ </p>
+ </>
+ )}
+
+ <p style={{ marginBottom: 0 }}>
+ <a className="btn" href={`/manage/${systemId}/address`}>
+ {system.slug ? "Change public address" : "Choose an address"}
+ </a>
+ </p>
+ </section>
+
+ <section className="mg-panel">
+ <h2>What visitors see</h2>
+ <p className="hint">Taken from PluralKit's public information.</p>
+ <dl style={{ margin: 0, display: "grid", gap: 10 }}>
+ <Row label="Name" value={system.name ?? "Not set"} />
+ <Row
+ label="Members listed"
+ value={
+ system.memberCount === null
+ ? "Unknown"
+ : `${system.memberCount} public ${system.memberCount === 1 ? "member" : "members"}`
+ }
+ />
+ <Row
+ label="Description"
+ value={system.description ? `${system.description.slice(0, 120)}${system.description.length > 120 ? "…" : ""}` : "Not set"}
+ />
+ </dl>
+ </section>
+
+ <section className="mg-panel">
+ <h2>Data freshness</h2>
+ <p className="hint">
+ pkviewer caches PluralKit's public data so pages stay fast and
+ stay up if PluralKit is briefly unavailable.
+ </p>
+ <p className="mg-note">
+ <ClockHistory aria-hidden="true" />
+ <span>
+ {system.snapshotAgeMs === null
+ ? "No cached copy yet."
+ : `Last refreshed ${formatAge(system.snapshotAgeMs)} ago.`}
+ </span>
+ </p>
+ </section>
+ </>
+ );
+}
+
+function Row({ label, value }: { label: string; value: string }) {
+ return (
+ <div style={{ display: "grid", gridTemplateColumns: "minmax(120px, 160px) 1fr", gap: 12 }}>
+ <dt className="desc" style={{ margin: 0 }}>{label}</dt>
+ <dd style={{ margin: 0, overflowWrap: "anywhere" }}>{value}</dd>
+ </div>
+ );
+}
+
+function formatAge(ms: number): string {
+ const minutes = Math.round(ms / 60_000);
+ if (minutes < 1) return "less than a minute";
+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"}`;
+ const hours = Math.round(minutes / 60);
+ if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"}`;
+ return `${Math.round(hours / 24)} days`;
+}
diff --git a/apps/web/src/app/manage/actions.ts b/apps/web/src/app/manage/actions.ts
new file mode 100644
index 0000000..c0663de
--- /dev/null
+++ b/apps/web/src/app/manage/actions.ts
@@ -0,0 +1,285 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+import { manageApi } from "@/lib/manage-api.ts";
+
+/**
+ * Server actions for the management UI.
+ *
+ * These are thin: they forward to the API, which re-validates everything and
+ * re-checks the grant. The client is never trusted to decide what it may
+ * manage, and these actions do not decide it either — they only carry the
+ * request and the session cookie.
+ */
+
+export type ActionResult = { ok: boolean; error?: string };
+
+function messageFor(error: string, status: number): string {
+ switch (error) {
+ case "unauthenticated":
+ return "Your session has expired. Sign in again.";
+ case "not_found":
+ return "You do not have access to this system.";
+ case "validation_failed":
+ return "Some settings were not accepted. Check the values and try again.";
+ case "api_unreachable":
+ return "Could not reach pkviewer. Check your connection and try again.";
+ default:
+ return status >= 500 ? "Something went wrong saving. Please try again." : "Could not save.";
+ }
+}
+
+export async function saveSystemTheme(
+ systemId: string,
+ tokens: Record<string, string | null>,
+): Promise<ActionResult> {
+ const result = await manageApi.put(`/manage/systems/${systemId}/theme`, { tokens });
+ if (!result.ok) return { ok: false, error: messageFor(result.error, result.status) };
+ revalidatePath(`/manage/${systemId}`, "layout");
+ return { ok: true };
+}
+
+export async function saveSystemComposition(
+ systemId: string,
+ composition: Record<string, string>,
+): Promise<ActionResult> {
+ const result = await manageApi.put(`/manage/systems/${systemId}/theme`, { composition });
+ if (!result.ok) return { ok: false, error: messageFor(result.error, result.status) };
+ revalidatePath(`/manage/${systemId}`, "layout");
+ return { ok: true };
+}
+
+export async function saveMemberTheme(
+ systemId: string,
+ memberRef: string,
+ tokens: Record<string, string | null>,
+): Promise<ActionResult> {
+ const result = await manageApi.put(
+ `/manage/systems/${systemId}/members/${encodeURIComponent(memberRef)}/theme`,
+ { tokens },
+ );
+ if (!result.ok) return { ok: false, error: messageFor(result.error, result.status) };
+ revalidatePath(`/manage/${systemId}/members/${memberRef}`);
+ return { ok: true };
+}
+
+export async function saveSystemSocials(
+ systemId: string,
+ links: Array<{ platform: string; label: string; url: string }>,
+): Promise<ActionResult> {
+ const result = await manageApi.put(`/manage/systems/${systemId}/socials`, { links });
+ if (!result.ok) return { ok: false, error: messageFor(result.error, result.status) };
+ revalidatePath(`/manage/${systemId}/links`);
+ return { ok: true };
+}
+
+export async function saveMemberSocials(
+ systemId: string,
+ memberRef: string,
+ links: Array<{ platform: string; label: string; url: string }>,
+): Promise<ActionResult> {
+ const result = await manageApi.put(
+ `/manage/systems/${systemId}/members/${encodeURIComponent(memberRef)}/socials`,
+ { links },
+ );
+ if (!result.ok) return { ok: false, error: messageFor(result.error, result.status) };
+ revalidatePath(`/manage/${systemId}/members/${memberRef}`);
+ return { ok: true };
+}
+
+// --------------------------------------------------------------- addresses
+
+/**
+ * Address (slug) operations.
+ *
+ * All validation and the whole reservation lifecycle live in the API. These
+ * carry the request and translate the server's answer into something a person
+ * can read; they never decide availability themselves.
+ */
+
+export async function checkSlug(
+ scope: "system" | "member",
+ subjectId: string,
+ systemId: string,
+ slug: string,
+): Promise<{ available: boolean; message?: string; availableAt?: number }> {
+ const params = new URLSearchParams({ scope, subjectId, slug, systemId });
+ const result = await manageApi.get<{
+ available: boolean;
+ reason?: string;
+ until?: number;
+ message?: string;
+ }>(`/manage/slugs/check?${params.toString()}`);
+
+ if (!result.ok) return { available: false, message: "Could not check that address." };
+ const value = result.value;
+ if (value.available) return { available: true };
+ return {
+ available: false,
+ ...(value.message ? { message: value.message } : {}),
+ ...(value.until ? { availableAt: value.until } : {}),
+ };
+}
+
+export async function claimSlugAction(
+ scope: "system" | "member",
+ subjectId: string,
+ slug: string,
+): Promise<{
+ ok: boolean;
+ error?: string;
+ slug?: string;
+ previousSlug?: string | null;
+ warnings?: Array<{ code: string; memberHid?: string }>;
+}> {
+ const result = await manageApi.post<{
+ slug: string;
+ previousSlug: string | null;
+ warnings: Array<{ code: string; memberHid?: string }>;
+ }>("/manage/slugs/claim", { scope, subjectId, slug });
+
+ if (!result.ok) {
+ // A held address never names who holds it.
+ const message =
+ result.error === "taken"
+ ? "That address is already in use."
+ : result.error === "reserved"
+ ? "That address is held for someone else at the moment."
+ : result.error === "conflict"
+ ? "Someone claimed that address just now. Try another."
+ : result.error === "invalid"
+ ? "That address is not allowed."
+ : result.error === "forbidden" || result.error === "not_found"
+ ? "You do not have access to change this address."
+ : "Could not set that address.";
+ return { ok: false, error: message };
+ }
+
+ revalidatePath("/manage", "layout");
+ return {
+ ok: true,
+ slug: result.value.slug,
+ previousSlug: result.value.previousSlug,
+ warnings: result.value.warnings,
+ };
+}
+
+export async function releaseSlugAction(
+ scope: "system" | "member",
+ subjectId: string,
+): Promise<{ ok: boolean; error?: string; reservedUntil?: number | null }> {
+ const result = await manageApi.post<{ released: string; reservedUntil: number | null }>(
+ "/manage/slugs/release",
+ { scope, subjectId, confirm: true },
+ );
+ if (!result.ok) {
+ return {
+ ok: false,
+ error:
+ result.error === "no_slug"
+ ? "There is no address to release."
+ : "Could not release that address.",
+ };
+ }
+ revalidatePath("/manage", "layout");
+ return { ok: true, reservedUntil: result.value.reservedUntil };
+}
+
+// ------------------------------------------------------------------ claiming
+
+/**
+ * Claiming a system.
+ *
+ * Two routes, in preference order. Neither requires a PluralKit token, and the
+ * product must never imply otherwise.
+ *
+ * 1. Discord link — PluralKit already knows which system your Discord account
+ * belongs to. Nothing changes hands.
+ * 2. Description code — put a short code in your system description for a
+ * moment so pkviewer can see it.
+ *
+ * The Discord identities used for the first are read from the session by the
+ * API, never sent from here (invariant S1).
+ */
+
+export type DiscoveredSystem = { hid: string; uuid: string; name: string | null };
+
+export async function discoverSystems(): Promise<
+ { ok: true; systems: DiscoveredSystem[] } | { ok: false; error: string }
+> {
+ const result = await manageApi.post<{ systems: DiscoveredSystem[] }>("/claims/discover", {});
+ if (!result.ok) {
+ return {
+ ok: false,
+ error:
+ result.error === "beta_not_allowed"
+ ? "Claiming is limited while pkviewer is in beta, and this account is not on the list yet."
+ : result.error === "unauthenticated"
+ ? "Your session has expired. Sign in again."
+ : "Could not reach PluralKit just now. Try again shortly.",
+ };
+ }
+ return { ok: true, systems: result.value.systems };
+}
+
+function claimError(error: string): string {
+ switch (error) {
+ case "already_claimed":
+ return "That system is already managed on pkviewer. If it should be yours, get in touch.";
+ case "not_verified":
+ return "pkviewer could not confirm that system belongs to you.";
+ case "not_found":
+ return "PluralKit does not have a system with that ID.";
+ case "beta_not_allowed":
+ return "Claiming is limited while pkviewer is in beta.";
+ case "upstream_unavailable":
+ return "PluralKit could not be reached. Try again shortly.";
+ default:
+ return "That did not work. Try again.";
+ }
+}
+
+export async function claimViaDiscord(
+ systemRef: string,
+): Promise<{ ok: true; systemId: string } | { ok: false; error: string }> {
+ const result = await manageApi.post<{ systemId: string }>("/claims/discord-link", { systemRef });
+ if (!result.ok) return { ok: false, error: claimError(result.error) };
+ revalidatePath("/manage", "layout");
+ return { ok: true, systemId: result.value.systemId };
+}
+
+export async function startChallenge(
+ systemRef: string,
+): Promise<
+ { ok: true; challengeId: string; nonce: string; systemHid: string } | { ok: false; error: string }
+> {
+ const result = await manageApi.post<{ challengeId: string; nonce: string; systemHid: string }>(
+ "/claims/challenge",
+ { systemRef },
+ );
+ if (!result.ok) return { ok: false, error: claimError(result.error) };
+ return { ok: true, ...result.value };
+}
+
+export async function verifyChallenge(
+ challengeId: string,
+): Promise<{ ok: true; systemId: string } | { ok: false; error: string }> {
+ const result = await manageApi.post<{ systemId: string }>("/claims/challenge/verify", {
+ challengeId,
+ });
+ if (!result.ok) {
+ const message =
+ result.error === "not_verified"
+ ? "The code is not in the system description yet. Save it in PluralKit, then check again."
+ : result.error === "description_unavailable"
+ ? "That system's description is not public, so pkviewer cannot read the code. Make it public briefly, or claim from the linked Discord account instead."
+ : result.error === "challenge_expired"
+ ? "That code expired. Start again for a new one."
+ : result.error === "too_many_attempts"
+ ? "Too many checks. Start again for a new code."
+ : claimError(result.error);
+ return { ok: false, error: message };
+ }
+ revalidatePath("/manage", "layout");
+ return { ok: true, systemId: result.value.systemId };
+}
diff --git a/apps/web/src/app/manage/claim/page.tsx b/apps/web/src/app/manage/claim/page.tsx
new file mode 100644
index 0000000..e32fdda
--- /dev/null
+++ b/apps/web/src/app/manage/claim/page.tsx
@@ -0,0 +1,66 @@
+import type { Metadata } from "next";
+import { ArrowLeft } from "react-bootstrap-icons";
+import { ClaimFlow } from "@/components/manage/ClaimFlow.tsx";
+import {
+ claimViaDiscord,
+ discoverSystems,
+ startChallenge,
+ verifyChallenge,
+} from "../actions.ts";
+
+export const metadata: Metadata = { title: "Claim a system" };
+
+/**
+ * Discovery runs on load so the common case — your Discord account is linked to
+ * your system — is already answered by the time the page appears, rather than
+ * hiding behind a button.
+ */
+export default async function ClaimPage() {
+ const discovered = await discoverSystems();
+
+ async function discover() {
+ "use server";
+ return discoverSystems();
+ }
+ async function claim(ref: string) {
+ "use server";
+ return claimViaDiscord(ref);
+ }
+ async function begin(ref: string) {
+ "use server";
+ return startChallenge(ref);
+ }
+ async function verify(id: string) {
+ "use server";
+ return verifyChallenge(id);
+ }
+
+ return (
+ <div className="mg-shell" style={{ maxWidth: "46rem" }}>
+ <p style={{ marginTop: 0 }}>
+ <a className="btn" href="/manage">
+ <ArrowLeft aria-hidden="true" /> Your systems
+ </a>
+ </p>
+
+ <div className="mg-head">
+ <h1>Claim a system</h1>
+ <p>
+ Claiming lets you manage how a system appears on the web. It does not
+ change anything in PluralKit.
+ </p>
+ </div>
+
+ <ClaimFlow
+ actions={{
+ discover,
+ claim,
+ startChallenge: begin,
+ verifyChallenge: verify,
+ }}
+ initialSystems={discovered.ok ? discovered.systems : []}
+ initialError={discovered.ok ? null : discovered.error}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/app/manage/error.tsx b/apps/web/src/app/manage/error.tsx
new file mode 100644
index 0000000..091a9ec
--- /dev/null
+++ b/apps/web/src/app/manage/error.tsx
@@ -0,0 +1,29 @@
+"use client";
+
+import { ArrowClockwise, ExclamationTriangle } from "react-bootstrap-icons";
+
+/**
+ * Management error boundary.
+ *
+ * Says what happened in ordinary words and offers the one useful action. The
+ * error object is deliberately not rendered: it can carry internal detail, and
+ * nothing in it would help the person reading the page.
+ */
+export default function ManageError({ reset }: { error: Error; reset: () => void }) {
+ return (
+ <div className="mg-shell">
+ <section className="mg-panel" role="alert">
+ <h2>
+ <ExclamationTriangle aria-hidden="true" /> This page could not be loaded
+ </h2>
+ <p className="hint">
+ Something went wrong on our side. Your settings have not been changed.
+ </p>
+ <button type="button" className="primary" onClick={reset}>
+ <ArrowClockwise aria-hidden="true" /> Try again
+ </button>{" "}
+ <a className="btn" href="/manage">Back to your systems</a>
+ </section>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/manage/layout.tsx b/apps/web/src/app/manage/layout.tsx
new file mode 100644
index 0000000..388197d
--- /dev/null
+++ b/apps/web/src/app/manage/layout.tsx
@@ -0,0 +1,40 @@
+import type { Metadata } from "next";
+import { redirect } from "next/navigation";
+import { BoxArrowUpRight } from "react-bootstrap-icons";
+import { isAuthenticated } from "@/lib/manage-api.ts";
+import { webConfig } from "@/lib/config.ts";
+
+export const metadata: Metadata = {
+ title: { default: "Manage", template: "%s · Manage · pkviewer" },
+ robots: { index: false, follow: false },
+};
+
+/**
+ * The management shell.
+ *
+ * Every /manage route requires a session, checked here so no page has to
+ * remember to. The server remains authoritative: this redirect is a courtesy
+ * for humans, and the API refuses unauthenticated calls regardless.
+ */
+export default async function ManageLayout({ children }: { children: React.ReactNode }) {
+ if (!(await isAuthenticated())) {
+ redirect("/login?return_to=/manage");
+ }
+
+ return (
+ <div className="mg">
+ <header className="mg-bar">
+ <a className="mg-brand" href="/manage">pkviewer</a>
+ <span className="mg-bar-note">Management</span>
+ <span className="spacer" />
+ <a className="btn" href={`${webConfig.publicOrigin}/`}>
+ Public site <BoxArrowUpRight aria-hidden="true" />
+ </a>
+ <form action="/manage/signout" method="post">
+ <button type="submit" className="ghost">Sign out</button>
+ </form>
+ </header>
+ {children}
+ </div>
+ );
+}
diff --git a/apps/web/src/app/manage/loading.tsx b/apps/web/src/app/manage/loading.tsx
new file mode 100644
index 0000000..1467c3e
--- /dev/null
+++ b/apps/web/src/app/manage/loading.tsx
@@ -0,0 +1,28 @@
+/**
+ * A stable skeleton rather than a spinner.
+ *
+ * The shell keeps its shape while data arrives, so nothing jumps when it does
+ * and there is no moment where controls look ready before they are.
+ */
+export default function ManageLoading() {
+ return (
+ <div className="mg-shell" aria-busy="true">
+ <p className="visually-hidden" role="status">Loading your systems…</p>
+ <div className="mg-head">
+ <span className="mg-skel" style={{ width: "12rem", height: "1.4rem" }} />
+ <span className="mg-skel" style={{ width: "22rem", height: "0.9rem", marginTop: 8 }} />
+ </div>
+ <ul className="mg-list">
+ {[0, 1].map((i) => (
+ <li className="mg-card" key={i}>
+ <span className="mg-skel mg-thumb" />
+ <span className="grow">
+ <span className="mg-skel" style={{ width: "9rem", height: "1rem" }} />
+ <span className="mg-skel" style={{ width: "15rem", height: "0.8rem", marginTop: 6 }} />
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/manage/not-found.tsx b/apps/web/src/app/manage/not-found.tsx
new file mode 100644
index 0000000..979649e
--- /dev/null
+++ b/apps/web/src/app/manage/not-found.tsx
@@ -0,0 +1,25 @@
+import { QuestionCircle } from "react-bootstrap-icons";
+
+/**
+ * One not-found page for the management area.
+ *
+ * A system that does not exist and a system this account cannot manage land
+ * here and read identically. Distinguishing them would confirm the system
+ * exists on pkviewer to someone with no access to it.
+ */
+export default function ManageNotFound() {
+ return (
+ <div className="mg-shell">
+ <section className="mg-panel">
+ <h2>
+ <QuestionCircle aria-hidden="true" /> Not found
+ </h2>
+ <p className="hint">
+ This is not something you can manage. It may not exist, or it may
+ belong to someone else.
+ </p>
+ <a className="btn" href="/manage">Back to your systems</a>
+ </section>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/manage/page.tsx b/apps/web/src/app/manage/page.tsx
new file mode 100644
index 0000000..fb340d9
--- /dev/null
+++ b/apps/web/src/app/manage/page.tsx
@@ -0,0 +1,108 @@
+import { ArrowRight, BoxArrowUpRight, ExclamationTriangle, PersonCircle } from "react-bootstrap-icons";
+import { manageApi, type ManagedSystemSummary } from "@/lib/manage-api.ts";
+import { webConfig } from "@/lib/config.ts";
+
+/**
+ * The dashboard.
+ *
+ * Lists only systems this account holds a grant for. The list comes from the
+ * server already filtered — the client is never sent systems it may not manage
+ * and asked to hide them.
+ */
+export default async function ManageDashboard() {
+ const result = await manageApi.get<{ systems: ManagedSystemSummary[] }>("/manage/systems");
+ const systems = result.ok ? result.value.systems : [];
+
+ return (
+ <div className="mg-shell">
+ {!result.ok ? (
+ <p className="mg-note" data-tone="warn" role="alert">
+ <ExclamationTriangle aria-hidden="true" />
+ Could not load your systems right now. Please refresh in a moment.
+ </p>
+ ) : systems.length === 0 ? (
+ <EmptyState />
+ ) : (
+ <>
+ <div className="mg-head">
+ <h1>Your systems</h1>
+ <p>Choose a system to edit how it appears on the web.</p>
+ </div>
+ <ul className="mg-list">
+ {systems.map((system) => (
+ <li key={system.systemId}>
+ <a className="mg-card" href={`/manage/${system.systemId}`}>
+ {system.avatarUrl ? (
+ <img className="mg-thumb" src={system.avatarUrl} alt="" />
+ ) : (
+ <PersonCircle className="mg-thumb" aria-hidden="true" />
+ )}
+ <span className="grow">
+ <span className="title">{system.name ?? system.pkSystemHid}</span>
+ <span className="sub">
+ {webConfig.publicOrigin.replace(/^https?:\/\//, "")}
+ {system.publicPath}
+ {system.memberCount !== null ? ` · ${system.memberCount} members` : ""}
+ </span>
+ </span>
+ {!system.reachable ? (
+ <span className="mg-tag" data-tone="warn">PluralKit unreachable</span>
+ ) : system.slug ? (
+ <span className="mg-tag" data-tone="ok">{system.slug}</span>
+ ) : (
+ <span className="mg-tag">No address yet</span>
+ )}
+ </a>
+ </li>
+ ))}
+ </ul>
+ <p style={{ marginTop: 18 }}>
+ <a className="btn" href="/manage/claim">
+ Claim another system <ArrowRight aria-hidden="true" />
+ </a>
+ </p>
+ </>
+ )}
+ </div>
+ );
+}
+
+function EmptyState() {
+ return (
+ <div className="mg-shell mg-empty">
+ <h1>No systems yet</h1>
+ <p>
+ pkviewer turns a PluralKit system into a website. PluralKit keeps the
+ identity and the data; pkviewer decides how it looks on the web.
+ </p>
+ <p>To manage a system here, pkviewer needs to confirm you can act for it:</p>
+ <ol>
+ <li>
+ <strong>Usually automatic.</strong> If the Discord account you signed in
+ with is linked to a PluralKit system, pkviewer can confirm that on its
+ own.
+ </li>
+ <li>
+ <strong>Otherwise, a short code.</strong> pkviewer gives you a code to
+ put in your system description for a moment, then checks for it.
+ </li>
+ </ol>
+ <p>
+ You never have to hand pkviewer a PluralKit token. Claiming is limited
+ while pkviewer is in beta.
+ </p>
+ <p>
+ <a className="btn" href="/manage/claim" style={{ fontWeight: 600 }}>
+ Claim a system <ArrowRight aria-hidden="true" />
+ </a>
+ </p>
+ {webConfig.docsUrl ? (
+ <p>
+ <a className="btn" href={webConfig.docsUrl} rel="noopener">
+ Read about claiming <BoxArrowUpRight aria-hidden="true" />
+ </a>
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/web/src/app/manage/signout/route.ts b/apps/web/src/app/manage/signout/route.ts
new file mode 100644
index 0000000..5625f47
--- /dev/null
+++ b/apps/web/src/app/manage/signout/route.ts
@@ -0,0 +1,28 @@
+import { NextResponse } from "next/server";
+import { cookies } from "next/headers";
+import { webConfig } from "@/lib/config.ts";
+
+/**
+ * Sign out.
+ *
+ * A POST, so a link or a prefetch cannot end someone's session. The API revokes
+ * the session server-side; clearing the cookie alone would leave a usable
+ * session behind.
+ */
+export async function POST() {
+ const cookieHeader = (await cookies()).toString();
+
+ await fetch(`${webConfig.apiOrigin}/auth/logout`, {
+ method: "POST",
+ headers: { cookie: cookieHeader, origin: webConfig.appOrigin },
+ }).catch(() => undefined);
+
+ const response = NextResponse.redirect(`${webConfig.appOrigin}/login`, 303);
+ response.cookies.set("__Host-pkv_session", "", {
+ path: "/",
+ maxAge: 0,
+ secure: true,
+ httpOnly: true,
+ });
+ return response;
+}
diff --git a/apps/web/src/app/not-found.tsx b/apps/web/src/app/not-found.tsx
new file mode 100644
index 0000000..8c8b6a4
--- /dev/null
+++ b/apps/web/src/app/not-found.tsx
@@ -0,0 +1,36 @@
+import { SiteDisclosure } from "@/components/Notices.tsx";
+import { webConfig } from "@/lib/config.ts";
+
+/**
+ * Rendered per request, not prerendered.
+ *
+ * This page embeds the configured public and app origins. Static prerendering
+ * would bake the BUILD-TIME origin into the HTML, so moving from the beta host
+ * to the production domain would need a rebuild rather than an env change —
+ * which is exactly what decision 1 says must not be true. The cost is rendering
+ * two tiny pages per request.
+ */
+export const dynamic = "force-dynamic";
+
+/**
+ * One 404 for everything.
+ *
+ * A system that does not exist, a member that does not exist, and a member
+ * PluralKit keeps private all land here and read identically. Distinguishing
+ * them would confirm that a private member exists (decision 5).
+ */
+export default function NotFound() {
+ return (
+ <main className="page stack">
+ <h1>Not found</h1>
+ <p className="prose">
+ There is nothing at this address. The system or member may not exist, or
+ may not be publicly listed.
+ </p>
+ <p>
+ <a href={`${webConfig.publicOrigin}/`}>Back to pkviewer</a>
+ </p>
+ <SiteDisclosure beta={webConfig.beta} />
+ </main>
+ );
+}
diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx
new file mode 100644
index 0000000..8fce776
--- /dev/null
+++ b/apps/web/src/app/page.tsx
@@ -0,0 +1,80 @@
+import { ArrowRight, BoxArrowUpRight } from "react-bootstrap-icons";
+import { SiteDisclosure } from "@/components/Notices.tsx";
+import { webConfig } from "@/lib/config.ts";
+
+/**
+ * Rendered per request, not prerendered.
+ *
+ * This page embeds the configured public and app origins. Static prerendering
+ * would bake the BUILD-TIME origin into the HTML, so moving from the beta host
+ * to the production domain would need a rebuild rather than an env change —
+ * which is exactly what decision 1 says must not be true. The cost is rendering
+ * two tiny pages per request.
+ */
+export const dynamic = "force-dynamic";
+
+/**
+ * The public landing page.
+ *
+ * Permanently logged out (O3). The __Host- session cookie is pinned to the app
+ * host and physically cannot reach this origin, so this page can never show
+ * "signed in as", "your systems", or any account state. The sign-in link is
+ * unconditional, and points at the app origin.
+ *
+ * Copy here is placeholder structure. The real wording is a product decision.
+ */
+export default function LandingPage() {
+ return (
+ <main className="page stack">
+ <header className="stack-tight">
+ <h1>pkviewer</h1>
+ <p className="prose">
+ PluralKit handles the identity and the data. pkviewer handles how that
+ identity is presented on the web.
+ </p>
+ </header>
+
+ <section className="stack-tight prose">
+ <h2>What it does</h2>
+ <p>
+ Every PluralKit system gets a public page, and every member can have
+ one too. Systems that sign in can choose a readable address and
+ customise how their pages look.
+ </p>
+ <p className="muted">
+ Viewing is open to everyone. An account is only needed to manage and
+ customise a system.
+ </p>
+ </section>
+
+ <section className="stack-tight prose">
+ <h2>Addresses</h2>
+ <p>
+ A system is always reachable by its PluralKit ID, and additionally by
+ its chosen name once it has one. Both work; the readable one is
+ canonical.
+ </p>
+ <ul className="meta-list" style={{ flexDirection: "column", alignItems: "flex-start" }}>
+ <li><code>/s/abcdef</code> <span className="muted">— PluralKit ID, always works</span></li>
+ <li><code>/s/your-system</code> <span className="muted">— chosen address</span></li>
+ <li><code>/s/your-system/a-member</code> <span className="muted">— a member</span></li>
+ </ul>
+ </section>
+
+ <p>
+ <a href={`${webConfig.appOrigin}/login`}>
+ Sign in with Discord <ArrowRight aria-hidden="true" />
+ </a>
+ </p>
+ {webConfig.docsUrl ? (
+ <p>
+ <a href={webConfig.docsUrl} rel="noopener">
+ Read the documentation <BoxArrowUpRight aria-hidden="true" />
+ </a>
+ </p>
+ ) : null}
+
+ <SiteDisclosure beta={webConfig.beta} />
+ </main>
+ );
+}
diff --git a/apps/web/src/app/s/[systemRef]/[memberRef]/page.tsx b/apps/web/src/app/s/[systemRef]/[memberRef]/page.tsx
new file mode 100644
index 0000000..b767074
--- /dev/null
+++ b/apps/web/src/app/s/[systemRef]/[memberRef]/page.tsx
@@ -0,0 +1,128 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { ArrowLeft, PersonCircle } from "react-bootstrap-icons";
+import { SiteDisclosure, StaleNotice } from "@/components/Notices.tsx";
+import { SocialLinks } from "@/components/SocialLinks.tsx";
+import { ThemeFonts } from "@/components/ThemeFonts.tsx";
+import { TokenStyle } from "@/components/TokenStyle.tsx";
+import { getMemberPage } from "@/lib/api.ts";
+import { buildPageTheme } from "@/lib/theme.ts";
+import { webConfig } from "@/lib/config.ts";
+
+type Params = { params: Promise<{ systemRef: string; memberRef: string }> };
+
+/**
+ * Public member page.
+ *
+ * A member PluralKit does not return publicly resolves to a 404 that is
+ * identical to the one for a member that never existed (decision 5) — including
+ * when a pkviewer slug points at it.
+ *
+ * Member pages are structurally independent of the system page rather than a
+ * variant of it, so they can grow into substantially more personal pages later
+ * without the system layout constraining them.
+ */
+
+export async function generateMetadata({ params }: Params): Promise<Metadata> {
+ const { systemRef, memberRef } = await params;
+ const result = await getMemberPage(systemRef, memberRef);
+ if (!result.ok || !result.value.member) return { title: "Not found" };
+
+ const { member, canonicalPath } = result.value;
+ const name = member.displayName ?? member.name ?? member.hid;
+
+ return {
+ title: name,
+ description: member.description?.slice(0, 200) ?? undefined,
+ alternates: { canonical: `${webConfig.publicOrigin}${canonicalPath}` },
+ openGraph: {
+ title: name,
+ description: member.description?.slice(0, 200) ?? undefined,
+ url: `${webConfig.publicOrigin}${canonicalPath}`,
+ images: member.avatarUrl ? [{ url: member.avatarUrl }] : undefined,
+ type: "profile",
+ },
+ };
+}
+
+export default async function MemberPage({ params }: Params) {
+ const { systemRef, memberRef } = await params;
+ const result = await getMemberPage(systemRef, memberRef);
+
+ if (!result.ok) {
+ if (result.status === 404) notFound();
+ return (
+ <main className="page stack">
+ <h1>Temporarily unavailable</h1>
+ <p className="prose">
+ This page could not be loaded right now. Please try again shortly.
+ </p>
+ </main>
+ );
+ }
+
+ const { system, member, socials, tokens, composition, beta } = result.value;
+ if (!member) notFound();
+
+ const showBanner = composition["banner.display"] !== "hidden";
+ const showPronouns = composition["show.pronouns"] !== "false";
+ const showBirthday = composition["show.birthday"] !== "false";
+
+ // Tokens arrive already merged system-under-member by the API, so this
+ // resolves platform defaults and maps to CSS without re-applying inheritance.
+ const theme = buildPageTheme(tokens, null, composition);
+
+ const name = member.displayName ?? member.name ?? member.hid;
+ const systemName = system.name ?? system.hid;
+
+ return (
+ <main className="page stack" id="pkv-user">
+ <ThemeFonts fonts={theme.fonts} />
+ <TokenStyle
+ vars={theme.vars}
+ darkVars={theme.darkVars}
+ colorScheme={theme.colorScheme}
+ scope=":root"
+ />
+
+ {system.staleSinceMs !== null ? <StaleNotice staleSinceMs={system.staleSinceMs} /> : null}
+
+ <a className="breadcrumb" href={`/s/${member.systemSlug ?? member.systemHid}`}>
+ <ArrowLeft aria-hidden="true" /> {systemName}
+ </a>
+
+ {showBanner && member.bannerUrl ? (
+ <img className="banner" src={member.bannerUrl} alt="" />
+ ) : null}
+
+ <header className="identity">
+ {member.avatarUrl ? (
+ <img className="avatar" src={member.avatarUrl} alt="" />
+ ) : (
+ <PersonCircle className="avatar" aria-hidden="true" />
+ )}
+ <div className="stack-tight" style={{ minWidth: 0 }}>
+ <h1 style={{ margin: 0, overflowWrap: "anywhere" }}>{name}</h1>
+ {member.name && member.displayName && member.name !== member.displayName ? (
+ <p className="muted" style={{ margin: 0 }}>{member.name}</p>
+ ) : null}
+ <ul className="meta-list muted">
+ <li><code>{member.hid}</code></li>
+ {showPronouns && member.pronouns ? <li>{member.pronouns}</li> : null}
+ {showBirthday && member.birthday ? <li>{member.birthday}</li> : null}
+ </ul>
+ </div>
+ </header>
+
+ {member.description ? (
+ <section className="prose">
+ <p style={{ whiteSpace: "pre-wrap" }}>{member.description}</p>
+ </section>
+ ) : null}
+
+ <SocialLinks links={socials} />
+
+ <SiteDisclosure beta={beta} />
+ </main>
+ );
+}
diff --git a/apps/web/src/app/s/[systemRef]/page.tsx b/apps/web/src/app/s/[systemRef]/page.tsx
new file mode 100644
index 0000000..a644112
--- /dev/null
+++ b/apps/web/src/app/s/[systemRef]/page.tsx
@@ -0,0 +1,123 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { PeopleFill, PersonCircle } from "react-bootstrap-icons";
+import { MemberDirectory } from "@/components/MemberDirectory.tsx";
+import { SiteDisclosure, StaleNotice } from "@/components/Notices.tsx";
+import { SocialLinks } from "@/components/SocialLinks.tsx";
+import { ThemeFonts } from "@/components/ThemeFonts.tsx";
+import { TokenStyle } from "@/components/TokenStyle.tsx";
+import { getSystemPage } from "@/lib/api.ts";
+import { buildPageTheme } from "@/lib/theme.ts";
+import { webConfig } from "@/lib/config.ts";
+
+type Params = { params: Promise<{ systemRef: string }> };
+
+/**
+ * Public system page.
+ *
+ * Both `/s/<pluralkit-id>` and `/s/<slug>` render this, each returning 200
+ * (decision 8). Neither redirects: a permanent redirect would outlive slug
+ * ownership and point a cached URL at whoever holds the name next. The
+ * canonical form is advertised with <link rel="canonical"> instead.
+ */
+
+export async function generateMetadata({ params }: Params): Promise<Metadata> {
+ const { systemRef } = await params;
+ const result = await getSystemPage(systemRef);
+ if (!result.ok) return { title: "Not found" };
+
+ const { system, canonicalPath } = result.value;
+ const name = system.name ?? system.hid;
+
+ return {
+ title: name,
+ description: system.description?.slice(0, 200) ?? `The ${name} system on pkviewer.`,
+ alternates: { canonical: `${webConfig.publicOrigin}${canonicalPath}` },
+ // Server-rendered so Discord's unfurler, which runs no JavaScript, gets a
+ // real preview card. This is the reason the public tier renders on the
+ // server at all (A2).
+ openGraph: {
+ title: name,
+ description: system.description?.slice(0, 200) ?? undefined,
+ url: `${webConfig.publicOrigin}${canonicalPath}`,
+ images: system.avatarUrl ? [{ url: system.avatarUrl }] : undefined,
+ type: "profile",
+ },
+ };
+}
+
+export default async function SystemPage({ params }: Params) {
+ const { systemRef } = await params;
+ const result = await getSystemPage(systemRef);
+
+ if (!result.ok) {
+ if (result.status === 404) notFound();
+ return (
+ <main className="page stack">
+ <h1>Temporarily unavailable</h1>
+ <p className="prose">
+ This page could not be loaded right now. Please try again shortly.
+ </p>
+ </main>
+ );
+ }
+
+ const { system, members, socials, tokens, composition, beta } = result.value;
+ const name = system.name ?? system.hid;
+ const theme = buildPageTheme(tokens, null, composition);
+ const showBanner = composition["banner.display"] !== "hidden";
+ const showPronouns = composition["show.pronouns"] !== "false";
+
+ return (
+ <main className="page stack" id="pkv-user">
+ <ThemeFonts fonts={theme.fonts} />
+ <TokenStyle
+ vars={theme.vars}
+ darkVars={theme.darkVars}
+ colorScheme={theme.colorScheme}
+ scope=":root"
+ />
+
+ {system.staleSinceMs !== null ? <StaleNotice staleSinceMs={system.staleSinceMs} /> : null}
+
+ {showBanner && system.bannerUrl ? (
+ <img className="banner" src={system.bannerUrl} alt="" />
+ ) : null}
+
+ <header className="identity">
+ {system.avatarUrl ? (
+ <img className="avatar" src={system.avatarUrl} alt="" />
+ ) : (
+ <PersonCircle className="avatar" aria-hidden="true" />
+ )}
+ <div className="stack-tight" style={{ minWidth: 0 }}>
+ <h1 style={{ margin: 0, overflowWrap: "anywhere" }}>{name}</h1>
+ <ul className="meta-list muted">
+ <li><code>{system.hid}</code></li>
+ {showPronouns && system.pronouns ? <li>{system.pronouns}</li> : null}
+ {system.tag ? <li>{system.tag}</li> : null}
+ <li>
+ <PeopleFill aria-hidden="true" /> {system.memberCount}{" "}
+ {system.memberCount === 1 ? "member" : "members"}
+ </li>
+ </ul>
+ </div>
+ </header>
+
+ {system.description ? (
+ <section className="prose">
+ <p style={{ whiteSpace: "pre-wrap" }}>{system.description}</p>
+ </section>
+ ) : null}
+
+ <SocialLinks links={socials} />
+
+ <section className="stack-tight">
+ <h2>Members</h2>
+ <MemberDirectory members={members} composition={composition} />
+ </section>
+
+ <SiteDisclosure beta={beta} />
+ </main>
+ );
+}
diff --git a/apps/web/src/components/MemberDirectory.tsx b/apps/web/src/components/MemberDirectory.tsx
new file mode 100644
index 0000000..ca38918
--- /dev/null
+++ b/apps/web/src/components/MemberDirectory.tsx
@@ -0,0 +1,72 @@
+import type { MemberView } from "@pkviewer/shared";
+import { PersonCircle } from "react-bootstrap-icons";
+
+/**
+ * The member directory.
+ *
+ * Only members PluralKit returns publicly ever reach this component, so a
+ * private member is absent rather than hidden — indistinguishable from one that
+ * never existed (decision 5).
+ *
+ * The grid is column-count-agnostic so the same markup works at five members
+ * and at a hundred and fifty. Search, filtering and grouping are product
+ * decisions still to be made; the structure does not preclude them.
+ */
+export function MemberDirectory({
+ members,
+ composition,
+}: {
+ members: MemberView[];
+ composition: Record<string, string>;
+}) {
+ const detailed = composition["directory.card"] === "detailed";
+ const showPronouns = composition["show.pronouns"] !== "false";
+
+ // Sorting is a presentation choice. PluralKit's own order is the default
+ // because it is the one the system already arranged deliberately.
+ const ordered =
+ composition["directory.sort"] === "name"
+ ? [...members].sort((a, b) =>
+ (a.displayName ?? a.name ?? a.hid).localeCompare(b.displayName ?? b.name ?? b.hid),
+ )
+ : members;
+
+ if (members.length === 0) {
+ return (
+ <p className="muted">
+ No members are publicly listed for this system.
+ </p>
+ );
+ }
+
+ return (
+ <ul className="directory">
+ {ordered.map((member) => (
+ <li key={member.hid}>
+ <a
+ className="member-card"
+ href={`/s/${member.systemSlug ?? member.systemHid}/${member.slug ?? member.hid}`}
+ >
+ {member.avatarUrl ? (
+ // PluralKit-hosted media, referenced directly and never proxied.
+ <img className="avatar avatar-sm" src={member.avatarUrl} alt="" loading="lazy" />
+ ) : (
+ <PersonCircle className="avatar avatar-sm" aria-hidden="true" />
+ )}
+ <span style={{ minWidth: 0 }}>
+ <span className="name">{member.displayName ?? member.name ?? member.hid}</span>
+ {showPronouns && member.pronouns ? (
+ <span className="muted" style={{ display: "block", fontSize: "0.85em" }}>
+ {member.pronouns}
+ </span>
+ ) : null}
+ {detailed && member.description ? (
+ <span className="card-blurb muted">{member.description}</span>
+ ) : null}
+ </span>
+ </a>
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/apps/web/src/components/Notices.tsx b/apps/web/src/components/Notices.tsx
new file mode 100644
index 0000000..e252992
--- /dev/null
+++ b/apps/web/src/components/Notices.tsx
@@ -0,0 +1,55 @@
+import { BoxArrowUpRight, ClockHistory, InfoCircle } from "react-bootstrap-icons";
+import { webConfig } from "@/lib/config.ts";
+
+/**
+ * The beta and third-party disclosures are ONE piece of UI, not two banners.
+ *
+ * Both say the same underlying thing — this is pkviewer, not PluralKit, and it
+ * is early — so stacking two notices on every page would be noise. The final
+ * wording is a product decision; this is the structure it will occupy.
+ */
+export function SiteDisclosure({ beta }: { beta: boolean }) {
+ return (
+ <footer className="site-footer muted">
+ <p className="prose">
+ <InfoCircle aria-hidden="true" /> Presented by pkviewer, a third-party
+ website for PluralKit systems. pkviewer is not PluralKit, and system and
+ member information shown here comes from PluralKit's public API.
+ {beta ? " pkviewer is in beta and things will change." : null}
+ </p>
+ {webConfig.docsUrl ? (
+ <p>
+ <a href={webConfig.docsUrl} rel="noopener">
+ Documentation <BoxArrowUpRight aria-hidden="true" />
+ </a>
+ </p>
+ ) : null}
+ </footer>
+ );
+}
+
+/**
+ * Shown when PluralKit was unreachable and the page rendered from the last good
+ * snapshot (P3). The page is informative rather than broken: the content is
+ * real, just possibly behind.
+ */
+export function StaleNotice({ staleSinceMs }: { staleSinceMs: number }) {
+ return (
+ <p className="notice muted" role="status">
+ <ClockHistory aria-hidden="true" />
+ <span>
+ PluralKit could not be reached, so this page is showing information
+ saved {formatAge(staleSinceMs)} ago. It may be out of date.
+ </span>
+ </p>
+ );
+}
+
+function formatAge(ms: number): string {
+ const minutes = Math.round(ms / 60_000);
+ if (minutes < 60) return `${Math.max(1, minutes)} minute${minutes === 1 ? "" : "s"}`;
+ const hours = Math.round(minutes / 60);
+ if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"}`;
+ const days = Math.round(hours / 24);
+ return `${days} day${days === 1 ? "" : "s"}`;
+}
diff --git a/apps/web/src/components/SocialLinks.tsx b/apps/web/src/components/SocialLinks.tsx
new file mode 100644
index 0000000..b6b3a79
--- /dev/null
+++ b/apps/web/src/components/SocialLinks.tsx
@@ -0,0 +1,40 @@
+import type { SocialLink } from "@pkviewer/shared";
+import { BoxArrowUpRight, Discord, Github, Globe, Mastodon, Twitch, Youtube } from "react-bootstrap-icons";
+
+/**
+ * Social links are rendered as links and never fetched server-side — no preview
+ * cards, no favicon lookups. Fetching a user-supplied URL from our server is an
+ * SSRF vector, and the guardrails rule it out.
+ *
+ * Icons come from the Bootstrap Icons set rather than bespoke SVGs (U1), with a
+ * generic fallback for platforms the set does not cover.
+ */
+
+const ICONS: Record<string, typeof Globe> = {
+ discord: Discord,
+ github: Github,
+ mastodon: Mastodon,
+ twitch: Twitch,
+ youtube: Youtube,
+ website: Globe,
+};
+
+export function SocialLinks({ links }: { links: SocialLink[] }) {
+ if (links.length === 0) return null;
+
+ return (
+ <ul className="socials">
+ {links.map((link) => {
+ const Icon = ICONS[link.platform.toLowerCase()] ?? BoxArrowUpRight;
+ return (
+ <li key={`${link.platform}-${link.url}`}>
+ <a href={link.url} rel="nofollow noopener ugc" target="_blank">
+ <Icon aria-hidden="true" />
+ {link.label ?? link.platform}
+ </a>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
diff --git a/apps/web/src/components/ThemeFonts.tsx b/apps/web/src/components/ThemeFonts.tsx
new file mode 100644
index 0000000..a4d7d97
--- /dev/null
+++ b/apps/web/src/components/ThemeFonts.tsx
@@ -0,0 +1,23 @@
+import type { FontEntry } from "@pkviewer/shared";
+
+/**
+ * Loads the typefaces a resolved theme actually uses.
+ *
+ * The families come from the fixed allow-list, never from stored strings, so
+ * this can only ever request a font we chose. A theme using the system stack
+ * loads nothing at all.
+ */
+export function ThemeFonts({ fonts }: { fonts: FontEntry[] }) {
+ const families = fonts
+ .filter((f) => f.family !== null)
+ .map((f) => `family=${encodeURIComponent(f.family!).replace(/%20/g, "+")}:wght@${f.weights.join(";")}`);
+
+ if (families.length === 0) return null;
+
+ return (
+ <link
+ rel="stylesheet"
+ href={`https://fonts.googleapis.com/css2?${families.join("&")}&display=swap`}
+ />
+ );
+}
diff --git a/apps/web/src/components/TokenStyle.tsx b/apps/web/src/components/TokenStyle.tsx
new file mode 100644
index 0000000..12308c3
--- /dev/null
+++ b/apps/web/src/components/TokenStyle.tsx
@@ -0,0 +1,97 @@
+/**
+ * Emits sanitized `--pkv-*` custom properties.
+ *
+ * Deliberately knows NOTHING about the theme vocabulary. It receives a record
+ * of names and values it does not interpret, so the vocabulary can change
+ * without touching this file. Validation and the vocabulary itself live in
+ * @pkviewer/shared/theme; this is the last line of defence, not the first.
+ *
+ * That defence still matters: themes are user-authored, so a value carrying
+ * `;`, `}`, `url(` or a comment sequence could otherwise escape its
+ * declaration and inject arbitrary CSS.
+ */
+
+const KEY_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
+
+/** Conservative by design: what colours, lengths and font stacks actually need.
+ * Anything else is dropped rather than escaped, because a dropped token is a
+ * visual bug and an escaped one is a security bug waiting to be got wrong. */
+const VALUE_PATTERN = /^[a-zA-Z0-9\s.,%#()'"_-]+$/;
+const FORBIDDEN = /url\(|@|\/\*|\*\/|<|>|;|\}|\{|expression|\\/i;
+
+/** `var(--pkv-...)` is the one function form allowed, because the mapping layer
+ * legitimately produces it and its shape is fully constrained. */
+const ALLOWED_VAR = /^var\(--pkv-[a-z0-9-]+\)$/;
+
+export function sanitizeCssVars(vars: Record<string, string>): Record<string, string> {
+ const safe: Record<string, string> = {};
+ for (const [key, value] of Object.entries(vars)) {
+ if (!KEY_PATTERN.test(key)) continue;
+ if (typeof value !== "string" || value.length === 0 || value.length > 200) continue;
+ if (ALLOWED_VAR.test(value)) {
+ safe[key] = value;
+ continue;
+ }
+ if (!VALUE_PATTERN.test(value)) continue;
+ if (FORBIDDEN.test(value)) continue;
+ safe[key] = value;
+ }
+ return safe;
+}
+
+/**
+ * Where the properties are declared.
+ *
+ * `:root` for a public page: the whole document belongs to that system, and
+ * custom properties inherit downward only — declaring them on an inner element
+ * means `body` never sees them, so the page background and base typography keep
+ * the platform defaults while everything inside is themed.
+ *
+ * An element id for the editor's preview, which sits inside pkviewer's own UI
+ * and must not leak its colours onto the surrounding page.
+ */
+export type TokenScope = ":root" | { elementId: string };
+
+const ELEMENT_ID = /^[a-z][a-z0-9-]*$/;
+
+function selectorFor(scope: TokenScope): string | null {
+ if (scope === ":root") return ":root";
+ return ELEMENT_ID.test(scope.elementId) ? `#${scope.elementId}` : null;
+}
+
+export function TokenStyle({
+ vars,
+ darkVars,
+ scope,
+ colorScheme,
+}: {
+ vars: Record<string, string>;
+ /** Emitted under prefers-color-scheme: dark. Omitted when the theme commits
+ * to a single ground. */
+ darkVars?: Record<string, string>;
+ scope: TokenScope;
+ colorScheme?: "auto" | "light" | "dark";
+}) {
+ const selector = selectorFor(scope);
+ if (!selector) return null;
+
+ const light = sanitizeCssVars(vars);
+ const dark = darkVars ? sanitizeCssVars(darkVars) : null;
+
+ const declare = (entries: Record<string, string>) =>
+ Object.entries(entries)
+ .map(([key, value]) => `--pkv-${key}: ${value};`)
+ .join(" ");
+
+ if (Object.keys(light).length === 0) return null;
+
+ const scheme =
+ colorScheme === "light" ? "light" : colorScheme === "dark" ? "dark" : "light dark";
+
+ let css = `${selector} { color-scheme: ${scheme}; ${declare(light)} }`;
+ if (dark && Object.keys(dark).length > 0 && colorScheme === "auto") {
+ css += ` @media (prefers-color-scheme: dark) { ${selector} { ${declare(dark)} } }`;
+ }
+
+ return <style>{css}</style>;
+}
diff --git a/apps/web/src/components/manage/ClaimFlow.tsx b/apps/web/src/components/manage/ClaimFlow.tsx
new file mode 100644
index 0000000..6217300
--- /dev/null
+++ b/apps/web/src/components/manage/ClaimFlow.tsx
@@ -0,0 +1,221 @@
+"use client";
+
+import { useState } from "react";
+import {
+ ArrowRepeat,
+ Check2Circle,
+ ClipboardCheck,
+ ExclamationTriangle,
+ PersonCircle,
+} from "react-bootstrap-icons";
+import type { DiscoveredSystem } from "@/app/manage/actions.ts";
+
+/**
+ * Claiming a system.
+ *
+ * Two routes, offered in order of how little they ask of the user. The token
+ * option is deliberately absent: it is a last resort, no feature depends on it,
+ * and putting it beside the others would imply it is a normal way to do this.
+ */
+
+type Actions = {
+ discover: () => Promise<{ ok: true; systems: DiscoveredSystem[] } | { ok: false; error: string }>;
+ claim: (ref: string) => Promise<{ ok: true; systemId: string } | { ok: false; error: string }>;
+ startChallenge: (
+ ref: string,
+ ) => Promise<
+ { ok: true; challengeId: string; nonce: string; systemHid: string } | { ok: false; error: string }
+ >;
+ verifyChallenge: (
+ id: string,
+ ) => Promise<{ ok: true; systemId: string } | { ok: false; error: string }>;
+};
+
+export function ClaimFlow({
+ actions,
+ initialSystems,
+ initialError,
+}: {
+ actions: Actions;
+ initialSystems: DiscoveredSystem[];
+ initialError: string | null;
+}) {
+ const [systems, setSystems] = useState(initialSystems);
+ const [error, setError] = useState<string | null>(initialError);
+ const [busy, setBusy] = useState<string | null>(null);
+
+ const [manualRef, setManualRef] = useState("");
+ const [challenge, setChallenge] = useState<{ id: string; nonce: string; hid: string } | null>(
+ null,
+ );
+
+ async function run<T>(key: string, fn: () => Promise<T>): Promise<T> {
+ setBusy(key);
+ setError(null);
+ try {
+ return await fn();
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ async function claim(ref: string) {
+ const result = await run(`claim:${ref}`, () => actions.claim(ref));
+ if (!result.ok) setError(result.error);
+ else window.location.href = `/manage/${result.systemId}`;
+ }
+
+ async function recheck() {
+ const result = await run("discover", () => actions.discover());
+ if (result.ok) {
+ setSystems(result.systems);
+ if (result.systems.length === 0) {
+ setError("PluralKit does not have a system linked to this Discord account.");
+ }
+ } else setError(result.error);
+ }
+
+ async function begin() {
+ const ref = manualRef.trim();
+ if (!ref) return;
+ const result = await run("challenge", () => actions.startChallenge(ref));
+ if (!result.ok) setError(result.error);
+ else setChallenge({ id: result.challengeId, nonce: result.nonce, hid: result.systemHid });
+ }
+
+ async function check() {
+ if (!challenge) return;
+ const result = await run("verify", () => actions.verifyChallenge(challenge.id));
+ if (!result.ok) setError(result.error);
+ else window.location.href = `/manage/${result.systemId}`;
+ }
+
+ return (
+ <>
+ {error ? (
+ <p className="mg-note" data-tone="warn" role="alert">
+ <ExclamationTriangle aria-hidden="true" />
+ <span>{error}</span>
+ </p>
+ ) : null}
+
+ <section className="mg-panel">
+ <h2>Systems linked to your Discord account</h2>
+ <p className="hint">
+ PluralKit already knows which system your Discord account belongs to.
+ If yours is here, that is all the confirmation pkviewer needs.
+ </p>
+
+ {systems.length > 0 ? (
+ <ul className="mg-list">
+ {systems.map((system) => (
+ <li className="mg-card" key={system.uuid}>
+ <PersonCircle className="mg-thumb" aria-hidden="true" />
+ <span className="grow">
+ <span className="title">{system.name ?? system.hid}</span>
+ <span className="sub">PluralKit ID {system.hid}</span>
+ </span>
+ <button
+ type="button"
+ className="primary"
+ disabled={busy !== null}
+ onClick={() => claim(system.hid)}
+ >
+ {busy === `claim:${system.hid}` ? "Claiming…" : "Claim this system"}
+ </button>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="desc">
+ Nothing found for this Discord account. Either it is not linked to a
+ PluralKit system, or you are signing in from a different account than
+ the one linked to it.
+ </p>
+ )}
+
+ <p style={{ marginTop: 14, marginBottom: 0 }}>
+ <button type="button" className="ghost" disabled={busy !== null} onClick={recheck}>
+ <ArrowRepeat aria-hidden="true" />
+ {busy === "discover" ? "Checking…" : "Check again"}
+ </button>
+ </p>
+ </section>
+
+ <section className="mg-panel">
+ <h2>Or confirm with a short code</h2>
+ <p className="hint">
+ Use this if your Discord account is not linked to the system, or you
+ are claiming from a different account. It needs nothing from PluralKit
+ except a moment's edit to your system description.
+ </p>
+
+ {!challenge ? (
+ <>
+ <div className="mg-field">
+ <label htmlFor="claim-ref">PluralKit system ID</label>
+ <input
+ id="claim-ref"
+ type="text"
+ value={manualRef}
+ spellCheck={false}
+ autoCapitalize="none"
+ autoComplete="off"
+ placeholder="abcdef"
+ aria-describedby="claim-ref-desc"
+ onChange={(e) => setManualRef(e.target.value)}
+ />
+ <span className="desc" id="claim-ref-desc">
+ The 5 or 6 character ID PluralKit shows, for example from{" "}
+ <code>pk;system</code>.
+ </span>
+ </div>
+ <button
+ type="button"
+ disabled={busy !== null || manualRef.trim().length === 0}
+ onClick={begin}
+ >
+ {busy === "challenge" ? "Getting a code…" : "Get a code"}
+ </button>
+ </>
+ ) : (
+ <>
+ <ol className="mg-steps">
+ <li>
+ Add this code anywhere in the description of system{" "}
+ <strong>{challenge.hid}</strong>:
+ <code className="mg-code">{challenge.nonce}</code>
+ </li>
+ <li>Save it in PluralKit.</li>
+ <li>Come back and check below. You can remove the code afterwards.</li>
+ </ol>
+ <p className="desc">
+ The code is only valid for a short while. If it expires, start
+ again for a new one.
+ </p>
+ <button type="button" className="primary" disabled={busy !== null} onClick={check}>
+ <Check2Circle aria-hidden="true" />
+ {busy === "verify" ? "Checking…" : "I have added the code"}
+ </button>{" "}
+ <button
+ type="button"
+ className="ghost"
+ disabled={busy !== null}
+ onClick={() => setChallenge(null)}
+ >
+ Start over
+ </button>
+ </>
+ )}
+ </section>
+
+ <p className="mg-note">
+ <ClipboardCheck aria-hidden="true" />
+ <span>
+ pkviewer never asks for a PluralKit token in order to claim a system.
+ Both options above work without one.
+ </span>
+ </p>
+ </>
+ );
+}
diff --git a/apps/web/src/components/manage/CompositionEditor.tsx b/apps/web/src/components/manage/CompositionEditor.tsx
new file mode 100644
index 0000000..722784b
--- /dev/null
+++ b/apps/web/src/components/manage/CompositionEditor.tsx
@@ -0,0 +1,183 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useUnsavedGuard } from "./useUnsavedGuard.ts";
+import { Check2, ExclamationTriangle } from "react-bootstrap-icons";
+import { COMPOSITION, type CompositionDef } from "@pkviewer/shared";
+
+/**
+ * Composition settings.
+ *
+ * A separate vocabulary with its own editor, because it answers a different
+ * question: not "how does this look" but "what is on the page and how is it
+ * arranged". These never become CSS custom properties.
+ */
+
+const LABELS: Record<string, string> = {
+ "banner.display": "Show banner",
+ "avatar.size": "Avatar size",
+ "directory.columns": "Member columns",
+ "directory.card": "Card style",
+ "directory.sort": "Sort members by",
+ "show.pronouns": "Show pronouns",
+ "show.birthday": "Show birthdays",
+};
+
+const OPTION_LABELS: Record<string, string> = {
+ auto: "Automatic",
+ hidden: "Hidden",
+ one: "One",
+ two: "Two",
+ three: "Three",
+ compact: "Compact",
+ detailed: "Detailed",
+ pluralkit: "PluralKit order",
+ name: "Name",
+ small: "Small",
+ medium: "Medium",
+ large: "Large",
+};
+
+export function CompositionEditor({
+ initialValues,
+ saveAction,
+}: {
+ initialValues: Record<string, string>;
+ saveAction: (values: Record<string, string>) => Promise<{ ok: boolean; error?: string }>;
+}) {
+ const [values, setValues] = useState(initialValues);
+ const [saved, setSaved] = useState(initialValues);
+ const [status, setStatus] = useState<"idle" | "saving" | "ok" | "error">("idle");
+ const [message, setMessage] = useState<string | null>(null);
+
+ const dirty = useMemo(
+ () => JSON.stringify(values) !== JSON.stringify(saved),
+ [values, saved],
+ );
+
+ useUnsavedGuard(dirty);
+
+ async function save() {
+ setStatus("saving");
+ const result = await saveAction(values);
+ if (result.ok) {
+ setSaved(values);
+ setStatus("ok");
+ setMessage("Saved.");
+ } else {
+ setStatus("error");
+ setMessage(result.error ?? "Could not save. Please try again.");
+ }
+ }
+
+ return (
+ <>
+ <section className="mg-panel">
+ <h2>Member directory</h2>
+ <p className="hint">How members are listed on your system page.</p>
+ <div className="mg-grid">
+ {COMPOSITION.filter((c) => c.key.startsWith("directory.")).map((def) => (
+ <Field key={def.key} def={def} value={values[def.key]} onChange={setValues} />
+ ))}
+ </div>
+ </section>
+
+ <section className="mg-panel">
+ <h2>Header</h2>
+ <p className="hint">Banner and avatar on system and member pages.</p>
+ <div className="mg-grid">
+ {COMPOSITION.filter((c) => c.key === "banner.display" || c.key === "avatar.size").map(
+ (def) => (
+ <Field key={def.key} def={def} value={values[def.key]} onChange={setValues} />
+ ),
+ )}
+ </div>
+ </section>
+
+ <section className="mg-panel">
+ <h2>Details to show</h2>
+ <p className="hint">
+ Only information PluralKit already makes public can be shown. Turning
+ something off here hides it on pkviewer; it does not change PluralKit.
+ </p>
+ <div className="mg-grid">
+ {COMPOSITION.filter((c) => c.key.startsWith("show.")).map((def) => (
+ <Field key={def.key} def={def} value={values[def.key]} onChange={setValues} />
+ ))}
+ </div>
+ </section>
+
+ <div className="mg-savebar">
+ <span
+ className="mg-status"
+ data-tone={status === "ok" ? "ok" : status === "error" ? "error" : dirty ? "dirty" : undefined}
+ role="status"
+ aria-live="polite"
+ >
+ {status === "error" ? <ExclamationTriangle aria-hidden="true" /> : null}
+ {status === "ok" ? <Check2 aria-hidden="true" /> : null}
+ {message ?? (dirty ? "Unsaved changes" : "No changes")}
+ </span>
+ <span className="spacer" />
+ <button type="button" className="ghost" onClick={() => { setValues(saved); setStatus("idle"); setMessage(null); }} disabled={!dirty}>
+ Discard changes
+ </button>
+ <button type="button" className="primary" onClick={save} disabled={!dirty || status === "saving"}>
+ {status === "saving" ? "Saving…" : "Save settings"}
+ </button>
+ </div>
+ </>
+ );
+}
+
+function Field({
+ def,
+ value,
+ onChange,
+}: {
+ def: CompositionDef;
+ value: string | undefined;
+ onChange: (fn: (v: Record<string, string>) => Record<string, string>) => void;
+}) {
+ const id = `comp-${def.key.replace(/\./g, "-")}`;
+ const label = LABELS[def.key] ?? def.label;
+
+ if (def.type === "boolean") {
+ return (
+ <div className="mg-field">
+ <div className="mg-field-head">
+ <label htmlFor={id}>{label}</label>
+ </div>
+ <select
+ id={id}
+ value={value ?? String(def.default)}
+ aria-describedby={`${id}-desc`}
+ onChange={(e) => onChange((v) => ({ ...v, [def.key]: e.target.value }))}
+ >
+ <option value="true">Shown</option>
+ <option value="false">Hidden</option>
+ </select>
+ <span className="desc" id={`${id}-desc`}>{def.help}</span>
+ </div>
+ );
+ }
+
+ return (
+ <div className="mg-field">
+ <div className="mg-field-head">
+ <label htmlFor={id}>{label}</label>
+ </div>
+ <select
+ id={id}
+ value={value ?? def.default}
+ aria-describedby={`${id}-desc`}
+ onChange={(e) => onChange((v) => ({ ...v, [def.key]: e.target.value }))}
+ >
+ {def.values.map((v) => (
+ <option key={v} value={v}>{OPTION_LABELS[v] ?? v}</option>
+ ))}
+ </select>
+ <span className="desc" id={`${id}-desc`}>{def.help}</span>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/manage/PublicUrl.tsx b/apps/web/src/components/manage/PublicUrl.tsx
new file mode 100644
index 0000000..99f1846
--- /dev/null
+++ b/apps/web/src/components/manage/PublicUrl.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { BoxArrowUpRight, Check2, Clipboard } from "react-bootstrap-icons";
+
+/**
+ * Displays a public URL with a copy action.
+ *
+ * Copying is never the only way to get the address: the URL is shown as text
+ * and offered as an ordinary link, so it works without JavaScript, without a
+ * clipboard permission, and for anyone who would rather select it by hand.
+ *
+ * Success is announced in words through a live region, not signalled by colour
+ * alone.
+ */
+export function PublicUrl({
+ url,
+ label = "Public address",
+ secondary,
+}: {
+ url: string;
+ label?: string;
+ /** Shown quietly beneath, e.g. the permanent ID address. */
+ secondary?: { url: string; note: string };
+}) {
+ const [copied, setCopied] = useState(false);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []);
+
+ async function copy() {
+ try {
+ await navigator.clipboard.writeText(url);
+ } catch {
+ // A blocked clipboard is not an error worth shouting about: the address
+ // is right there as selectable text and as a link.
+ return;
+ }
+ setCopied(true);
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = setTimeout(() => setCopied(false), 2200);
+ }
+
+ return (
+ <div className="mg-field">
+ <span className="desc">{label}</span>
+ <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
+ <code style={{ fontSize: 13.5, overflowWrap: "anywhere", flex: "1 1 16rem" }}>{url}</code>
+ <button type="button" onClick={copy}>
+ {copied ? <Check2 aria-hidden="true" /> : <Clipboard aria-hidden="true" />}
+ {copied ? "Copied" : "Copy"}
+ </button>
+ <a className="btn" href={url} target="_blank" rel="noopener">
+ Open <BoxArrowUpRight aria-hidden="true" />
+ </a>
+ </div>
+ <span role="status" aria-live="polite" className="visually-hidden">
+ {copied ? "Address copied to clipboard" : ""}
+ </span>
+ {secondary ? (
+ <span className="desc">
+ {secondary.note}{" "}
+ <a href={secondary.url} target="_blank" rel="noopener">
+ <code>{secondary.url}</code>
+ </a>
+ </span>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/manage/SlugEditor.tsx b/apps/web/src/components/manage/SlugEditor.tsx
new file mode 100644
index 0000000..5ce173b
--- /dev/null
+++ b/apps/web/src/components/manage/SlugEditor.tsx
@@ -0,0 +1,303 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { Check2, ExclamationTriangle, InfoCircle } from "react-bootstrap-icons";
+import { PublicUrl } from "./PublicUrl.tsx";
+
+/**
+ * Address editor for a system or a member.
+ *
+ * The client validates as you type purely so the feedback is immediate. The
+ * server re-runs the same rules and its answer is the one that counts — the
+ * check endpoint is advisory, and availability can change between checking and
+ * claiming, which is why claiming re-checks transactionally.
+ */
+
+export type SlugScope = "system" | "member";
+
+export type SlugStatus = {
+ current: { slug: string; claimedAt: number | null } | null;
+ reservations: Array<{ slug: string; until: number }>;
+ reservationDays: number;
+};
+
+export type SlugActions = {
+ check: (slug: string) => Promise<{ available: boolean; message?: string; availableAt?: number }>;
+ claim: (slug: string) => Promise<{
+ ok: boolean;
+ error?: string;
+ slug?: string;
+ previousSlug?: string | null;
+ warnings?: Array<{ code: string; memberHid?: string }>;
+ }>;
+ release: () => Promise<{ ok: boolean; error?: string; reservedUntil?: number | null }>;
+};
+
+export function SlugEditor({
+ scope,
+ status,
+ actions,
+ publicOrigin,
+ basePath,
+ idPath,
+ idLabel,
+}: {
+ scope: SlugScope;
+ status: SlugStatus;
+ actions: SlugActions;
+ publicOrigin: string;
+ /** Path prefix the address sits under, e.g. "/s" or "/s/doughmination". */
+ basePath: string;
+ /** The permanent ID address, which always works. */
+ idPath: string;
+ idLabel: string;
+}) {
+ const [value, setValue] = useState("");
+ const [availability, setAvailability] = useState<
+ { state: "idle" | "checking" | "free" | "taken" | "invalid"; message?: string }
+ >({ state: "idle" });
+ const [busy, setBusy] = useState(false);
+ const [result, setResult] = useState<{ tone: "ok" | "error"; text: string } | null>(null);
+ const [confirmRelease, setConfirmRelease] = useState(false);
+ const debounce = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const minLength = scope === "system" ? 3 : 2;
+ const trimmed = value.trim().toLowerCase();
+
+ useEffect(() => {
+ if (debounce.current) clearTimeout(debounce.current);
+ if (trimmed.length === 0) {
+ setAvailability({ state: "idle" });
+ return;
+ }
+ setAvailability({ state: "checking" });
+ debounce.current = setTimeout(async () => {
+ const check = await actions.check(trimmed);
+ if (check.available) setAvailability({ state: "free" });
+ else if (check.message) setAvailability({ state: "invalid", message: check.message });
+ else if (check.availableAt) {
+ setAvailability({
+ state: "taken",
+ message: `That address is held until ${formatDate(check.availableAt)}.`,
+ });
+ } else setAvailability({ state: "taken", message: "That address is already in use." });
+ }, 350);
+ return () => {
+ if (debounce.current) clearTimeout(debounce.current);
+ };
+ }, [trimmed, actions]);
+
+ const previewUrl = useMemo(
+ () => `${publicOrigin}${basePath}/${trimmed || "your-address"}`,
+ [publicOrigin, basePath, trimmed],
+ );
+
+ async function claim() {
+ setBusy(true);
+ setResult(null);
+ const response = await actions.claim(trimmed);
+ setBusy(false);
+ if (!response.ok) {
+ setResult({ tone: "error", text: response.error ?? "Could not set that address." });
+ return;
+ }
+ const warning = response.warnings?.find((w) => w.code === "shadows_member_id");
+ setResult({
+ tone: "ok",
+ text: [
+ `Address set to ${response.slug}.`,
+ response.previousSlug
+ ? `Your previous address ${response.previousSlug} is held for you for ${status.reservationDays} days.`
+ : "",
+ warning
+ ? `Note: this matches another member's PluralKit ID (${warning.memberHid}), so that member's ID address now points here instead.`
+ : "",
+ ]
+ .filter(Boolean)
+ .join(" "),
+ });
+ setValue("");
+ }
+
+ async function release() {
+ setBusy(true);
+ setResult(null);
+ const response = await actions.release();
+ setBusy(false);
+ setConfirmRelease(false);
+ if (!response.ok) {
+ setResult({ tone: "error", text: response.error ?? "Could not release that address." });
+ return;
+ }
+ setResult({
+ tone: "ok",
+ text: `Address released. It is held for you until ${response.reservedUntil ? formatDate(response.reservedUntil) : "later"}, then anyone can take it.`,
+ });
+ }
+
+ return (
+ <>
+ <section className="mg-panel">
+ <h2>Public address</h2>
+ {status.current ? (
+ <>
+ <p className="hint">This is where people find this page.</p>
+ <PublicUrl
+ url={`${publicOrigin}${basePath}/${status.current.slug}`}
+ secondary={{
+ url: `${publicOrigin}${idPath}`,
+ note: `The ${idLabel} address also works and always will:`,
+ }}
+ />
+ </>
+ ) : (
+ <>
+ <p className="hint">
+ This page is already public. A chosen address just makes it easier
+ to share.
+ </p>
+ <PublicUrl url={`${publicOrigin}${idPath}`} label="Current address" />
+ <p className="mg-note">
+ <InfoCircle aria-hidden="true" />
+ <span>
+ No chosen address yet. The {idLabel} address above works now and
+ keeps working afterwards — a chosen one is simply friendlier to
+ pass around.
+ </span>
+ </p>
+ </>
+ )}
+ </section>
+
+ <section className="mg-panel">
+ <h2>{status.current ? "Change the address" : "Choose an address"}</h2>
+ <p className="hint">
+ Lowercase letters, numbers and hyphens. At least {minLength} characters.
+ </p>
+
+ <div className="mg-field">
+ <label htmlFor="slug-input">New address</label>
+ <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
+ <span className="desc" style={{ whiteSpace: "nowrap" }}>
+ {publicOrigin.replace(/^https?:\/\//, "")}{basePath}/
+ </span>
+ <input
+ id="slug-input"
+ type="text"
+ value={value}
+ spellCheck={false}
+ autoCapitalize="none"
+ autoComplete="off"
+ style={{ flex: "1 1 12rem" }}
+ aria-describedby="slug-feedback"
+ aria-invalid={availability.state === "invalid" || availability.state === "taken" ? "true" : undefined}
+ onChange={(e) => {
+ setValue(e.target.value);
+ setResult(null);
+ }}
+ />
+ </div>
+
+ {/* Availability is stated in words, with an icon, never colour alone. */}
+ <span
+ className={availability.state === "free" ? "desc" : "err"}
+ id="slug-feedback"
+ role="status"
+ aria-live="polite"
+ >
+ {availability.state === "idle" ? " " : null}
+ {availability.state === "checking" ? "Checking…" : null}
+ {availability.state === "free" ? (
+ <>
+ <Check2 aria-hidden="true" /> Available — {previewUrl}
+ </>
+ ) : null}
+ {availability.state === "invalid" || availability.state === "taken" ? (
+ <>
+ <ExclamationTriangle aria-hidden="true" /> {availability.message}
+ </>
+ ) : null}
+ </span>
+ </div>
+
+ <button
+ type="button"
+ className="primary"
+ disabled={busy || availability.state !== "free"}
+ onClick={claim}
+ >
+ {busy ? "Saving…" : status.current ? "Change address" : "Set address"}
+ </button>
+
+ {status.current ? (
+ <p className="desc" style={{ marginTop: 10 }}>
+ Changing the address holds the old one for you for {status.reservationDays} days
+ before anyone else can take it. Links to the old address stop working
+ when you change it, so share the new one.
+ </p>
+ ) : null}
+ </section>
+
+ {status.reservations.length > 0 ? (
+ <section className="mg-panel">
+ <h2>Addresses held for you</h2>
+ <p className="hint">
+ Released addresses stay reserved for {status.reservationDays} days. You can take one
+ back by entering it above; after that anyone can claim it.
+ </p>
+ <ul className="mg-list">
+ {status.reservations.map((r) => (
+ <li className="mg-card" key={r.slug}>
+ <span className="grow">
+ <span className="title">{r.slug}</span>
+ <span className="sub">Held until {formatDate(r.until)}</span>
+ </span>
+ <button type="button" onClick={() => setValue(r.slug)}>Take it back</button>
+ </li>
+ ))}
+ </ul>
+ </section>
+ ) : null}
+
+ {status.current ? (
+ <section className="mg-panel">
+ <h2>Release the address</h2>
+ <p className="hint">
+ This page stays public either way — it goes back to its {idLabel}{" "}
+ address. The released address is held for you for {status.reservationDays} days.
+ </p>
+ {confirmRelease ? (
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
+ <span className="desc">Release <strong>{status.current.slug}</strong>?</span>
+ <button type="button" className="danger" onClick={release} disabled={busy}>
+ Yes, release it
+ </button>
+ <button type="button" className="ghost" onClick={() => setConfirmRelease(false)}>
+ Cancel
+ </button>
+ </div>
+ ) : (
+ <button type="button" className="danger" onClick={() => setConfirmRelease(true)}>
+ Release address
+ </button>
+ )}
+ </section>
+ ) : null}
+
+ {result ? (
+ <p className="mg-note" data-tone={result.tone === "error" ? "warn" : undefined} role="status" aria-live="polite">
+ {result.tone === "error" ? <ExclamationTriangle aria-hidden="true" /> : <Check2 aria-hidden="true" />}
+ <span>{result.text}</span>
+ </p>
+ ) : null}
+ </>
+ );
+}
+
+function formatDate(ms: number): string {
+ return new Date(ms).toLocaleDateString(undefined, {
+ day: "numeric",
+ month: "long",
+ year: "numeric",
+ });
+}
diff --git a/apps/web/src/components/manage/SocialLinksEditor.tsx b/apps/web/src/components/manage/SocialLinksEditor.tsx
new file mode 100644
index 0000000..00f31e1
--- /dev/null
+++ b/apps/web/src/components/manage/SocialLinksEditor.tsx
@@ -0,0 +1,246 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useUnsavedGuard } from "./useUnsavedGuard.ts";
+import {
+ ArrowDown,
+ ArrowUp,
+ Check2,
+ ExclamationTriangle,
+ Plus,
+ Trash,
+} from "react-bootstrap-icons";
+import {
+ MAX_SOCIAL_LINKS,
+ SOCIAL_PLATFORMS,
+ SOCIAL_URL_MESSAGES,
+ validateSocialUrl,
+} from "@pkviewer/shared";
+
+/**
+ * Social links editor.
+ *
+ * Links are data, never something pkviewer visits. There is no preview fetch,
+ * no favicon lookup and no title scraping: fetching a user-supplied URL from
+ * our server is an SSRF vector, so the platform choice is a label the user
+ * picks, not something detected from the address.
+ *
+ * The whole ordered list is saved at once, which makes reordering, editing and
+ * deleting one operation instead of three that can interleave badly.
+ */
+
+export type EditableLink = {
+ platform: string;
+ label: string;
+ url: string;
+};
+
+export function SocialLinksEditor({
+ initialLinks,
+ saveAction,
+ ownerLabel,
+}: {
+ initialLinks: EditableLink[];
+ saveAction: (links: EditableLink[]) => Promise<{ ok: boolean; error?: string }>;
+ ownerLabel: string;
+}) {
+ const [links, setLinks] = useState<EditableLink[]>(initialLinks);
+ const [saved, setSaved] = useState<EditableLink[]>(initialLinks);
+ const [status, setStatus] = useState<"idle" | "saving" | "ok" | "error">("idle");
+ const [message, setMessage] = useState<string | null>(null);
+
+ const dirty = useMemo(
+ () => JSON.stringify(links) !== JSON.stringify(saved),
+ [links, saved],
+ );
+
+ useUnsavedGuard(dirty);
+
+ // Client-side validation is a courtesy so people see the problem next to the
+ // field. The server revalidates everything regardless.
+ const errors = useMemo(
+ () =>
+ links.map((link) => {
+ if (link.url.trim().length === 0) return null;
+ const result = validateSocialUrl(link.url);
+ return result.ok ? null : SOCIAL_URL_MESSAGES[result.reason];
+ }),
+ [links],
+ );
+
+ const hasErrors = errors.some((e) => e !== null);
+
+ function update(index: number, patch: Partial<EditableLink>) {
+ setLinks((current) => current.map((l, i) => (i === index ? { ...l, ...patch } : l)));
+ setStatus("idle");
+ }
+
+ function move(index: number, delta: number) {
+ setLinks((current) => {
+ const target = index + delta;
+ if (target < 0 || target >= current.length) return current;
+ const next = [...current];
+ const [item] = next.splice(index, 1);
+ next.splice(target, 0, item!);
+ return next;
+ });
+ setStatus("idle");
+ }
+
+ async function save() {
+ setStatus("saving");
+ const usable = links.filter((l) => l.url.trim().length > 0);
+ const result = await saveAction(usable);
+ if (result.ok) {
+ setLinks(usable);
+ setSaved(usable);
+ setStatus("ok");
+ setMessage("Saved.");
+ } else {
+ setStatus("error");
+ setMessage(result.error ?? "Could not save. Please try again.");
+ }
+ }
+
+ return (
+ <>
+ <section className="mg-panel">
+ <h2>Links on {ownerLabel}</h2>
+ <p className="hint">
+ Shown as links on the public page. pkviewer never visits them, so
+ nothing is loaded from these addresses on your visitors' behalf.
+ </p>
+
+ {links.length === 0 ? (
+ <p className="desc">No links yet.</p>
+ ) : (
+ <ul className="mg-list">
+ {links.map((link, index) => {
+ const platform = SOCIAL_PLATFORMS.find((p) => p.id === link.platform);
+ const errorId = `link-${index}-error`;
+ return (
+ <li className="mg-panel" key={index} style={{ boxShadow: "none" }}>
+ <div className="mg-grid">
+ <div className="mg-field">
+ <label htmlFor={`link-${index}-platform`}>Type</label>
+ <select
+ id={`link-${index}-platform`}
+ value={link.platform}
+ onChange={(e) => update(index, { platform: e.target.value })}
+ >
+ {SOCIAL_PLATFORMS.map((p) => (
+ <option key={p.id} value={p.id}>{p.label}</option>
+ ))}
+ </select>
+ </div>
+
+ <div className="mg-field">
+ <label htmlFor={`link-${index}-label`}>Label (optional)</label>
+ <input
+ id={`link-${index}-label`}
+ type="text"
+ value={link.label}
+ maxLength={60}
+ placeholder={platform?.label ?? ""}
+ onChange={(e) => update(index, { label: e.target.value })}
+ />
+ <span className="desc">What the link says. Defaults to the type.</span>
+ </div>
+
+ <div className="mg-field">
+ <label htmlFor={`link-${index}-url`}>Address</label>
+ <input
+ id={`link-${index}-url`}
+ type="url"
+ value={link.url}
+ inputMode="url"
+ spellCheck={false}
+ placeholder={platform?.placeholder ?? "https://"}
+ aria-invalid={errors[index] ? "true" : undefined}
+ aria-describedby={errors[index] ? errorId : undefined}
+ onChange={(e) => update(index, { url: e.target.value })}
+ />
+ {errors[index] ? (
+ <span className="err" id={errorId}>{errors[index]}</span>
+ ) : null}
+ </div>
+ </div>
+
+ <div style={{ display: "flex", gap: 6, marginTop: 8, flexWrap: "wrap" }}>
+ <button
+ type="button"
+ className="icon"
+ onClick={() => move(index, -1)}
+ disabled={index === 0}
+ aria-label={`Move ${link.label || platform?.label || "link"} up`}
+ >
+ <ArrowUp aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ className="icon"
+ onClick={() => move(index, 1)}
+ disabled={index === links.length - 1}
+ aria-label={`Move ${link.label || platform?.label || "link"} down`}
+ >
+ <ArrowDown aria-hidden="true" />
+ </button>
+ <span style={{ flex: 1 }} />
+ <button
+ type="button"
+ className="danger"
+ onClick={() => {
+ setLinks((c) => c.filter((_, i) => i !== index));
+ setStatus("idle");
+ }}
+ >
+ <Trash aria-hidden="true" /> Remove
+ </button>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+
+ <p style={{ marginTop: 14, marginBottom: 0 }}>
+ <button
+ type="button"
+ onClick={() => {
+ setLinks((c) => [...c, { platform: "website", label: "", url: "" }]);
+ setStatus("idle");
+ }}
+ disabled={links.length >= MAX_SOCIAL_LINKS}
+ >
+ <Plus aria-hidden="true" /> Add a link
+ </button>
+ {links.length >= MAX_SOCIAL_LINKS ? (
+ <span className="desc"> Maximum of {MAX_SOCIAL_LINKS} links.</span>
+ ) : null}
+ </p>
+ </section>
+
+ <div className="mg-savebar">
+ <span
+ className="mg-status"
+ data-tone={status === "ok" ? "ok" : status === "error" || hasErrors ? "error" : dirty ? "dirty" : undefined}
+ role="status"
+ aria-live="polite"
+ >
+ {status === "error" || hasErrors ? <ExclamationTriangle aria-hidden="true" /> : null}
+ {status === "ok" ? <Check2 aria-hidden="true" /> : null}
+ {hasErrors
+ ? "Fix the highlighted addresses before saving"
+ : (message ?? (dirty ? "Unsaved changes" : "No changes"))}
+ </span>
+ <span className="spacer" />
+ <button type="button" className="ghost" onClick={() => { setLinks(saved); setStatus("idle"); setMessage(null); }} disabled={!dirty}>
+ Discard changes
+ </button>
+ <button type="button" className="primary" onClick={save} disabled={!dirty || hasErrors || status === "saving"}>
+ {status === "saving" ? "Saving…" : "Save links"}
+ </button>
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/components/manage/SystemNav.tsx b/apps/web/src/components/manage/SystemNav.tsx
new file mode 100644
index 0000000..ab1a2d2
--- /dev/null
+++ b/apps/web/src/components/manage/SystemNav.tsx
@@ -0,0 +1,41 @@
+"use client";
+
+import { usePathname } from "next/navigation";
+import { Globe2, Grid1x2, Link45deg, PaletteFill, People, Sliders } from "react-bootstrap-icons";
+
+/**
+ * Section navigation.
+ *
+ * A column on wide screens and a horizontal scroller on narrow ones. Shrinking
+ * a sidebar until it is unusable is worse than changing its shape.
+ */
+const SECTIONS = [
+ { slug: "", label: "Overview", Icon: Grid1x2 },
+ { slug: "address", label: "Public address", Icon: Globe2 },
+ { slug: "appearance", label: "Appearance", Icon: PaletteFill },
+ { slug: "directory", label: "Layout", Icon: Sliders },
+ { slug: "links", label: "Social links", Icon: Link45deg },
+ { slug: "members", label: "Members", Icon: People },
+];
+
+export function SystemNav({ systemId }: { systemId: string }) {
+ const pathname = usePathname();
+ const base = `/manage/${systemId}`;
+
+ return (
+ <nav className="mg-nav" aria-label="System settings">
+ {SECTIONS.map(({ slug, label, Icon }) => {
+ const href = slug ? `${base}/${slug}` : base;
+ const active = slug
+ ? pathname.startsWith(href)
+ : pathname === base || pathname === `${base}/`;
+ return (
+ <a key={label} href={href} aria-current={active ? "page" : undefined}>
+ <Icon aria-hidden="true" />
+ {label}
+ </a>
+ );
+ })}
+ </nav>
+ );
+}
diff --git a/apps/web/src/components/manage/ThemeEditor.tsx b/apps/web/src/components/manage/ThemeEditor.tsx
new file mode 100644
index 0000000..e6025b4
--- /dev/null
+++ b/apps/web/src/components/manage/ThemeEditor.tsx
@@ -0,0 +1,435 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useUnsavedGuard } from "./useUnsavedGuard.ts";
+import {
+ ArrowCounterclockwise,
+ Check2,
+ ExclamationTriangle,
+ PencilSquare,
+} from "react-bootstrap-icons";
+import {
+ FONTS,
+ FONT_IDS,
+ PRESETS,
+ THEME_TOKENS,
+ resolveTheme,
+ themeToCssVars,
+ type TokenDef,
+} from "@pkviewer/shared";
+import { ThemePreview } from "./ThemePreview.tsx";
+
+/**
+ * The appearance editor.
+ *
+ * Two levels share this component:
+ *
+ * system — defines the default appearance for the whole site
+ * member — overrides that default for one member's page
+ *
+ * The three inheritance states are expressed as UI rather than as data the user
+ * has to author. Nobody types `null`, deletes a field, or edits JSON: a control
+ * is either following what it inherits or explicitly set, and there is a button
+ * to move between those.
+ */
+
+type Level = "system" | "member";
+
+const GROUPS: Array<{ title: string; hint: string; keys: string[] }> = [
+ {
+ title: "Colours",
+ hint: "The palette everything is drawn from.",
+ keys: ["color.page", "color.surface", "color.text", "color.muted", "color.accent", "color.border"],
+ },
+ {
+ title: "Typography",
+ hint: "Typefaces and reading size.",
+ keys: ["font.body", "font.heading", "font.size"],
+ },
+ {
+ title: "Shape and surfaces",
+ hint: "How cards and edges are drawn.",
+ keys: ["shape.radius", "surface.style", "avatar.shape"],
+ },
+ { title: "Feel", hint: "How much room everything is given.", keys: ["density"] },
+ { title: "Display", hint: "Light or dark.", keys: ["color.scheme"] },
+];
+
+export type ThemeEditorProps = {
+ level: Level;
+ /** Values explicitly set at THIS level. Absent key = inheriting. */
+ initialValues: Record<string, string | null>;
+ /** The layer beneath: platform defaults for a system, system theme for a
+ * member. Used to show what "inherited" actually looks like. */
+ inheritedFrom: Record<string, string>;
+ saveAction: (values: Record<string, string | null>) => Promise<{ ok: boolean; error?: string }>;
+ previewName: string;
+};
+
+export function ThemeEditor({
+ level,
+ initialValues,
+ inheritedFrom,
+ saveAction,
+ previewName,
+}: ThemeEditorProps) {
+ const [values, setValues] = useState<Record<string, string | null>>(initialValues);
+ const [saved, setSaved] = useState<Record<string, string | null>>(initialValues);
+ const [status, setStatus] = useState<"idle" | "saving" | "ok" | "error">("idle");
+ const [message, setMessage] = useState<string | null>(null);
+
+ const dirty = useMemo(
+ () => JSON.stringify(values) !== JSON.stringify(saved),
+ [values, saved],
+ );
+
+ useUnsavedGuard(dirty);
+
+ // The preview resolves through the SAME functions the public renderer uses,
+ // so there is exactly one source of truth for how a token becomes a style.
+ const preview = useMemo(() => {
+ const resolved =
+ level === "system"
+ ? resolveTheme(values, {})
+ : resolveTheme(inheritedFrom, values);
+ return {
+ vars: themeToCssVars(resolved.light),
+ darkVars: themeToCssVars(resolved.dark),
+ scheme: resolved.scheme,
+ fonts: resolved.fonts,
+ };
+ }, [values, inheritedFrom, level]);
+
+ const editableTokens = THEME_TOKENS.filter(
+ (t) => level === "system" || t.memberOverridable,
+ );
+ const editableKeys = new Set(editableTokens.map((t) => t.key));
+
+ function setValue(key: string, value: string) {
+ setValues((v) => ({ ...v, [key]: value }));
+ setStatus("idle");
+ }
+
+ /** Returns a control to inheriting: the key is removed entirely, which is
+ * exactly what "absent means inherit" is. */
+ function inherit(key: string) {
+ setValues((v) => {
+ const next = { ...v };
+ delete next[key];
+ return next;
+ });
+ setStatus("idle");
+ }
+
+ /** Member-only: pin a control to the platform default, ignoring the system.
+ * This is the explicit-null state, exposed as a button rather than as data. */
+ function resetToPlatform(key: string) {
+ setValues((v) => ({ ...v, [key]: null }));
+ setStatus("idle");
+ }
+
+ function applyPreset(presetId: string) {
+ const preset = PRESETS.find((p) => p.id === presetId);
+ if (!preset) return;
+ // A preset applied at member level becomes an explicit member configuration.
+ // It never reaches up and changes the system.
+ const next: Record<string, string | null> = { ...values };
+ for (const [key, value] of Object.entries(preset.tokens)) {
+ if (editableKeys.has(key)) next[key] = value;
+ }
+ setValues(next);
+ setStatus("idle");
+ setMessage(`${preset.name} applied. Review and save.`);
+ }
+
+ async function save() {
+ setStatus("saving");
+ setMessage(null);
+ const result = await saveAction(values);
+ if (result.ok) {
+ setSaved(values);
+ setStatus("ok");
+ setMessage("Saved.");
+ } else {
+ setStatus("error");
+ setMessage(result.error ?? "Could not save. Please try again.");
+ }
+ }
+
+ return (
+ <>
+ <div className="mg-panel">
+ <h2>Start from a preset</h2>
+ <p className="hint">
+ {level === "system"
+ ? "A preset fills in every setting below. You can change anything afterwards."
+ : "Applying a preset here sets these values for this member only. It does not change the system."}
+ </p>
+ <div className="mg-presets">
+ {PRESETS.map((preset) => (
+ <button
+ type="button"
+ key={preset.id}
+ className="mg-preset"
+ onClick={() => applyPreset(preset.id)}
+ >
+ <span className="pname">{preset.name}</span>
+ <span className="mg-swatches" aria-hidden="true">
+ {["color.page", "color.surface", "color.text", "color.accent"].map((k) => (
+ <span
+ key={k}
+ className="mg-swatch"
+ style={{ background: preset.tokens[k] ?? "#fff" }}
+ />
+ ))}
+ </span>
+ <span className="pchar">{preset.character}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="mg-panel">
+ <h2>Preview</h2>
+ <p className="hint">
+ A representative sample. Open the public page to see the real thing.
+ </p>
+ <ThemePreview
+ vars={preview.vars}
+ darkVars={preview.darkVars}
+ scheme={preview.scheme}
+ name={previewName}
+ />
+ </div>
+
+ {GROUPS.map((group) => {
+ const keys = group.keys.filter((k) => editableKeys.has(k));
+ if (keys.length === 0) return null;
+ return (
+ <section className="mg-panel" key={group.title}>
+ <h2>{group.title}</h2>
+ <p className="hint">{group.hint}</p>
+ <div className="mg-grid">
+ {keys.map((key) => {
+ const def = THEME_TOKENS.find((t) => t.key === key);
+ if (!def) return null;
+ return (
+ <TokenField
+ key={key}
+ def={def}
+ level={level}
+ value={values[key]}
+ explicitlySet={Object.hasOwn(values, key)}
+ inherited={inheritedFrom[key] ?? ""}
+ onChange={setValue}
+ onInherit={inherit}
+ onResetToPlatform={resetToPlatform}
+ />
+ );
+ })}
+ </div>
+ </section>
+ );
+ })}
+
+ <div className="mg-savebar">
+ <span
+ className="mg-status"
+ data-tone={status === "ok" ? "ok" : status === "error" ? "error" : dirty ? "dirty" : undefined}
+ role="status"
+ aria-live="polite"
+ >
+ {status === "error" ? <ExclamationTriangle aria-hidden="true" /> : null}
+ {status === "ok" ? <Check2 aria-hidden="true" /> : null}
+ {message ?? (dirty ? "Unsaved changes" : "No changes")}
+ </span>
+ <span className="spacer" />
+ <button
+ type="button"
+ className="ghost"
+ onClick={() => {
+ setValues(saved);
+ setStatus("idle");
+ setMessage(null);
+ }}
+ disabled={!dirty || status === "saving"}
+ >
+ Discard changes
+ </button>
+ <button
+ type="button"
+ className="primary"
+ onClick={save}
+ disabled={!dirty || status === "saving"}
+ >
+ {status === "saving" ? "Saving…" : "Save appearance"}
+ </button>
+ </div>
+ </>
+ );
+}
+
+/**
+ * One setting.
+ *
+ * State is conveyed by a word ("Inherited" / "Custom") and a border, never by
+ * colour alone — the state has to survive colour blindness and a greyscale
+ * screenshot.
+ */
+function TokenField({
+ def,
+ level,
+ value,
+ explicitlySet,
+ inherited,
+ onChange,
+ onInherit,
+ onResetToPlatform,
+}: {
+ def: TokenDef;
+ level: Level;
+ value: string | null | undefined;
+ explicitlySet: boolean;
+ inherited: string;
+ onChange: (key: string, value: string) => void;
+ onInherit: (key: string) => void;
+ onResetToPlatform: (key: string) => void;
+}) {
+ const id = `tok-${def.key.replace(/\./g, "-")}`;
+ const isReset = explicitlySet && value === null;
+ const state = explicitlySet ? "override" : "inherit";
+ const effective = explicitlySet && typeof value === "string" ? value : inherited;
+
+ const stateLabel =
+ level === "system"
+ ? explicitlySet
+ ? "Custom"
+ : "Default"
+ : isReset
+ ? "Platform default"
+ : explicitlySet
+ ? "Custom"
+ : "Using system appearance";
+
+ return (
+ <div className="mg-field" data-state={state}>
+ <div className="mg-field-head">
+ <label htmlFor={id}>{def.label}</label>
+ <span className="spacer" />
+ <span className="mg-inherit" data-state={state}>
+ {explicitlySet ? <PencilSquare aria-hidden="true" /> : null}
+ {stateLabel}
+ </span>
+ </div>
+
+ <Control def={def} id={id} value={effective} onChange={onChange} />
+
+ <span className="desc" id={`${id}-desc`}>
+ {def.help}
+ </span>
+
+ {explicitlySet ? (
+ <span>
+ <button type="button" className="ghost" onClick={() => onInherit(def.key)}>
+ <ArrowCounterclockwise aria-hidden="true" />
+ {level === "system" ? "Use pkviewer default" : "Use system appearance"}
+ </button>
+ </span>
+ ) : level === "member" ? (
+ <span>
+ <button type="button" className="ghost" onClick={() => onChange(def.key, effective)}>
+ <PencilSquare aria-hidden="true" />
+ Override for this member
+ </button>
+ {" "}
+ <button type="button" className="ghost" onClick={() => onResetToPlatform(def.key)}>
+ Use pkviewer default instead
+ </button>
+ </span>
+ ) : null}
+ </div>
+ );
+}
+
+function Control({
+ def,
+ id,
+ value,
+ onChange,
+}: {
+ def: TokenDef;
+ id: string;
+ value: string;
+ onChange: (key: string, value: string) => void;
+}) {
+ if (def.type === "color") {
+ const safe = /^#[0-9A-Fa-f]{6}$/.test(value) ? value : "#000000";
+ return (
+ <span className="mg-colour">
+ <input
+ type="color"
+ id={id}
+ value={safe}
+ aria-describedby={`${id}-desc`}
+ onChange={(e) => onChange(def.key, e.target.value.toUpperCase())}
+ />
+ <input
+ type="text"
+ value={value}
+ aria-label={`${def.label} hex value`}
+ spellCheck={false}
+ onChange={(e) => onChange(def.key, e.target.value.toUpperCase())}
+ />
+ </span>
+ );
+ }
+
+ if (def.type === "font") {
+ return (
+ <select
+ id={id}
+ value={FONT_IDS.includes(value as never) ? value : def.default}
+ aria-describedby={`${id}-desc`}
+ onChange={(e) => onChange(def.key, e.target.value)}
+ >
+ {FONT_IDS.map((fid) => (
+ <option key={fid} value={fid}>
+ {FONTS[fid].label} — {FONTS[fid].note}
+ </option>
+ ))}
+ </select>
+ );
+ }
+
+ if (def.type === "enum") {
+ const current = def.values.includes(value) ? value : def.default;
+ return (
+ <select
+ id={id}
+ value={current}
+ aria-describedby={`${id}-desc`}
+ onChange={(e) => onChange(def.key, e.target.value)}
+ >
+ {def.values.map((v) => (
+ <option key={v} value={v}>
+ {sentence(v)}
+ </option>
+ ))}
+ </select>
+ );
+ }
+
+ return (
+ <input
+ type="text"
+ id={id}
+ value={value}
+ aria-describedby={`${id}-desc`}
+ onChange={(e) => onChange(def.key, e.target.value)}
+ />
+ );
+}
+
+function sentence(value: string): string {
+ return value.charAt(0).toUpperCase() + value.slice(1).replace(/-/g, " ");
+}
diff --git a/apps/web/src/components/manage/ThemePreview.tsx b/apps/web/src/components/manage/ThemePreview.tsx
new file mode 100644
index 0000000..e88e0f8
--- /dev/null
+++ b/apps/web/src/components/manage/ThemePreview.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import { PersonCircle } from "react-bootstrap-icons";
+import { TokenStyle } from "../TokenStyle.tsx";
+
+/**
+ * A representative sample of the public presentation.
+ *
+ * Deliberately not an iframe of the real page: it uses the SAME `--pkv-*`
+ * custom properties and the same mapping functions the public renderer does, so
+ * there is one source of truth for how a token becomes a style. Only the sample
+ * content is local to the editor.
+ */
+export function ThemePreview({
+ vars,
+ darkVars,
+ scheme,
+ name,
+}: {
+ vars: Record<string, string>;
+ darkVars: Record<string, string>;
+ scheme: "auto" | "light" | "dark";
+ name: string;
+}) {
+ return (
+ <div id="pkv-preview" className="pkv-preview">
+ <TokenStyle vars={vars} darkVars={darkVars} colorScheme={scheme} scope={{ elementId: "pkv-preview" }} />
+ <style>{`
+ .pkv-preview {
+ background: var(--pkv-color-page);
+ color: var(--pkv-color-text);
+ font-family: var(--pkv-font-body);
+ font-size: var(--pkv-font-size);
+ border: 1px solid var(--mg-line);
+ border-radius: var(--mg-radius);
+ padding: calc(1.25rem * var(--pkv-density));
+ overflow: hidden;
+ }
+ .pkv-preview .pv-name {
+ font-family: var(--pkv-font-heading);
+ font-size: 1.55em; font-weight: 600; line-height: 1.15; margin: 0;
+ }
+ .pkv-preview .pv-id { color: var(--pkv-color-muted); font-size: 0.85em; margin: 2px 0 0; }
+ .pkv-preview .pv-body { margin: calc(0.75rem * var(--pkv-density)) 0 0; line-height: 1.55; }
+ .pkv-preview .pv-link { color: var(--pkv-color-accent); text-decoration: underline; }
+ .pkv-preview .pv-head { display: flex; gap: calc(0.9rem * var(--pkv-density)); align-items: center; }
+ .pkv-preview .pv-avatar {
+ width: 56px; height: 56px; flex: none;
+ border-radius: var(--pkv-avatar-radius);
+ background: var(--pkv-color-border);
+ display: grid; place-items: center; color: var(--pkv-color-muted);
+ }
+ .pkv-preview .pv-cards {
+ margin-top: calc(1rem * var(--pkv-density));
+ display: grid; gap: calc(0.6rem * var(--pkv-density));
+ grid-template-columns: repeat(auto-fill, minmax(min(100%, 9rem), 1fr));
+ }
+ .pkv-preview .pv-card {
+ background: var(--pkv-surface-bg);
+ border: 1px solid var(--pkv-surface-border);
+ border-radius: var(--pkv-radius);
+ padding: calc(0.7rem * var(--pkv-density) * var(--pkv-surface-pad) + 0.2rem);
+ font-size: 0.9em;
+ }
+ .pkv-preview .pv-card .pv-sub { color: var(--pkv-color-muted); font-size: 0.85em; }
+ `}</style>
+
+ <div className="pv-head">
+ <div className="pv-avatar" aria-hidden="true">
+ <PersonCircle size={26} />
+ </div>
+ <div>
+ <p className="pv-name">{name}</p>
+ <p className="pv-id">they/them · 12 members</p>
+ </div>
+ </div>
+
+ <p className="pv-body">
+ This is how a description reads, with a <span className="pv-link">link</span> in it.
+ </p>
+
+ <div className="pv-cards">
+ {["Ash", "Juniper", "Wren"].map((member) => (
+ <div className="pv-card" key={member}>
+ <div>{member}</div>
+ <div className="pv-sub">she/her</div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/manage/useUnsavedGuard.ts b/apps/web/src/components/manage/useUnsavedGuard.ts
new file mode 100644
index 0000000..c1a22a7
--- /dev/null
+++ b/apps/web/src/components/manage/useUnsavedGuard.ts
@@ -0,0 +1,24 @@
+"use client";
+
+import { useEffect } from "react";
+
+/**
+ * Warns before leaving a page with unsaved edits.
+ *
+ * Deliberately minimal: a `beforeunload` listener, which the browser turns into
+ * its own confirmation. Intercepting in-app navigation would mean owning a
+ * router-level state machine, which is far more machinery than this earns — the
+ * save bar already states plainly when there are unsaved changes.
+ */
+export function useUnsavedGuard(dirty: boolean): void {
+ useEffect(() => {
+ if (!dirty) return;
+ const handler = (event: BeforeUnloadEvent) => {
+ event.preventDefault();
+ // Required by some browsers for the prompt to appear at all.
+ event.returnValue = "";
+ };
+ window.addEventListener("beforeunload", handler);
+ return () => window.removeEventListener("beforeunload", handler);
+ }, [dirty]);
+}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
new file mode 100644
index 0000000..736d44d
--- /dev/null
+++ b/apps/web/src/lib/api.ts
@@ -0,0 +1,46 @@
+import type { PageModel } from "@pkviewer/shared";
+import { webConfig } from "./config.ts";
+
+/**
+ * The web tier's only route to data.
+ *
+ * One call per page: the API returns a fully resolved model with PluralKit
+ * data, slugs, socials and tokens already merged, so server rendering is a
+ * single hop rather than a fan-out.
+ */
+
+export type PublicPage = PageModel & { canonicalPath: string };
+
+export type FetchOutcome<T> =
+ | { ok: true; value: T }
+ | { ok: false; status: number; reason: string };
+
+async function getJson<T>(path: string): Promise<FetchOutcome<T>> {
+ let res: Response;
+ try {
+ res = await fetch(`${webConfig.apiOrigin}${path}`, {
+ headers: { accept: "application/json" },
+ // Public pages are re-rendered per request; the API holds the cache, so a
+ // second cache here would only make staleness harder to reason about.
+ cache: "no-store",
+ });
+ } catch {
+ return { ok: false, status: 503, reason: "api_unreachable" };
+ }
+
+ if (!res.ok) {
+ const body = (await res.json().catch(() => null)) as { error?: string } | null;
+ return { ok: false, status: res.status, reason: body?.error ?? "error" };
+ }
+ return { ok: true, value: (await res.json()) as T };
+}
+
+export function getSystemPage(ref: string): Promise<FetchOutcome<PublicPage>> {
+ return getJson<PublicPage>(`/public/systems/${encodeURIComponent(ref)}`);
+}
+
+export function getMemberPage(ref: string, memberRef: string): Promise<FetchOutcome<PublicPage>> {
+ return getJson<PublicPage>(
+ `/public/systems/${encodeURIComponent(ref)}/members/${encodeURIComponent(memberRef)}`,
+ );
+}
diff --git a/apps/web/src/lib/config.ts b/apps/web/src/lib/config.ts
new file mode 100644
index 0000000..a90979f
--- /dev/null
+++ b/apps/web/src/lib/config.ts
@@ -0,0 +1,35 @@
+/**
+ * Web-tier configuration.
+ *
+ * Only origins and flags: the rendering tier holds no secrets and no database
+ * credentials. Every value is read from the environment so the deployment
+ * origin stays configuration rather than architecture (decision 1).
+ */
+
+function required(name: string, fallback?: string): string {
+ const value = process.env[name] ?? fallback;
+ if (!value) throw new Error(`missing environment variable: ${name}`);
+ return value.replace(/\/+$/, "");
+}
+
+export const webConfig = {
+ /** Session-bearing. /login, /auth, /manage. */
+ appOrigin: required("PUBLIC_APP_ORIGIN", "http://app.localhost:3000"),
+ /** Public and shareable. / and /s/... Never receives the session cookie. */
+ publicOrigin: required("PUBLIC_USERCONTENT_ORIGIN", "http://system.localhost:3000"),
+ /** Internal only. Never reaches the browser. */
+ apiOrigin: required("INTERNAL_API_ORIGIN", "http://127.0.0.1:3001"),
+ /**
+ * Where the documentation lives.
+ *
+ * Documentation is a separate site, not part of this application. It is a
+ * deployment hostname like any other, so it is configuration rather than a
+ * literal in the code.
+ */
+ docsUrl: (process.env["PUBLIC_DOCS_URL"] ?? "").replace(/\/+$/, ""),
+ beta: (process.env["BETA_MODE"] ?? "true") === "true",
+} as const;
+
+export function hostOf(origin: string): string {
+ return new URL(origin).host;
+}
diff --git a/apps/web/src/lib/manage-api.ts b/apps/web/src/lib/manage-api.ts
new file mode 100644
index 0000000..a1a4239
--- /dev/null
+++ b/apps/web/src/lib/manage-api.ts
@@ -0,0 +1,115 @@
+import "server-only";
+import { cookies } from "next/headers";
+import { webConfig } from "./config.ts";
+
+/**
+ * Server-side calls into the management API.
+ *
+ * The browser never talks to the API directly: INTERNAL_API_ORIGIN stays
+ * internal, and the session cookie is forwarded from the server component or
+ * server action making the call. That keeps the __Host- cookie's host pinning
+ * intact — a cross-origin browser call would need it loosened.
+ */
+
+export type ApiResult<T> =
+ | { ok: true; value: T }
+ | { ok: false; status: number; error: string; detail?: unknown };
+
+async function call<T>(
+ path: string,
+ init: { method?: string; body?: unknown } = {},
+): Promise<ApiResult<T>> {
+ const cookieHeader = (await cookies()).toString();
+
+ const headers: Record<string, string> = {
+ accept: "application/json",
+ cookie: cookieHeader,
+ // The API rejects state-changing requests without a recognised Origin, so a
+ // server-side mutation must present one explicitly.
+ origin: webConfig.appOrigin,
+ };
+ if (init.body !== undefined) headers["content-type"] = "application/json";
+
+ let res: Response;
+ try {
+ res = await fetch(`${webConfig.apiOrigin}${path}`, {
+ method: init.method ?? "GET",
+ headers,
+ ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
+ cache: "no-store",
+ });
+ } catch {
+ return { ok: false, status: 503, error: "api_unreachable" };
+ }
+
+ const payload = (await res.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!res.ok) {
+ return {
+ ok: false,
+ status: res.status,
+ error: typeof payload?.["error"] === "string" ? (payload["error"] as string) : "error",
+ detail: payload?.["rejected"] ?? payload?.["errors"],
+ };
+ }
+ return { ok: true, value: (payload ?? {}) as T };
+}
+
+export const manageApi = {
+ get: <T>(path: string) => call<T>(path),
+ put: <T>(path: string, body: unknown) => call<T>(path, { method: "PUT", body }),
+ post: <T>(path: string, body: unknown) => call<T>(path, { method: "POST", body }),
+};
+
+export type ManagedSystemSummary = {
+ systemId: string;
+ pkSystemHid: string;
+ role: string;
+ name: string | null;
+ avatarUrl: string | null;
+ slug: string | null;
+ publicPath: string;
+ memberCount: number | null;
+ snapshotAgeMs: number | null;
+ reachable: boolean;
+};
+
+export type SystemOverview = {
+ systemId: string;
+ pkSystemHid: string;
+ name: string | null;
+ avatarUrl: string | null;
+ description: string | null;
+ memberCount: number | null;
+ slug: string | null;
+ publicPath: string;
+ snapshotAgeMs: number | null;
+ reachable: boolean;
+};
+
+export type ManagedMemberSummary = {
+ memberId: string | null;
+ pkMemberHid: string;
+ pkMemberUuid: string;
+ name: string | null;
+ displayName: string | null;
+ avatarUrl: string | null;
+ pronouns: string | null;
+ slug: string | null;
+ hasThemeOverrides: boolean;
+};
+
+export type StoredSocial = {
+ id: number;
+ platform: string;
+ label: string | null;
+ url: string;
+ visible: boolean;
+ sortOrder: number;
+};
+
+/** Whether the caller has a session at all. Used to send anonymous visitors to
+ * the login page rather than showing them an error. */
+export async function isAuthenticated(): Promise<boolean> {
+ const result = await call<{ authenticated: boolean }>("/auth/me");
+ return result.ok && result.value.authenticated === true;
+}
diff --git a/apps/web/src/lib/theme.ts b/apps/web/src/lib/theme.ts
new file mode 100644
index 0000000..89ad569
--- /dev/null
+++ b/apps/web/src/lib/theme.ts
@@ -0,0 +1,43 @@
+import {
+ compositionToCssVars,
+ resolveComposition,
+ resolveTheme,
+ themeToCssVars,
+ type FontEntry,
+} from "@pkviewer/shared";
+
+/**
+ * Bridges stored theme data to what the renderer needs.
+ *
+ * The vocabulary and its validation live in @pkviewer/shared; this only wires
+ * them to the page, so a vocabulary change never reaches into components.
+ */
+export type PageTheme = {
+ vars: Record<string, string>;
+ darkVars: Record<string, string>;
+ colorScheme: "auto" | "light" | "dark";
+ fonts: FontEntry[];
+ composition: Record<string, string>;
+};
+
+export function buildPageTheme(
+ systemTokens: unknown,
+ memberTokens: unknown = null,
+ /**
+ * Composition already resolved by the API. Passed through rather than
+ * re-resolved so there is one place inheritance happens, not two.
+ */
+ resolvedComposition: Record<string, string> | null = null,
+): PageTheme {
+ const theme = resolveTheme(systemTokens, memberTokens);
+ const composition = resolvedComposition ?? resolveComposition({}, {});
+ const compositionVars = compositionToCssVars(composition);
+
+ return {
+ vars: { ...themeToCssVars(theme.light), ...compositionVars },
+ darkVars: { ...themeToCssVars(theme.dark), ...compositionVars },
+ colorScheme: theme.scheme,
+ fonts: theme.fonts,
+ composition,
+ };
+}
diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts
new file mode 100644
index 0000000..c74527f
--- /dev/null
+++ b/apps/web/src/middleware.ts
@@ -0,0 +1,76 @@
+import { NextResponse, type NextRequest } from "next/server";
+
+/**
+ * Enforces the origin split (O1) at the edge of the rendering tier.
+ *
+ * One Next application serves both hostnames; this decides which routes each
+ * one may answer. The rule:
+ *
+ * public origin -> /, /docs, /s/... never session-aware
+ * app origin -> /login, /auth, /manage session-bearing
+ *
+ * Serving a session-bearing route from the public origin would defeat the
+ * reason /s/... lives there, and serving /s/... from the app origin would put
+ * user-authored presentation on the same origin as the session cookie.
+ *
+ * In development both hostnames resolve to 127.0.0.1 via *.localhost, so the
+ * Host header behaves exactly as it does in production and this code path is
+ * genuinely exercised rather than bypassed.
+ */
+
+const PUBLIC_PREFIXES = ["/s"];
+const APP_PREFIXES = ["/login", "/auth", "/manage"];
+
+function isUnder(pathname: string, prefixes: string[]): boolean {
+ return prefixes.some((p) => pathname === p || pathname.startsWith(`${p}/`));
+}
+
+export function middleware(req: NextRequest) {
+ const host = req.headers.get("host") ?? "";
+ const { pathname } = req.nextUrl;
+
+ const appHost = safeHost(process.env["PUBLIC_APP_ORIGIN"]);
+ const publicHost = safeHost(process.env["PUBLIC_USERCONTENT_ORIGIN"]);
+
+ // A host we do not recognise gets no origin enforcement decision made for it;
+ // routing it would mean guessing which side of the split it belongs to.
+ if (!appHost || !publicHost || (host !== appHost && host !== publicHost)) {
+ return NextResponse.next();
+ }
+
+ const onApp = host === appHost;
+
+ if (onApp && isUnder(pathname, PUBLIC_PREFIXES)) {
+ return NextResponse.redirect(new URL(pathname + req.nextUrl.search, originOf(publicHost, req)));
+ }
+
+ if (!onApp && isUnder(pathname, APP_PREFIXES)) {
+ return NextResponse.redirect(new URL(pathname + req.nextUrl.search, originOf(appHost, req)));
+ }
+
+ // The app origin has no landing page of its own: its front door is the
+ // control plane. Without this, signing in drops you on the public landing
+ // page and you have to find /manage yourself.
+ if (onApp && (pathname === "/" || pathname === "")) {
+ return NextResponse.redirect(new URL("/manage", originOf(appHost, req)));
+ }
+
+ return NextResponse.next();
+}
+
+function safeHost(origin: string | undefined): string | null {
+ if (!origin) return null;
+ try {
+ return new URL(origin).host;
+ } catch {
+ return null;
+ }
+}
+
+function originOf(host: string, req: NextRequest): string {
+ return `${req.nextUrl.protocol}//${host}`;
+}
+
+export const config = {
+ matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
+};
diff --git a/apps/web/test/csp.test.ts b/apps/web/test/csp.test.ts
new file mode 100644
index 0000000..7995333
--- /dev/null
+++ b/apps/web/test/csp.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+/**
+ * The content security policy is not covered by any request-level test, because
+ * a policy that breaks the browser still returns 200 to a request that does not
+ * execute JavaScript.
+ *
+ * A `script-src` without `'unsafe-eval'` blocked hydration in development while
+ * every check still passed: pages rendered correctly, because they are
+ * server-rendered, and nothing on them was interactive. Buttons did nothing and
+ * no request ever reached the server.
+ *
+ * These assert the shape of the policy directly.
+ */
+const config = readFileSync(join(import.meta.dir, "..", "next.config.ts"), "utf8");
+
+describe("content security policy", () => {
+ // Next's development bundles evaluate modules through eval(); main-app.js
+ // alone contains well over a hundred calls.
+ test("development permits eval, which Next's dev bundles require", () => {
+ expect(config).toContain("'unsafe-eval'");
+ });
+
+ test("development permits the hot-reload websocket", () => {
+ expect(config).toContain("connect-src 'self' ws: wss:");
+ });
+
+ // Production bundles contain no eval, so the strict policy is safe there.
+ test("production keeps the strict script and connect policy", () => {
+ expect(config).toMatch(/isProduction[\s\S]{0,80}"script-src 'self' 'unsafe-inline'"/);
+ expect(config).toMatch(/isProduction[\s\S]{0,80}"connect-src 'self'"/);
+ });
+
+ test("the relaxations are conditional, not unconditional", () => {
+ expect(config).toContain("const scriptSrc = isProduction");
+ expect(config).toContain("const connectSrc = isProduction");
+ });
+
+ // The directive that actually protects the management UI from clickjacking.
+ test("framing is refused in every environment", () => {
+ expect(config).toContain("frame-ancestors 'none'");
+ expect(config).toContain('key: "X-Frame-Options", value: "DENY"');
+ });
+
+ test("the theme's style element and the font host stay allowed", () => {
+ expect(config).toContain("style-src 'self' 'unsafe-inline' https://fonts.googleapis.com");
+ expect(config).toContain("font-src 'self' https://fonts.gstatic.com");
+ });
+
+ // Avatars and banners live wherever each system put them.
+ test("images may come from any https host", () => {
+ expect(config).toContain("img-src 'self' https: data:");
+ });
+
+ test("HSTS is production-only", () => {
+ expect(config).toMatch(/isProduction[\s\S]{0,300}Strict-Transport-Security/);
+ });
+});
diff --git a/apps/web/test/token-style.test.ts b/apps/web/test/token-style.test.ts
new file mode 100644
index 0000000..bfaabd5
--- /dev/null
+++ b/apps/web/test/token-style.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, test } from "bun:test";
+import { TokenStyle, sanitizeCssVars } from "../src/components/TokenStyle.tsx";
+
+/**
+ * TokenStyle is the last line of defence, not the first. The vocabulary and its
+ * validation already reject invalid data; these tests prove that even if
+ * something bypassed all of that, nothing can escape a CSS declaration.
+ */
+describe("TokenStyle sanitisation", () => {
+ test("passes through legitimate values", () => {
+ const out = sanitizeCssVars({
+ "color-page": "#FAF8FB",
+ "font-body": 'system-ui, -apple-system, "Segoe UI", sans-serif',
+ radius: "10px",
+ density: "1.3",
+ });
+ expect(Object.keys(out)).toHaveLength(4);
+ });
+
+ test("allows the constrained var() form the mapping layer produces", () => {
+ expect(sanitizeCssVars({ "avatar-radius": "var(--pkv-radius)" })).toEqual({
+ "avatar-radius": "var(--pkv-radius)",
+ });
+ });
+
+ test("rejects declaration escapes", () => {
+ const out = sanitizeCssVars({
+ a: "#fff; } body { display: none } .x {",
+ b: "red; background: url(https://evil.test/x)",
+ c: "}</style><script>alert(1)</script>",
+ });
+ expect(out).toEqual({});
+ });
+
+ test("rejects url(), at-rules and comments", () => {
+ for (const value of [
+ "url(https://evil.test/pixel.png)",
+ "@import url(x)",
+ "red /* comment */",
+ "expression(alert(1))",
+ "var(--x); color: red",
+ "\\75 rl(x)",
+ ]) {
+ expect(sanitizeCssVars({ k: value })).toEqual({});
+ }
+ });
+
+ test("rejects malformed property names", () => {
+ for (const key of ["Color-Page", "color_page", "--evil", "a}b", "color-page;x"]) {
+ expect(sanitizeCssVars({ [key]: "#FFFFFF" })).toEqual({});
+ }
+ });
+
+ test("rejects absurdly long values", () => {
+ expect(sanitizeCssVars({ k: "a".repeat(201) })).toEqual({});
+ });
+});
+
+describe("where theme properties are declared", () => {
+ /**
+ * Custom properties inherit downward only. Declaring a public page's theme on
+ * an inner element meant `body` never saw it: the page background and base
+ * typography kept the platform defaults while everything inside the element
+ * was themed. A preset looked like it "only applied to the members".
+ */
+ test("a public page declares its theme at the document root", () => {
+ const rendered = renderTokenStyle({ scope: ":root", vars: { "color-page": "#FDF6F8" } });
+ expect(rendered).toContain(":root {");
+ expect(rendered).not.toContain("#:root");
+ expect(rendered).toContain("--pkv-color-page: #FDF6F8;");
+ });
+
+ // The editor's preview sits inside pkviewer's own UI and must not repaint it.
+ test("a scoped preview declares its theme on its own element only", () => {
+ const rendered = renderTokenStyle({
+ scope: { elementId: "pkv-preview" },
+ vars: { "color-page": "#FDF6F8" },
+ });
+ expect(rendered).toContain("#pkv-preview {");
+ expect(rendered).not.toContain(":root {");
+ });
+
+ test("dark values are emitted against the same selector", () => {
+ const rendered = renderTokenStyle({
+ scope: ":root",
+ vars: { "color-page": "#FFFFFF" },
+ darkVars: { "color-page": "#151219" },
+ colorScheme: "auto",
+ });
+ expect(rendered).toContain("@media (prefers-color-scheme: dark) { :root {");
+ });
+
+ test("a malformed element id produces nothing rather than broken CSS", () => {
+ expect(
+ renderTokenStyle({ scope: { elementId: "evil } body { display:none" }, vars: { a: "1px" } }),
+ ).toBe("");
+ });
+});
+
+/** Renders TokenStyle to the CSS text it would emit. */
+function renderTokenStyle(props: {
+ scope: ":root" | { elementId: string };
+ vars: Record<string, string>;
+ darkVars?: Record<string, string>;
+ colorScheme?: "auto" | "light" | "dark";
+}): string {
+ const element = TokenStyle(props as never) as { props?: { children?: string } } | null;
+ return element?.props?.children ?? "";
+}
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
new file mode 100644
index 0000000..d2c739f
--- /dev/null
+++ b/apps/web/tsconfig.json
@@ -0,0 +1,40 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "lib": [
+ "ES2023",
+ "DOM",
+ "DOM.Iterable"
+ ],
+ "types": [],
+ "jsx": "preserve",
+ "allowJs": true,
+ "incremental": true,
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "plugins": [
+ {
+ "name": "next"
+ }
+ ],
+ "paths": {
+ "@pkviewer/shared": [
+ "../../packages/shared/src/index.ts"
+ ],
+ "@/*": [
+ "./src/*"
+ ]
+ },
+ "esModuleInterop": true
+ },
+ "include": [
+ ".next/types/**/*.ts",
+ "next-env.d.ts",
+ "src/**/*.ts",
+ "src/**/*.tsx",
+ ".next-prod/types/**/*.ts"
+ ],
+ "exclude": [
+ "node_modules"
+ ]
+}
diff --git a/apps/web/tsconfig.tsbuildinfo b/apps/web/tsconfig.tsbuildinfo
new file mode 100644
index 0000000..fa4f33a
--- /dev/null
+++ b/apps/web/tsconfig.tsbuildinfo
@@ -0,0 +1 @@
+{"fileNames":["../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es5.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2015.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2016.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2017.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2018.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2019.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2020.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2021.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2022.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2023.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.dom.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.dom.iterable.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2015.core.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2015.collection.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2015.generator.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2015.iterable.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2015.promise.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2015.proxy.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2015.reflect.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2015.symbol.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2016.array.include.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2016.intl.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2017.arraybuffer.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2017.date.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2017.object.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2017.sharedmemory.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2017.string.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2017.intl.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2017.typedarrays.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2018.asyncgenerator.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2018.asynciterable.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2018.intl.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2018.promise.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2018.regexp.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2019.array.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2019.object.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2019.string.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2019.symbol.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2019.intl.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2020.bigint.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2020.date.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2020.promise.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2020.sharedmemory.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2020.string.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2020.symbol.wellknown.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2020.intl.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2020.number.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2021.promise.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2021.string.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2021.weakref.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2021.intl.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2022.array.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2022.error.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2022.intl.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2022.object.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2022.string.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2022.regexp.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2023.array.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2023.collection.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.es2023.intl.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.decorators.d.ts","../../node_modules/.bun/[email protected]/node_modules/typescript/lib/lib.decorators.legacy.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/unstable-cache.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/revalidate.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/unstable-no-store.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/use-cache/cache-tag.d.ts","./.next/types/cache-life.d.ts","./.next/types/routes.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/compatibility/disposable.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/compatibility/indexable.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/compatibility/iterators.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/compatibility/index.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/globals.typedarray.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/buffer.buffer.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/globals.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/web-globals/abortcontroller.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/web-globals/domexception.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/web-globals/events.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/header.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/readable.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/file.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/fetch.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/formdata.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/connector.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/client.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/errors.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/dispatcher.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/global-dispatcher.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/global-origin.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/pool-stats.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/pool.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/handlers.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/balanced-pool.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/agent.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/mock-interceptor.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/mock-agent.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/mock-client.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/mock-pool.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/mock-errors.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/proxy-agent.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/env-http-proxy-agent.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/retry-handler.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/retry-agent.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/api.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/interceptors.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/util.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/cookies.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/patch.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/websocket.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/eventsource.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/filereader.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/diagnostics-channel.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/content-type.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/cache.d.ts","../../node_modules/.bun/[email protected]/node_modules/undici-types/index.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/web-globals/fetch.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/web-globals/navigator.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/web-globals/storage.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/web-globals/streams.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/assert.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/assert/strict.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/async_hooks.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/buffer.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/child_process.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/cluster.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/console.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/constants.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/crypto.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/dgram.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/diagnostics_channel.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/dns.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/dns/promises.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/domain.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/events.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/fs.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/fs/promises.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/http.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/http2.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/https.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/inspector.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/inspector.generated.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/module.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/net.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/os.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/path.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/perf_hooks.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/process.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/punycode.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/querystring.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/readline.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/readline/promises.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/repl.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/sea.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/sqlite.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/stream.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/stream/promises.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/stream/consumers.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/stream/web.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/string_decoder.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/test.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/timers.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/timers/promises.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/tls.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/trace_events.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/tty.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/url.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/util.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/v8.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/vm.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/wasi.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/worker_threads.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/zlib.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/node/index.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/react/global.d.ts","../../node_modules/.bun/[email protected]/node_modules/csstype/index.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/react/index.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/react/canary.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/react/experimental.d.ts","../../node_modules/.bun/@[email protected]+bb30d84b8e9977d1/node_modules/@types/react-dom/index.d.ts","../../node_modules/.bun/@[email protected]+bb30d84b8e9977d1/node_modules/@types/react-dom/client.d.ts","../../node_modules/.bun/@[email protected]+bb30d84b8e9977d1/node_modules/@types/react-dom/canary.d.ts","../../node_modules/.bun/@[email protected]+bb30d84b8e9977d1/node_modules/@types/react-dom/experimental.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/get-page-files.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/compiled/webpack/webpack.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/plugins/next-font-manifest-plugin.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/deep-readonly.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/html-context.shared-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/load-custom-routes.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/image-config.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/plugins/subresource-integrity-plugin.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/api-utils/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/base-http/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/body-streams.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/cache-control.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/setup-exception-listeners.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/worker.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/constants.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/app-router-headers.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/rendering-mode.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/router-utils/build-prefetch-segment-data-route.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/require-hook.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/experimental/ppr.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/plugins/app-build-manifest-plugin.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/page-types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/segment-config/app/app-segment-config.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/segment-config/pages/pages-segment-config.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/analysis/get-page-static-info.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/loaders/get-module-build-info.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/plugins/middleware-plugin.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/node-polyfill-crypto.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/node-environment-baseline.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/node-environment-extensions/error-inspect.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/node-environment-extensions/random.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/node-environment-extensions/date.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/node-environment-extensions/web-crypto.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/node-environment-extensions/node-crypto.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/node-environment.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/page-extensions-type.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/fallback.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/plugins/flight-manifest-plugin.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/instrumentation/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/coalesced-function.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/router-utils/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/modern-browserslist-target.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/constants.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/trace/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/trace/trace.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/trace/shared.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/trace/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/load-jsconfig.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@next/env/dist/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/plugins/telemetry-plugin/use-cache-tracker-utils.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/plugins/telemetry-plugin/telemetry-plugin.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/telemetry/storage.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/build-context.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/bloom-filter.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack-config.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-kind.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-definitions/route-definition.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/swc/generated-native.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/swc/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/dev/parse-version-info.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/next-devtools/shared/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/dev/dev-indicator-server-state.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/parse-stack.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/next-devtools/server/shared.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/next-devtools/shared/stack-frame.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/next-devtools/dev-overlay/utils/get-error-by-type.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/react/jsx-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/next-devtools/dev-overlay/container/runtime-error/render-error.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/next-devtools/dev-overlay/shared.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/dev/hot-reloader-types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/cache-handlers/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/response-cache/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/resume-data-cache/cache-store.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/resume-data-cache/resume-data-cache.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/render-result.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/i18n-provider.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/next-url.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/compiled/@edge-runtime/cookies/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/cookies.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/request.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/after/builtin-request-context.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/fetch-event.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/response.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/segment-config/middleware/middleware-config.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/plugins/pages-manifest-plugin.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/router/utils/parse-url.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/base-http/node.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-definitions/locale-route-definition.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-definitions/pages-route-definition.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/mitt.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/with-router.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/router.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/route-loader.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/page-loader.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/router/router.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/router-context.shared-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/loadable-context.shared-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/loadable.shared-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/image-config-context.shared-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-definitions/app-page-route-definition.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/loaders/metadata/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/webpack/loaders/next-app-loader/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/app-dir-module.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/async-storage/draft-mode-provider.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/adapters/headers.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/cache-signal.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/dynamic-rendering.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/request/fallback-params.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/work-unit-async-storage-instance.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/response-cache/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/lazy-result.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/implicit-tags.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/work-unit-async-storage.external.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/router/utils/parse-relative-url.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/app-render.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/amp-context.shared-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/entrypoints.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/app-page/module.compiled.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/error-boundary.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/layout-router.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/render-from-template-context.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/action-async-storage-instance.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/action-async-storage.external.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/client-page.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/client-segment.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/request/search-params.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/hooks-server-context.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/http-access-fallback/error-boundary.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/types/alternative-urls-types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/types/extra-types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/types/metadata-types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/types/manifest-types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/types/opengraph-types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/types/twitter-types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/types/metadata-interface.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/types/resolvers.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/types/icons.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/resolve-metadata.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/metadata/metadata.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/lib/framework/boundary-components.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/rsc/preloads.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/rsc/postpone.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/rsc/taint.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/segment-cache/segment-value-encoding.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/collect-segment-data.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/next-devtools/userspace/app/segment-explorer-node.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/entry-base.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/templates/app-page.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/react/jsx-dev-runtime.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@types/react/compiler-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/entrypoints.d.ts","../../node_modules/.bun/@[email protected]+bb30d84b8e9977d1/node_modules/@types/react-dom/static.d.ts","../../node_modules/.bun/@[email protected]+bb30d84b8e9977d1/node_modules/@types/react-dom/server.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/entrypoints.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/app-page/module.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/adapter.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/use-cache/cache-life.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/router-reducer/router-reducer-types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/flight-data-helpers.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/router-reducer/fetch-server-response.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/app-router-context.shared-runtime.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/pages/vendored/contexts/entrypoints.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/pages/module.compiled.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/templates/pages.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/pages/module.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/next-devtools/userspace/pages/pages-dev-overlay-setup.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/render.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-definitions/pages-api-route-definition.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-matches/pages-api-route-match.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-matchers/route-matcher.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-matcher-providers/route-matcher-provider.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-matcher-managers/route-matcher-manager.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/normalizers/normalizer.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/normalizers/locale-route-normalizer.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/normalizers/request/pathname-normalizer.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/normalizers/request/suffix.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/normalizers/request/rsc.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/normalizers/request/prefetch-rsc.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/normalizers/request/next-data.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/normalizers/request/segment-prefix-rsc.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/static-paths/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/base-server.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/async-callback-set.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/router/utils/route-regex.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/router/utils/route-matcher.d.ts","../../node_modules/.bun/@[email protected]/node_modules/@img/colour/index.d.ts","../../node_modules/.bun/[email protected]+696fb5033f112e6a/node_modules/sharp/dist/index.d.mts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/image-optimizer.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/next-server.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/lru-cache.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/dev-bundler-service.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/dev/static-paths-worker.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/dev/next-dev-server.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/next.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/render-server.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/router-server.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/router/utils/path-match.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/router-utils/filesystem.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/router-utils/setup-dev-bundler.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/router-utils/router-server-context.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/route-module.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/load-components.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-definitions/app-route-route-definition.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/async-storage/work-store.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/http.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/app-route/shared-modules.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/redirect-status-code.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/redirect-error.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/templates/app-route.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/app-route/module.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-modules/app-route/module.compiled.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/segment-config/app/app-segments.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/utils.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/turborepo-access-trace/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/turborepo-access-trace/result.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/turborepo-access-trace/helpers.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/turborepo-access-trace/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/export/routes/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/export/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/export/worker.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/worker.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/build/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/lib/incremental-cache/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/after/after.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/after/after-context.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/work-async-storage-instance.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/app-render/work-async-storage.external.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/request/params.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/route-matches/route-match.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/request-meta.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/cli/next-test.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/config-shared.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/config.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/utils.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/user-agent.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/compiled/@edge-runtime/primitives/url.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/web/spec-extension/image-response.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/compiled/@vercel/og/satori/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/compiled/@vercel/og/emoji/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/compiled/@vercel/og/types.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/after/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/request/root-params.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/request/connection.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/server.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/styled-jsx/types/css.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/styled-jsx/types/macro.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/styled-jsx/types/style.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/styled-jsx/types/global.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/styled-jsx/types/index.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/amp.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/amp.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/pages/_app.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/app.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/cache.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/runtime-config.external.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/config.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/pages/_document.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/document.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/dynamic.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dynamic.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/pages/_error.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/error.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/head.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/head.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/request/cookies.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/request/headers.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/server/request/draft-mode.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/headers.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/get-img-props.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/image-component.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/shared/lib/image-external.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/image.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/link.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/link.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/redirect.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/not-found.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/forbidden.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/unauthorized.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/unstable-rethrow.server.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/unstable-rethrow.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/navigation.react-server.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/unrecognized-action-error.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/components/navigation.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/navigation.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/router.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/dist/client/script.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/script.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/types/global.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/types/compiled.d.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/index.d.ts","../../node_modules/.bun/[email protected]+0f58469d5b3bd39f/node_modules/react-bootstrap-icons/dist/index.d.ts","./src/lib/config.ts","./src/app/login/page.tsx","./src/components/manage/publicurl.tsx","./src/components/manage/slugeditor.tsx","./src/lib/manage-api.ts","./src/app/manage/actions.ts","./src/app/manage/[systemid]/address/page.tsx","../../packages/shared/src/theme/vocabulary.ts","../../packages/shared/src/theme/validate.ts","../../packages/shared/src/theme/resolve.ts","../../packages/shared/src/theme/presets.ts","../../packages/shared/src/theme/index.ts","../../packages/shared/src/social.ts","../../packages/shared/src/index.ts","./src/components/manage/useunsavedguard.ts","./src/components/tokenstyle.tsx","./src/components/manage/themepreview.tsx","./src/components/manage/themeeditor.tsx","./src/app/manage/[systemid]/appearance/page.tsx","./src/components/manage/compositioneditor.tsx","./src/app/manage/[systemid]/directory/page.tsx","./src/components/manage/sociallinkseditor.tsx","./src/app/manage/[systemid]/links/page.tsx","./src/app/manage/[systemid]/members/[memberref]/page.tsx","./src/app/manage/[systemid]/members/page.tsx","./src/app/manage/[systemid]/page.tsx","./src/components/manage/claimflow.tsx","./src/app/manage/claim/page.tsx","./src/app/manage/page.tsx","./src/components/notices.tsx","./src/app/page.tsx","./src/components/sociallinks.tsx","./src/components/themefonts.tsx","./src/lib/api.ts","./src/lib/theme.ts","./src/app/s/[systemref]/[memberref]/page.tsx","./src/components/memberdirectory.tsx","./src/app/s/[systemref]/page.tsx","./src/app/auth/[...segments]/route.ts","./src/app/manage/signout/route.ts","./src/app/layout.tsx","./src/components/manage/systemnav.tsx","./src/app/manage/[systemid]/layout.tsx","./src/app/manage/layout.tsx","./.next/types/validator.ts","./.next/types/app/layout.ts","./.next/types/app/page.ts","./.next/types/app/login/page.ts","./.next/types/app/manage/layout.ts","./.next/types/app/manage/page.ts","./.next/types/app/manage/[systemid]/layout.ts","./.next/types/app/manage/[systemid]/page.ts","./.next/types/app/manage/[systemid]/address/page.ts","./.next/types/app/manage/[systemid]/appearance/page.ts","./.next/types/app/manage/[systemid]/directory/page.ts","./.next/types/app/manage/[systemid]/links/page.ts","./.next/types/app/manage/[systemid]/members/page.ts","./.next/types/app/manage/[systemid]/members/[memberref]/page.ts","./.next/types/app/s/[systemref]/page.ts","./.next/types/app/s/[systemref]/[memberref]/page.ts","../../node_modules/.bun/[email protected]+e8c85658066b2611/node_modules/next/image-types/global.d.ts","./next-env.d.ts","./src/middleware.ts","./src/app/not-found.tsx","./src/app/manage/error.tsx","./src/app/manage/loading.tsx","./src/app/manage/not-found.tsx","./src/app/manage/[systemid]/loading.tsx","./.next-prod/types/cache-life.d.ts","./.next-prod/types/routes.d.ts","./.next-prod/types/validator.ts","./.next-prod/types/app/layout.ts","./.next-prod/types/app/page.ts","./.next-prod/types/app/auth/[...segments]/route.ts","./.next-prod/types/app/login/page.ts","./.next-prod/types/app/manage/page.ts","./.next-prod/types/app/manage/[systemid]/layout.ts","./.next-prod/types/app/manage/[systemid]/page.ts","./.next-prod/types/app/manage/[systemid]/address/page.ts","./.next-prod/types/app/manage/[systemid]/appearance/page.ts","./.next-prod/types/app/manage/[systemid]/directory/page.ts","./.next-prod/types/app/manage/[systemid]/links/page.ts","./.next-prod/types/app/manage/[systemid]/members/page.ts","./.next-prod/types/app/manage/[systemid]/members/[memberref]/page.ts","./.next-prod/types/app/manage/claim/page.ts","./.next-prod/types/app/manage/signout/route.ts","./.next-prod/types/app/s/[systemref]/page.ts","./.next-prod/types/app/s/[systemref]/[memberref]/page.ts"],"fileIdsList":[[68,75,124,141,142,437,523,553],[68,75,124,141,142,324,525,553],[68,75,124,141,142,324,486,553],[68,75,124,141,142,324,491,553],[68,75,124,141,142,324,503,553],[68,75,124,141,142,324,505,553],[68,75,124,141,142,324,527,553],[68,75,124,141,142,324,507,553],[68,75,124,141,142,324,508,553],[68,75,124,141,142,324,509,553],[68,75,124,141,142,324,510,553],[68,75,124,141,142,324,512,553],[68,75,124,141,142,324,513,553],[68,75,124,141,142,437,524,553],[68,75,124,141,142,324,515,553],[68,75,124,141,142,324,520,553],[68,75,124,141,142,324,522,553],[64,65,66,67,68,75,124,141,142],[68,75,124,141,142,553],[68,75,124,141,142,427,437,486,491,503,505,507,508,509,510,512,513,515,520,522,523,524,525,527,528,553,554],[68,75,124,141,142,324,528,553],[64,65,66,67,75,124,141,142,553],[68,69,75,124,141,142,427,437,486,491,503,505,507,508,509,510,512,513,515,520,522,523,524,525,527,528,553],[68,69,75,124,141,142,483,545,553],[68,75,124,141,142,437,461,485,553],[68,75,124,141,142,483,553],[68,75,124,141,142,483,484,485,553],[68,75,124,141,142,477,483,485,488,489,490,553],[68,75,124,141,142,477,483,489,490,498,502,553],[68,75,124,141,142,477,483,489,490,498,504,553],[68,75,124,141,142,477,489,526,553],[68,75,124,141,142,477,483,489,490,506,553],[68,75,124,141,142,477,483,484,485,488,489,490,498,502,506,553],[68,75,124,141,142,477,483,484,489,553],[68,75,124,141,142,477,483,484,485,487,489,553],[68,75,124,141,142,489,553],[68,75,124,141,142,483,484,490,511,553],[68,75,124,141,142,484,553],[68,75,124,141,142,477,483,484,485,489,553],[68,75,124,141,142,484,485,489,553],[68,75,124,141,142,485,514,553],[68,75,124,141,142,484,485,514,553],[68,75,124,141,142,477,483,484,485,500,514,516,517,518,519,553],[68,75,124,141,142,477,483,484,485,500,514,516,517,518,519,521,553],[68,75,124,141,142,177,484,490,553],[68,75,124,141,142,177,484,498,499,553],[68,75,124,141,142,177,484,553],[68,75,124,141,142,177,484,487,553],[68,75,124,141,142,477,484,553],[68,75,124,141,142,177,484,498,499,501,553],[68,75,124,141,142,484,500,553],[68,75,124,141,142,177,553],[68,75,124,141,142,484,498,553],[68,75,124,141,142,484,485,553],[68,75,124,141,142,498,553],[68,75,124,141,142,485,498,553],[68,75,124,141,142,461,481,485,553],[68,75,124,141,142,437,553],[68,75,121,122,124,141,142,553],[68,75,123,124,141,142,553],[68,124,141,142,553],[68,75,124,129,141,142,159,553],[68,75,124,125,130,135,141,142,144,156,167,553],[68,75,124,125,126,135,141,142,144,553],[68,70,71,72,75,124,141,142,553],[68,75,124,127,141,142,168,553],[68,75,124,128,129,136,141,142,145,553],[68,75,124,129,141,142,156,164,553],[68,75,124,130,132,135,141,142,144,553],[68,75,123,124,131,141,142,553],[68,75,124,132,133,141,142,553],[68,75,124,134,135,141,142,553],[68,75,123,124,135,141,142,553],[68,75,124,135,136,137,141,142,156,167,553],[68,75,124,135,136,137,141,142,151,156,159,553],[68,75,116,124,132,135,138,141,142,144,156,167,553],[68,75,124,135,136,138,139,141,142,144,156,164,167,553],[68,75,124,138,140,141,142,156,164,167,553],[68,73,74,75,76,77,78,79,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,553],[68,75,124,135,141,142,553],[68,75,124,141,142,143,167,553],[68,75,124,132,135,141,142,144,156,553],[68,75,124,141,142,145,553],[68,75,124,141,142,146,553],[68,75,123,124,141,142,147,553],[68,75,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,553],[68,75,124,141,142,149,553],[68,75,124,141,142,150,553],[68,75,124,135,141,142,151,152,553],[68,75,124,141,142,151,153,168,170,553],[68,75,124,136,141,142,553],[68,75,124,135,141,142,156,157,159,553],[68,75,124,141,142,158,159,553],[68,75,124,141,142,156,157,553],[68,75,124,141,142,159,553],[68,75,124,141,142,160,553],[68,75,121,124,141,142,156,161,167,553],[68,75,124,135,141,142,162,163,553],[68,75,124,141,142,162,163,553],[68,75,124,129,141,142,144,156,164,553],[68,75,124,141,142,165,553],[68,75,124,141,142,144,166,553],[68,75,124,138,141,142,150,167,553],[68,75,124,129,141,142,168,553],[68,75,124,141,142,156,169,553],[68,75,124,141,142,143,170,553],[68,75,124,141,142,171,553],[68,75,116,124,141,142,553],[68,75,116,124,135,137,141,142,147,156,159,167,169,170,172,553],[68,75,124,141,142,156,173,553],[68,75,124,141,142,177,178,179,180,181,182,183,341,342,426,433,441,553],[68,75,124,141,142,177,178,179,180,181,182,426,433,441,553],[68,75,124,141,142,177,178,179,182,183,426,433,441,553],[68,75,124,141,142,177,181,182,183,341,553],[68,75,124,141,142,177,181,183,553],[68,75,124,141,142,177,179,180,182,183,426,433,441,553],[68,75,124,141,142,177,178,180,182,183,426,433,441,553],[68,75,124,141,142,175,176,553],[68,75,124,141,142,443,553],[68,75,124,141,142,445,553],[64,65,66,67,68,75,124,141,142,553],[68,75,124,141,142,448,553],[68,75,124,141,142,189,205,206,207,209,423,553],[68,75,124,141,142,189,192,231,233,235,236,239,423,553],[68,75,124,141,142,189,192,195,197,198,199,200,201,412,423,553],[68,75,124,141,142,423,553],[68,75,124,141,142,206,307,393,402,419,553],[68,75,124,141,142,189,553],[68,75,124,141,142,220,419,553],[68,75,124,141,142,243,553],[68,75,124,141,142,192,242,423,553],[68,75,124,138,141,142,290,307,336,482,553],[68,75,124,138,141,142,301,316,402,418,553],[68,75,124,138,141,142,353,553],[68,75,124,141,142,406,553],[68,75,124,141,142,405,406,407,553],[68,75,124,141,142,405,553],[68,75,124,138,141,142,184,189,195,198,202,203,204,206,210,218,219,220,346,371,403,423,426,553],[68,75,124,141,142,189,208,227,231,232,237,238,423,482,553],[68,75,124,141,142,208,482,553],[68,75,124,141,142,219,227,288,423,482,553],[68,75,124,141,142,482,553],[68,75,124,141,142,189,208,209,482,553],[68,75,124,141,142,234,482,553],[68,75,124,141,142,202,404,411,553],[68,75,124,141,142,150,251,419,553],[68,75,124,141,142,251,419,553],[68,75,124,141,142,177,251,553],[68,75,124,141,142,177,308,553],[68,75,124,141,142,304,351,419,474,475,553],[68,75,124,141,142,399,468,469,470,471,473,553],[68,75,124,141,142,398,553],[68,75,124,141,142,398,399,553],[68,75,124,141,142,199,347,348,349,553],[68,75,124,141,142,347,350,351,553],[68,75,124,141,142,472,553],[68,75,124,141,142,347,351,553],[68,75,124,141,142,177,190,462,553],[68,75,124,141,142,167,177,553],[68,75,124,141,142,177,208,278,553],[68,75,124,141,142,177,208,553],[68,75,124,141,142,276,280,553],[68,75,124,141,142,177,277,425,553],[68,75,124,138,141,142,174,177,178,179,180,182,183,426,431,432,441,553],[68,75,124,138,141,142,553],[68,75,124,138,141,142,193,195,258,347,357,372,393,408,409,423,482,553],[68,75,124,141,142,218,410,553],[68,75,124,141,142,426,553],[68,75,124,141,142,424,553],[68,75,124,141,142,177,290,303,315,325,327,418,553],[68,75,124,141,142,150,290,303,324,325,326,418,481,553],[68,75,124,141,142,318,319,320,321,322,323,553],[68,75,124,141,142,320,553],[68,75,124,141,142,324,553],[68,75,124,141,142,249,250,251,253,553],[68,75,124,141,142,177,244,245,246,252,553],[68,75,124,141,142,249,252,553],[68,75,124,141,142,247,553],[68,75,124,141,142,248,553],[68,75,124,141,142,177,251,277,425,553],[68,75,124,141,142,177,188,251,425,553],[68,75,124,141,142,177,251,425,553],[68,75,124,141,142,372,415,553],[68,75,124,141,142,415,553],[68,75,124,138,141,142,193,425,553],[68,75,124,141,142,312,553],[68,75,123,124,141,142,311,553],[68,75,124,141,142,187,193,221,259,296,298,300,301,302,344,347,418,421,553],[68,75,124,141,142,221,333,347,351,553],[68,75,124,141,142,301,418,553],[68,75,124,141,142,177,301,309,310,312,313,314,315,316,317,328,329,330,331,332,334,335,418,419,482,553],[68,75,124,141,142,295,553],[68,75,124,138,141,142,150,186,187,192,193,221,222,258,344,345,346,351,372,393,414,423,426,482,553],[68,75,124,141,142,418,553],[68,75,123,124,141,142,187,193,206,299,346,414,416,417,553],[68,75,124,141,142,301,553],[68,75,123,124,141,142,258,263,291,292,293,294,295,296,297,298,300,418,419,553],[68,75,124,138,141,142,192,193,263,264,291,553],[68,75,124,141,142,193,206,346,347,372,414,418,553],[68,75,124,138,141,142,192,423,553],[68,75,124,138,141,142,156,192,193,421,553],[68,75,124,138,141,142,150,167,186,187,192,193,195,208,220,221,222,224,259,260,265,270,298,347,357,359,362,364,367,368,369,370,371,393,413,414,419,421,423,553],[68,75,124,138,141,142,156,553],[68,75,124,141,142,189,190,191,195,200,203,208,227,413,421,422,425,426,482,553],[68,75,124,138,141,142,156,167,239,241,243,244,245,246,253,482,553],[68,75,124,141,142,150,167,220,231,241,269,270,271,272,298,347,362,371,372,379,382,383,393,414,419,421,553],[68,75,124,141,142,202,203,218,346,371,414,423,553],[68,75,124,138,141,142,167,190,195,298,377,421,423,553],[68,75,124,141,142,289,553],[68,75,124,138,141,142,380,381,390,553],[68,75,124,141,142,421,423,553],[68,75,124,141,142,296,299,553],[68,75,124,141,142,187,298,413,425,553],[68,75,124,138,141,142,150,225,231,272,362,372,379,382,385,421,553],[68,75,124,138,141,142,202,218,231,386,553],[68,75,124,141,142,189,224,388,413,423,553],[68,75,124,138,141,142,167,423,553],[68,75,124,138,141,142,208,223,224,225,236,254,387,389,413,423,553],[68,75,124,141,142,184,187,221,392,425,426,553],[68,75,124,138,141,142,150,167,186,195,202,210,218,222,259,265,269,270,271,272,298,347,359,372,373,375,378,393,413,414,419,420,421,425,553],[68,75,124,138,141,142,156,202,379,384,390,421,553],[68,75,124,141,142,213,214,215,216,217,553],[68,75,124,141,142,260,363,553],[68,75,124,141,142,365,553],[68,75,124,141,142,363,553],[68,75,124,141,142,365,366,553],[68,75,124,138,141,142,193,195,198,199,258,553],[68,75,124,138,141,142,150,186,187,190,192,221,259,355,356,393,421,424,425,426,553],[68,75,124,138,141,142,150,167,193,194,199,298,356,420,553],[68,75,124,141,142,291,553],[68,75,124,141,142,292,553],[68,75,124,141,142,293,553],[68,75,124,141,142,419,553],[68,75,124,141,142,240,256,553],[68,75,124,138,141,142,195,240,259,553],[68,75,124,141,142,255,256,553],[68,75,124,141,142,257,553],[68,75,124,141,142,240,241,553],[68,75,124,141,142,240,273,553],[68,75,124,141,142,240,553],[68,75,124,141,142,260,361,420,553],[68,75,124,141,142,360,553],[68,75,124,141,142,241,419,420,553],[68,75,124,141,142,358,420,553],[68,75,124,141,142,241,419,553],[68,75,124,141,142,344,553],[68,75,124,141,142,187,193,195,200,259,287,290,296,298,303,306,337,340,343,347,392,413,421,553],[68,75,124,141,142,281,284,285,286,304,305,351,553],[68,75,124,141,142,177,180,182,183,251,338,339,553],[68,75,124,141,142,177,180,182,183,251,338,339,342,553],[68,75,124,141,142,401,553],[68,75,124,141,142,187,206,264,301,312,316,347,392,394,395,396,397,399,400,403,413,418,423,553],[68,75,124,141,142,351,553],[68,75,124,141,142,355,553],[68,75,124,138,141,142,259,274,352,354,357,392,421,425,426,553],[68,75,124,141,142,188,281,282,283,284,285,286,304,305,351,553],[68,75,124,138,141,142,150,167,184,186,187,193,222,240,241,298,390,391,393,413,414,423,426,553],[68,75,124,141,142,264,266,269,414,553],[68,75,124,138,141,142,260,423,553],[68,75,124,141,142,263,301,553],[68,75,124,141,142,262,553],[68,75,124,141,142,264,265,553],[68,75,124,141,142,261,263,423,553],[68,75,124,138,141,142,193,194,264,266,267,268,423,553],[68,75,124,141,142,177,347,348,350,553],[68,75,124,141,142,226,553],[68,75,124,141,142,177,190,553],[68,75,124,141,142,177,419,553],[68,75,124,141,142,177,184,186,187,425,426,553],[68,75,124,141,142,190,462,463,553],[68,75,124,141,142,177,280,553],[68,75,124,141,142,150,167,177,238,275,277,279,424,425,553],[68,75,124,141,142,193,208,419,553],[68,75,124,141,142,374,419,553],[68,75,124,141,142,347,553],[68,75,124,136,138,141,142,150,177,188,227,233,280,424,426,553],[68,75,124,141,142,177,178,179,180,182,183,426,433,553],[68,75,124,141,142,177,438,439,440,441,553],[68,75,124,129,141,142,553],[68,75,124,141,142,228,229,230,553],[68,75,124,141,142,228,553],[68,75,124,138,140,141,142,150,174,177,178,179,180,182,183,192,220,222,324,385,423,424,425,433,441,553],[68,75,124,141,142,450,553],[68,75,124,141,142,452,553],[68,75,124,141,142,454,553],[68,75,124,141,142,456,553],[68,75,124,141,142,458,459,460,553],[68,75,124,141,142,464,553],[68,75,124,141,142,427,437,442,444,446,447,449,451,453,455,457,461,465,467,477,478,480,481,482,553],[68,75,124,141,142,466,553],[68,75,124,141,142,476,553],[68,75,124,141,142,277,553],[68,75,124,141,142,479,553],[68,75,123,124,141,142,264,266,267,269,315,419,428,429,430,433,434,435,436,553],[68,75,124,141,142,174,553],[68,75,124,141,142,156,174,376,553],[68,75,88,92,124,141,142,167,553],[68,75,88,124,141,142,156,167,553],[68,75,83,124,141,142,553],[68,75,85,88,124,141,142,164,167,553],[68,75,124,141,142,144,164,553],[68,75,83,124,141,142,174,553],[68,75,85,88,124,141,142,144,167,553],[68,75,80,81,84,87,124,135,141,142,156,167,553],[68,75,88,95,124,141,142,553],[68,75,80,86,124,141,142,553],[68,75,88,109,110,124,141,142,553],[68,75,84,88,124,141,142,159,167,174,553],[68,75,109,124,141,142,174,553],[68,75,82,83,124,141,142,174,553],[68,75,88,124,141,142,553],[68,75,82,83,84,85,86,87,88,89,90,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,110,111,112,113,114,115,124,141,142,553],[68,75,88,103,124,141,142,553],[68,75,88,95,96,124,141,142,553],[68,75,86,88,96,97,124,141,142,553],[68,75,87,124,141,142,553],[68,75,80,83,88,124,141,142,553],[68,75,88,92,96,97,124,141,142,553],[68,75,92,124,141,142,553],[68,75,86,88,91,124,141,142,167,553],[68,75,80,85,88,95,124,141,142,553],[68,75,124,141,142,156,553],[68,75,83,88,109,124,141,142,172,174,553],[68,75,124,141,142,496,497,553],[68,75,124,141,142,492,493,494,495,553],[68,75,124,141,142,492,493,553],[68,75,124,141,142,492,553]],"fileInfos":[{"version":"c430d44666289dae81f30fa7b2edebf186ecc91a2d4c71266ea6ae76388792e1","affectsGlobalScope":true,"impliedFormat":1},{"version":"45b7ab580deca34ae9729e97c13cfd999df04416a79116c3bfb483804f85ded4","impliedFormat":1},{"version":"3facaf05f0c5fc569c5649dd359892c98a85557e3e0c847964caeb67076f4d75","impliedFormat":1},{"version":"e44bb8bbac7f10ecc786703fe0a6a4b952189f908707980ba8f3c8975a760962","impliedFormat":1},{"version":"5e1c4c362065a6b95ff952c0eab010f04dcd2c3494e813b493ecfd4fcb9fc0d8","impliedFormat":1},{"version":"68d73b4a11549f9c0b7d352d10e91e5dca8faa3322bfb77b661839c42b1ddec7","impliedFormat":1},{"version":"5efce4fc3c29ea84e8928f97adec086e3dc876365e0982cc8479a07954a3efd4","impliedFormat":1},{"version":"feecb1be483ed332fad555aff858affd90a48ab19ba7272ee084704eb7167569","impliedFormat":1},{"version":"ee7bad0c15b58988daa84371e0b89d313b762ab83cb5b31b8a2d1162e8eb41c2","impliedFormat":1},{"version":"27bdc30a0e32783366a5abeda841bc22757c1797de8681bbe81fbc735eeb1c10","impliedFormat":1},{"version":"080941d9f9ff9307f7e27a83bcd888b7c8270716c39af943532438932ec1d0b9","affectsGlobalScope":true,"impliedFormat":1},{"version":"2e80ee7a49e8ac312cc11b77f1475804bee36b3b2bc896bead8b6e1266befb43","affectsGlobalScope":true,"impliedFormat":1},{"version":"c57796738e7f83dbc4b8e65132f11a377649c00dd3eee333f672b8f0a6bea671","affectsGlobalScope":true,"impliedFormat":1},{"version":"dc2df20b1bcdc8c2d34af4926e2c3ab15ffe1160a63e58b7e09833f616efff44","affectsGlobalScope":true,"impliedFormat":1},{"version":"515d0b7b9bea2e31ea4ec968e9edd2c39d3eebf4a2d5cbd04e88639819ae3b71","affectsGlobalScope":true,"impliedFormat":1},{"version":"0559b1f683ac7505ae451f9a96ce4c3c92bdc71411651ca6ddb0e88baaaad6a3","affectsGlobalScope":true,"impliedFormat":1},{"version":"0dc1e7ceda9b8b9b455c3a2d67b0412feab00bd2f66656cd8850e8831b08b537","affectsGlobalScope":true,"impliedFormat":1},{"version":"ce691fb9e5c64efb9547083e4a34091bcbe5bdb41027e310ebba8f7d96a98671","affectsGlobalScope":true,"impliedFormat":1},{"version":"8d697a2a929a5fcb38b7a65594020fcef05ec1630804a33748829c5ff53640d0","affectsGlobalScope":true,"impliedFormat":1},{"version":"4ff2a353abf8a80ee399af572debb8faab2d33ad38c4b4474cff7f26e7653b8d","affectsGlobalScope":true,"impliedFormat":1},{"version":"fb0f136d372979348d59b3f5020b4cdb81b5504192b1cacff5d1fbba29378aa1","affectsGlobalScope":true,"impliedFormat":1},{"version":"d15bea3d62cbbdb9797079416b8ac375ae99162a7fba5de2c6c505446486ac0a","affectsGlobalScope":true,"impliedFormat":1},{"version":"68d18b664c9d32a7336a70235958b8997ebc1c3b8505f4f1ae2b7e7753b87618","affectsGlobalScope":true,"impliedFormat":1},{"version":"eb3d66c8327153d8fa7dd03f9c58d351107fe824c79e9b56b462935176cdf12a","affectsGlobalScope":true,"impliedFormat":1},{"version":"38f0219c9e23c915ef9790ab1d680440d95419ad264816fa15009a8851e79119","affectsGlobalScope":true,"impliedFormat":1},{"version":"69ab18c3b76cd9b1be3d188eaf8bba06112ebbe2f47f6c322b5105a6fbc45a2e","affectsGlobalScope":true,"impliedFormat":1},{"version":"a680117f487a4d2f30ea46f1b4b7f58bef1480456e18ba53ee85c2746eeca012","affectsGlobalScope":true,"impliedFormat":1},{"version":"2f11ff796926e0832f9ae148008138ad583bd181899ab7dd768a2666700b1893","affectsGlobalScope":true,"impliedFormat":1},{"version":"4de680d5bb41c17f7f68e0419412ca23c98d5749dcaaea1896172f06435891fc","affectsGlobalScope":true,"impliedFormat":1},{"version":"954296b30da6d508a104a3a0b5d96b76495c709785c1d11610908e63481ee667","affectsGlobalScope":true,"impliedFormat":1},{"version":"ac9538681b19688c8eae65811b329d3744af679e0bdfa5d842d0e32524c73e1c","affectsGlobalScope":true,"impliedFormat":1},{"version":"0a969edff4bd52585473d24995c5ef223f6652d6ef46193309b3921d65dd4376","affectsGlobalScope":true,"impliedFormat":1},{"version":"9e9fbd7030c440b33d021da145d3232984c8bb7916f277e8ffd3dc2e3eae2bdb","affectsGlobalScope":true,"impliedFormat":1},{"version":"811ec78f7fefcabbda4bfa93b3eb67d9ae166ef95f9bff989d964061cbf81a0c","affectsGlobalScope":true,"impliedFormat":1},{"version":"717937616a17072082152a2ef351cb51f98802fb4b2fdabd32399843875974ca","affectsGlobalScope":true,"impliedFormat":1},{"version":"d7e7d9b7b50e5f22c915b525acc5a49a7a6584cf8f62d0569e557c5cfc4b2ac2","affectsGlobalScope":true,"impliedFormat":1},{"version":"71c37f4c9543f31dfced6c7840e068c5a5aacb7b89111a4364b1d5276b852557","affectsGlobalScope":true,"impliedFormat":1},{"version":"576711e016cf4f1804676043e6a0a5414252560eb57de9faceee34d79798c850","affectsGlobalScope":true,"impliedFormat":1},{"version":"89c1b1281ba7b8a96efc676b11b264de7a8374c5ea1e6617f11880a13fc56dc6","affectsGlobalScope":true,"impliedFormat":1},{"version":"74f7fa2d027d5b33eb0471c8e82a6c87216223181ec31247c357a3e8e2fddc5b","affectsGlobalScope":true,"impliedFormat":1},{"version":"d6d7ae4d1f1f3772e2a3cde568ed08991a8ae34a080ff1151af28b7f798e22ca","affectsGlobalScope":true,"impliedFormat":1},{"version":"063600664504610fe3e99b717a1223f8b1900087fab0b4cad1496a114744f8df","affectsGlobalScope":true,"impliedFormat":1},{"version":"934019d7e3c81950f9a8426d093458b65d5aff2c7c1511233c0fd5b941e608ab","affectsGlobalScope":true,"impliedFormat":1},{"version":"52ada8e0b6e0482b728070b7639ee42e83a9b1c22d205992756fe020fd9f4a47","affectsGlobalScope":true,"impliedFormat":1},{"version":"3bdefe1bfd4d6dee0e26f928f93ccc128f1b64d5d501ff4a8cf3c6371200e5e6","affectsGlobalScope":true,"impliedFormat":1},{"version":"59fb2c069260b4ba00b5643b907ef5d5341b167e7d1dbf58dfd895658bda2867","affectsGlobalScope":true,"impliedFormat":1},{"version":"639e512c0dfc3fad96a84caad71b8834d66329a1f28dc95e3946c9b58176c73a","affectsGlobalScope":true,"impliedFormat":1},{"version":"368af93f74c9c932edd84c58883e736c9e3d53cec1fe24c0b0ff451f529ceab1","affectsGlobalScope":true,"impliedFormat":1},{"version":"af3dd424cf267428f30ccfc376f47a2c0114546b55c44d8c0f1d57d841e28d74","affectsGlobalScope":true,"impliedFormat":1},{"version":"995c005ab91a498455ea8dfb63aa9f83fa2ea793c3d8aa344be4a1678d06d399","affectsGlobalScope":true,"impliedFormat":1},{"version":"959d36cddf5e7d572a65045b876f2956c973a586da58e5d26cde519184fd9b8a","affectsGlobalScope":true,"impliedFormat":1},{"version":"965f36eae237dd74e6cca203a43e9ca801ce38824ead814728a2807b1910117d","affectsGlobalScope":true,"impliedFormat":1},{"version":"3925a6c820dcb1a06506c90b1577db1fdbf7705d65b62b99dce4be75c637e26b","affectsGlobalScope":true,"impliedFormat":1},{"version":"0a3d63ef2b853447ec4f749d3f368ce642264246e02911fcb1590d8c161b8005","affectsGlobalScope":true,"impliedFormat":1},{"version":"8cdf8847677ac7d20486e54dd3fcf09eda95812ac8ace44b4418da1bbbab6eb8","affectsGlobalScope":true,"impliedFormat":1},{"version":"8444af78980e3b20b49324f4a16ba35024fef3ee069a0eb67616ea6ca821c47a","affectsGlobalScope":true,"impliedFormat":1},{"version":"3287d9d085fbd618c3971944b65b4be57859f5415f495b33a6adc994edd2f004","affectsGlobalScope":true,"impliedFormat":1},{"version":"b4b67b1a91182421f5df999988c690f14d813b9850b40acd06ed44691f6727ad","affectsGlobalScope":true,"impliedFormat":1},{"version":"df83c2a6c73228b625b0beb6669c7ee2a09c914637e2d35170723ad49c0f5cd4","affectsGlobalScope":true,"impliedFormat":1},{"version":"436aaf437562f276ec2ddbee2f2cdedac7664c1e4c1d2c36839ddd582eeb3d0a","affectsGlobalScope":true,"impliedFormat":1},{"version":"8e3c06ea092138bf9fa5e874a1fdbc9d54805d074bee1de31b99a11e2fec239d","affectsGlobalScope":true,"impliedFormat":1},{"version":"8e7f8264d0fb4c5339605a15daadb037bf238c10b654bb3eee14208f860a32ea","affectsGlobalScope":true,"impliedFormat":1},{"version":"782dec38049b92d4e85c1585fbea5474a219c6984a35b004963b00beb1aab538","affectsGlobalScope":true,"impliedFormat":1},{"version":"f9fe6af238339a0e5f7563acee3178f51db37f32a2e7c09f85273098cee7ec49","impliedFormat":1},{"version":"407a06ba04eede4074eec470ecba2784cbb3bf4e7de56833b097dd90a2aa0651","impliedFormat":1},{"version":"77e71242e71ebf8528c5802993697878f0533db8f2299b4d36aa015bae08a79c","impliedFormat":1},{"version":"98a787be42bd92f8c2a37d7df5f13e5992da0d967fab794adbb7ee18370f9849","impliedFormat":1},"2552a31fad45a9ed1bde87e51b038dc0e786cd364b597162263abbf57018949b",{"version":"ae9b49ddf7f8a2b939d1ccc4b84876e7a74f8284521a513233b6014b9861541f","affectsGlobalScope":true},{"version":"6c7176368037af28cb72f2392010fa1cef295d6d6744bca8cfb54985f3a18c3e","affectsGlobalScope":true,"impliedFormat":1},{"version":"ab41ef1f2cdafb8df48be20cd969d875602483859dc194e9c97c8a576892c052","affectsGlobalScope":true,"impliedFormat":1},{"version":"437e20f2ba32abaeb7985e0afe0002de1917bc74e949ba585e49feba65da6ca1","affectsGlobalScope":true,"impliedFormat":1},{"version":"21d819c173c0cf7cc3ce57c3276e77fd9a8a01d35a06ad87158781515c9a438a","impliedFormat":1},{"version":"98cffbf06d6bab333473c70a893770dbe990783904002c4f1a960447b4b53dca","affectsGlobalScope":true,"impliedFormat":1},{"version":"3af97acf03cc97de58a3a4bc91f8f616408099bc4233f6d0852e72a8ffb91ac9","affectsGlobalScope":true,"impliedFormat":1},{"version":"808069bba06b6768b62fd22429b53362e7af342da4a236ed2d2e1c89fcca3b4a","affectsGlobalScope":true,"impliedFormat":1},{"version":"1db0b7dca579049ca4193d034d835f6bfe73096c73663e5ef9a0b5779939f3d0","affectsGlobalScope":true,"impliedFormat":1},{"version":"9798340ffb0d067d69b1ae5b32faa17ab31b82466a3fc00d8f2f2df0c8554aaa","affectsGlobalScope":true,"impliedFormat":1},{"version":"f26b11d8d8e4b8028f1c7d618b22274c892e4b0ef5b3678a8ccbad85419aef43","affectsGlobalScope":true,"impliedFormat":1},{"version":"5929864ce17fba74232584d90cb721a89b7ad277220627cc97054ba15a98ea8f","impliedFormat":1},{"version":"763fe0f42b3d79b440a9b6e51e9ba3f3f91352469c1e4b3b67bfa4ff6352f3f4","impliedFormat":1},{"version":"25c8056edf4314820382a5fdb4bb7816999acdcb929c8f75e3f39473b87e85bc","impliedFormat":1},{"version":"c464d66b20788266e5353b48dc4aa6bc0dc4a707276df1e7152ab0c9ae21fad8","impliedFormat":1},{"version":"78d0d27c130d35c60b5e5566c9f1e5be77caf39804636bc1a40133919a949f21","impliedFormat":1},{"version":"c6fd2c5a395f2432786c9cb8deb870b9b0e8ff7e22c029954fabdd692bff6195","impliedFormat":1},{"version":"1d6e127068ea8e104a912e42fc0a110e2aa5a66a356a917a163e8cf9a65e4a75","impliedFormat":1},{"version":"5ded6427296cdf3b9542de4471d2aa8d3983671d4cac0f4bf9c637208d1ced43","impliedFormat":1},{"version":"7f182617db458e98fc18dfb272d40aa2fff3a353c44a89b2c0ccb3937709bfb5","impliedFormat":1},{"version":"cadc8aced301244057c4e7e73fbcae534b0f5b12a37b150d80e5a45aa4bebcbd","impliedFormat":1},{"version":"385aab901643aa54e1c36f5ef3107913b10d1b5bb8cbcd933d4263b80a0d7f20","impliedFormat":1},{"version":"9670d44354bab9d9982eca21945686b5c24a3f893db73c0dae0fd74217a4c219","impliedFormat":1},{"version":"0b8a9268adaf4da35e7fa830c8981cfa22adbbe5b3f6f5ab91f6658899e657a7","impliedFormat":1},{"version":"11396ed8a44c02ab9798b7dca436009f866e8dae3c9c25e8c1fbc396880bf1bb","impliedFormat":1},{"version":"ba7bc87d01492633cb5a0e5da8a4a42a1c86270e7b3d2dea5d156828a84e4882","impliedFormat":1},{"version":"4893a895ea92c85345017a04ed427cbd6a1710453338df26881a6019432febdd","impliedFormat":1},{"version":"c21dc52e277bcfc75fac0436ccb75c204f9e1b3fa5e12729670910639f27343e","impliedFormat":1},{"version":"13f6f39e12b1518c6650bbb220c8985999020fe0f21d818e28f512b7771d00f9","impliedFormat":1},{"version":"9b5369969f6e7175740bf51223112ff209f94ba43ecd3bb09eefff9fd675624a","impliedFormat":1},{"version":"4fe9e626e7164748e8769bbf74b538e09607f07ed17c2f20af8d680ee49fc1da","impliedFormat":1},{"version":"24515859bc0b836719105bb6cc3d68255042a9f02a6022b3187948b204946bd2","impliedFormat":1},{"version":"ea0148f897b45a76544ae179784c95af1bd6721b8610af9ffa467a518a086a43","impliedFormat":1},{"version":"24c6a117721e606c9984335f71711877293a9651e44f59f3d21c1ea0856f9cc9","impliedFormat":1},{"version":"dd3273ead9fbde62a72949c97dbec2247ea08e0c6952e701a483d74ef92d6a17","impliedFormat":1},{"version":"405822be75ad3e4d162e07439bac80c6bcc6dbae1929e179cf467ec0b9ee4e2e","impliedFormat":1},{"version":"0db18c6e78ea846316c012478888f33c11ffadab9efd1cc8bcc12daded7a60b6","impliedFormat":1},{"version":"e61be3f894b41b7baa1fbd6a66893f2579bfad01d208b4ff61daef21493ef0a8","impliedFormat":1},{"version":"bd0532fd6556073727d28da0edfd1736417a3f9f394877b6d5ef6ad88fba1d1a","impliedFormat":1},{"version":"89167d696a849fce5ca508032aabfe901c0868f833a8625d5a9c6e861ef935d2","impliedFormat":1},{"version":"615ba88d0128ed16bf83ef8ccbb6aff05c3ee2db1cc0f89ab50a4939bfc1943f","impliedFormat":1},{"version":"a4d551dbf8746780194d550c88f26cf937caf8d56f102969a110cfaed4b06656","impliedFormat":1},{"version":"8bd86b8e8f6a6aa6c49b71e14c4ffe1211a0e97c80f08d2c8cc98838006e4b88","impliedFormat":1},{"version":"317e63deeb21ac07f3992f5b50cdca8338f10acd4fbb7257ebf56735bf52ab00","impliedFormat":1},{"version":"4732aec92b20fb28c5fe9ad99521fb59974289ed1e45aecb282616202184064f","impliedFormat":1},{"version":"2e85db9e6fd73cfa3d7f28e0ab6b55417ea18931423bd47b409a96e4a169e8e6","impliedFormat":1},{"version":"c46e079fe54c76f95c67fb89081b3e399da2c7d109e7dca8e4b58d83e332e605","impliedFormat":1},{"version":"bf67d53d168abc1298888693338cb82854bdb2e69ef83f8a0092093c2d562107","impliedFormat":1},{"version":"b52476feb4a0cbcb25e5931b930fc73cb6643fb1a5060bf8a3dda0eeae5b4b68","affectsGlobalScope":true,"impliedFormat":1},{"version":"f9501cc13ce624c72b61f12b3963e84fad210fbdf0ffbc4590e08460a3f04eba","affectsGlobalScope":true,"impliedFormat":1},{"version":"e7721c4f69f93c91360c26a0a84ee885997d748237ef78ef665b153e622b36c1","affectsGlobalScope":true,"impliedFormat":1},{"version":"d97fb21da858fb18b8ae72c314e9743fd52f73ebe2764e12af1db32fc03f853f","affectsGlobalScope":true,"impliedFormat":1},{"version":"0fa06ada475b910e2106c98c68b10483dc8811d0c14a8a8dd36efb2672485b29","impliedFormat":1},{"version":"33e5e9aba62c3193d10d1d33ae1fa75c46a1171cf76fef750777377d53b0303f","impliedFormat":1},{"version":"2b06b93fd01bcd49d1a6bd1f9b65ddcae6480b9a86e9061634d6f8e354c1468f","impliedFormat":1},{"version":"6a0cd27e5dc2cfbe039e731cf879d12b0e2dded06d1b1dedad07f7712de0d7f4","affectsGlobalScope":true,"impliedFormat":1},{"version":"13f5c844119c43e51ce777c509267f14d6aaf31eafb2c2b002ca35584cd13b29","impliedFormat":1},{"version":"e60477649d6ad21542bd2dc7e3d9ff6853d0797ba9f689ba2f6653818999c264","impliedFormat":1},{"version":"c2510f124c0293ab80b1777c44d80f812b75612f297b9857406468c0f4dafe29","affectsGlobalScope":true,"impliedFormat":1},{"version":"5524481e56c48ff486f42926778c0a3cce1cc85dc46683b92b1271865bcf015a","impliedFormat":1},{"version":"4c829ab315f57c5442c6667b53769975acbf92003a66aef19bce151987675bd1","affectsGlobalScope":true,"impliedFormat":1},{"version":"b2ade7657e2db96d18315694789eff2ddd3d8aea7215b181f8a0b303277cc579","impliedFormat":1},{"version":"78dbea00e90d2df8ea3dbef0cc379d95b8be9b71cd6bde4c28728f306811803b","impliedFormat":1},{"version":"4d631b81fa2f07a0e63a9a143d6a82c25c5f051298651a9b69176ba28930756d","impliedFormat":1},{"version":"836a356aae992ff3c28a0212e3eabcb76dd4b0cc06bcb9607aeef560661b860d","impliedFormat":1},{"version":"1e0d1f8b0adfa0b0330e028c7941b5a98c08b600efe7f14d2d2a00854fb2f393","impliedFormat":1},{"version":"41670ee38943d9cbb4924e436f56fc19ee94232bc96108562de1a734af20dc2c","affectsGlobalScope":true,"impliedFormat":1},{"version":"8e1e46d0a9837ee058c100501080c920fa98081ea3956af0374308ba6f22a33e","impliedFormat":1},{"version":"272ca407e0c9068bdc5152552d876e68037ceae3de62e529306403e973dec8e1","impliedFormat":1},{"version":"fa7834c715d5357e4540cee40ce96c3250ddb67a7b879a6b7fa0e86d6696f121","impliedFormat":1},{"version":"22dfb07a7ab15b66ac043829056fe70124844636ae719551812ac631ba04985b","impliedFormat":1},{"version":"a10f0e1854f3316d7ee437b79649e5a6ae3ae14ffe6322b02d4987071a95362e","impliedFormat":1},{"version":"e208f73ef6a980104304b0d2ca5f6bf1b85de6009d2c7e404028b875020fa8f2","impliedFormat":1},{"version":"d163b6bc2372b4f07260747cbc6c0a6405ab3fbcea3852305e98ac43ca59f5bc","impliedFormat":1},{"version":"e6fa9ad47c5f71ff733744a029d1dc472c618de53804eae08ffc243b936f87ff","affectsGlobalScope":true,"impliedFormat":1},{"version":"a6f137d651076822d4fe884287e68fd61785a0d3d1fdb250a5059b691fa897db","impliedFormat":1},{"version":"24826ed94a78d5c64bd857570fdbd96229ad41b5cb654c08d75a9845e3ab7dde","impliedFormat":1},{"version":"8b479a130ccb62e98f11f136d3ac80f2984fdc07616516d29881f3061f2dd472","impliedFormat":1},{"version":"928af3d90454bf656a52a48679f199f64c1435247d6189d1caf4c68f2eaf921f","affectsGlobalScope":true,"impliedFormat":1},{"version":"bceb58df66ab8fb00170df20cd813978c5ab84be1d285710c4eb005d8e9d8efb","affectsGlobalScope":true,"impliedFormat":1},{"version":"3f16a7e4deafa527ed9995a772bb380eb7d3c2c0fd4ae178c5263ed18394db2c","impliedFormat":1},{"version":"933921f0bb0ec12ef45d1062a1fc0f27635318f4d294e4d99de9a5493e618ca2","impliedFormat":1},{"version":"71a0f3ad612c123b57239a7749770017ecfe6b66411488000aba83e4546fde25","impliedFormat":1},{"version":"77fbe5eecb6fac4b6242bbf6eebfc43e98ce5ccba8fa44e0ef6a95c945ff4d98","impliedFormat":1},{"version":"4f9d8ca0c417b67b69eeb54c7ca1bedd7b56034bb9bfd27c5d4f3bc4692daca7","impliedFormat":1},{"version":"0cb167c371eaa8c869f8a7656a7296f2e4fae43b4d8b803a680236b24794e5f9","impliedFormat":1},{"version":"0a839dba0287cc0481ad4beedd48a1c64acf1e212ae865d1315f7007ca215161","impliedFormat":1},{"version":"38dc4655376cd1a4bd6bb3763d92949233e33d38d3dd3cbea7bbf218175a38ef","impliedFormat":1},{"version":"37ba7b45141a45ce6e80e66f2a96c8a5ab1bcef0fc2d0f56bb58df96ec67e972","impliedFormat":1},{"version":"45650f47bfb376c8a8ed39d4bcda5902ab899a3150029684ee4c10676d9fbaee","impliedFormat":1},{"version":"d61e0a64cd175208ac0b83670151a9a6b5916f0d1ffcdc5c29c90b1cebfc5045","affectsGlobalScope":true,"impliedFormat":1},{"version":"18fd40412d102c5564136f29735e5d1c3b455b8a37f920da79561f1fde068208","impliedFormat":1},{"version":"48a679952eefe4cb776d5a0e1ccba2d3eb53b57448bbb7abc1fcebcbd5440188","impliedFormat":1},{"version":"f0be1b8078cd549d91f37c30c222c2a187ac1cf981d994fb476a1adc61387b14","affectsGlobalScope":true,"impliedFormat":1},{"version":"0aaed1d72199b01234152f7a60046bc947f1f37d78d182e9ae09c4289e06a592","impliedFormat":1},{"version":"2d14da6ecb49bf828d83948765ec2d3a579d476bbb9645e749610baa6ec880ca","impliedFormat":1},{"version":"66ba1b2c3e3a3644a1011cd530fb444a96b1b2dfe2f5e837a002d41a1a799e60","impliedFormat":1},{"version":"7e514f5b852fdbc166b539fdd1f4e9114f29911592a5eb10a94bb3a13ccac3c4","impliedFormat":1},{"version":"5b7aa3c4c1a5d81b411e8cb302b45507fea9358d3569196b27eb1a27ae3a90ef","affectsGlobalScope":true,"impliedFormat":1},{"version":"5987a903da92c7462e0b35704ce7da94d7fdc4b89a984871c0e2b87a8aae9e69","affectsGlobalScope":true,"impliedFormat":1},{"version":"ea08a0345023ade2b47fbff5a76d0d0ed8bff10bc9d22b83f40858a8e941501c","impliedFormat":1},{"version":"0aef708fb4c7a6b915e8305cbfac40cd207b032dbaabe9a01889a5fff3254681","impliedFormat":1},{"version":"ae062ce7d9510060c5d7e7952ae379224fb3f8f2dd74e88959878af2057c143b","impliedFormat":1},{"version":"ad9bdafb4e7abf14cc53ce7970486a84c87831e62891e5dfe798ddcd55e84701","affectsGlobalScope":true,"impliedFormat":1},{"version":"358765d5ea8afd285d4fd1532e78b88273f18cb3f87403a9b16fef61ac9fdcfe","impliedFormat":1},{"version":"71d3ae6a5e73ca4130762560425e00984ebaff64d5353a3333d1bb7eb86ef336","impliedFormat":1},{"version":"7e29f41b158de217f94cb9676bf9cbd0cd9b5a46e1985141ed36e075c52bf6ad","affectsGlobalScope":true,"impliedFormat":1},{"version":"ac51dd7d31333793807a6abaa5ae168512b6131bd41d9c5b98477fc3b7800f9f","impliedFormat":1},{"version":"814d5c7384f3ca276e9dc4bcfde5545801a3ea0bfae09916b3336774e662fd1b","impliedFormat":1},{"version":"2beff543f6e9a9701df88daeee3cdd70a34b4a1c11cb4c734472195a5cb2af54","impliedFormat":1},{"version":"2e07abf27aa06353d46f4448c0bbac73431f6065eef7113128a5cd804d0c384d","impliedFormat":1},{"version":"be1cc4d94ea60cbe567bc29ed479d42587bf1e6cba490f123d329976b0fe4ee5","impliedFormat":1},{"version":"bc03c3c352f689e38c0ddd50c39b1e65d59273991bfc8858a9e3c0ebb79c023b","impliedFormat":1},{"version":"99a69bfe4675103d6c07bf9d1d3d190bcb944f5e55a914755c9993987abc4d47","impliedFormat":1},{"version":"9894dafe342b976d251aac58e616ac6df8db91fb9d98934ff9dd103e9e82578f","impliedFormat":1},{"version":"631eff75b0e35d1b1b31081d55209abc43e16b49426546ab5a9b40bdd40b1f60","impliedFormat":1},{"version":"db6d2d9daad8a6d83f281af12ce4355a20b9a3e71b82b9f57cddcca0a8964a96","impliedFormat":1},{"version":"c5426dbfc1cf90532f66965a7aa8c1136a78d4d0f96d8180ecbfc11d7722f1a5","impliedFormat":1},{"version":"9c82171d836c47486074e4ca8e059735bf97b205e70b196535b5efd40cbe1bc5","impliedFormat":1},{"version":"8f828825d077c2fa0ea606649faeb122749273a353daab23924fe674e98ba44c","impliedFormat":1},{"version":"24f8562308dd8ba6013120557fa7b44950b619610b2c6cb8784c79f11e3c4f90","impliedFormat":1},{"version":"5f90b8c733a1bda63e42160b15a2301051e83a6f9d5332a59d16eb12f463270d","impliedFormat":1},{"version":"a86f82d646a739041d6702101afa82dcb935c416dd93cbca7fd754fd0282ce1f","impliedFormat":1},{"version":"1fffe726740f9787f15b532e1dc870af3cd964dbe29e191e76121aa3dd8693f2","impliedFormat":1},{"version":"35e6379c3f7cb27b111ad4c1aa69538fd8e788ab737b8ff7596a1b40e96f4f90","impliedFormat":1},{"version":"ad0d1d75d129b1c80f911be438d6b61bfa8703930a8ff2be2f0e1f8a91841c64","impliedFormat":1},{"version":"ce75b1aebb33d510ff28af960a9221410a3eaf7f18fc5f21f9404075fba77256","impliedFormat":1},{"version":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","impliedFormat":1},{"version":"496bbf339f3838c41f164238543e9fe5f1f10659cb30b68903851618464b98ba","impliedFormat":1},{"version":"5178eb4415a172c287c711dc60a619e110c3fd0b7de01ed0627e51a5336aa09c","impliedFormat":1},{"version":"ca6e5264278b53345bc1ce95f42fb0a8b733a09e3d6479c6ccfca55cdc45038c","impliedFormat":1},{"version":"9e2739b32f741859263fdba0244c194ca8e96da49b430377930b8f721d77c000","impliedFormat":1},{"version":"fb1d8e814a3eeb5101ca13515e0548e112bd1ff3fb358ece535b93e94adf5a3a","impliedFormat":1},{"version":"ffa495b17a5ef1d0399586b590bd281056cee6ce3583e34f39926f8dcc6ecdb5","impliedFormat":1},{"version":"98b18458acb46072947aabeeeab1e410f047e0cacc972943059ca5500b0a5e95","impliedFormat":1},{"version":"361e2b13c6765d7f85bb7600b48fde782b90c7c41105b7dab1f6e7871071ba20","impliedFormat":1},{"version":"c86fe861cf1b4c46a0fb7d74dffe596cf679a2e5e8b1456881313170f092e3fa","impliedFormat":1},{"version":"b6db56e4903e9c32e533b78ac85522de734b3d3a8541bf24d256058d464bf04b","impliedFormat":1},{"version":"24daa0366f837d22c94a5c0bad5bf1fd0f6b29e1fae92dc47c3072c3fdb2fbd5","impliedFormat":1},{"version":"570bb5a00836ffad3e4127f6adf581bfc4535737d8ff763a4d6f4cc877e60d98","impliedFormat":1},{"version":"889c00f3d32091841268f0b994beba4dceaa5df7573be12c2c829d7c5fbc232c","impliedFormat":1},{"version":"65f43099ded6073336e697512d9b80f2d4fec3182b7b2316abf712e84104db00","impliedFormat":1},{"version":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","impliedFormat":1},{"version":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","impliedFormat":1},{"version":"8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881","impliedFormat":1},{"version":"acf5a2ac47b59ca07afa9abbd2b31d001bf7448b041927befae2ea5b1951d9f9","impliedFormat":1},{"version":"8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881","impliedFormat":1},{"version":"d71291eff1e19d8762a908ba947e891af44749f3a2cbc5bd2ec4b72f72ea795f","impliedFormat":1},{"version":"c0480e03db4b816dff2682b347c95f2177699525c54e7e6f6aa8ded890b76be7","impliedFormat":1},{"version":"27ab780875bcbb65e09da7496f2ca36288b0c541abaa75c311450a077d54ec15","impliedFormat":1},{"version":"b620391fe8060cf9bedc176a4d01366e6574d7a71e0ac0ab344a4e76576fcbb8","impliedFormat":1},{"version":"413df52d4ea14472c2fa5bee62f7a40abd1eb49be0b9722ee01ee4e52e63beb2","impliedFormat":1},{"version":"380647d8f3b7f852cca6d154a376dbf8ac620a2f12b936594504a8a852e71d2f","impliedFormat":1},{"version":"208c9af9429dd3c76f5927b971263174aaa4bc7621ddec63f163640cbd3c473c","impliedFormat":1},{"version":"6459054aabb306821a043e02b89d54da508e3a6966601a41e71c166e4ea1474f","impliedFormat":1},{"version":"a23185bc5ef590c287c28a91baf280367b50ae4ea40327366ad01f6f4a8edbc5","impliedFormat":1},{"version":"bb37588926aba35c9283fe8d46ebf4e79ffe976343105f5c6d45f282793352b2","impliedFormat":1},{"version":"002eae065e6960458bda3cf695e578b0d1e2785523476f8a9170b103c709cd4f","impliedFormat":1},{"version":"c83bb0c9c5645a46c68356c2f73fdc9de339ce77f7f45a954f560c7e0b8d5ebb","impliedFormat":1},{"version":"05c97cddbaf99978f83d96de2d8af86aded9332592f08ce4a284d72d0952c391","impliedFormat":1},{"version":"72179f9dd22a86deaad4cc3490eb0fe69ee084d503b686985965654013f1391b","impliedFormat":1},{"version":"2e6114a7dd6feeef85b2c80120fdbfb59a5529c0dcc5bfa8447b6996c97a69f5","impliedFormat":1},{"version":"7b6ff760c8a240b40dab6e4419b989f06a5b782f4710d2967e67c695ef3e93c4","impliedFormat":1},{"version":"c8f004e6036aa1c764ad4ec543cf89a5c1893a9535c80ef3f2b653e370de45e6","impliedFormat":1},{"version":"dd80b1e600d00f5c6a6ba23f455b84a7db121219e68f89f10552c54ba46e4dc9","impliedFormat":1},{"version":"b064c36f35de7387d71c599bfcf28875849a1dbc733e82bd26cae3d1cd060521","impliedFormat":1},{"version":"6a148329edecbda07c21098639ef4254ef7869fb25a69f58e5d6a8b7b69d4236","impliedFormat":1},{"version":"8de9fe97fa9e00ec00666fa77ab6e91b35d25af8ca75dabcb01e14ad3299b150","impliedFormat":1},{"version":"f63ab283a1c8f5c79fabe7ca4ef85f9633339c4f0e822fce6a767f9d59282af2","impliedFormat":1},{"version":"dba114fb6a32b355a9cfc26ca2276834d72fe0e94cd2c3494005547025015369","impliedFormat":1},{"version":"a54c996c8870ef1728a2c1fa9b8eaec0bf4a8001cd2583c02dd5869289465b10","impliedFormat":1},{"version":"3e7efde639c6a6c3edb9847b3f61e308bf7a69685b92f665048c45132f51c218","impliedFormat":1},{"version":"df45ca1176e6ac211eae7ddf51336dc075c5314bc5c253651bae639defd5eec5","impliedFormat":1},{"version":"3754982006a3b32c502cff0867ca83584f7a43b1035989ca73603f400de13c96","impliedFormat":1},{"version":"a30ae9bb8a8fa7b90f24b8a0496702063ae4fe75deb27da731ed4a03b2eb6631","impliedFormat":1},{"version":"f974e4a06953682a2c15d5bd5114c0284d5abf8bc0fe4da25cb9159427b70072","impliedFormat":1},{"version":"50256e9c31318487f3752b7ac12ff365c8949953e04568009c8705db802776fb","impliedFormat":1},{"version":"7d73b24e7bf31dfb8a931ca6c4245f6bb0814dfae17e4b60c9e194a631fe5f7b","impliedFormat":1},{"version":"413586add0cfe7369b64979d4ec2ed56c3f771c0667fbde1bf1f10063ede0b08","impliedFormat":1},{"version":"06472528e998d152375ad3bd8ebcb69ff4694fd8d2effaf60a9d9f25a37a097a","impliedFormat":1},{"version":"50b5bc34ce6b12eccb76214b51aadfa56572aa6cc79c2b9455cdbb3d6c76af1d","impliedFormat":1},{"version":"b7e16ef7f646a50991119b205794ebfd3a4d8f8e0f314981ebbe991639023d0e","impliedFormat":1},{"version":"b838d4c72740eb0afd284bf7575b74c624b105eff2e8c7b4aeead57e7ac320ff","impliedFormat":1},{"version":"a401617604fa1f6ce437b81689563dfdc377069e4c58465dbd8d16069aede0a5","impliedFormat":1},{"version":"e9dd71cf12123419c60dab867d44fbee5c358169f99529121eaef277f5c83531","impliedFormat":1},{"version":"5b6a189ba3a0befa1f5d9cb028eb9eec2af2089c32f04ff50e2411f63d70f25d","impliedFormat":1},{"version":"d6e73f8010935b7b4c7487b6fb13ea197cc610f0965b759bec03a561ccf8423a","impliedFormat":1},{"version":"174f3864e398f3f33f9a446a4f403d55a892aa55328cf6686135dfaf9e171657","impliedFormat":1},{"version":"824c76aec8d8c7e65769688cbee102238c0ef421ed6686f41b2a7d8e7e78a931","impliedFormat":1},{"version":"75b868be3463d5a8cfc0d9396f0a3d973b8c297401d00bfb008a42ab16643f13","impliedFormat":1},{"version":"15a234e5031b19c48a69ccc1607522d6e4b50f57d308ecb7fe863d44cd9f9eb3","impliedFormat":1},{"version":"d682336018141807fb602709e2d95a192828fcb8d5ba06dda3833a8ea98f69e3","impliedFormat":1},{"version":"6124e973eab8c52cabf3c07575204efc1784aca6b0a30c79eb85fe240a857efa","impliedFormat":1},{"version":"0d891735a21edc75df51f3eb995e18149e119d1ce22fd40db2b260c5960b914e","impliedFormat":1},{"version":"3b414b99a73171e1c4b7b7714e26b87d6c5cb03d200352da5342ab4088a54c85","impliedFormat":1},{"version":"4fbd3116e00ed3a6410499924b6403cc9367fdca303e34838129b328058ede40","impliedFormat":1},{"version":"b01bd582a6e41457bc56e6f0f9de4cb17f33f5f3843a7cf8210ac9c18472fb0f","impliedFormat":1},{"version":"0a437ae178f999b46b6153d79095b60c42c996bc0458c04955f1c996dc68b971","impliedFormat":1},{"version":"74b2a5e5197bd0f2e0077a1ea7c07455bbea67b87b0869d9786d55104006784f","impliedFormat":1},{"version":"4a7baeb6325920044f66c0f8e5e6f1f52e06e6d87588d837bdf44feb6f35c664","impliedFormat":1},{"version":"6dcf60530c25194a9ee0962230e874ff29d34c59605d8e069a49928759a17e0a","impliedFormat":1},{"version":"7274fbffbd7c9589d8d0ffba68157237afd5cecff1e99881ea3399127e60572f","impliedFormat":1},{"version":"1a42d2ec31a1fe62fdc51591768695ed4a2dc64c01be113e7ff22890bebb5e3f","impliedFormat":1},{"version":"1a82deef4c1d39f6882f28d275cad4c01f907b9b39be9cbc472fcf2cf051e05b","impliedFormat":1},{"version":"65a15fc47900787c0bd18b603afb98d33ede930bed1798fc984d5ebb78b26cf9","impliedFormat":1},{"version":"9d202701f6e0744adb6314d03d2eb8fc994798fc83d91b691b75b07626a69801","impliedFormat":1},{"version":"de9d2df7663e64e3a91bf495f315a7577e23ba088f2949d5ce9ec96f44fba37d","impliedFormat":1},{"version":"c7af78a2ea7cb1cd009cfb5bdb48cd0b03dad3b54f6da7aab615c2e9e9d570c5","impliedFormat":1},{"version":"1ee45496b5f8bdee6f7abc233355898e5bf9bd51255db65f5ff7ede617ca0027","impliedFormat":1},{"version":"0c7c947ff881c4274c0800deaa0086971e0bfe51f89a33bd3048eaa3792d4876","affectsGlobalScope":true,"impliedFormat":1},{"version":"db01d18853469bcb5601b9fc9826931cc84cc1a1944b33cad76fd6f1e3d8c544","affectsGlobalScope":true,"impliedFormat":1},{"version":"a8f8e6ab2fa07b45251f403548b78eaf2022f3c2254df3dc186cb2671fe4996d","affectsGlobalScope":true,"impliedFormat":1},{"version":"fa6c12a7c0f6b84d512f200690bfc74819e99efae69e4c95c4cd30f6884c526e","impliedFormat":1},{"version":"f1c32f9ce9c497da4dc215c3bc84b722ea02497d35f9134db3bb40a8d918b92b","impliedFormat":1},{"version":"b73c319af2cc3ef8f6421308a250f328836531ea3761823b4cabbd133047aefa","affectsGlobalScope":true,"impliedFormat":1},{"version":"e433b0337b8106909e7953015e8fa3f2d30797cea27141d1c5b135365bb975a6","impliedFormat":1},{"version":"15b36126e0089bfef173ab61329e8286ce74af5e809d8a72edcafd0cc049057f","impliedFormat":1},{"version":"ddff7fc6edbdc5163a09e22bf8df7bef75f75369ebd7ecea95ba55c4386e2441","impliedFormat":1},{"version":"106c6025f1d99fd468fd8bf6e5bda724e11e5905a4076c5d29790b6c3745e50c","impliedFormat":1},{"version":"a57b1802794433adec9ff3fed12aa79d671faed86c49b09e02e1ac41b4f1d33a","impliedFormat":1},{"version":"ad10d4f0517599cdeca7755b930f148804e3e0e5b5a3847adce0f1f71bbccd74","impliedFormat":1},{"version":"1042064ece5bb47d6aba91648fbe0635c17c600ebdf567588b4ca715602f0a9d","impliedFormat":1},{"version":"c49469a5349b3cc1965710b5b0f98ed6c028686aa8450bcb3796728873eb923e","impliedFormat":1},{"version":"4a889f2c763edb4d55cb624257272ac10d04a1cad2ed2948b10ed4a7fda2a428","impliedFormat":1},{"version":"7bb79aa2fead87d9d56294ef71e056487e848d7b550c9a367523ee5416c44cfa","impliedFormat":1},{"version":"72d63643a657c02d3e51cd99a08b47c9b020a565c55f246907050d3c8a5e77fb","impliedFormat":1},{"version":"1d415445ea58f8033ba199703e55ff7483c52ac6742075b803bd3e7bbe9f5d61","impliedFormat":1},{"version":"d6406c629bb3efc31aedb2de809bef471e475c86c7e67f3ef9b676b5d7e0d6b2","impliedFormat":1},{"version":"27ff4196654e6373c9af16b6165120e2dd2169f9ad6abb5c935af5abd8c7938c","impliedFormat":1},{"version":"71d8ba39a9e024d9e4bb922464d18542ed8d2c25ee78efa7890c27213cc6e5d3","impliedFormat":1},{"version":"8c030e515014c10a2b98f9f48408e3ba18023dfd3f56e3312c6c2f3ae1f55a16","impliedFormat":1},{"version":"dafc31e9e8751f437122eb8582b93d477e002839864410ff782504a12f2a550c","impliedFormat":1},{"version":"754498c5208ce3c5134f6eabd49b25cf5e1a042373515718953581636491f3c3","impliedFormat":1},{"version":"f56bdc6884648806d34bc66d31cdb787c4718d04105ce2cd88535db214631f82","impliedFormat":1},{"version":"633d58a237f4bb25ec7d565e4ffa32cecdcee8660ac12189c4351c52557cee9e","impliedFormat":1},{"version":"2e4f37ffe8862b14d8e24ae8763daaa8340c0df0b859d9a9733def0eee7562d9","impliedFormat":1},{"version":"13283350547389802aa35d9f2188effaeac805499169a06ef5cd77ce2a0bd63f","impliedFormat":1},{"version":"ce791f6ea807560f08065d1af6014581eeb54a05abd73294777a281b6dfd73c2","impliedFormat":1},{"version":"6ac6715916fa75a1f7ebdfeacac09513b4d904b667d827b7535e84ff59679aff","impliedFormat":1},{"version":"49f95e989b4632c6c2a578cc0078ee19a5831832d79cc59abecf5160ea71abad","impliedFormat":1},{"version":"9666533332f26e8995e4d6fe472bdeec9f15d405693723e6497bf94120c566c8","impliedFormat":1},{"version":"ce0df82a9ae6f914ba08409d4d883983cc08e6d59eb2df02d8e4d68309e7848b","impliedFormat":1},{"version":"796273b2edc72e78a04e86d7c58ae94d370ab93a0ddf40b1aa85a37a1c29ecd7","impliedFormat":1},{"version":"5df15a69187d737d6d8d066e189ae4f97e41f4d53712a46b2710ff9f8563ec9f","impliedFormat":1},{"version":"e17cd049a1448de4944800399daa4a64c5db8657cc9be7ef46be66e2a2cd0e7c","impliedFormat":1},{"version":"43fa6ea8714e18adc312b30450b13562949ba2f205a1972a459180fa54471018","impliedFormat":1},{"version":"6e89c2c177347d90916bad67714d0fb473f7e37fb3ce912f4ed521fe2892cd0d","impliedFormat":1},{"version":"43ba4f2fa8c698f5c304d21a3ef596741e8e85a810b7c1f9b692653791d8d97a","impliedFormat":1},{"version":"4d4927cbee21750904af7acf940c5e3c491b4d5ebc676530211e389dd375607a","impliedFormat":1},{"version":"72105519d0390262cf0abe84cf41c926ade0ff475d35eb21307b2f94de985778","impliedFormat":1},{"version":"8a97e578a9bc40eb4f1b0ca78f476f2e9154ecbbfd5567ee72943bab37fc156a","impliedFormat":1},{"version":"c857e0aae3f5f444abd791ec81206020fbcc1223e187316677e026d1c1d6fe08","impliedFormat":1},{"version":"ccf6dd45b708fb74ba9ed0f2478d4eb9195c9dfef0ff83a6092fa3cf2ff53b4f","impliedFormat":1},{"version":"2d7db1d73456e8c5075387d4240c29a2a900847f9c1bff106a2e490da8fbd457","impliedFormat":1},{"version":"2b15c805f48e4e970f8ec0b1915f22d13ca6212375e8987663e2ef5f0205e832","impliedFormat":1},{"version":"f22d05663d873ee7a600faf78abb67f3f719d32266803440cf11d5db7ac0cab2","impliedFormat":1},{"version":"d93c544ad20197b3976b0716c6d5cd5994e71165985d31dcab6e1f77feb4b8f2","impliedFormat":1},{"version":"35069c2c417bd7443ae7c7cafd1de02f665bf015479fec998985ffbbf500628c","impliedFormat":1},{"version":"a8b1c79a833ee148251e88a2553d02ce1641d71d2921cce28e79678f3d8b96aa","impliedFormat":1},{"version":"126d4f950d2bba0bd45b3a86c76554d4126c16339e257e6d2fabf8b6bf1ce00c","impliedFormat":1},{"version":"7e0b7f91c5ab6e33f511efc640d36e6f933510b11be24f98836a20a2dc914c2d","impliedFormat":1},{"version":"045b752f44bf9bbdcaffd882424ab0e15cb8d11fa94e1448942e338c8ef19fba","impliedFormat":1},{"version":"2894c56cad581928bb37607810af011764a2f511f575d28c9f4af0f2ef02d1ab","impliedFormat":1},{"version":"0a72186f94215d020cb386f7dca81d7495ab6c17066eb07d0f44a5bf33c1b21a","impliedFormat":1},{"version":"2d3cc2211f352f46ea6b7cf2c751c141ffcdf514d6e7ae7ee20b7b6742da313f","impliedFormat":1},{"version":"c75445151ff8b77d9923191efed7203985b1a9e09eccf4b054e7be864e27923d","impliedFormat":1},{"version":"0aedb02516baf3e66b2c1db9fef50666d6ed257edac0f866ea32f1aa05aa474f","impliedFormat":1},{"version":"fa8a8fbf91ee2a4779496225f0312aac6635b0f21aa09cdafa4283fe32d519c5","affectsGlobalScope":true,"impliedFormat":1},{"version":"0e8aef93d79b000deb6ec336b5645c87de167168e184e84521886f9ecc69a4b5","impliedFormat":1},{"version":"c30436b130b6218b7714314dc41d3f459590db4bdf099eecd51cb1bda32109a8","impliedFormat":1},{"version":"20fa37b636fdcc1746ea0738f733d0aed17890d1cd7cb1b2f37010222c23f13e","impliedFormat":1},{"version":"d90b9f1520366d713a73bd30c5a9eb0040d0fb6076aff370796bc776fd705943","impliedFormat":1},{"version":"cf212598bab498017f7bb92beea6d7c30ca35dc027553b8e647a6aacfe993b5e","affectsGlobalScope":true,"impliedFormat":1},{"version":"41250cef8d5f886fc56713c6d9774a7d793817254c20a87b6e209ae4fe9cb9c1","affectsGlobalScope":true,"impliedFormat":1},{"version":"bef86adb77316505c6b471da1d9b8c9e428867c2566270e8894d4d773a1c4dc2","impliedFormat":1},{"version":"de7052bfee2981443498239a90c04ea5cc07065d5b9bb61b12cb6c84313ad4ef","impliedFormat":1},{"version":"a3e7d932dc9c09daa99141a8e4800fc6c58c625af0d4bbb017773dc36da75426","impliedFormat":1},{"version":"43e96a3d5d1411ab40ba2f61d6a3192e58177bcf3b133a80ad2a16591611726d","impliedFormat":1},{"version":"4a2edd238d9104eac35b60d727f1123de5062f452b70ed8e0366cb36387dfdfd","impliedFormat":1},{"version":"ca921bf56756cb6fe957f6af693a35251b134fb932dc13f3dfff0bb7106f80b4","impliedFormat":1},{"version":"fee92c97f1aa59eb7098a0cc34ff4df7e6b11bae71526aca84359a2575f313d8","impliedFormat":1},{"version":"0bd0297484aacea217d0b76e55452862da3c5d9e33b24430e0719d1161657225","impliedFormat":1},{"version":"2ab6d334bcbf2aff3acfc4fd8c73ecd82b981d3c3aa47b3f3b89281772286904","impliedFormat":1},{"version":"d07cbc787a997d83f7bde3877fec5fb5b12ce8c1b7047eb792996ed9726b4dde","impliedFormat":1},{"version":"6ac6715916fa75a1f7ebdfeacac09513b4d904b667d827b7535e84ff59679aff","impliedFormat":1},{"version":"4805f6161c2c8cefb8d3b8bd96a080c0fe8dbc9315f6ad2e53238f9a79e528a6","impliedFormat":1},{"version":"b83cb14474fa60c5f3ec660146b97d122f0735627f80d82dd03e8caa39b4388c","impliedFormat":1},{"version":"f374cb24e93e7798c4d9e83ff872fa52d2cdb36306392b840a6ddf46cb925cb6","impliedFormat":1},{"version":"49179c6a23701c642bd99abe30d996919748014848b738d8e85181fc159685ff","impliedFormat":1},{"version":"b73cbf0a72c8800cf8f96a9acfe94f3ad32ca71342a8908b8ae484d61113f647","impliedFormat":1},{"version":"bae6dd176832f6423966647382c0d7ba9e63f8c167522f09a982f086cd4e8b23","impliedFormat":1},{"version":"20865ac316b8893c1a0cc383ccfc1801443fbcc2a7255be166cf90d03fac88c9","impliedFormat":1},{"version":"c9958eb32126a3843deedda8c22fb97024aa5d6dd588b90af2d7f2bfac540f23","impliedFormat":1},{"version":"461d0ad8ae5f2ff981778af912ba71b37a8426a33301daa00f21c6ccb27f8156","impliedFormat":1},{"version":"e927c2c13c4eaf0a7f17e6022eee8519eb29ef42c4c13a31e81a611ab8c95577","impliedFormat":1},{"version":"fcafff163ca5e66d3b87126e756e1b6dfa8c526aa9cd2a2b0a9da837d81bbd72","impliedFormat":1},{"version":"70246ad95ad8a22bdfe806cb5d383a26c0c6e58e7207ab9c431f1cb175aca657","impliedFormat":1},{"version":"f00f3aa5d64ff46e600648b55a79dcd1333458f7a10da2ed594d9f0a44b76d0b","impliedFormat":1},{"version":"772d8d5eb158b6c92412c03228bd9902ccb1457d7a705b8129814a5d1a6308fc","impliedFormat":1},{"version":"45490817629431853543adcb91c0673c25af52a456479588b6486daba34f68bb","impliedFormat":1},{"version":"802e797bcab5663b2c9f63f51bdf67eff7c41bc64c0fd65e6da3e7941359e2f7","impliedFormat":1},{"version":"8b4327413e5af38cd8cb97c59f48c3c866015d5d642f28518e3a891c469f240e","impliedFormat":1},{"version":"8514c62ce38e58457d967e9e73f128eedc1378115f712b9eef7127f7c88f82ae","impliedFormat":1},{"version":"f1289e05358c546a5b664fbb35a27738954ec2cc6eb4137350353099d154fc62","impliedFormat":1},{"version":"4b20fcf10a5413680e39f5666464859fc56b1003e7dfe2405ced82371ebd49b6","impliedFormat":1},{"version":"1d17ba45cfbe77a9c7e0df92f7d95f3eefd49ee23d1104d0548b215be56945ad","impliedFormat":1},{"version":"f7d628893c9fa52ba3ab01bcb5e79191636c4331ee5667ecc6373cbccff8ae12","impliedFormat":1},{"version":"2467b00d963828f540f4acd7910f4c04cfe4b489550e6bb682212f65583bca5b","impliedFormat":1},{"version":"a68f36dc8c71757c01f7b0a32333997f510dd61a2de0a3ae1ac23072c368ec37","impliedFormat":99},{"version":"ac47421bbc96f79b2de2475223ca0512a9ff9f3d1f6c01823ffb2ac4c49e1d64","impliedFormat":1},{"version":"46273e8c29816125d0d0b56ce9a849cc77f60f9a5ba627447501d214466f0ff3","impliedFormat":1},{"version":"d663134457d8d669ae0df34eabd57028bddc04fc444c4bc04bc5215afc91e1f4","impliedFormat":1},{"version":"e91f7b1344577a02f051b9b471f33044fef8334a76dc9e1de003d17595a5219b","impliedFormat":1},{"version":"3af3584f79c57853028ef9421ec172539e1fe01853296dc05a9d615ade4ffaf6","impliedFormat":1},{"version":"f82579d87701d639ff4e3930a9b24f4ee13ca74221a9a3a792feb47f01881a9c","impliedFormat":1},{"version":"d7e5d5245a8ba34a274717d085174b2c9827722778129b0081fefd341cca8f55","impliedFormat":1},{"version":"d9d32f94056181c31f553b32ce41d0ef75004912e27450738d57efcd2409c324","impliedFormat":1},{"version":"752513f35f6cff294ffe02d6027c41373adf7bfa35e593dbfd53d95c203635ee","impliedFormat":1},{"version":"6c800b281b9e89e69165fd11536195488de3ff53004e55905e6c0059a2d8591e","impliedFormat":1},{"version":"7d4254b4c6c67a29d5e7f65e67d72540480ac2cfb041ca484847f5ae70480b62","impliedFormat":1},{"version":"1a7e2ea171726446850ec72f4d1525d547ff7e86724cc9e7eec509725752a758","impliedFormat":1},{"version":"8c901126d73f09ecdea4785e9a187d1ac4e793e07da308009db04a7283ec2f37","impliedFormat":1},{"version":"c1de754ab5f3b0f4036d6893c74a0fc984c7fcb07936086f19bbe2974406775b","impliedFormat":1},{"version":"aab290b8e4b7c399f2c09b957666fc95335eb4522b2dd9ead1bf0cb64da6d6ee","impliedFormat":1},{"version":"94fe3281392e1015b22f39535878610b4fa6f1388dc8d78746be3bc4e4bb8950","impliedFormat":1},{"version":"2652448ac55a2010a1f71dd141f828b682298d39728f9871e1cdf8696ef443fd","impliedFormat":1},{"version":"06c25ddfc2242bd06c19f66c9eae4c46d937349a267810f89783680a1d7b5259","impliedFormat":1},{"version":"120599fd965257b1f4d0ff794bc696162832d9d8467224f4665f713a3119078b","impliedFormat":1},{"version":"5433f33b0a20300cca35d2f229a7fc20b0e8477c44be2affeb21cb464af60c76","impliedFormat":1},{"version":"db036c56f79186da50af66511d37d9fe77fa6793381927292d17f81f787bb195","impliedFormat":1},{"version":"bd4131091b773973ca5d2326c60b789ab1f5e02d8843b3587effe6e1ea7c9d86","impliedFormat":1},{"version":"c7f6485931085bf010fbaf46880a9b9ec1a285ad9dc8c695a9e936f5a48f34b4","impliedFormat":1},{"version":"14f6b927888a1112d662877a5966b05ac1bf7ed25d6c84386db4c23c95a5363b","impliedFormat":1},{"version":"6ac6715916fa75a1f7ebdfeacac09513b4d904b667d827b7535e84ff59679aff","impliedFormat":1},{"version":"0427df5c06fafc5fe126d14b9becd24160a288deff40e838bfbd92a35f8d0d00","impliedFormat":1},{"version":"90c54a02432d04e4246c87736e53a6a83084357acfeeba7a489c5422b22f5c7a","impliedFormat":1},{"version":"49c346823ba6d4b12278c12c977fb3a31c06b9ca719015978cb145eb86da1c61","impliedFormat":1},{"version":"bfac6e50eaa7e73bb66b7e052c38fdc8ccfc8dbde2777648642af33cf349f7f1","impliedFormat":1},{"version":"92f7c1a4da7fbfd67a2228d1687d5c2e1faa0ba865a94d3550a3941d7527a45d","impliedFormat":1},{"version":"f53b120213a9289d9a26f5af90c4c686dd71d91487a0aa5451a38366c70dc64b","impliedFormat":1},{"version":"83fe880c090afe485a5c02262c0b7cdd76a299a50c48d9bde02be8e908fb4ae6","impliedFormat":1},{"version":"0a372c2d12a259da78e21b25974d2878502f14d89c6d16b97bd9c5017ab1bc12","impliedFormat":1},{"version":"57d67b72e06059adc5e9454de26bbfe567d412b962a501d263c75c2db430f40e","impliedFormat":1},{"version":"6511e4503cf74c469c60aafd6589e4d14d5eb0a25f9bf043dcbecdf65f261972","impliedFormat":1},{"version":"ec1ca97598eda26b7a5e6c8053623acbd88e43be7c4d29c77ccd57abc4c43999","impliedFormat":1},{"version":"efc0e6a64feef102d5edef7525de0c2ac5961821f12ae5038f0d3a8631457e10","impliedFormat":1},{"version":"a67b87d0281c97dfc1197ef28dfe397fc2c865ccd41f7e32b53f647184cc7307","impliedFormat":1},{"version":"771ffb773f1ddd562492a6b9aaca648192ac3f056f0e1d997678ff97dbb6bf9b","impliedFormat":1},{"version":"232f70c0cf2b432f3a6e56a8dc3417103eb162292a9fd376d51a3a9ea5fbbf6f","impliedFormat":1},{"version":"a47e6d954d22dd9ebb802e7e431b560ed7c581e79fb885e44dc92ed4f60d4c07","impliedFormat":1},{"version":"f019e57d2491c159d47a107fd90219a1734bdd2e25cd8d1db3c8fae5c6b414c4","impliedFormat":1},{"version":"8a0e762ceb20c7e72504feef83d709468a70af4abccb304f32d6b9bac1129b2c","impliedFormat":1},{"version":"d1c9bf292a54312888a77bb19dba5e2503ad803f5393beafd45d78d2f4fe9b48","impliedFormat":1},{"version":"9252d498a77517aab5d8d4b5eb9d71e4b225bbc7123df9713e08181de63180f6","impliedFormat":1},{"version":"d9c46395b3980848a6c4b2f44e986d27d07faee3b3b4b1f214793255b8c64f2a","impliedFormat":1},{"version":"829b9e6028b29e6a8b1c01ddb713efe59da04d857089298fa79acbdb3cfcfdef","impliedFormat":1},{"version":"2896c2e673a5d3bd9b4246811f79486a073cbb03950c3d252fba10003c57411a","impliedFormat":1},{"version":"3be035da7bee86b4c3abf392e0edaa44fc6e45092995eefe36b39118c8a84068","affectsGlobalScope":true,"impliedFormat":1},{"version":"3dc14e1ab45e497e5d5e4295271d54ff689aeae00b4277979fdd10fa563540ae","impliedFormat":1},{"version":"5c634644d45a1b6bc7b05e71e05e52ec04f3d73d9ac85d5927f647a5f965181a","impliedFormat":1},{"version":"4b7f74b772140395e7af67c4841be1ab867c11b3b82a51b1aeb692822b76c872","impliedFormat":1},{"version":"27be6622e2922a1b412eb057faa854831b95db9db5035c3f6d4b677b902ab3b7","impliedFormat":1},{"version":"a68d4b3182e8d776cdede7ac9630c209a7bfbb59191f99a52479151816ef9f9e","impliedFormat":99},{"version":"39644b343e4e3d748344af8182111e3bbc594930fff0170256567e13bbdbebb0","impliedFormat":99},{"version":"ed7fd5160b47b0de3b1571c5c5578e8e7e3314e33ae0b8ea85a895774ee64749","impliedFormat":99},{"version":"63a7595a5015e65262557f883463f934904959da563b4f788306f699411e9bac","impliedFormat":1},{"version":"ecbaf0da125974be39c0aac869e403f72f033a4e7fd0d8cd821a8349b4159628","impliedFormat":1},{"version":"4ba137d6553965703b6b55fd2000b4e07ba365f8caeb0359162ad7247f9707a6","impliedFormat":1},{"version":"ceec3c81b2d81f5e3b855d9367c1d4c664ab5046dff8fd56552df015b7ccbe8f","affectsGlobalScope":true,"impliedFormat":1},{"version":"acd8fd5090ac73902278889c38336ff3f48af6ba03aa665eb34a75e7ba1dccc4","impliedFormat":1},{"version":"d6258883868fb2680d2ca96bc8b1352cab69874581493e6d52680c5ffecdb6cc","impliedFormat":1},{"version":"1b61d259de5350f8b1e5db06290d31eaebebc6baafd5f79d314b5af9256d7153","impliedFormat":1},{"version":"f258e3960f324a956fc76a3d3d9e964fff2244ff5859dcc6ce5951e5413ca826","impliedFormat":1},{"version":"643f7232d07bf75e15bd8f658f664d6183a0efaca5eb84b48201c7671a266979","impliedFormat":1},{"version":"0f6666b58e9276ac3a38fdc80993d19208442d6027ab885580d93aec76b4ef00","impliedFormat":1},{"version":"05fd364b8ef02fb1e174fbac8b825bdb1e5a36a016997c8e421f5fab0a6da0a0","impliedFormat":1},{"version":"616775f16134fa9d01fc677ad3f76e68c051a056c22ab552c64cc281a9686790","impliedFormat":1},{"version":"65c24a8baa2cca1de069a0ba9fba82a173690f52d7e2d0f1f7542d59d5eb4db0","impliedFormat":1},{"version":"5c96bad5f78466785cdad664c056e9e2802d5482ca5f862ed19ba34ffbb7b3a4","impliedFormat":1},{"version":"81d8603ac527e75cfec72bb9391228b58f161c2b33514a9d814c7f3ebd3ef466","impliedFormat":1},{"version":"5f3dc10ae646f375776b4e028d2bed039a93eebbba105694d8b910feebbe8b9c","impliedFormat":1},{"version":"bb0cd7862b72f5eba39909c9889d566e198fcaddf7207c16737d0c2246112678","impliedFormat":1},{"version":"4545c1a1ceca170d5d83452dd7c4994644c35cf676a671412601689d9a62da35","impliedFormat":1},{"version":"320f4091e33548b554d2214ce5fc31c96631b513dffa806e2e3a60766c8c49d9","impliedFormat":1},{"version":"a2d648d333cf67b9aeac5d81a1a379d563a8ffa91ddd61c6179f68de724260ff","impliedFormat":1},{"version":"d90d5f524de38889d1e1dbc2aeef00060d779f8688c02766ddb9ca195e4a713d","impliedFormat":1},{"version":"a3f41ed1b4f2fc3049394b945a68ae4fdefd49fa1739c32f149d32c0545d67f5","impliedFormat":1},{"version":"bad68fd0401eb90fe7da408565c8aee9c7a7021c2577aec92fa1382e8876071a","impliedFormat":1},{"version":"47699512e6d8bebf7be488182427189f999affe3addc1c87c882d36b7f2d0b0e","impliedFormat":1},{"version":"fec01479923e169fb52bd4f668dbeef1d7a7ea6e6d491e15617b46f2cacfa37d","impliedFormat":1},{"version":"8a8fb3097ba52f0ae6530ec6ab34e43e316506eb1d9aa29420a4b1e92a81442d","impliedFormat":1},{"version":"44e09c831fefb6fe59b8e65ad8f68a7ecc0e708d152cfcbe7ba6d6080c31c61e","impliedFormat":1},{"version":"1c0a98de1323051010ce5b958ad47bc1c007f7921973123c999300e2b7b0ecc0","impliedFormat":1},{"version":"4655709c9cb3fd6db2b866cab7c418c40ed9533ce8ea4b66b5f17ec2feea46a9","impliedFormat":1},{"version":"87affad8e2243635d3a191fa72ef896842748d812e973b7510a55c6200b3c2a4","impliedFormat":1},{"version":"ad036a85efcd9e5b4f7dd5c1a7362c8478f9a3b6c3554654ca24a29aa850a9c5","impliedFormat":1},{"version":"fedebeae32c5cdd1a85b4e0504a01996e4a8adf3dfa72876920d3dd6e42978e7","impliedFormat":1},{"version":"3eecb25bb467a948c04874d70452b14ae7edb707660aac17dc053e42f2088b00","impliedFormat":1},{"version":"cdf21eee8007e339b1b9945abf4a7b44930b1d695cc528459e68a3adc39a622e","impliedFormat":1},{"version":"330896c1a2b9693edd617be24fbf9e5895d6e18c7955d6c08f028f272b37314d","impliedFormat":1},{"version":"1d9c0a9a6df4e8f29dc84c25c5aa0bb1da5456ebede7a03e03df08bb8b27bae6","impliedFormat":1},{"version":"84380af21da938a567c65ef95aefb5354f676368ee1a1cbb4cae81604a4c7d17","impliedFormat":1},{"version":"1af3e1f2a5d1332e136f8b0b95c0e6c0a02aaabd5092b36b64f3042a03debf28","impliedFormat":1},{"version":"30d8da250766efa99490fc02801047c2c6d72dd0da1bba6581c7e80d1d8842a4","impliedFormat":1},{"version":"03566202f5553bd2d9de22dfab0c61aa163cabb64f0223c08431fb3fc8f70280","impliedFormat":1},{"version":"5f0292a40df210ab94b9fb44c8b775c51e96777e14e073900e392b295ca1061b","impliedFormat":1},{"version":"bc9ee0192f056b3d5527bcd78dc3f9e527a9ba2bdc0a2c296fbc9027147df4b2","impliedFormat":1},{"version":"8627ad129bcf56e82adff0ab5951627c993937aa99f5949c33240d690088b803","impliedFormat":1},{"version":"1de80059b8078ea5749941c9f863aa970b4735bdbb003be4925c853a8b6b4450","impliedFormat":1},{"version":"1d079c37fa53e3c21ed3fa214a27507bda9991f2a41458705b19ed8c2b61173d","impliedFormat":1},{"version":"5bf5c7a44e779790d1eb54c234b668b15e34affa95e78eada73e5757f61ed76a","impliedFormat":1},{"version":"5835a6e0d7cd2738e56b671af0e561e7c1b4fb77751383672f4b009f4e161d70","impliedFormat":1},{"version":"8fac4a15690b27612d8474fb2fc7cc00388df52d169791b78d1a3645d60b4c8b","affectsGlobalScope":true,"impliedFormat":1},{"version":"064ac1c2ac4b2867c2ceaa74bbdce0cb6a4c16e7c31a6497097159c18f74aa7c","impliedFormat":1},{"version":"1d63055b690a582006435ddd3aa9c03aac16a696fac77ce2ed808f3e5a06efab","impliedFormat":1},{"version":"77b60830cd76434ef688bccaee34e40343ecb43e5d14c3753b8120e95e7398a7","impliedFormat":1},{"version":"2a1e5c2b1e57e1d541b2c0feb4a7a56268911eb6b0b3ae529c2b14b07fd85954","signature":"d3484dfd7c327fc1d0d56675c6e7752e6ef8d708079d8e6a9f086b40ceb039bb"},{"version":"87888524bbfa8c654c70788cfb24d30bd184d82665a4bc866567bec42f699993","signature":"6ec5739b3318cf3bdc1c08001bb41a6008d7b59ca68d130e54e8064426ac0950"},{"version":"098f9ba1a9dc1f5cc086444050e1b2eb966fd394821c953aa30faa9933b16f20","signature":"ba51c1bddc5e5477ffb183e7acbafc0a305ace7367a3cc6143db18d939f75e10"},{"version":"9a1306666a181cc6e5351cea2e8cfa6c7063035ab1e87c88b1da5949cd6ac516","signature":"783433fc1a912687b008a5b7c3ec4246b56eea7c5de524c083a55051b1b82aaf"},{"version":"a11631e2c8ff72ff295256658fb1046f3a034241b42a57a2df91cedc5f7f4edd","signature":"58302756e569a3ea4f51bafb27a9be8f28e4d2fa64e8ebfcb79527cb481ee699"},{"version":"4aa9d53c734989e7be6e8d13aa66b0941947d39422e869e7080f0a15ae0b37f5","signature":"32a077259e30629ad738ad31b976838a6188894cfbae8c68d5fa9f7b887970a1"},{"version":"ce6468bbf512d191800273bffd4a97be947b737476afeae8afbe09f42dc00895","signature":"869ce6205b3d708b25369f6363c465b24e45960dc090e88d668497e6adb2995e"},{"version":"94254cb075140fd0b826b22485fb8c61973f0a91de8a072db3d898fa911f4270","signature":"c8802c05fd2b489cf479276d4cbbe419cad80d64eb9b444e2aeef08570e8d563"},{"version":"cbcd7fb0c6b76b3939556c2c3916bbb0236cc32622f0c5c2324df836b36220c3","signature":"d860c9cc985d71407dd237d401a12cd069f6cef012e49fe9fdedb792148f9e86"},{"version":"8b35257319552780f598f1bfbe70a0b5cbf885efa6c445e4f3f90d2aabd08629","signature":"8a521eaa2173186610aa9dd4323e58177e74bad97aa8d05d2e0dbb703ca99deb"},{"version":"ab8ebbd8ab624d6c61bd01ffc8aa6b852dae9998725da718eb912b6c54a40a30","signature":"18d754deee1ac95cf04f328e0244fc4c82eb261591c90ec0bae1140fc3a5ca99"},"6af905ab73fd46fa7644c2ffd78243b5868fb9ae744e16abe4e5373914d9e0fa",{"version":"60c6aa175c2d8effee822c2abab40289ac751bbdfbc6da8a1873d63b5397fdfc","signature":"44025d09a4644ee3f547c3cde1bad8ed12bcb4180cb4a5af4f94a9cf48401252"},{"version":"603e5d865d544882bfe929f443d21faf6451ad3e0016a789ea6c38bae5475b57","signature":"b4e4118d280206fe9079e753855c9e546442bc912108612cced9c8ee4c546da7"},{"version":"bfe8c198a74f87a7025902cd4704f2c4c8ad52eb8a91ca525d93275b2e4a7c19","signature":"9405ead1cd9afa3e01b4411cc7f5059441e5cbbe21ccfb5b51a9a09ef37ce85e"},{"version":"bc0ee5896e662598992058d34334d52150ae1ee0aa72b3ddb26113ffc823c2fc","signature":"e6b9fdb333c4d3af1a6847e374f1ae4bab77ac888a509321d359e04189728255"},{"version":"3ba342621f04834618ae132aa19031355e47b03eb2c775566c4f261987a13c08","signature":"a34a0e2c0c035b7392a543786c0e8e6df6f52188ac6078023dd7c12ad9ac2578"},"7b7185e8b22cd5467dc85613b19fffdb4d5786236d3e1c680e4d33d8cb29221d","3f322d07617882109b905830b459bf5a8697b3d33a0a8a6401bc44f2a50fdc7d",{"version":"559a17fd85d0df25405b323ed71a21bb294af9f9d065f6f2c743f5804204a044","signature":"81c28d166db2f7080157cbe8c501c4a80fca101873140057553316e8d5268280"},{"version":"38cdcbf6b5643a7b2cef1dda7bca697eeda877766a8f286afe39225325f0f21f","signature":"bde10ff89bc3de9c7291427ba55fb22c334dad54bfc938677b616723f86bf232"},{"version":"05e48a0ff7c58eac21ad827db14827adcd907f3de2526ba8a2fe57939e402a0e","signature":"6d11171f78f4dec5cf638d45235b658068e634122b62085daf797942811a57d3"},{"version":"ab4f38d9989d578b1f0e903eace6df573bcc8e019fa821a368efb40f9f5cf1ed","signature":"ec1fbcfd02eb6ab5a9107bb984c443158b9a899e8c254ecc1f7672764baa3983"},"e2f77ebadcb936378eae249c8ede183d778a7de30214e33760ce5913773597ba",{"version":"8e4491f61d603d1a04d561314d7cf1ec017248e0e61fad6ea017f6b38c993362","signature":"a324b7982119fe4d3bb0a6647243308fd04f67cfbecc80528c987760fafb6821"},{"version":"b8901504aff4ec063947dd8e7a7f1fc49f55db25a13025ba724ea31a8686d306","signature":"dd083e7a95b4938758c5c3f0fd31ce9cb82cc220df48cd86808fee953af05584"},{"version":"59286462b39b1ebc428ffb3265b278ff9d7e9f0cbecf5c0e5c7b214ad261c4eb","signature":"269dc2aa6dadb072edaca483ffa5990e1e2dc220f3f3a167e3f0f61f4d720e2d"},{"version":"d07542d548f137f313facb76665a1745bb61be062c4761d45b174e84a90c8424","signature":"bbbcb5f8c6b3a6a33680bb7a7de501f69d6a76bfa9665ec9a8246a5b0f64b30e"},{"version":"9e5bfed0e3608d418672845dbb59c11158f5c690566f7d48fb8bc26ea36bf1dc","signature":"888b9bb287c78acb484b0b697eebb9b0062c19f3d78d290db188f04370c7a75c"},{"version":"04c95825e8296590cde0e077392dc997966eb717b900ba81b06226e3d14fc812","signature":"d06d4e78c42579417ae5f2e18c978333bc703aedf9748730fa62f7b9bf4427e1"},{"version":"c157c37945fbd2d551f7994a97e4559a6b886cfaff9911d7d4c602f53f69f91f","signature":"1273a3ad3598fd4829d45c276c2473d2b448fb8d9f3d3fb973a494c43ba9bfef"},{"version":"26c3ccb79477858914470ebe5b2b823d7c3806b8e123e23caf0aad1e4e83ed56","signature":"ef9cba269e754b7fa510c7e796b498b0c569f806a0a5446c41f1371f3968ee68"},{"version":"824bd0454dde36fdad20c66923a196fe9036e52fa273f54b8f1d45df77cbada3","signature":"c20163375d30a60407d6c18f24bda7fd06088795352ddb35eb3a56f90906bfb6"},{"version":"f2bdc7df284b953bfb2b1031664c3e5fe7b03cf398ab96b392eefeb84184c6f5","signature":"1ac5fc906a60daeec2216a2090d376b94e580949a06d721506dccd3baa576c98"},{"version":"d6024215f55572abf693e3e413e4453544c34f932df9d55845744b2a37bf24ea","signature":"700e37c5fb53a4c997cd665ba6c51e3b18ffd0a7a939d56f3f39baa1312ff700"},{"version":"90b5b4282a92d7740459309d7f7c6e6829bc1c7bea963d9a2461b3860d0c788c","signature":"4029b03307dafa9759842155249791e1bcace1b83721e7b64b1a9ceb710b1b10"},{"version":"b60ab656184076b65fd17b271f9c39089bc46e841dbeb0459d0119392715edbd","signature":"27e578fabc568907dbeb60aa71426d5569f5ad7eac8a5e7369b5f0f8dce98a6f"},{"version":"6a2b4ceebff278e06509b9012f7c4526d7b3a467755909abd4d5118e110c8c68","signature":"cc7c3ba52dcb5a9af919a4636515964f683a7152127491ea9a86c80493ac5610"},{"version":"e03e1839bac36c52e5ae30e495b72e453d18b35af185f7c3699b6a64a7f78df5","signature":"5cfa7f69dccac813285050e460bc678f41f1cb43de1faa99d35f9439f339db12"},{"version":"0c7c10c607827ebf6eac30034cdb93a4276106569e8be375834381c7fa3aa3a6","signature":"09fd8c2d436cacb4bbae67710d98627907d1c1cae6d7f181e36c69818f8e9401"},{"version":"1a33cb63c3d2483e1a93a8cb219fa078e8ce1921420eb4844b00bcfe12ed26cd","signature":"d50234446709c93924529c0508fb514f3a19916424febb911dd43644b268c3ce"},{"version":"a2e24d66b89ab74b297ddd7ba7d705e4827e33739d6048aac3785bc1762a9847","signature":"f1d6148ed5dd35a68f441050e3e012604b12c50390a8c10ebee7eca51c220148"},{"version":"b60e5f2fe53325448f74703123f79b9b8a0683a0a8d008860fd6a143a8cb4c6e","signature":"935fdba2eecea540e2b306d60610a2fbc64876909709508209e4d0e706edc69c"},{"version":"eb082a4c45dd070fa06a1db8951b3493a322d50ebf0af3a355faa94e766330bc","signature":"61ac0fbbde13ac63d1e163d1bf185af2ce050c7f408ec782fda1d4a237c25c72"},"19ccfe1a2ddbc9d55a7bdf6378ebbd15d65f48ffa9f487634487a424bd9d19fa",{"version":"2ce36c8872855fc2f61e635ccaa63be020bf137256f75a4487cc0686d0e89233","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"97de9297b0760d6e7334fd793540a5d48a48bfae7773d5ed2f88694c01effe6e","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"e6cc09c52d124e810244b22dbb80096a82fdfcbbcf759fe21792f6196883757e","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"bfa59fbdc79232f4839a6f9a25a68574a6b4fc8f79611ef5d6793038b2275e22","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"d8dbeebe239b9e73dd1c65e525de8b1305ce63a84a28317cb953dd5e26eddb70","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"8fa79f79ffb146a196d9b489a1e0420c68cf5c1e43eb1d535b0071a5d813eb3c","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"c5be2f2db3a7cad9b1e85c72d5d99282e7d8770ac5812491bda1cacc10e4bb30","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"9a1122cc79a3b6c130a1f37e903ef93eca885c09c185fff399e507ec1e9eea19","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"0dc29d1983bb62591767360b0436b0deffd644117e75e65dff4f1ebc8b4e26b5","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"c4c3228dd35f345f09e5e6ddeff826b7c365cc3f796ecace49adc2852b129b13","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"ea395d64b4351b53cf4aadd7548d2a317e80243663d741f41dd08583d4370410","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"6702ca6bbc86eac80bb47360b935252551289894c66b10cfdc1c8b1edee925dc","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"1b650a03295b6cd2a9b83ff7f25bf2add592ab18f7db39477993c72f03605ea1","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"801470e9200a9a651bf4d047d3f1dbd5ce035a5eeab1321729dcb07c7775aff4","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"5628c76701079bf54dd67277250abb90949683f28601c90847dad5fc1ff2ac49","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"b789bf89eb19c777ed1e956dbad0925ca795701552d22e68fd130a032008b9f9","impliedFormat":1},"85ae5aee75f011967cf2d25cbc342f62d69314e9d925f7f4aa3456fc2cffcca6",{"version":"096c91fc22a57119fe2fd55028549aadcefd11c6d9bbcd811d1ebf28b20fdd97","signature":"23641819f541482577d98833be23d4bacbc17bba1f0f3ac1974bcfa4a2563cac"},{"version":"0ab9ec2c71610d621fea73c0040a2016332d8b023be9bfeb5aafeafdfbe2495c","signature":"306c4f012c60941c2e6dc103cf5f72dc9181fd63dd1a72eb3dc3780c94b01919"},{"version":"5eda71d82d63643ab80e27fed7f6f5edad12c3e0c1b05b2a4af9331a003392e6","signature":"55ced09e64e40b82861610ec5fb38057c6221bb0cff96c4e4ee59c5d73d420f9"},{"version":"31328081fde0d30211679f00f735dea8de798439b6d286401b7f675c08afe489","signature":"364fee0ee80cfeeebec46fe3610cc79d3095ecf44d183a7b1c0f61d7150a3b97"},{"version":"5b4d2ece2c699c67803c143571e993ff47b80822b486e22abb066635fe47564f","signature":"4181ebf8eda762ab55339bbac4f8a6dc07f9a1633a6baa8cbee84e6517b3b233"},{"version":"a56b0ebe2f5dde79e26868e87b5eddde855b487534792ec68150cbeff1baa844","signature":"3a79d2e6ffc3b2948ea4bc2071e5fea9c80f747684b5924014c6e28462a4e8bb"},"2552a31fad45a9ed1bde87e51b038dc0e786cd364b597162263abbf57018949b",{"version":"ae9b49ddf7f8a2b939d1ccc4b84876e7a74f8284521a513233b6014b9861541f","affectsGlobalScope":true},"19ccfe1a2ddbc9d55a7bdf6378ebbd15d65f48ffa9f487634487a424bd9d19fa",{"version":"2ce36c8872855fc2f61e635ccaa63be020bf137256f75a4487cc0686d0e89233","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"97de9297b0760d6e7334fd793540a5d48a48bfae7773d5ed2f88694c01effe6e","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"8e723d89db7b361c84250c5b33fd7dc001e27f663e3ae263321597dfaa7459bc","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"e6cc09c52d124e810244b22dbb80096a82fdfcbbcf759fe21792f6196883757e","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"d8dbeebe239b9e73dd1c65e525de8b1305ce63a84a28317cb953dd5e26eddb70","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"8fa79f79ffb146a196d9b489a1e0420c68cf5c1e43eb1d535b0071a5d813eb3c","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"c5be2f2db3a7cad9b1e85c72d5d99282e7d8770ac5812491bda1cacc10e4bb30","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"9a1122cc79a3b6c130a1f37e903ef93eca885c09c185fff399e507ec1e9eea19","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},"0dc29d1983bb62591767360b0436b0deffd644117e75e65dff4f1ebc8b4e26b5",{"version":"c4c3228dd35f345f09e5e6ddeff826b7c365cc3f796ecace49adc2852b129b13","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"ea395d64b4351b53cf4aadd7548d2a317e80243663d741f41dd08583d4370410","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"6702ca6bbc86eac80bb47360b935252551289894c66b10cfdc1c8b1edee925dc","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},"1b650a03295b6cd2a9b83ff7f25bf2add592ab18f7db39477993c72f03605ea1",{"version":"729d8fcae15384f7df4886becde8a8743f2dce8c0c24f617c8031a67e2a1431c","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},{"version":"fe2bb43840c83a9ed67e0e8240a86e9bb2522b9b0176ccb3e0b620204f2d4f6d","signature":"89b0f68f8f0b901f9dfff2b9e7255520283a783d6af7f2bc2953d771232317a2"},"801470e9200a9a651bf4d047d3f1dbd5ce035a5eeab1321729dcb07c7775aff4","5628c76701079bf54dd67277250abb90949683f28601c90847dad5fc1ff2ac49"],"root":[68,69,[485,491],[499,544],[546,572]],"options":{"allowImportingTsExtensions":true,"allowJs":true,"esModuleInterop":true,"exactOptionalPropertyTypes":true,"jsx":1,"module":99,"noFallthroughCasesInSwitch":true,"noImplicitOverride":true,"noUncheckedIndexedAccess":true,"skipLibCheck":true,"strict":true,"target":9,"verbatimModuleSyntax":true},"referencedMap":[[558,1],[556,2],[559,3],[563,4],[564,5],[565,6],[561,7],[566,8],[568,9],[567,10],[562,11],[569,12],[560,13],[570,14],[557,15],[572,16],[571,17],[553,18],[554,19],[555,20],[530,2],[532,3],[537,4],[538,5],[539,6],[535,7],[540,8],[542,9],[541,10],[536,11],[533,21],[534,13],[531,15],[544,16],[543,17],[68,22],[69,19],[529,23],[546,24],[523,25],[525,26],[486,27],[491,28],[503,29],[505,30],[527,31],[507,32],[552,19],[508,33],[509,34],[510,35],[490,36],[512,37],[549,38],[528,39],[550,19],[551,38],[513,40],[524,25],[548,41],[515,42],[520,43],[522,44],[511,45],[504,46],[487,47],[488,48],[506,46],[526,49],[502,50],[501,51],[499,52],[521,53],[514,54],[516,53],[517,55],[500,19],[518,56],[485,19],[489,57],[519,55],[547,58],[376,19],[233,19],[121,59],[122,59],[123,60],[75,61],[124,62],[125,63],[126,64],[70,19],[73,65],[71,19],[72,19],[127,66],[128,67],[129,68],[130,69],[131,70],[132,71],[133,71],[134,72],[135,73],[136,74],[137,75],[76,19],[74,19],[138,76],[139,77],[140,78],[174,79],[141,80],[142,19],[143,81],[144,82],[145,83],[146,84],[147,85],[148,86],[149,87],[150,88],[151,89],[152,89],[153,90],[154,19],[155,91],[156,92],[158,93],[157,94],[159,95],[160,96],[161,97],[162,98],[163,99],[164,100],[165,101],[166,102],[167,103],[168,104],[169,105],[170,106],[171,107],[77,19],[78,19],[79,19],[117,108],[118,19],[119,19],[120,95],[172,109],[173,110],[182,111],[181,52],[183,112],[180,113],[342,114],[341,115],[178,116],[339,19],[179,117],[175,19],[177,118],[338,52],[251,52],[176,19],[444,119],[446,120],[447,121],[449,122],[208,123],[237,124],[413,125],[232,126],[219,19],[200,19],[206,19],[403,127],[268,128],[207,19],[371,129],[242,130],[243,131],[337,132],[400,133],[354,134],[407,135],[408,136],[406,137],[405,19],[404,138],[239,139],[209,140],[288,19],[289,141],[204,19],[221,142],[210,143],[186,142],[270,142],[191,142],[235,144],[234,19],[412,145],[422,19],[199,19],[313,146],[314,147],[308,52],[470,19],[316,19],[317,148],[309,149],[476,150],[474,151],[469,19],[399,152],[398,19],[468,153],[310,52],[350,154],[348,155],[471,19],[475,19],[473,156],[472,19],[349,157],[463,158],[466,159],[279,160],[278,161],[277,162],[479,52],[276,163],[262,19],[429,19],[432,19],[431,52],[433,164],[185,19],[409,165],[410,166],[411,167],[223,19],[198,168],[220,19],[329,52],[189,169],[328,170],[327,171],[318,19],[319,19],[326,19],[321,19],[324,172],[320,19],[322,173],[325,174],[323,173],[205,19],[196,19],[197,142],[252,175],[253,176],[250,177],[248,178],[249,179],[245,19],[335,148],[356,148],[445,180],[450,181],[454,182],[416,183],[415,19],[265,19],[434,184],[192,185],[311,186],[312,187],[303,188],[294,19],[334,189],[295,190],[336,191],[331,192],[330,19],[332,19],[347,193],[417,194],[418,195],[297,196],[301,197],[292,198],[395,199],[193,200],[272,201],[372,202],[194,203],[423,204],[424,126],[246,19],[254,205],[384,206],[244,19],[383,207],[184,19],[378,208],[222,19],[290,209],[373,19],[195,19],[255,19],[382,210],[203,19],[260,211],[300,212],[414,213],[299,19],[381,19],[247,19],[386,214],[387,215],[201,19],[389,216],[391,217],[390,218],[225,19],[380,203],[393,219],[379,220],[385,221],[212,19],[215,19],[213,19],[217,19],[214,19],[216,19],[218,222],[211,19],[364,223],[363,19],[369,224],[365,225],[368,226],[367,226],[370,224],[366,225],[259,227],[357,228],[421,229],[436,19],[458,230],[460,231],[296,19],[459,232],[419,194],[435,233],[315,194],[202,19],[298,234],[256,235],[257,236],[258,237],[287,238],[394,238],[273,238],[358,239],[274,239],[241,240],[240,19],[362,241],[361,242],[360,243],[359,244],[420,245],[307,246],[344,247],[306,248],[340,249],[343,250],[402,251],[401,252],[397,253],[353,254],[355,255],[352,256],[392,257],[346,19],[67,19],[345,258],[396,19],[261,259],[293,165],[291,260],[263,261],[266,262],[430,19],[264,263],[267,263],[65,19],[64,19],[66,19],[428,19],[269,264],[305,52],[443,19],[351,265],[238,19],[227,266],[187,19],[452,52],[462,267],[286,52],[456,148],[285,268],[188,269],[284,267],[190,19],[464,270],[282,52],[283,52],[275,19],[226,19],[281,271],[280,272],[224,273],[302,88],[271,88],[388,19],[375,274],[374,19],[448,19],[333,275],[304,52],[425,276],[438,52],[441,277],[442,278],[439,52],[440,19],[236,279],[231,280],[230,19],[229,281],[228,19],[426,282],[451,283],[453,284],[455,285],[457,286],[461,287],[545,288],[465,288],[483,289],[467,290],[477,291],[478,292],[480,293],[437,294],[427,168],[482,19],[481,295],[484,52],[377,296],[62,19],[63,19],[11,19],[12,19],[14,19],[13,19],[2,19],[15,19],[16,19],[17,19],[18,19],[19,19],[20,19],[21,19],[22,19],[3,19],[23,19],[24,19],[4,19],[25,19],[29,19],[26,19],[27,19],[28,19],[30,19],[31,19],[32,19],[5,19],[33,19],[34,19],[35,19],[36,19],[6,19],[40,19],[37,19],[38,19],[39,19],[41,19],[7,19],[42,19],[47,19],[48,19],[43,19],[44,19],[45,19],[46,19],[8,19],[52,19],[49,19],[50,19],[51,19],[53,19],[9,19],[54,19],[55,19],[56,19],[58,19],[57,19],[59,19],[60,19],[10,19],[61,19],[1,19],[95,297],[105,298],[94,297],[115,299],[86,300],[85,301],[114,295],[108,302],[113,303],[88,304],[102,305],[87,306],[111,307],[83,308],[82,295],[112,309],[84,310],[89,311],[90,19],[93,311],[80,19],[116,312],[106,313],[97,314],[98,315],[100,316],[96,317],[99,318],[109,295],[91,319],[92,320],[101,321],[81,322],[104,313],[103,311],[107,19],[110,323],[498,324],[497,19],[496,325],[495,19],[494,326],[493,327],[492,19]],"affectedFilesPendingEmit":[558,556,559,563,564,565,561,566,568,567,562,569,560,570,557,572,571,555,530,532,537,538,539,535,540,542,541,536,533,534,531,544,543,529,523,525,486,491,503,505,527,507,552,508,509,510,490,512,549,528,550,551,513,524,548,515,520,522,511,504,487,488,506,526,502,501,499,521,514,516,517,500,518,485,489,519,547,498,497,496,495,494,493,492],"version":"5.9.3"}
\ No newline at end of file
diff --git a/bun.lock b/bun.lock
new file mode 100644
index 0000000..a189a42
--- /dev/null
+++ b/bun.lock
@@ -0,0 +1,195 @@
+{
+ "lockfileVersion": 2,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "pkviewer",
+ "devDependencies": {
+ "@types/bun": "latest",
+ "typescript": "^5.6.0",
+ },
+ },
+ "apps/api": {
+ "name": "@pkviewer/api",
+ "version": "0.1.0",
+ "dependencies": {
+ "@pkviewer/shared": "workspace:*",
+ "hono": "^4.6.0",
+ "zod": "^3.23.8",
+ },
+ },
+ "apps/web": {
+ "name": "@pkviewer/web",
+ "version": "0.1.0",
+ "dependencies": {
+ "@pkviewer/shared": "workspace:*",
+ "next": "^15.1.0",
+ "react": "^19.0.0",
+ "react-bootstrap-icons": "^1.11.6",
+ "react-dom": "^19.0.0",
+ "server-only": "^0.0.1",
+ },
+ "devDependencies": {
+ "@types/node": "^22.0.0",
+ "@types/react": "^19.0.0",
+ "@types/react-dom": "^19.0.0",
+ "typescript": "^5.6.0",
+ },
+ },
+ "packages/shared": {
+ "name": "@pkviewer/shared",
+ "version": "0.1.0",
+ },
+ },
+ "packages": {
+ "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
+
+ "@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
+
+ "@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.3" }, "os": "darwin", "cpu": "arm64" }, "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA=="],
+
+ "@img/sharp-darwin-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.3" }, "os": "darwin", "cpu": "x64" }, "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw=="],
+
+ "@img/sharp-freebsd-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "os": "freebsd" }, "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA=="],
+
+ "@img/sharp-libvips-darwin-arm64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg=="],
+
+ "@img/sharp-libvips-darwin-x64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw=="],
+
+ "@img/sharp-libvips-linux-arm": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA=="],
+
+ "@img/sharp-libvips-linux-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A=="],
+
+ "@img/sharp-libvips-linux-ppc64": ["@img/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w=="],
+
+ "@img/sharp-libvips-linux-riscv64": ["@img/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ=="],
+
+ "@img/sharp-libvips-linux-s390x": ["@img/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q=="],
+
+ "@img/sharp-libvips-linux-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA=="],
+
+ "@img/sharp-libvips-linuxmusl-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw=="],
+
+ "@img/sharp-libvips-linuxmusl-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw=="],
+
+ "@img/sharp-linux-arm": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.3" }, "os": "linux", "cpu": "arm" }, "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A=="],
+
+ "@img/sharp-linux-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64" }, "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ=="],
+
+ "@img/sharp-linux-ppc64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.3" }, "os": "linux", "cpu": "ppc64" }, "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ=="],
+
+ "@img/sharp-linux-riscv64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.3" }, "os": "linux", "cpu": "none" }, "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA=="],
+
+ "@img/sharp-linux-s390x": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.3" }, "os": "linux", "cpu": "s390x" }, "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ=="],
+
+ "@img/sharp-linux-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.3" }, "os": "linux", "cpu": "x64" }, "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA=="],
+
+ "@img/sharp-linuxmusl-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64" }, "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA=="],
+
+ "@img/sharp-linuxmusl-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.3" }, "os": "linux", "cpu": "x64" }, "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg=="],
+
+ "@img/sharp-wasm32": ["@img/[email protected]", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="],
+
+ "@img/sharp-webcontainers-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "cpu": "none" }, "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA=="],
+
+ "@img/sharp-win32-arm64": ["@img/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw=="],
+
+ "@img/sharp-win32-ia32": ["@img/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw=="],
+
+ "@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg=="],
+
+ "@next/env": ["@next/[email protected]", "", {}, "sha512-42h1lLr07vl4gawALP1hsgRZjHB1xYa58JfUfHwr0f7jG/zhPakh5GHkADHXOC9ZxUvlQFOPIrp7s6qX4DezPQ=="],
+
+ "@next/swc-darwin-arm64": ["@next/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-w+RR0v/QuApnWEjRGm1z6gcObKwGMb5YPA7V3bzBEVSBpMFUXprer0tS27UxjUcEnqbhL7Zuzohej79B6rYmBg=="],
+
+ "@next/swc-darwin-x64": ["@next/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-QiGGBUSakt8S1H4Lt9Ehsh6Ja87axiBnQQgysOObvCbI7iUfJnRGntF1P64S4/ijuHFnSB8KLsEddkY3nN26uw=="],
+
+ "@next/swc-linux-arm64-gnu": ["@next/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-ehLos/66zo0d/mJCU5u96a/VDcr01aaUrX0o/i16UdInxz8qPTCDSxGtjk/Lps1sIr1RJFdiX3hxc0fxJo+cPA=="],
+
+ "@next/swc-linux-arm64-musl": ["@next/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-ZVMrqLiJ7DiChgmbkQwFtdhAnUkSH/4p7tB29QY+giATb0Q/XGHNRSKAb/B8XGDHRUaA67NepOW5W8u3ZRJBAA=="],
+
+ "@next/swc-linux-x64-gnu": ["@next/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-UOewtDGkTMJTiODrEdeLZ50yGb59xCZSriNpXkfPMxRRgwDkGc7i8mLWqV5076wEdb+Ca/XN7MhJyM3CupyNyQ=="],
+
+ "@next/swc-linux-x64-musl": ["@next/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-UBHwA8AhkCZgtRfU1aJpunuAJe/6gZv6jDESQe4p5MjTb5V0YEeJBWCdNqx15Vj3x+5jmauRfeMJSjfQj9HGFQ=="],
+
+ "@next/swc-win32-arm64-msvc": ["@next/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-QcFcPRr16djk5IqK5+e8O80eZfgWzIvVBXfitIq0tQ/uc+eyfdoZ0NmKc0cnbIJyfVwREapKuG97YcxWA9gcpA=="],
+
+ "@next/swc-win32-x64-msvc": ["@next/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-zREeykps3ndWr9egJgvJKqVkkDuaw6Zrrg23cYBos0ygydFkAWYU4+PaPVwXzP1eAYQJe53ShSK45iDM529BOg=="],
+
+ "@pkviewer/api": ["@pkviewer/api@workspace:apps/api"],
+
+ "@pkviewer/shared": ["@pkviewer/shared@workspace:packages/shared"],
+
+ "@pkviewer/web": ["@pkviewer/web@workspace:apps/web"],
+
+ "@swc/helpers": ["@swc/[email protected]", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g=="],
+
+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="],
+
+ "@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w=="],
+
+ "@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-I8bPpDLcHBv1qiIiXDCy71Rt8eQDKJP0sMSWJphDdAcdqiJ1sGpZamavoEIRZmYzjia9LuEb2HlYdDpmoENpvQ=="],
+
+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],
+
+ "caniuse-lite": ["[email protected]", "", {}, "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg=="],
+
+ "client-only": ["[email protected]", "", {}, "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="],
+
+ "csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
+
+ "detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
+
+ "hono": ["[email protected]", "", {}, "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ=="],
+
+ "js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
+
+ "loose-envify": ["[email protected]", "", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="],
+
+ "nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="],
+
+ "next": ["[email protected]", "", { "dependencies": { "@next/env": "15.5.25", "@swc/helpers": "0.5.15", "caniuse-lite": "^1.0.30001579", "postcss": "8.4.31", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "15.5.25", "@next/swc-darwin-x64": "15.5.25", "@next/swc-linux-arm64-gnu": "15.5.25", "@next/swc-linux-arm64-musl": "15.5.25", "@next/swc-linux-x64-gnu": "15.5.25", "@next/swc-linux-x64-musl": "15.5.25", "@next/swc-win32-arm64-msvc": "15.5.25", "@next/swc-win32-x64-msvc": "15.5.25", "sharp": "^0.34.3 || ^0.35.4" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-OMWNulIIqKM2ykvC2qMjIt0IoavB4UB2SCs4iXJ6z6847FvyH8jBmBWcvrF5iuhTu8Przh20Fo/aoszIdqx4PA=="],
+
+ "object-assign": ["[email protected]", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
+
+ "picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
+
+ "postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" } }, "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ=="],
+
+ "prop-types": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", "react-is": "^16.13.1" } }, "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg=="],
+
+ "react": ["[email protected]", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="],
+
+ "react-bootstrap-icons": ["[email protected]", "", { "dependencies": { "prop-types": "^15.7.2" }, "peerDependencies": { "react": ">=16.8.6" } }, "sha512-ycXiyeSyzbS1C4+MlPTYe0riB+UlZ7LV7YZQYqlERV2cxDiKtntI0huHmP/3VVvzPt4tGxqK0K+Y6g7We3U6tQ=="],
+
+ "react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.8" } }, "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ=="],
+
+ "react-is": ["[email protected]", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
+
+ "scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
+
+ "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
+
+ "server-only": ["[email protected]", "", {}, "sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA=="],
+
+ "sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.4", "@img/sharp-darwin-x64": "0.35.4", "@img/sharp-freebsd-wasm32": "0.35.4", "@img/sharp-libvips-darwin-arm64": "1.3.3", "@img/sharp-libvips-darwin-x64": "1.3.3", "@img/sharp-libvips-linux-arm": "1.3.3", "@img/sharp-libvips-linux-arm64": "1.3.3", "@img/sharp-libvips-linux-ppc64": "1.3.3", "@img/sharp-libvips-linux-riscv64": "1.3.3", "@img/sharp-libvips-linux-s390x": "1.3.3", "@img/sharp-libvips-linux-x64": "1.3.3", "@img/sharp-libvips-linuxmusl-arm64": "1.3.3", "@img/sharp-libvips-linuxmusl-x64": "1.3.3", "@img/sharp-linux-arm": "0.35.4", "@img/sharp-linux-arm64": "0.35.4", "@img/sharp-linux-ppc64": "0.35.4", "@img/sharp-linux-riscv64": "0.35.4", "@img/sharp-linux-s390x": "0.35.4", "@img/sharp-linux-x64": "0.35.4", "@img/sharp-linuxmusl-arm64": "0.35.4", "@img/sharp-linuxmusl-x64": "0.35.4", "@img/sharp-webcontainers-wasm32": "0.35.4", "@img/sharp-win32-arm64": "0.35.4", "@img/sharp-win32-ia32": "0.35.4", "@img/sharp-win32-x64": "0.35.4" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA=="],
+
+ "source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
+
+ "styled-jsx": ["[email protected]", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "@babel/core": "*", "babel-plugin-macros": "*", "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" }, "optionalPeers": ["@babel/core", "babel-plugin-macros"] }, "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA=="],
+
+ "tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+ "typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
+
+ "zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
+
+ "bun-types/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-k97ENvZWtvA6yqz5/FS6a7duDgOPEeOQOc2iKS/nY6mX6qJUKtLnWzQS+Xj6tXweyj6ZcTAK2Qecetnvi9nCLA=="],
+
+ "bun-types/@types/node/undici-types": ["[email protected]", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
+ }
+}
diff --git a/docs/decisions.md b/docs/decisions.md
new file mode 100644
index 0000000..1ee64ea
--- /dev/null
+++ b/docs/decisions.md
@@ -0,0 +1,490 @@
+# pkviewer — decision log
+
+Signed-off decisions. Implementation follows these; changing one is a deliberate
+act, not a refactor. Numbering is stable so other documents can cite it.
+
+## Architecture
+
+**A1. Two processes.** Hono on Bun owns everything stateful — database, sessions,
+PluralKit client, OAuth, business logic — and is the only process that opens
+SQLite, so there is exactly one writer. Next.js on Node renders and reaches the
+API over HTTP. **Next.js never imports anything under `apps/api/src/db`.**
+
+**A2. SSR is required**, not decorative: public pages are shared into Discord,
+whose unfurler does not run JavaScript. Server-rendered `<meta>` is the point.
+
+**A3. No serverless.** SQLite needs a persistent disk. Single VPS or a volume.
+
+## The twelve
+
+1. **Domain is configuration.** `system.doughmination.gay` is the beta
+ deployment. No absolute pkviewer URL is ever persisted to the database; public
+ URLs are composed at render time from config. Enforced by
+ `scripts/check-no-hardcoded-origin.sh` in CI.
+2. **User content gets its own origin**, from day one. See O1 below.
+3. **Management lives under `/manage/...`**, never `/s/:system/...`, so a member
+ slug can never collide with an app route.
+4. **MVP slugs are `[a-z0-9-]` only.** Eliminates homograph squatting outright
+ rather than mitigating it. Unicode can come later with confusable folding.
+5. **Private members 404**, with nothing distinguishing them from a member that
+ never existed. PluralKit's own 404 already behaves this way, and `PkNotFound`
+ deliberately does not separate the two cases.
+6. **Slug reservation is 7 days and subject-owned** — the reclaim right follows
+ the system or member, not the account that held it.
+7. **A contested claim is blocked automatically**, with a manual appeal path.
+ The legitimate case and the attack case are indistinguishable to us, so there
+ is no safe automatic policy.
+8. **`/s/<pk-id>` and `/s/<slug>` both return 200**; the slug is canonical via
+ `<link rel="canonical">`. Never a 301 for anything slug-based — permanent
+ redirects outlive slug ownership.
+9. **Member logins are post-MVP**, but `grants(subject_type, subject_id)` already
+ models them. Adding member principals needs rows, not a migration.
+10. **PluralKit Dispatch is opt-in**, never required for claiming. A system has
+ only one webhook URL, so enabling ours overwrites any other integration —
+ this must be stated plainly in the UI.
+11. **Unclaiming**: 7-day slug reservation, 30-day configuration grace, reclaim
+ within the window restores everything.
+12. **Custom CSS is v1.1.** MVP ships token-based theming only. The origin split
+ (O1) is still built now so CSS drops in later without a URL migration.
+
+## Origins
+
+**O1. Which origin serves what.** Decided, permanent.
+
+| | Origin (beta) | Serves |
+|---|---|---|
+| Public / user content | `system.doughmination.gay` | `/`, `/docs`, `/s/<pk-id>`, `/s/<slug>`, `/s/<slug>/<member>` |
+| Application | `app.doughmination.gay` | `/login`, `/auth/...`, `/manage`, `/manage/...` |
+
+One rule underneath: anything rendering user-authored presentation goes on the
+public origin; anything reading or writing a session goes on the app origin.
+
+`/s/...` lives on the public origin **from day one**, even though MVP has no
+custom CSS. Those pages become user-authored presentation the moment v1.1 lands,
+and moving them then would break every public URL ever shared — the exact
+failure decision 8 exists to prevent. **The origin is therefore permanent.**
+
+The public origin is the website people encounter and share. The app origin is
+the private control surface behind it.
+
+**O2. `__Host-` cookie prefix is non-negotiable.** It forbids a `Domain`
+attribute, pinning the session cookie to exactly one host. That is the mechanism
+making a sibling public origin safe — not the subdomain naming. It also prevents
+cookie-tossing from the public side.
+
+**O3. `/` is permanently logged-out.** It must NEVER be session-aware. The `__Host-` cookie physically cannot reach the
+public origin, so these pages can never show "Signed in as …", "Your systems",
+"Go to your dashboard", personalised recommendations, or any account state.
+
+`/` carries an unconditional **Sign in** link to `<app origin>/login`. Any
+signed-in landing experience belongs at `/manage` on the app origin.
+
+Documentation is a separate site, so it carries no session either way.
+
+## Public routes
+
+All first-class, not afterthoughts. Split by origin per O1:
+
+- **Public origin** — `/` landing and about, `/s/...` public system and member
+ pages. **Documentation is a separate site** (`PUBLIC_DOCS_URL`) and is not
+ served by this application; an empty value hides the links entirely.
+- **App origin** — `/login`, `/auth/...` (OAuth is session-bearing by
+ definition, so it belongs here beside `/login`), `/manage/...`.
+
+## Beta
+
+- `X-Robots-Tag: noindex, nofollow` on every response while `BETA_MODE=true`.
+- Public viewing is never gated. **Claiming** is gated by
+ `BETA_ALLOWED_DISCORD_IDS`.
+- `SIGNUP_ENABLED` gates creating a *new* account only; existing testers can
+ always sign in.
+- Beta and production Discord redirect URIs are both registered ahead of the
+ domain move, so the cutover needs no flag day.
+- The old `/dispatch` endpoint stays alive across the move: PluralKit stores the
+ webhook URL on its side and may not follow redirects on POST.
+
+## Credentials
+
+**C1. No PluralKit token is ever persisted in MVP.** A PK token is full
+read/write — it can delete members. Tier-3 claim verification uses one within a
+single request and discards it.
+
+**C2. No feature may require a PluralKit token.** Tier 1 (Discord-linked account)
+and tier 2 (description challenge) both work without one.
+
+**C3. Authenticated responses never enter a public cache.** Enforced structurally
+by `auth_scope` in the `pk_snapshots` primary key, not by convention.
+
+**C4. Discord access tokens are discarded** immediately after the code exchange.
+We read the user id once and never call Discord again — no refresh tokens, no
+token table.
+
+## PluralKit
+
+**P1. One canonical User-Agent**, from config, non-overridable, pointing at the
+**repository** rather than the deployment origin so it survives the domain move.
+
+**P2. Limits are per-IP and our limiter is per-process.** Correct for a single
+API process. A second instance behind the same egress IP requires a shared
+limiter.
+
+**P3. PluralKit downtime must not take public pages down.** Stale-while-revalidate
+from `pk_snapshots`, with a visible "may be out of date" marker.
+
+## UI
+
+**U1. Bootstrap Icons via `react-bootstrap-icons`** is the standard icon set —
+navigation, settings, socials, status, actions, auth, editing, alerts, menus,
+chevrons, external links, privacy indicators, management. Named imports only
+(`import { Github } from "react-bootstrap-icons"`), never namespace imports, so
+it tree-shakes: the package sets `sideEffects: false` and ships an ESM entry.
+
+A bespoke icon is introduced only where no suitable Bootstrap Icon exists and the
+distinction matters to the product.
+
+**U2. Bootstrap Icons are the icon source only.** The visual design is pkviewer's
+own and does not adopt Bootstrap's styling.
+
+## Security invariants
+
+Properties the tests already demonstrate, written down so a later refactor
+cannot weaken one by accident. Each names the test that would catch its loss.
+
+**S1. The caller can never choose the identity used as proof of ownership.**
+Tier-1 verification reads Discord ids from the authenticated session and
+server-side account state only, never from request-controlled input. A request
+body naming a Discord id must never influence which identity is treated as
+proven. *Guarded by: "refuses when the system is not linked to the caller".*
+
+**S2. A description challenge is bound to the `(account, system)` pair that
+created it**, and can only be redeemed by that account. The lookup is keyed on
+both, so another account presenting a valid challenge id gets
+`challenge_not_found` — not a different error, and not a hint the challenge
+exists. *Guarded by: "another account cannot verify someone else's challenge".*
+
+**S3. Challenge verification never reads a cached description.** It fetches with
+`maxAgeMs: 0`, which is an unconditional cache bypass rather than "fresh within
+0ms". A stale copy must never prove ownership the user no longer holds.
+*Guarded by: "maxAgeMs 0 always refetches, even within the same millisecond" and
+"verification reads the description fresh, bypassing the cache".*
+
+**S4. A PluralKit token is never persisted, cached or logged.** Tier 3 uses one
+inside a single request and discards it. *Guarded by: "the token is never
+persisted", which dumps every row of every table and asserts the token appears
+nowhere.*
+
+**S5. At most one owner per subject, enforced by the database.** The partial
+unique index `idx_grants_single_owner` is the gate; the application-level check
+exists only for a clean error message. *Guarded by: "the single-owner index
+blocks a second owner row outright".*
+
+**S6. Refusals leak nothing about who holds a thing.** `already_claimed` never
+identifies the owner; a reserved slug reports only when the reservation lapses,
+never the holder. *Guarded by: "a reserved slug is refused to others, without
+naming the holder".*
+
+**S7. Discord snowflakes are not public pkviewer identifiers.** Public `/s/...`
+resolution must reject a Discord snowflake rather than resolving it to a system.
+
+The distinction is deliberate and must be preserved:
+
+- Discord ids MAY participate in authenticated ownership verification.
+- Tier-1 claiming takes the Discord identity from authenticated session and
+ account state, never from request input (see S1).
+- Public URL resolution must NEVER turn a Discord id into a browsable system
+ lookup.
+
+Without this, pkviewer would expose a Discord-account to PluralKit-system
+mapping through URL enumeration — a mapping PluralKit's API permits but which no
+public pkviewer URL should hand out by guessing. *Guarded by: "a Discord
+snowflake is refused as a public reference".*
+
+**S8. A private member is indistinguishable from one that never existed** — even
+when a pkviewer slug points at it. *Guarded by: "a slug pointing at a non-public
+member resolves to nothing".*
+
+**S9. The PluralKit UUID is the identity; the short id is mutable metadata.**
+Grants, slugs, reservations, foreign keys and cache keys are all keyed on the
+UUID. The short id is refreshed on claim because users can re-roll it, and is
+used only for display and lookup. It must never become an identity.
+
+**S10. Identity and navigation are separate.** A slug is a mutable presentation
+label. Changing one never changes what a system or member *is*, and never
+transfers anything.
+
+## Slugs
+
+**L1. System slugs may not take the shape of a PluralKit short id**
+(`[a-z]{5,6}`). System slugs and system ids share one global namespace at
+`/s/<ref>`, so an id-shaped slug could shadow another system's id URL — a URL
+its owner never gave up. Removing the shape from the namespace removes the
+ambiguity with no lookup required.
+
+**Member slugs are deliberately not restricted this way.** They are namespaced
+per system, so a collision can only shadow a member of a system the claimant
+already controls: self-inflicted, not an attack. Claiming one warns
+(`shadows_member_id`) rather than refusing, which keeps ordinary names like
+`clove` available where people actually want them.
+
+**L1b. A slug must not contain `--` anywhere.** Stated as the literal substring
+rather than "no consecutive hyphens", so every validator enforces exactly the
+same rule. The purpose is to keep the punycode marker `xn--` unclaimable, so
+slugs stay safe to place in a hostname if per-system subdomains ever happen.
+
+**L2. `SLUG_MAX_LENGTH` is 32, below a UUID's 36.** This guarantees no slug can
+ever shadow `/s/<uuid>`, so every system keeps one permanently unambiguous URL
+no matter what anyone claims. Raising this limit past 35 would break that.
+
+**L3. Resolution is slug first, then id**, and neither redirects — both return
+200 and the canonical form is advertised with `<link rel="canonical">`. A 301
+would outlive slug ownership and permanently point a cached URL at whoever holds
+the name next.
+
+**L4. A subject holds at most one active slug per scope.** Claiming a new one
+releases the previous into its own 7-day reservation rather than freeing it, so
+a rename cannot be used to snipe the old URL and the owner can change their mind.
+
+**L5. Reservations follow the subject, not the account.** A different account
+managing the same system can reclaim a slug that system released.
+
+## Unclaiming
+
+**Unclaiming removes management access. Reclaiming within the grace period
+restores the saved configuration, but does not restore previous manager
+grants.** Every grant is deleted on unclaim, not just the owner's — an unclaimed
+system genuinely has no managers. The 30-day grace window restores themes and
+reserved slugs; anyone who was previously a manager must be re-invited.
+
+## Theme vocabulary
+
+The product's public design API. Locked in step 8; changing it is a product
+decision, not a refactor. Lives in `packages/shared/src/theme/`.
+
+**T1. Theme is how things look. Composition is what appears and how it is
+arranged.** A knob that changes which information is on the page, or where it
+sits, is composition. A knob that changes the appearance of whatever is there is
+a theme token. This is why `directory.columns` is composition and `shape.radius`
+is a token — and why `directory.card.min` never became a token at all: the
+renderer needed a pixel value, but the product concept is "how many columns".
+
+**T2. Named options, never free values.** A user picks `relaxed`, not `1.3`.
+Every enum maps to concrete CSS in exactly one function, so the scale can be
+retuned later without invalidating a single stored theme. This is what keeps the
+product from being "CSS custom properties with a UI".
+
+**T3. Colour is six-digit hex only.** Not `rgb()`, not `color-mix()`, not named
+colours, not three-digit hex. One shape is trivial to validate, trivial to put
+behind a colour picker, and leaves no room for a function call to smuggle
+something through.
+
+**T4. Fonts come from a fixed table of eight**, each either the system stack or
+a Google Fonts family. A font token carries an id, never a family name and never
+a URL, so a theme can never point the browser at a resource we did not choose.
+
+**T5. One colour value per token, not one per scheme.** The platform default
+carries both light and dark grounds; a custom colour applies to whichever ground
+is active. Doubling the vocabulary to carry two of every colour would be the
+wrong trade for a non-technical editor.
+
+### Theme tokens (14)
+
+| Key | Type | Default | Member |
+|---|---|---|---|
+| `color.scheme` | enum auto/light/dark | `auto` | no |
+| `color.page` | color | `#FAF8FB` / `#151219` | yes |
+| `color.surface` | color | `#FFFFFF` / `#1E1A24` | yes |
+| `color.text` | color | `#1C1721` / `#EEEAF2` | yes |
+| `color.muted` | color | `#6B6478` / `#9A93A6` | yes |
+| `color.accent` | color | `#A23B72` / `#F58FC2` | yes |
+| `color.border` | color | `#E6E1EC` / `#302938` | yes |
+| `font.body` | font | `system` | yes |
+| `font.heading` | font | `newsreader` | yes |
+| `font.size` | enum small/medium/large | `medium` | yes |
+| `shape.radius` | enum none/small/medium/large | `medium` | yes |
+| `surface.style` | enum outlined/filled/plain | `outlined` | yes |
+| `density` | enum compact/normal/relaxed | `normal` | yes |
+| `avatar.shape` | enum circle/rounded/square | `rounded` | yes |
+
+`color.scheme` is the only system-only token. It is a property of the SITE: a
+member page flipping to dark while the system page is light reads as broken
+navigation rather than personal expression. Everything else is member
+overridable, because a member page being visually its own thing is the point.
+
+### Composition configuration (7)
+
+Separate vocabulary, separate storage, not CSS custom properties.
+
+| Key | Type | Default | Member |
+|---|---|---|---|
+| `banner.display` | enum auto/hidden | `auto` | yes |
+| `avatar.size` | enum small/medium/large | `medium` | yes |
+| `directory.columns` | enum auto/one/two/three | `auto` | no |
+| `directory.card` | enum compact/detailed | `compact` | no |
+| `directory.sort` | enum pluralkit/name | `pluralkit` | no |
+| `show.pronouns` | boolean | `true` | yes |
+| `show.birthday` | boolean | `true` | yes |
+
+Directory settings are system-only: the directory belongs to the system page,
+so a member has nothing to override there.
+
+### The `length` and `boolean` types
+
+Both are implemented and tested in the validation layer. No MVP theme token uses
+`length` — every dimension is a named option instead, which is what keeps
+arbitrary values out. Tokens were not invented merely to exercise a type.
+
+### Presets (5)
+
+Applied by copying values into a system theme, so a preset is a starting point
+rather than a mode: everything stays editable, and a preset can be retuned later
+without silently changing anyone's page.
+
+- **Notebook** — the default, refined. Warm off-white, serif headings, soft
+ outlined cards, normal density.
+- **Broadsheet** — editorial and dense. Display serif, square corners, hairline
+ rules instead of cards, compact.
+- **Bloom** — soft and friendly. Rounded typeface, large radius, filled cards,
+ circular avatars, relaxed.
+- **Terminal** — deliberately technical. Monospaced, near-black, square, no card
+ decoration, compact.
+- **Midnight** — modern dark. Geometric headings, filled cards, soft corners.
+
+They differ in typeface, corner treatment, card style, density and ground — a
+test asserts that, so five colour swaps could not pass for five presets.
+
+### Inheritance
+
+`platform default -> system theme -> member override`, with the three states
+already locked: absent inherits, a value overrides, and an explicit `null` resets
+to the platform default while ignoring the system. That third state is what lets
+a member escape a loud system theme without restating every default by hand.
+
+Member-overridability is enforced in validation, not merely ignored at render, so
+an editor can say why something was refused.
+
+## Management plane
+
+**M1. The server is authoritative for authorization.** Every management read and
+write re-checks the grant server-side. The client can ask about any system id it
+likes; it is told 404 for every one it does not manage.
+
+**M2. Unauthorised access reports 404, never 403.** A 403 would confirm the
+system exists on pkviewer, which an unauthorised caller should not be able to
+probe for.
+
+**M3. A save is all or nothing.** If any value in a save is rejected, nothing is
+written. Dropping the invalid keys and saving the rest would silently discard
+settings the user already had — a destructive save wearing the costume of a
+validation error. *Guarded by: "a rejected save leaves existing settings
+untouched".*
+
+**M4. Theme and composition are written independently.** A save names the layer
+it touches, so saving appearance can never wipe directory settings. *Guarded by:
+"saving one layer leaves the other untouched".*
+
+**M5. The management UI does not reveal private members.** It lists the members
+PluralKit returns publicly, from the same public request the public site makes.
+Being signed in as the owner does not change what the public API returns and
+pkviewer does not ask for more, so a private member is absent here and 404s
+individually. *Guarded by: "a member PluralKit withholds is absent, and 404s
+individually".*
+
+**M6. The management app has its own visual language.** It never inherits the
+user's public theme: it must look the same whichever system you are editing. Its
+custom properties are namespaced `--mg-*` so they cannot collide with the
+`--pkv-*` tokens a preview renders with.
+
+**M7. One source of truth for how a token becomes a style.** The editor's
+preview calls the same `resolveTheme` and `themeToCssVars` the public renderer
+does. Only the sample content is local to the editor.
+
+**M8. The browser never talks to the API directly.** Server components and
+server actions forward the session cookie, so `INTERNAL_API_ORIGIN` stays
+internal and the `__Host-` cookie's host pinning is never loosened to permit a
+cross-origin call.
+
+**M9. Inheritance is UI, not data the user authors.** Nobody types `null`,
+deletes a field, or edits JSON. A control is either following what it inherits
+or explicitly set, with buttons to move between those states. Inherited versus
+overridden is shown by a word and a border, never by colour alone.
+
+**M10. Applying a preset at member level is an explicit member configuration.**
+It never reaches up and changes the system.
+
+## Public addresses
+
+The public URL is a product feature, not an implementation detail. "Slug" is
+internal vocabulary; the UI says **address** throughout.
+
+**U3. A chosen address is never required for a page to be public.** A claimed
+system is reachable at its PluralKit ID address from the moment it is claimed. A
+chosen address only makes the link friendlier to share, and the ID address keeps
+working afterwards. The no-address state says so plainly rather than reading as
+an incomplete setup.
+
+**U4. Copying is never the only way to get an address.** Every public URL is
+shown as selectable text and offered as an ordinary link alongside the copy
+button, so it works without JavaScript, without clipboard permission, and for
+anyone who would rather select it by hand. Copy success is announced in words
+through a live region, never signalled by colour alone.
+
+**U5. Availability checks are advisory.** The client checks as you type purely
+for immediate feedback; the claim path re-checks transactionally, because
+availability can change between the two. The server's answer is the only one
+that counts.
+
+**U6. A held address never names its holder.** A conflict reports only that the
+address is held and when the hold lapses. Neither the holding system nor its
+managers appear anywhere in the response.
+
+**U7. Changing an address breaks links to the old one.** The old address enters
+its 7-day hold immediately and stops resolving; it is not redirected, because a
+redirect would outlive ownership. The UI says this before the change, not after.
+
+## Audit findings (step 11)
+
+**A4. Nothing may be statically prerendered if it embeds a configured origin.**
+Prerendering bakes the BUILD-TIME origin into the HTML, so the beta-to-production
+move would need a rebuild rather than an env change — which is precisely what
+decision 1 forbids. `/`, `/docs` and the not-found page are therefore
+`force-dynamic`. Verified by building with one origin and serving with another.
+
+**A5. A visibility setting removes the value, it does not hide it.** `show.pronouns`
+and `show.birthday` strip the field in the page model rather than omitting it in
+markup, so a hidden value is not shipped in the page source at all. This is
+public PluralKit data either way, but a setting should do what it says.
+
+**A6. The three inheritance states must survive storage.** A reset is stored as
+an explicit null; reading a layer through a string-only filter collapsed three
+states into two and made "use the platform default" land on the system's value.
+Stored layers are read as `Record<string, string | null>`.
+
+**A7. Staleness is measured against the reference that was actually fetched.**
+A slug resolves through the stored UUID and an id through the id itself, so
+asking "how old is this data" under a guessed key silently missed for id-based
+URLs. `ResolvedSystem.cacheRef` carries the key that was used.
+
+**A8. Audit breadcrumbs must not block account deletion.** `grants.granted_by`
+and `themes.updated_by` record who did something; they are not ownership. Left
+without an `ON DELETE` rule they defaulted to RESTRICT, so deleting an account
+that had ever granted a role or saved a theme failed outright — and account
+deletion is a stated requirement. Both are now `ON DELETE SET NULL`
+(migration 004). *Guarded by: "an account that has granted a role and saved a
+theme can be deleted".*
+
+### Known limitation
+
+`notFound()` called under a layout that has already streamed renders the correct
+page but does not set a 404 status, so unauthorised `/manage/<id>` returns 200
+with the right content. Confirmed in both dev and production builds. The content
+is correct and discloses nothing — a system that does not exist and one that
+belongs to someone else are indistinguishable — and every management page is
+`noindex`. Worth revisiting if it ever matters for monitoring.
+
+## Guardrails
+
+No user JavaScript, ever. No arbitrary HTML. No custom CSS in MVP. No
+server-side fetching of user-supplied URLs (SSRF) — social links are rendered as
+links and never fetched for previews or favicons. Public pages show only what
+PluralKit makes public. Fonts come from a fixed allow-list; no arbitrary font
+URLs or uploads.
diff --git a/docs/deployment.md b/docs/deployment.md
new file mode 100644
index 0000000..7905256
--- /dev/null
+++ b/docs/deployment.md
@@ -0,0 +1,195 @@
+# Deploying pkviewer
+
+## Shape
+
+Two processes on one machine, behind a reverse proxy that terminates TLS:
+
+```
+ ┌──────────────────────────────┐
+ public ────┤ proxy │
+ app ────┤ routes both hostnames │
+ └──────────────┬───────────────┘
+ │
+ apps/web (Node) :3000
+ │ localhost HTTP
+ apps/api (Bun) :3001
+ │
+ SQLite file on a persistent disk
+```
+
+Both hostnames point at the same Next process; middleware decides which routes
+each may answer, from the `Host` header.
+
+**This cannot run on a serverless platform.** SQLite needs a persistent disk and
+a single long-lived writer. A small VPS, or a container with a real volume.
+
+Only the web tier should be reachable from the internet. The API listens on
+localhost and is not exposed.
+
+## Environment variables
+
+`.env` lives at the repository root and is read by both tiers.
+
+Legend: **required** = the process refuses to start without it ·
+**production** = additionally required when `NODE_ENV=production` ·
+*secret* = never commit, never log, never send to the browser.
+
+### Origins — required
+
+| Variable | Consumed by | Notes |
+|---|---|---|
+| `PUBLIC_APP_ORIGIN` | api, web | Session-bearing origin. `/login`, `/auth`, `/manage`. Must be https in production. |
+| `PUBLIC_USERCONTENT_ORIGIN` | api, web | Public, shareable origin. `/` and `/s/...`. **Must differ from the app origin in every environment, including development** — the process refuses to start otherwise. |
+| `PUBLIC_ASSET_ORIGIN` | api | May equal the public origin. |
+| `INTERNAL_API_ORIGIN` | web | Where the web tier reaches the API. Internal; never reaches the browser. |
+| `PUBLIC_DOCS_URL` | web | *Optional.* The separate documentation site. Empty hides every documentation link rather than producing a dead one. |
+
+These are read at **runtime**, not baked into the build. A domain move is a
+config change plus a restart, not a rebuild — every page that embeds an origin
+is `force-dynamic` specifically to keep that true.
+
+### PluralKit — one required
+
+| Variable | Required | Notes |
+|---|---|---|
+| `PK_USER_AGENT_CONTACT` | **required** | URL placed in the `User-Agent`. **Point it at the repository, not the deployment origin**, so it survives a domain move. PluralKit asks that an application's UA be stable and identifiable. |
+| `PK_API_BASE` | optional | Defaults to `https://api.pluralkit.me/v2`. |
+| `PK_RATE_LIMIT_READ_RPS` | optional | Default 6, deliberately under PluralKit's documented 10/s. |
+| `PK_RATE_LIMIT_WRITE_RPS` | optional | Default 2, under their 3/s. |
+
+### Sessions and Discord
+
+| Variable | Required | Notes |
+|---|---|---|
+| `SESSION_SECRET` *secret* | **production** | ≥32 chars. `openssl rand -base64 32`. Outside production an ephemeral one is generated per start, with a warning. |
+| `DISCORD_CLIENT_ID` | **production** | From the Discord developer portal. |
+| `DISCORD_CLIENT_SECRET` *secret* | **production** | Same. |
+| `DISCORD_REDIRECT_URIS` | **production** | Comma-separated. **Register the beta and production URIs together** so the domain move is a cutover, not a flag day. Each must be `<app origin>/auth/discord/callback` and registered identically in Discord. |
+
+Without Discord credentials the app still runs and every public page works —
+nobody can sign in. That is a legitimate read-only deployment.
+
+### Database
+
+| Variable | Required | Notes |
+|---|---|---|
+| `DATABASE_PATH` | optional | Default `./data/pkviewer.db`. **Relative paths resolve against the API process's working directory**, which is `apps/api` under `bun run dev` — so the dev database is at `apps/api/data/pkviewer.db`. **Use an absolute path in production.** |
+
+### Beta flags
+
+| Variable | Default | Notes |
+|---|---|---|
+| `BETA_MODE` | `false` | When true: `noindex` on everything, and claiming is limited to the allow-list. |
+| `SIGNUP_ENABLED` | `false` | Gates creating a **new** account only. Turning it off never locks existing testers out. |
+| `BETA_ALLOWED_DISCORD_IDS` | empty | Comma-separated Discord user IDs permitted to claim a system while in beta. **Empty means nobody can claim.** |
+| `API_PORT` | `3001` | |
+| `NODE_ENV` | `development` | `production` turns on the stricter checks above. |
+
+### Minimum production set
+
+```
+NODE_ENV=production
+PUBLIC_APP_ORIGIN=https://app.example
+PUBLIC_USERCONTENT_ORIGIN=https://public.example
+PUBLIC_ASSET_ORIGIN=https://public.example
+INTERNAL_API_ORIGIN=http://127.0.0.1:3001
+DATABASE_PATH=/var/lib/pkviewer/pkviewer.db
+PK_USER_AGENT_CONTACT=https://github.com/OWNER/pkviewer
+PUBLIC_DOCS_URL=https://docs.example
+SESSION_SECRET=<openssl rand -base64 32>
+DISCORD_CLIENT_ID=<from Discord>
+DISCORD_CLIENT_SECRET=<from Discord>
+DISCORD_REDIRECT_URIS=https://app.example/auth/discord/callback
+BETA_MODE=true
+SIGNUP_ENABLED=true
+BETA_ALLOWED_DISCORD_IDS=<your Discord user id>
+```
+
+Configuration is validated at startup and a missing or malformed value fails
+loudly, naming the variable. It never falls back to an insecure default in
+production.
+
+## Database
+
+One SQLite file, in WAL mode. Migrations apply automatically at API start, in
+filename order, each in its own transaction; already-applied ones are skipped.
+
+Schema changes are additive: **add a new migration, never edit an applied one.**
+
+### What to back up
+
+| | |
+|---|---|
+| `DATABASE_PATH` | The database. Everything pkviewer owns. |
+| `<path>-wal`, `<path>-shm` | Sidecars. Present while running; a copy without them can be inconsistent. |
+| `.env` | Secrets. **Back up separately from the database, not alongside it.** |
+
+**Never `cp` a live database.** WAL means a plain copy can be torn. Take a
+consistent snapshot while running with:
+
+```bash
+sqlite3 /var/lib/pkviewer/pkviewer.db ".backup '/backups/pkviewer-$(date +%F).db'"
+```
+
+or `VACUUM INTO`. Both are safe against a running server. For continuous
+protection, [Litestream](https://litestream.io) replicates WAL to object storage
+and preserves the "it's just a file" model — the highest-value addition when this
+carries other people's data.
+
+### If the database is lost
+
+PluralKit data is not lost — it is PluralKit's, and re-fetches. What is lost is
+everything pkviewer owns: accounts and their Discord links, which systems are
+claimed and by whom, chosen addresses and their reservations, themes, layout
+settings, and social links.
+
+Public pages would keep working for systems reachable by PluralKit ID; chosen
+addresses would stop resolving and would become claimable by anyone. Claiming
+would have to be redone. **Treat the database as the thing that actually needs
+backing up.**
+
+## Deploying a change
+
+```bash
+bun install
+bun run check # guard, typecheck, tests
+bun run build
+# restart both processes; migrations run on API start
+```
+
+Migrations are forward-only. Test them against a copy of production data before
+deploying a schema change.
+
+The production build writes to `.next-prod` and the dev server uses `.next`, so
+building never disturbs a running development server. `NEXT_DIST_DIR` overrides
+the directory if a deployment needs it elsewhere.
+
+## Moving domains
+
+Under the rules above this is configuration, with two things that are not free:
+
+1. **Sessions end.** Cookies are host-scoped; everyone signs in again.
+2. **PluralKit dispatch webhooks break silently** if that integration is ever
+ enabled — the URL lives on PluralKit's side. Keep the old host answering
+ `/dispatch` through the transition; do not rely on a redirect.
+
+Register both redirect URIs in Discord before the move, and keep the old host
+redirecting for a long while.
+
+## Security posture
+
+Set by the web tier, since the browser never talks to the API directly:
+`Content-Security-Policy` (including `frame-ancestors 'none'`),
+`X-Content-Type-Options`, `Referrer-Policy`, `X-Frame-Options`,
+`Permissions-Policy`, `Cross-Origin-Opener-Policy`, and `Strict-Transport-Security`
+in production.
+
+Two deliberate CSP exceptions, both documented in `apps/web/next.config.ts`:
+`script-src` allows `'unsafe-inline'` because Next bootstraps through inline
+scripts and tightening it needs per-request nonces; `img-src` allows any https
+host because avatars and banners live wherever each system put them. Neither is
+load-bearing for XSS, because pkviewer accepts no user HTML, no user JavaScript
+and no free-form CSS.
+
+TLS is terminated at the proxy. Cookies are `Secure` and `__Host-` prefixed, so
+**the app must be served over https in production or sign-in will not work.**
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..b55feeb
--- /dev/null
+++ b/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "pkviewer",
+ "private": true,
+ "type": "module",
+ "workspaces": [
+ "apps/*",
+ "packages/*"
+ ],
+ "scripts": {
+ "dev:api": "bun run --cwd apps/api dev",
+ "migrate": "bun run --cwd apps/api migrate",
+ "test": "bun test",
+ "typecheck": "bun run --cwd apps/api typecheck && bun run --cwd packages/shared typecheck && bun run --cwd apps/web typecheck",
+ "check:domain": "bash scripts/check-no-hardcoded-origin.sh",
+ "check": "bun run check:domain && bun run typecheck && bun test",
+ "dev": "bun run scripts/dev.ts",
+ "dev:web": "bun run --cwd apps/web dev",
+ "build": "bun run --cwd apps/web build"
+ },
+ "devDependencies": {
+ "@types/bun": "latest",
+ "typescript": "^5.6.0"
+ }
+}
diff --git a/packages/shared/package.json b/packages/shared/package.json
new file mode 100644
index 0000000..32b041c
--- /dev/null
+++ b/packages/shared/package.json
@@ -0,0 +1,9 @@
+{
+ "name": "@pkviewer/shared",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "main": "src/index.ts",
+ "exports": { ".": "./src/index.ts" },
+ "scripts": { "typecheck": "tsc -p tsconfig.json" }
+}
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
new file mode 100644
index 0000000..4407c22
--- /dev/null
+++ b/packages/shared/src/index.ts
@@ -0,0 +1,69 @@
+/**
+ * Types shared between the API and the web tier.
+ *
+ * Nothing here may import from the API's database or PluralKit modules: the web
+ * tier consumes these types and reaches the API over HTTP, never the database
+ * directly. That rule is what keeps the two-process split from decaying into
+ * two backends.
+ */
+
+/** A resolved public view of a system, as the web tier receives it. */
+export type SystemView = {
+ /** PluralKit HID, the stable identity in URLs. */
+ hid: string;
+ /** pkviewer slug, when one is claimed. Canonical for display. */
+ slug: string | null;
+ name: string | null;
+ description: string | null;
+ tag: string | null;
+ pronouns: string | null;
+ avatarUrl: string | null;
+ bannerUrl: string | null;
+ color: string | null;
+ memberCount: number;
+ claimed: boolean;
+ /** Set when served from a snapshot older than the freshness window. */
+ staleSinceMs: number | null;
+};
+
+export type MemberView = {
+ hid: string;
+ slug: string | null;
+ systemHid: string;
+ systemSlug: string | null;
+ name: string | null;
+ displayName: string | null;
+ description: string | null;
+ pronouns: string | null;
+ avatarUrl: string | null;
+ bannerUrl: string | null;
+ color: string | null;
+ birthday: string | null;
+};
+
+export type SocialLink = {
+ platform: string;
+ label: string | null;
+ url: string;
+};
+
+/** Resolved theme tokens, flat and dotted, ready to become CSS custom properties. */
+export type ResolvedTokens = Readonly<Record<string, string>>;
+
+export * from "./theme/index.ts";
+export * from "./social.ts";
+
+export type PageModel = {
+ system: SystemView;
+ member: MemberView | null;
+ members: MemberView[];
+ socials: SocialLink[];
+ tokens: ResolvedTokens;
+ /**
+ * Resolved composition: what appears on the page and how it is arranged.
+ * Separate from tokens throughout, and never turned into CSS properties by
+ * the renderer except for the two layout values that genuinely are lengths.
+ */
+ composition: Readonly<Record<string, string>>;
+ beta: boolean;
+};
diff --git a/packages/shared/src/social.ts b/packages/shared/src/social.ts
new file mode 100644
index 0000000..816f89f
--- /dev/null
+++ b/packages/shared/src/social.ts
@@ -0,0 +1,79 @@
+/**
+ * Social link platforms.
+ *
+ * A fixed list plus a "custom" escape hatch. The platform is a label and an
+ * icon choice — it never causes pkviewer to contact the linked service.
+ *
+ * Links are rendered as links and nothing more: no server-side fetching, no
+ * preview cards, no favicon lookups. Fetching a user-supplied URL from our
+ * server is an SSRF vector, and the guardrails rule it out entirely.
+ */
+
+export type SocialPlatformId =
+ | "website"
+ | "discord"
+ | "github"
+ | "mastodon"
+ | "bluesky"
+ | "tumblr"
+ | "twitch"
+ | "youtube"
+ | "custom";
+
+export type SocialPlatform = {
+ id: SocialPlatformId;
+ label: string;
+ /** Placeholder shown in the editor. Illustrative only, never fetched. */
+ placeholder: string;
+};
+
+export const SOCIAL_PLATFORMS: readonly SocialPlatform[] = [
+ { id: "website", label: "Website", placeholder: "https://example.com" },
+ { id: "discord", label: "Discord", placeholder: "https://discord.gg/..." },
+ { id: "github", label: "GitHub", placeholder: "https://github.com/..." },
+ { id: "mastodon", label: "Mastodon", placeholder: "https://mastodon.social/@..." },
+ { id: "bluesky", label: "Bluesky", placeholder: "https://bsky.app/profile/..." },
+ { id: "tumblr", label: "Tumblr", placeholder: "https://example.tumblr.com" },
+ { id: "twitch", label: "Twitch", placeholder: "https://twitch.tv/..." },
+ { id: "youtube", label: "YouTube", placeholder: "https://youtube.com/@..." },
+ { id: "custom", label: "Other", placeholder: "https://..." },
+];
+
+export const SOCIAL_PLATFORM_IDS: readonly string[] = SOCIAL_PLATFORMS.map((p) => p.id);
+
+export const MAX_SOCIAL_LINKS = 12;
+export const MAX_SOCIAL_URL_LENGTH = 500;
+export const MAX_SOCIAL_LABEL_LENGTH = 60;
+
+export type SocialUrlFailure = "empty" | "too_long" | "not_a_url" | "unsupported_scheme";
+
+/**
+ * Validates a social URL.
+ *
+ * Only http and https. `javascript:` and `data:` are the reason this exists —
+ * a link rendered into an href is an XSS vector if any scheme is permitted.
+ */
+export function validateSocialUrl(raw: unknown): { ok: true; url: string } | { ok: false; reason: SocialUrlFailure } {
+ if (typeof raw !== "string") return { ok: false, reason: "not_a_url" };
+ const value = raw.trim();
+ if (value.length === 0) return { ok: false, reason: "empty" };
+ if (value.length > MAX_SOCIAL_URL_LENGTH) return { ok: false, reason: "too_long" };
+
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return { ok: false, reason: "not_a_url" };
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ return { ok: false, reason: "unsupported_scheme" };
+ }
+ return { ok: true, url: url.toString() };
+}
+
+export const SOCIAL_URL_MESSAGES: Readonly<Record<SocialUrlFailure, string>> = {
+ empty: "Enter a link.",
+ too_long: "That link is too long.",
+ not_a_url: "That does not look like a web address.",
+ unsupported_scheme: "Links must start with http:// or https://",
+};
diff --git a/packages/shared/src/theme/index.ts b/packages/shared/src/theme/index.ts
new file mode 100644
index 0000000..0c2c487
--- /dev/null
+++ b/packages/shared/src/theme/index.ts
@@ -0,0 +1,4 @@
+export * from "./vocabulary.ts";
+export * from "./validate.ts";
+export * from "./resolve.ts";
+export * from "./presets.ts";
diff --git a/packages/shared/src/theme/presets.ts b/packages/shared/src/theme/presets.ts
new file mode 100644
index 0000000..661d932
--- /dev/null
+++ b/packages/shared/src/theme/presets.ts
@@ -0,0 +1,142 @@
+/**
+ * Shipped presets.
+ *
+ * One click, five genuinely different directions. They differ in typeface,
+ * corner treatment, card style, density and ground — not in accent colour
+ * alone, which would only prove the vocabulary can hold five hex values.
+ *
+ * A preset is applied by copying its values into a system theme, so it is a
+ * starting point rather than a mode: everything stays editable afterwards, and
+ * a preset can be retuned later without silently changing anyone's page.
+ */
+
+export type Preset = {
+ id: string;
+ name: string;
+ /** Product-facing description of the visual character. */
+ character: string;
+ tokens: Record<string, string>;
+};
+
+export const PRESETS: readonly Preset[] = [
+ {
+ id: "notebook",
+ name: "Notebook",
+ character:
+ "The default, and the quietest. Warm off-white paper, a serif for names, " +
+ "soft outlined cards and room to breathe. Gets out of the way of whatever " +
+ "you put on it.",
+ tokens: {
+ "color.scheme": "auto",
+ "color.page": "#FAF8FB",
+ "color.surface": "#FFFFFF",
+ "color.text": "#1C1721",
+ "color.muted": "#6B6478",
+ "color.accent": "#A23B72",
+ "color.border": "#E6E1EC",
+ "font.body": "system",
+ "font.heading": "newsreader",
+ "font.size": "medium",
+ "shape.radius": "medium",
+ "surface.style": "outlined",
+ density: "normal",
+ "avatar.shape": "rounded",
+ },
+ },
+ {
+ id: "broadsheet",
+ name: "Broadsheet",
+ character:
+ "Editorial and dense. High-contrast ink on paper, an expressive display " +
+ "serif, square corners and hairline rules instead of cards. Reads like " +
+ "something printed.",
+ tokens: {
+ "color.scheme": "light",
+ "color.page": "#FFFDF8",
+ "color.surface": "#FFFDF8",
+ "color.text": "#141210",
+ "color.muted": "#5F5A52",
+ "color.accent": "#8C2F1E",
+ "color.border": "#D6D0C4",
+ "font.body": "newsreader",
+ "font.heading": "fraunces",
+ "font.size": "medium",
+ "shape.radius": "none",
+ "surface.style": "plain",
+ density: "compact",
+ "avatar.shape": "square",
+ },
+ },
+ {
+ id: "bloom",
+ name: "Bloom",
+ character:
+ "Soft and friendly. Rounded typeface throughout, generous corners, filled " +
+ "cards with no outlines, circular avatars and plenty of space. The " +
+ "gentlest of the set.",
+ tokens: {
+ "color.scheme": "light",
+ "color.page": "#FDF6F8",
+ "color.surface": "#FFFFFF",
+ "color.text": "#33232B",
+ "color.muted": "#7C6670",
+ "color.accent": "#C4547F",
+ "color.border": "#F0DCE4",
+ "font.body": "nunito",
+ "font.heading": "nunito",
+ "font.size": "medium",
+ "shape.radius": "large",
+ "surface.style": "filled",
+ density: "relaxed",
+ "avatar.shape": "circle",
+ },
+ },
+ {
+ id: "terminal",
+ name: "Terminal",
+ character:
+ "Deliberately technical. Monospaced throughout, near-black ground, square " +
+ "corners and no card decoration at all. Everything aligns to a grid.",
+ tokens: {
+ "color.scheme": "dark",
+ "color.page": "#0E0F12",
+ "color.surface": "#14161A",
+ "color.text": "#D9DEE4",
+ "color.muted": "#7C8794",
+ "color.accent": "#5FD3A6",
+ "color.border": "#242830",
+ "font.body": "jetbrains-mono",
+ "font.heading": "jetbrains-mono",
+ "font.size": "small",
+ "shape.radius": "none",
+ "surface.style": "plain",
+ density: "compact",
+ "avatar.shape": "square",
+ },
+ },
+ {
+ id: "midnight",
+ name: "Midnight",
+ character:
+ "Modern dark. Geometric headings on a deep blue-grey, filled cards with " +
+ "soft corners and a cool accent. Comfortable to read at night.",
+ tokens: {
+ "color.scheme": "dark",
+ "color.page": "#12141C",
+ "color.surface": "#1B1E29",
+ "color.text": "#E8E9F0",
+ "color.muted": "#959AB0",
+ "color.accent": "#8AB4F8",
+ "color.border": "#2A2E3D",
+ "font.body": "inter",
+ "font.heading": "space-grotesk",
+ "font.size": "medium",
+ "shape.radius": "medium",
+ "surface.style": "filled",
+ density: "normal",
+ "avatar.shape": "rounded",
+ },
+ },
+];
+
+export const PRESET_MAP: ReadonlyMap<string, Preset> = new Map(PRESETS.map((p) => [p.id, p]));
diff --git a/packages/shared/src/theme/resolve.ts b/packages/shared/src/theme/resolve.ts
new file mode 100644
index 0000000..45ce171
--- /dev/null
+++ b/packages/shared/src/theme/resolve.ts
@@ -0,0 +1,248 @@
+import { sanitizeComposition, sanitizeTheme } from "./validate.ts";
+import {
+ COMPOSITION,
+ FONTS,
+ THEME_TOKENS,
+ type FontEntry,
+ type FontId,
+ type TokenDef,
+} from "./vocabulary.ts";
+
+/**
+ * Inheritance and CSS mapping.
+ *
+ * platform default -> system theme -> member override
+ *
+ * key absent inherit
+ * key = value override
+ * key = null reset to the platform default, ignoring the system
+ *
+ * The three-state model lives here and nowhere else.
+ */
+
+export type Scheme = "light" | "dark";
+
+export type ResolvedTheme = {
+ /** Every declared token, with a value, for each scheme. */
+ light: Record<string, string>;
+ dark: Record<string, string>;
+ /** What the system chose: follow the device, or commit to one ground. */
+ scheme: "auto" | "light" | "dark";
+ /** Families the page must load, derived from the resolved fonts. */
+ fonts: FontEntry[];
+};
+
+export type ResolvedComposition = Record<string, string>;
+
+function defaultFor(def: TokenDef, scheme: Scheme): string {
+ switch (def.type) {
+ case "color":
+ return def.default[scheme];
+ case "boolean":
+ return def.default ? "true" : "false";
+ default:
+ return def.default;
+ }
+}
+
+/**
+ * Resolves theme layers into complete per-scheme value maps.
+ *
+ * Both a light and a dark map always come back. When the scheme is `auto` the
+ * renderer emits both and lets `prefers-color-scheme` choose; when it is
+ * committed, only one is used. Custom colours apply to whichever ground is
+ * active — the vocabulary does not double in size to carry two of every colour,
+ * which would be the wrong trade for a non-technical editor.
+ */
+export function resolveTheme(
+ systemRaw: unknown,
+ memberRaw: unknown = null,
+): ResolvedTheme {
+ const system = sanitizeTheme(systemRaw, { level: "system" });
+ const member = sanitizeTheme(memberRaw, { level: "member" });
+
+ const build = (scheme: Scheme): Record<string, string> => {
+ const out: Record<string, string> = {};
+ for (const def of THEME_TOKENS) {
+ const platform = defaultFor(def, scheme);
+
+ // A member reset ignores the system layer entirely and lands on the
+ // platform default. That is the whole point of the third state: escaping
+ // a loud system theme should not require restating every default.
+ if (member.resets.includes(def.key)) {
+ out[def.key] = platform;
+ continue;
+ }
+
+ const memberValue = member.values[def.key];
+ if (memberValue !== undefined && def.memberOverridable) {
+ out[def.key] = memberValue;
+ continue;
+ }
+
+ out[def.key] = system.values[def.key] ?? platform;
+ }
+ return out;
+ };
+
+ const light = build("light");
+ const dark = build("dark");
+
+ const schemeValue = (light["color.scheme"] ?? "auto") as "auto" | "light" | "dark";
+
+ const fontIds = new Set<FontId>();
+ for (const key of ["font.body", "font.heading"]) {
+ const id = light[key] as FontId | undefined;
+ if (id && Object.hasOwn(FONTS, id)) fontIds.add(id);
+ }
+
+ return {
+ light,
+ dark,
+ scheme: schemeValue,
+ fonts: [...fontIds].map((id) => FONTS[id]).filter((f) => f.family !== null),
+ };
+}
+
+export function resolveComposition(
+ systemRaw: unknown,
+ memberRaw: unknown = null,
+): ResolvedComposition {
+ const system = sanitizeComposition(systemRaw, { level: "system" });
+ const member = sanitizeComposition(memberRaw, { level: "member" });
+
+ const out: ResolvedComposition = {};
+ for (const def of COMPOSITION) {
+ const platform = def.type === "boolean" ? (def.default ? "true" : "false") : def.default;
+
+ if (member.resets.includes(def.key)) {
+ out[def.key] = platform;
+ continue;
+ }
+ const memberValue = member.values[def.key];
+ if (memberValue !== undefined && def.memberOverridable) {
+ out[def.key] = memberValue;
+ continue;
+ }
+ out[def.key] = system.values[def.key] ?? platform;
+ }
+ return out;
+}
+
+// -------------------------------------------------------------- CSS mapping
+
+/**
+ * Named options become concrete CSS here, and only here.
+ *
+ * This indirection is what keeps the vocabulary from being "CSS variables with
+ * a UI": a user picks `relaxed`, not `1.35`. The scale can be retuned later
+ * without invalidating a single stored theme.
+ */
+const RADIUS: Record<string, string> = {
+ none: "0px",
+ small: "4px",
+ medium: "10px",
+ large: "18px",
+};
+
+const FONT_SIZE: Record<string, string> = {
+ small: "15px",
+ medium: "16.5px",
+ large: "18.5px",
+};
+
+const DENSITY: Record<string, string> = {
+ compact: "0.8",
+ normal: "1",
+ relaxed: "1.3",
+};
+
+const AVATAR_RADIUS: Record<string, string> = {
+ circle: "50%",
+ rounded: "var(--pkv-radius)",
+ square: "0px",
+};
+
+/** Card treatment expands into the three properties it actually controls. */
+function surfaceProperties(style: string): Record<string, string> {
+ switch (style) {
+ case "filled":
+ return {
+ "surface-bg": "var(--pkv-color-surface)",
+ "surface-border": "transparent",
+ "surface-pad": "1",
+ };
+ case "plain":
+ return {
+ "surface-bg": "transparent",
+ "surface-border": "transparent",
+ "surface-pad": "0",
+ };
+ default:
+ return {
+ "surface-bg": "var(--pkv-color-surface)",
+ "surface-border": "var(--pkv-color-border)",
+ "surface-pad": "1",
+ };
+ }
+}
+
+/**
+ * Maps resolved tokens to the `--pkv-*` custom properties the stylesheet reads.
+ *
+ * Returned as a plain record so `TokenStyle` stays entirely opaque: it receives
+ * names and values it does not interpret, exactly as it did before this
+ * vocabulary existed.
+ */
+export function themeToCssVars(resolved: Record<string, string>): Record<string, string> {
+ const vars: Record<string, string> = {};
+
+ const put = (name: string, value: string | undefined) => {
+ if (value !== undefined) vars[name] = value;
+ };
+
+ put("color-page", resolved["color.page"]);
+ put("color-surface", resolved["color.surface"]);
+ put("color-text", resolved["color.text"]);
+ put("color-muted", resolved["color.muted"]);
+ put("color-accent", resolved["color.accent"]);
+ put("color-border", resolved["color.border"]);
+
+ const bodyId = (resolved["font.body"] ?? "system") as FontId;
+ const headingId = (resolved["font.heading"] ?? "system") as FontId;
+ put("font-body", FONTS[bodyId]?.stack);
+ put("font-heading", FONTS[headingId]?.stack);
+ put("font-size", FONT_SIZE[resolved["font.size"] ?? "medium"]);
+
+ put("radius", RADIUS[resolved["shape.radius"] ?? "medium"]);
+ put("density", DENSITY[resolved["density"] ?? "normal"]);
+ put("avatar-radius", AVATAR_RADIUS[resolved["avatar.shape"] ?? "rounded"]);
+
+ for (const [name, value] of Object.entries(
+ surfaceProperties(resolved["surface.style"] ?? "outlined"),
+ )) {
+ vars[name] = value;
+ }
+
+ return vars;
+}
+
+/** Composition values the stylesheet needs as custom properties. Kept minimal:
+ * composition is mostly consumed as data by components, not as CSS. */
+export function compositionToCssVars(resolved: ResolvedComposition): Record<string, string> {
+ const columns: Record<string, string> = {
+ auto: "repeat(auto-fill, minmax(min(100%, 15rem), 1fr))",
+ one: "1fr",
+ two: "repeat(auto-fill, minmax(min(100%, 45%), 1fr))",
+ three: "repeat(auto-fill, minmax(min(100%, 30%), 1fr))",
+ };
+ const avatarSize: Record<string, string> = {
+ small: "56px",
+ medium: "88px",
+ large: "128px",
+ };
+ return {
+ "directory-columns": columns[resolved["directory.columns"] ?? "auto"] ?? columns["auto"]!,
+ "avatar-size": avatarSize[resolved["avatar.size"] ?? "medium"] ?? avatarSize["medium"]!,
+ };
+}
diff --git a/packages/shared/src/theme/validate.ts b/packages/shared/src/theme/validate.ts
new file mode 100644
index 0000000..9a42de5
--- /dev/null
+++ b/packages/shared/src/theme/validate.ts
@@ -0,0 +1,175 @@
+import {
+ COMPOSITION_MAP,
+ FONTS,
+ THEME_TOKEN_MAP,
+ type CompositionDef,
+ type TokenDef,
+} from "./vocabulary.ts";
+
+/**
+ * Validation for stored theme and composition data.
+ *
+ * Nothing reaches the renderer without passing through here. A theme is
+ * user-authored data, so this is a trust boundary: the point of the typed
+ * vocabulary is that an arbitrary string can never become an arbitrary CSS
+ * declaration.
+ */
+
+export type ValidationFailure =
+ | "unknown_key"
+ | "not_a_string"
+ | "invalid_color"
+ | "invalid_enum"
+ | "unknown_font"
+ | "invalid_length"
+ | "invalid_boolean"
+ | "not_member_overridable";
+
+export type ValidationResult =
+ | { ok: true; value: string }
+ | { ok: false; reason: ValidationFailure };
+
+/**
+ * Six-digit hex only.
+ *
+ * Not `rgb()`, not `color-mix()`, not named colours, and not three-digit hex:
+ * one shape is trivial to validate, trivial to render in a colour picker, and
+ * leaves no room for a function call to smuggle something through.
+ */
+const HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
+
+function validateAgainst(def: TokenDef | CompositionDef, raw: unknown): ValidationResult {
+ if (typeof raw !== "string") return { ok: false, reason: "not_a_string" };
+ const value = raw.trim();
+
+ switch (def.type) {
+ case "color":
+ if (!HEX_COLOR.test(value)) return { ok: false, reason: "invalid_color" };
+ return { ok: true, value: value.toUpperCase() };
+
+ case "enum":
+ if (!def.values.includes(value)) return { ok: false, reason: "invalid_enum" };
+ return { ok: true, value };
+
+ case "font":
+ if (!Object.hasOwn(FONTS, value)) return { ok: false, reason: "unknown_font" };
+ return { ok: true, value };
+
+ case "length": {
+ const match = value.match(/^(-?\d+(?:\.\d+)?)(px|rem)$/);
+ if (!match || match[2] !== def.unit) return { ok: false, reason: "invalid_length" };
+ const magnitude = Number(match[1]);
+ if (!Number.isFinite(magnitude) || magnitude < def.min || magnitude > def.max) {
+ return { ok: false, reason: "invalid_length" };
+ }
+ return { ok: true, value };
+ }
+
+ case "boolean":
+ if (value !== "true" && value !== "false") return { ok: false, reason: "invalid_boolean" };
+ return { ok: true, value };
+ }
+}
+
+export function validateThemeToken(
+ key: string,
+ raw: unknown,
+ opts: { level: "system" | "member" } = { level: "system" },
+): ValidationResult {
+ const def = THEME_TOKEN_MAP.get(key);
+ if (!def) return { ok: false, reason: "unknown_key" };
+ if (opts.level === "member" && !def.memberOverridable) {
+ return { ok: false, reason: "not_member_overridable" };
+ }
+ return validateAgainst(def, raw);
+}
+
+export function validateCompositionValue(
+ key: string,
+ raw: unknown,
+ opts: { level: "system" | "member" } = { level: "system" },
+): ValidationResult {
+ const def = COMPOSITION_MAP.get(key);
+ if (!def) return { ok: false, reason: "unknown_key" };
+ if (opts.level === "member" && !def.memberOverridable) {
+ return { ok: false, reason: "not_member_overridable" };
+ }
+ return validateAgainst(def, raw);
+}
+
+export type SanitizedTheme = {
+ /** Only keys that validated. */
+ values: Record<string, string>;
+ /** Keys explicitly reset to the platform default (stored as null). */
+ resets: string[];
+ /** Rejected keys, for reporting in an editor rather than silent loss. */
+ rejected: Array<{ key: string; reason: ValidationFailure }>;
+};
+
+/**
+ * Sanitizes a stored theme blob.
+ *
+ * Three states are preserved exactly as specified: a key that is absent
+ * inherits, a key with a value overrides, and a key explicitly set to null
+ * resets to the platform default rather than inheriting.
+ *
+ * Anything unrecognised or invalid is dropped and reported. Dropping is
+ * deliberate: a theme stored before a vocabulary change must not break a page,
+ * and a value we cannot validate must never be rendered.
+ */
+export function sanitizeTheme(
+ raw: unknown,
+ opts: { level: "system" | "member" },
+): SanitizedTheme {
+ const out: SanitizedTheme = { values: {}, resets: [], rejected: [] };
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
+
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
+ if (value === null) {
+ // An explicit reset is only meaningful at member level, where there is
+ // something to reset away from.
+ const def = THEME_TOKEN_MAP.get(key);
+ if (!def) {
+ out.rejected.push({ key, reason: "unknown_key" });
+ continue;
+ }
+ if (opts.level === "member" && !def.memberOverridable) {
+ out.rejected.push({ key, reason: "not_member_overridable" });
+ continue;
+ }
+ out.resets.push(key);
+ continue;
+ }
+
+ const result = validateThemeToken(key, value, opts);
+ if (result.ok) out.values[key] = result.value;
+ else out.rejected.push({ key, reason: result.reason });
+ }
+
+ return out;
+}
+
+export function sanitizeComposition(
+ raw: unknown,
+ opts: { level: "system" | "member" },
+): SanitizedTheme {
+ const out: SanitizedTheme = { values: {}, resets: [], rejected: [] };
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
+
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
+ if (value === null) {
+ const def = COMPOSITION_MAP.get(key);
+ if (!def) {
+ out.rejected.push({ key, reason: "unknown_key" });
+ continue;
+ }
+ out.resets.push(key);
+ continue;
+ }
+ const result = validateCompositionValue(key, value, opts);
+ if (result.ok) out.values[key] = result.value;
+ else out.rejected.push({ key, reason: result.reason });
+ }
+
+ return out;
+}
diff --git a/packages/shared/src/theme/vocabulary.ts b/packages/shared/src/theme/vocabulary.ts
new file mode 100644
index 0000000..5dd6e13
--- /dev/null
+++ b/packages/shared/src/theme/vocabulary.ts
@@ -0,0 +1,411 @@
+/**
+ * The pkviewer theme vocabulary.
+ *
+ * This is the product's public design API. It is deliberately small: a person
+ * who does not write CSS should be able to hold all of it in their head, and
+ * every option should produce a page that still looks composed. It is not
+ * "CSS custom properties with a UI" — there is no token here that exists only
+ * because a stylesheet happened to need a number.
+ *
+ * The dividing line used throughout:
+ *
+ * THEME how things look — colour, type, radius, surface, density
+ * COMPOSITION what appears and how it is arranged — sections, columns, order
+ *
+ * A knob that changes which information is on the page, or where it sits, is
+ * composition. A knob that changes the appearance of whatever is there is a
+ * theme token. `directory.columns` is composition; `shape.radius` is a token.
+ */
+
+export type TokenType = "color" | "length" | "enum" | "font" | "boolean";
+
+/** Values are stored as strings throughout, matching the storage mechanism. */
+export type TokenValue = string;
+
+export type TokenDefBase = {
+ key: string;
+ label: string;
+ /** One line, written for a non-technical editor UI. */
+ help: string;
+ /**
+ * Whether a member may override this on their own page.
+ *
+ * False is reserved for tokens where a per-member override would make the
+ * SITE incoherent rather than the page distinctive.
+ */
+ memberOverridable: boolean;
+};
+
+export type ColorTokenDef = TokenDefBase & {
+ type: "color";
+ /** Platform default carries both grounds so the default identity works in
+ * either scheme without the vocabulary doubling in size. */
+ default: { light: string; dark: string };
+};
+
+export type EnumTokenDef = TokenDefBase & {
+ type: "enum";
+ values: readonly string[];
+ default: string;
+};
+
+export type FontTokenDef = TokenDefBase & {
+ type: "font";
+ default: FontId;
+};
+
+export type LengthTokenDef = TokenDefBase & {
+ type: "length";
+ unit: "px" | "rem";
+ min: number;
+ max: number;
+ default: string;
+};
+
+export type BooleanTokenDef = TokenDefBase & {
+ type: "boolean";
+ default: boolean;
+};
+
+export type TokenDef =
+ | ColorTokenDef
+ | EnumTokenDef
+ | FontTokenDef
+ | LengthTokenDef
+ | BooleanTokenDef;
+
+// ---------------------------------------------------------------- typefaces
+
+/**
+ * The font allow-list.
+ *
+ * Fixed and finite. No arbitrary families, no uploads, no URLs: a font token
+ * carries an id from this table and nothing else, so a theme can never point
+ * the browser at a resource we did not choose.
+ *
+ * Every entry is either the system stack (no network cost at all) or a Google
+ * Fonts family, which is the one font host the platform already allows.
+ */
+export type FontId =
+ | "system"
+ | "inter"
+ | "nunito"
+ | "atkinson"
+ | "newsreader"
+ | "fraunces"
+ | "space-grotesk"
+ | "jetbrains-mono";
+
+export type FontEntry = {
+ id: FontId;
+ label: string;
+ /** Google Fonts family name, or null for the system stack. */
+ family: string | null;
+ stack: string;
+ weights: readonly number[];
+ note: string;
+};
+
+const SYSTEM_STACK =
+ 'system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
+
+export const FONTS: Readonly<Record<FontId, FontEntry>> = {
+ system: {
+ id: "system",
+ label: "System",
+ family: null,
+ stack: SYSTEM_STACK,
+ weights: [400, 600],
+ note: "Whatever the reader's device uses. Loads instantly.",
+ },
+ inter: {
+ id: "inter",
+ label: "Inter",
+ family: "Inter",
+ stack: `"Inter", ${SYSTEM_STACK}`,
+ weights: [400, 600],
+ note: "Neutral and modern.",
+ },
+ nunito: {
+ id: "nunito",
+ label: "Nunito",
+ family: "Nunito",
+ stack: `"Nunito", ${SYSTEM_STACK}`,
+ weights: [400, 700],
+ note: "Rounded and friendly.",
+ },
+ atkinson: {
+ id: "atkinson",
+ label: "Atkinson Hyperlegible",
+ family: "Atkinson Hyperlegible",
+ stack: `"Atkinson Hyperlegible", ${SYSTEM_STACK}`,
+ weights: [400, 700],
+ note: "Designed for maximum legibility, including for low vision.",
+ },
+ newsreader: {
+ id: "newsreader",
+ label: "Newsreader",
+ family: "Newsreader",
+ stack: '"Newsreader", Georgia, "Iowan Old Style", serif',
+ weights: [400, 600],
+ note: "A warm serif that reads well at length.",
+ },
+ fraunces: {
+ id: "fraunces",
+ label: "Fraunces",
+ family: "Fraunces",
+ stack: '"Fraunces", Georgia, "Iowan Old Style", serif',
+ weights: [400, 600],
+ note: "An expressive display serif with real character.",
+ },
+ "space-grotesk": {
+ id: "space-grotesk",
+ label: "Space Grotesk",
+ family: "Space Grotesk",
+ stack: `"Space Grotesk", ${SYSTEM_STACK}`,
+ weights: [400, 600],
+ note: "Geometric and slightly technical.",
+ },
+ "jetbrains-mono": {
+ id: "jetbrains-mono",
+ label: "JetBrains Mono",
+ family: "JetBrains Mono",
+ stack: '"JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace',
+ weights: [400, 700],
+ note: "Monospaced, for a deliberately technical look.",
+ },
+};
+
+export const FONT_IDS = Object.keys(FONTS) as FontId[];
+
+// ------------------------------------------------------------ theme tokens
+
+/**
+ * Fourteen tokens.
+ *
+ * Colour is seven of them because colour is what people actually want to
+ * change, and the rest are single decisions with a handful of named options
+ * rather than free numbers. Named options are what keep every combination
+ * looking composed: a person cannot pick 3px of border radius and 41px of
+ * padding and end up with something that reads as broken.
+ */
+export const THEME_TOKENS: readonly TokenDef[] = [
+ {
+ key: "color.scheme",
+ type: "enum",
+ values: ["auto", "light", "dark"],
+ default: "auto",
+ label: "Colour scheme",
+ help: "Follow the reader's device, or always use light or dark.",
+ // System-only: this is a property of the SITE. A member page flipping to
+ // dark while the system page is light makes navigation feel broken rather
+ // than personal.
+ memberOverridable: false,
+ },
+ {
+ key: "color.page",
+ type: "color",
+ default: { light: "#FAF8FB", dark: "#151219" },
+ label: "Page background",
+ help: "The colour behind everything.",
+ memberOverridable: true,
+ },
+ {
+ key: "color.surface",
+ type: "color",
+ default: { light: "#FFFFFF", dark: "#1E1A24" },
+ label: "Card background",
+ help: "The colour of cards and panels sitting on the page.",
+ memberOverridable: true,
+ },
+ {
+ key: "color.text",
+ type: "color",
+ default: { light: "#1C1721", dark: "#EEEAF2" },
+ label: "Text",
+ help: "Main text colour.",
+ memberOverridable: true,
+ },
+ {
+ key: "color.muted",
+ type: "color",
+ default: { light: "#6B6478", dark: "#9A93A6" },
+ label: "Secondary text",
+ help: "Pronouns, IDs, dates and other supporting detail.",
+ memberOverridable: true,
+ },
+ {
+ key: "color.accent",
+ type: "color",
+ default: { light: "#A23B72", dark: "#F58FC2" },
+ label: "Accent",
+ help: "Links and highlights.",
+ memberOverridable: true,
+ },
+ {
+ key: "color.border",
+ type: "color",
+ default: { light: "#E6E1EC", dark: "#302938" },
+ label: "Lines",
+ help: "Card edges and dividers.",
+ memberOverridable: true,
+ },
+ {
+ key: "font.body",
+ type: "font",
+ default: "system",
+ label: "Body typeface",
+ help: "Used for descriptions and general text.",
+ memberOverridable: true,
+ },
+ {
+ key: "font.heading",
+ type: "font",
+ default: "newsreader",
+ label: "Heading typeface",
+ help: "Used for names and section headings.",
+ memberOverridable: true,
+ },
+ {
+ key: "font.size",
+ type: "enum",
+ values: ["small", "medium", "large"],
+ default: "medium",
+ label: "Text size",
+ help: "Overall reading size.",
+ memberOverridable: true,
+ },
+ {
+ key: "shape.radius",
+ type: "enum",
+ values: ["none", "small", "medium", "large"],
+ default: "medium",
+ label: "Corner rounding",
+ help: "How rounded cards and images are.",
+ memberOverridable: true,
+ },
+ {
+ key: "surface.style",
+ type: "enum",
+ values: ["outlined", "filled", "plain"],
+ default: "outlined",
+ label: "Card style",
+ help: "Cards can have an outline, a filled background, or neither.",
+ memberOverridable: true,
+ },
+ {
+ key: "density",
+ type: "enum",
+ values: ["compact", "normal", "relaxed"],
+ default: "normal",
+ label: "Spacing",
+ help: "How much room everything is given.",
+ memberOverridable: true,
+ },
+ {
+ key: "avatar.shape",
+ type: "enum",
+ values: ["circle", "rounded", "square"],
+ default: "rounded",
+ label: "Avatar shape",
+ help: "How avatars are cropped.",
+ memberOverridable: true,
+ },
+];
+
+export const THEME_TOKEN_MAP: ReadonlyMap<string, TokenDef> = new Map(
+ THEME_TOKENS.map((t) => [t.key, t]),
+);
+
+export const THEME_TOKEN_KEYS: readonly string[] = THEME_TOKENS.map((t) => t.key);
+
+/** Tokens a member may override on their own page. */
+export const MEMBER_OVERRIDABLE_KEYS: readonly string[] = THEME_TOKENS.filter(
+ (t) => t.memberOverridable,
+).map((t) => t.key);
+
+// ------------------------------------------------------ composition config
+
+/**
+ * Composition configuration.
+ *
+ * Deliberately a SEPARATE vocabulary with its own storage, not theme tokens
+ * wearing a different hat. These change what is on the page and how it is
+ * arranged; they are not styling, they do not become CSS custom properties,
+ * and they belong in a different part of an editor.
+ *
+ * This is the reason `directory.card.min` never became a token. The renderer
+ * needed a pixel value; the product concept is "how many columns", and the
+ * pixel value is an implementation detail of expressing that.
+ */
+export type CompositionDef = EnumTokenDef | BooleanTokenDef;
+
+export const COMPOSITION: readonly CompositionDef[] = [
+ {
+ key: "banner.display",
+ type: "enum",
+ values: ["auto", "hidden"],
+ default: "auto",
+ label: "Banner",
+ help: "Show the banner from PluralKit when there is one.",
+ memberOverridable: true,
+ },
+ {
+ key: "avatar.size",
+ type: "enum",
+ values: ["small", "medium", "large"],
+ default: "medium",
+ label: "Avatar size",
+ help: "How prominent the avatar is.",
+ memberOverridable: true,
+ },
+ {
+ key: "directory.columns",
+ type: "enum",
+ values: ["auto", "one", "two", "three"],
+ default: "auto",
+ label: "Member columns",
+ help: "How many members sit side by side. Auto fits the reader's screen.",
+ memberOverridable: false,
+ },
+ {
+ key: "directory.card",
+ type: "enum",
+ values: ["compact", "detailed"],
+ default: "compact",
+ label: "Member cards",
+ help: "Compact shows a name; detailed adds pronouns and a line of description.",
+ memberOverridable: false,
+ },
+ {
+ key: "directory.sort",
+ type: "enum",
+ values: ["pluralkit", "name"],
+ default: "pluralkit",
+ label: "Member order",
+ help: "Keep PluralKit's order, or sort by name.",
+ memberOverridable: false,
+ },
+ {
+ key: "show.pronouns",
+ type: "boolean",
+ default: true,
+ label: "Show pronouns",
+ help: "Show pronouns where PluralKit makes them public.",
+ memberOverridable: true,
+ },
+ {
+ key: "show.birthday",
+ type: "boolean",
+ default: true,
+ label: "Show birthday",
+ help: "Show birthdays where PluralKit makes them public.",
+ memberOverridable: true,
+ },
+];
+
+export const COMPOSITION_MAP: ReadonlyMap<string, CompositionDef> = new Map(
+ COMPOSITION.map((c) => [c.key, c]),
+);
+
+export const COMPOSITION_KEYS: readonly string[] = COMPOSITION.map((c) => c.key);
diff --git a/packages/shared/test/theme.test.ts b/packages/shared/test/theme.test.ts
new file mode 100644
index 0000000..d0e59f8
--- /dev/null
+++ b/packages/shared/test/theme.test.ts
@@ -0,0 +1,359 @@
+import { describe, expect, test } from "bun:test";
+import {
+ COMPOSITION,
+ COMPOSITION_KEYS,
+ FONTS,
+ FONT_IDS,
+ MEMBER_OVERRIDABLE_KEYS,
+ PRESETS,
+ THEME_TOKENS,
+ THEME_TOKEN_KEYS,
+ compositionToCssVars,
+ resolveComposition,
+ resolveTheme,
+ sanitizeTheme,
+ themeToCssVars,
+ validateCompositionValue,
+ validateThemeToken,
+} from "../src/theme/index.ts";
+
+const TYPES = ["color", "length", "enum", "font", "boolean"];
+
+describe("vocabulary shape", () => {
+ test("every token declares a supported type", () => {
+ for (const def of THEME_TOKENS) {
+ expect(TYPES).toContain(def.type);
+ }
+ });
+
+ test("every token has a platform default", () => {
+ for (const def of THEME_TOKENS) {
+ if (def.type === "color") {
+ expect(def.default.light).toMatch(/^#[0-9A-Fa-f]{6}$/);
+ expect(def.default.dark).toMatch(/^#[0-9A-Fa-f]{6}$/);
+ } else if (def.type === "boolean") {
+ expect(typeof def.default).toBe("boolean");
+ } else {
+ expect(def.default).toBeTruthy();
+ }
+ }
+ });
+
+ test("every default is itself a valid value", () => {
+ for (const def of THEME_TOKENS) {
+ const value =
+ def.type === "color"
+ ? def.default.light
+ : def.type === "boolean"
+ ? String(def.default)
+ : def.default;
+ expect(validateThemeToken(def.key, value).ok).toBe(true);
+ }
+ });
+
+ test("enum defaults are members of their own value list", () => {
+ for (const def of THEME_TOKENS) {
+ if (def.type === "enum") expect(def.values).toContain(def.default);
+ }
+ });
+
+ test("font defaults name a font in the allow-list", () => {
+ for (const def of THEME_TOKENS) {
+ if (def.type === "font") expect(FONT_IDS).toContain(def.default);
+ }
+ });
+
+ test("keys are unique, flat and dotted", () => {
+ expect(new Set(THEME_TOKEN_KEYS).size).toBe(THEME_TOKEN_KEYS.length);
+ for (const key of THEME_TOKEN_KEYS) expect(key).toMatch(/^[a-z]+(\.[a-z]+)*$/);
+ });
+
+ // The vocabulary is a product surface, not a CSS dumping ground: it has to
+ // stay small enough for a person to hold in their head.
+ test("stays small enough to be understood at a glance", () => {
+ expect(THEME_TOKENS.length).toBeLessThanOrEqual(20);
+ expect(COMPOSITION.length).toBeLessThanOrEqual(12);
+ });
+
+ // Composition changes what appears and how it is arranged; theme changes how
+ // it looks. Mixing them is what turns a design API into CSS-with-a-UI.
+ test("theme and composition vocabularies do not overlap", () => {
+ for (const key of COMPOSITION_KEYS) {
+ expect(THEME_TOKEN_KEYS).not.toContain(key);
+ }
+ });
+
+ test("every font entry has a usable stack", () => {
+ for (const id of FONT_IDS) {
+ const font = FONTS[id];
+ expect(font.stack.length).toBeGreaterThan(0);
+ expect(font.weights.length).toBeGreaterThan(0);
+ }
+ });
+});
+
+describe("validation", () => {
+ test("enum tokens reject undeclared values", () => {
+ expect(validateThemeToken("density", "spacious")).toEqual({
+ ok: false,
+ reason: "invalid_enum",
+ });
+ expect(validateThemeToken("density", "relaxed").ok).toBe(true);
+ });
+
+ test("font tokens reject fonts outside the allow-list", () => {
+ expect(validateThemeToken("font.body", "Comic Sans MS")).toEqual({
+ ok: false,
+ reason: "unknown_font",
+ });
+ // No URLs, ever.
+ expect(validateThemeToken("font.body", "https://evil.test/font.woff2")).toEqual({
+ ok: false,
+ reason: "unknown_font",
+ });
+ expect(validateThemeToken("font.body", "atkinson").ok).toBe(true);
+ });
+
+ test("colour tokens accept only six-digit hex", () => {
+ expect(validateThemeToken("color.accent", "#A23B72").ok).toBe(true);
+ for (const bad of ["#fff", "red", "rgb(1,2,3)", "var(--x)", "#GGGGGG", "#A23B72;"]) {
+ expect(validateThemeToken("color.accent", bad).ok).toBe(false);
+ }
+ });
+
+ test("colour values are normalised so equal colours compare equal", () => {
+ const result = validateThemeToken("color.accent", " #a23b72 ");
+ expect(result).toEqual({ ok: true, value: "#A23B72" });
+ });
+
+ test("unknown keys are rejected", () => {
+ expect(validateThemeToken("color.rainbow", "#FFFFFF")).toEqual({
+ ok: false,
+ reason: "unknown_key",
+ });
+ });
+
+ test("non-string values are rejected", () => {
+ expect(validateThemeToken("density", 3)).toEqual({ ok: false, reason: "not_a_string" });
+ expect(validateThemeToken("density", { evil: true })).toEqual({
+ ok: false,
+ reason: "not_a_string",
+ });
+ });
+
+ test("boolean composition values accept only true and false", () => {
+ expect(validateCompositionValue("show.pronouns", "true").ok).toBe(true);
+ expect(validateCompositionValue("show.pronouns", "yes")).toEqual({
+ ok: false,
+ reason: "invalid_boolean",
+ });
+ });
+
+ // Member-level overrides are enforced at validation, not merely ignored at
+ // render: an editor must be able to say why something was refused.
+ test("member-only enforcement rejects system-only tokens", () => {
+ expect(validateThemeToken("color.scheme", "dark", { level: "member" })).toEqual({
+ ok: false,
+ reason: "not_member_overridable",
+ });
+ expect(validateThemeToken("color.scheme", "dark", { level: "system" }).ok).toBe(true);
+ });
+
+ test("sanitize reports rejections instead of silently dropping them", () => {
+ const result = sanitizeTheme(
+ { "color.accent": "#A23B72", "color.rainbow": "#FFFFFF", density: "spacious" },
+ { level: "system" },
+ );
+ expect(result.values).toEqual({ "color.accent": "#A23B72" });
+ expect(result.rejected).toHaveLength(2);
+ });
+
+ test("sanitize survives junk input", () => {
+ for (const junk of [null, undefined, "string", 42, [1, 2, 3]]) {
+ expect(sanitizeTheme(junk, { level: "system" }).values).toEqual({});
+ }
+ });
+});
+
+describe("inheritance", () => {
+ const system = { "color.accent": "#112233", density: "compact", "font.body": "nunito" };
+
+ test("absent means inherit from the system", () => {
+ const resolved = resolveTheme(system, {});
+ expect(resolved.light["color.accent"]).toBe("#112233");
+ expect(resolved.light["density"]).toBe("compact");
+ });
+
+ test("a value overrides the system", () => {
+ const resolved = resolveTheme(system, { "color.accent": "#445566" });
+ expect(resolved.light["color.accent"]).toBe("#445566");
+ });
+
+ // The third state is what lets a member escape a loud system theme without
+ // restating every platform default by hand.
+ test("explicit null resets to the platform default, not the system value", () => {
+ const resolved = resolveTheme(system, { "color.accent": null, density: null });
+ expect(resolved.light["color.accent"]).toBe("#A23B72");
+ expect(resolved.light["density"]).toBe("normal");
+ });
+
+ test("unset tokens fall through to the platform default", () => {
+ const resolved = resolveTheme({}, {});
+ for (const key of THEME_TOKEN_KEYS) {
+ expect(resolved.light[key]).toBeDefined();
+ expect(resolved.dark[key]).toBeDefined();
+ }
+ });
+
+ test("a member cannot override a system-only token", () => {
+ const resolved = resolveTheme({ "color.scheme": "light" }, { "color.scheme": "dark" });
+ expect(resolved.scheme).toBe("light");
+ });
+
+ test("member-overridable tokens are exactly those declared", () => {
+ for (const def of THEME_TOKENS) {
+ const attempt = resolveTheme({}, { [def.key]: sampleValueFor(def) });
+ const applied = attempt.light[def.key] === sampleValueFor(def);
+ expect(applied).toBe(def.memberOverridable);
+ }
+ });
+
+ test("light and dark differ only in colour", () => {
+ const resolved = resolveTheme({}, {});
+ for (const def of THEME_TOKENS) {
+ if (def.type === "color") {
+ expect(resolved.light[def.key]).not.toBe(resolved.dark[def.key]);
+ } else {
+ expect(resolved.light[def.key]).toBe(resolved.dark[def.key]);
+ }
+ }
+ });
+
+ test("composition resolves through the same three states", () => {
+ const resolved = resolveComposition({ "avatar.size": "large" }, { "avatar.size": null });
+ expect(resolved["avatar.size"]).toBe("medium");
+ expect(resolveComposition({ "avatar.size": "large" }, {})["avatar.size"]).toBe("large");
+ expect(
+ resolveComposition({ "directory.columns": "two" }, { "directory.columns": "three" })[
+ "directory.columns"
+ ],
+ // Not member-overridable: the system's directory layout wins.
+ ).toBe("two");
+ });
+});
+
+describe("presets", () => {
+ test("there are between three and five", () => {
+ expect(PRESETS.length).toBeGreaterThanOrEqual(3);
+ expect(PRESETS.length).toBeLessThanOrEqual(5);
+ });
+
+ test("every preset value is a valid declared token", () => {
+ for (const preset of PRESETS) {
+ for (const [key, value] of Object.entries(preset.tokens)) {
+ const result = validateThemeToken(key, value);
+ expect(result.ok, `${preset.id}.${key} = ${value}`).toBe(true);
+ }
+ }
+ });
+
+ test("presets carry an id, a name and a described character", () => {
+ const ids = new Set<string>();
+ for (const preset of PRESETS) {
+ expect(preset.name.length).toBeGreaterThan(0);
+ expect(preset.character.length).toBeGreaterThan(30);
+ expect(ids.has(preset.id)).toBe(false);
+ ids.add(preset.id);
+ }
+ });
+
+ // Five colour swaps would not demonstrate the vocabulary's range.
+ test("presets differ in more than colour", () => {
+ const shape = (p: (typeof PRESETS)[number]) =>
+ [p.tokens["font.body"], p.tokens["shape.radius"], p.tokens["surface.style"], p.tokens["density"]].join("|");
+ expect(new Set(PRESETS.map(shape)).size).toBe(PRESETS.length);
+ });
+
+ test("presets cover both light and dark grounds", () => {
+ const schemes = new Set(PRESETS.map((p) => p.tokens["color.scheme"]));
+ expect(schemes.has("light") || schemes.has("auto")).toBe(true);
+ expect(schemes.has("dark")).toBe(true);
+ });
+});
+
+describe("css mapping", () => {
+ test("maps every resolved theme to concrete CSS values", () => {
+ const vars = themeToCssVars(resolveTheme({}, {}).light);
+ for (const name of ["color-page", "color-text", "font-body", "radius", "density"]) {
+ expect(vars[name]).toBeDefined();
+ }
+ });
+
+ // Named options exist so the scale can be retuned without invalidating stored
+ // themes: the user picked "relaxed", not a number.
+ test("named options become values, not raw user input", () => {
+ const compact = themeToCssVars(resolveTheme({ density: "compact" }, {}).light);
+ const relaxed = themeToCssVars(resolveTheme({ density: "relaxed" }, {}).light);
+ expect(compact["density"]).not.toBe(relaxed["density"]);
+ expect(Number(relaxed["density"])).toBeGreaterThan(Number(compact["density"]));
+ });
+
+ test("font tokens map to allow-listed stacks only", () => {
+ const vars = themeToCssVars(resolveTheme({ "font.body": "jetbrains-mono" }, {}).light);
+ expect(vars["font-body"]).toContain("JetBrains Mono");
+ });
+
+ test("composition maps to layout values", () => {
+ const vars = compositionToCssVars(resolveComposition({ "directory.columns": "one" }, {}));
+ expect(vars["directory-columns"]).toBe("1fr");
+ });
+
+ // Invalid data must never reach the renderer, even if it somehow reached
+ // storage: resolution drops it and the platform default stands.
+ test("invalid stored data cannot produce a CSS value", () => {
+ const hostile = {
+ "color.page": "#fff; } body { display:none } .x {",
+ "font.body": "url(https://evil.test/x.woff2)",
+ density: "9999",
+ "color.accent": "expression(alert(1))",
+ };
+ const resolved = resolveTheme(hostile, {});
+ const vars = themeToCssVars(resolved.light);
+ const dump = JSON.stringify(vars);
+
+ expect(dump).not.toContain("display:none");
+ expect(dump).not.toContain("evil.test");
+ expect(dump).not.toContain("expression");
+ expect(vars["color-page"]).toBe("#FAF8FB");
+ expect(vars["density"]).toBe("1");
+ });
+
+ test("resolved values only ever contain safe characters", () => {
+ const vars = themeToCssVars(resolveTheme({}, {}).light);
+ for (const value of Object.values(vars)) {
+ expect(value).not.toMatch(/[;{}<>]/);
+ }
+ });
+});
+
+function sampleValueFor(def: (typeof THEME_TOKENS)[number]): string {
+ switch (def.type) {
+ case "color":
+ return "#123456";
+ case "enum":
+ return def.values.find((v) => v !== def.default) ?? def.default;
+ case "font":
+ return def.default === "system" ? "nunito" : "system";
+ case "boolean":
+ return def.default ? "false" : "true";
+ case "length":
+ return def.default;
+ }
+}
+
+describe("member overridability declaration", () => {
+ test("the exported list matches the declarations", () => {
+ const declared = THEME_TOKENS.filter((t) => t.memberOverridable).map((t) => t.key);
+ expect([...MEMBER_OVERRIDABLE_KEYS].sort()).toEqual(declared.sort());
+ });
+});
diff --git a/packages/shared/tsconfig.json b/packages/shared/tsconfig.json
new file mode 100644
index 0000000..4e0e7f6
--- /dev/null
+++ b/packages/shared/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": { "rootDir": "." },
+ "include": ["src/**/*.ts"]
+}
diff --git a/scripts/check-no-hardcoded-origin.sh b/scripts/check-no-hardcoded-origin.sh
new file mode 100755
index 0000000..114ffee
--- /dev/null
+++ b/scripts/check-no-hardcoded-origin.sh
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+# Guards the domain-portability rule: the deployment's own hostnames must not
+# appear anywhere except configuration and documentation.
+#
+# The domain is deployment configuration, not architecture. Discipline alone
+# does not survive months of commits; this check does. Run it in CI.
+set -uo pipefail
+
+cd "$(dirname "$0")/.." || exit 1
+
+# Hostnames that identify a specific deployment. Add production hosts here too
+# once they exist -- the rule is about ANY deployment origin, not just the beta.
+#
+# Matched fully qualified, so the bare word stays usable as ordinary data: it is
+# a perfectly good SLUG, and slugs are user content, not configuration. The rule
+# being enforced is "no deployment hostname in the code", not "never write these
+# letters".
+PATTERN='doughmination\.gay'
+
+# Config and docs are where a deployment origin legitimately appears.
+ALLOWED='^(\./)?(\.env(\.example)?|scripts/check-no-hardcoded-origin\.sh|docs/|README\.md)'
+
+files=""
+if command -v git >/dev/null 2>&1 && [ -n "$(git ls-files 2>/dev/null)" ]; then
+ files="$(git ls-files)"
+else
+ # Nothing tracked yet: scan the working tree so the check is useful before the
+ # first commit.
+ files="$(find . -type f \
+ ! -path './node_modules/*' ! -path './*/node_modules/*' \
+ ! -path './.git/*' ! -path './data/*' ! -path './.next/*' \
+ ! -name '*.db' ! -name '*.db-shm' ! -name '*.db-wal' \
+ | sed 's|^\./||')"
+fi
+
+violations=""
+while IFS= read -r file; do
+ [ -z "$file" ] && continue
+ [ -f "$file" ] || continue
+ if printf '%s' "$file" | grep -qE "$ALLOWED"; then continue; fi
+ if grep -qIE "$PATTERN" "$file" 2>/dev/null; then
+ violations="${violations} ${file}
+"
+ fi
+done <<EOF
+$files
+EOF
+
+if [ -n "$violations" ]; then
+ echo "FAIL: a deployment hostname is hardcoded outside config and docs:" >&2
+ printf '%s' "$violations" >&2
+ echo "Origins belong in .env, read through apps/api/src/config." >&2
+ exit 1
+fi
+
+echo "check-no-hardcoded-origin: ok"
diff --git a/scripts/dev.ts b/scripts/dev.ts
new file mode 100755
index 0000000..312858c
--- /dev/null
+++ b/scripts/dev.ts
@@ -0,0 +1,90 @@
+#!/usr/bin/env bun
+/**
+ * Runs the API and the web tier together with prefixed, interleaved output.
+ *
+ * Two processes rather than one is the architecture, not an inconvenience: the
+ * API owns SQLite and is its only writer, and the web tier only renders (A1).
+ *
+ * Both hostnames are served by the single Next process. Browsers resolve
+ * *.localhost to 127.0.0.1 without any hosts-file entry, so the Host header
+ * differs exactly as it does in production and the origin split is genuinely
+ * exercised in development rather than bypassed.
+ */
+
+import { spawn, type Subprocess } from "bun";
+
+const RESET = "\x1b[0m";
+const TIERS = [
+ { name: "api", colour: "\x1b[35m", cwd: "apps/api", cmd: ["bun", "run", "--hot", "src/index.ts"] },
+ { name: "web", colour: "\x1b[36m", cwd: "apps/web", cmd: ["bun", "run", "dev"] },
+] as const;
+
+const children: Subprocess[] = [];
+let shuttingDown = false;
+
+function prefix(name: string, colour: string, stream: ReadableStream<Uint8Array>) {
+ const decoder = new TextDecoder();
+ const reader = stream.getReader();
+ let buffer = "";
+ void (async () => {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split("\n");
+ buffer = lines.pop() ?? "";
+ for (const line of lines) {
+ console.log(`${colour}[${name}]${RESET} ${line}`);
+ }
+ }
+ if (buffer.length > 0) console.log(`${colour}[${name}]${RESET} ${buffer}`);
+ })();
+}
+
+function shutdown(code = 0) {
+ if (shuttingDown) return;
+ shuttingDown = true;
+ for (const child of children) {
+ try {
+ child.kill();
+ } catch {
+ // Already gone.
+ }
+ }
+ process.exit(code);
+}
+
+process.on("SIGINT", () => shutdown(0));
+process.on("SIGTERM", () => shutdown(0));
+
+for (const tier of TIERS) {
+ const child = spawn({
+ cmd: [...tier.cmd],
+ cwd: tier.cwd,
+ stdout: "pipe",
+ stderr: "pipe",
+ env: { ...process.env, FORCE_COLOR: "1" },
+ onExit(_proc, exitCode) {
+ if (shuttingDown) return;
+ console.log(`${tier.colour}[${tier.name}]${RESET} exited (${exitCode ?? "signal"})`);
+ // One tier dying alone leaves a confusing half-running stack.
+ shutdown(exitCode ?? 1);
+ },
+ });
+ children.push(child);
+ prefix(tier.name, tier.colour, child.stdout as ReadableStream<Uint8Array>);
+ prefix(tier.name, tier.colour, child.stderr as ReadableStream<Uint8Array>);
+}
+
+const appOrigin = process.env["PUBLIC_APP_ORIGIN"] ?? "http://app.localhost:3000";
+const publicOrigin = process.env["PUBLIC_USERCONTENT_ORIGIN"] ?? "http://system.localhost:3000";
+
+console.log("");
+console.log(" pkviewer dev");
+console.log(` public ${publicOrigin} / , /docs , /s/...`);
+console.log(` app ${appOrigin} /login , /manage`);
+console.log(` api ${process.env["INTERNAL_API_ORIGIN"] ?? "http://127.0.0.1:3001"}/health`);
+console.log("");
+console.log(" Both hostnames hit the same Next process; *.localhost resolves");
+console.log(" to 127.0.0.1 in Chrome and Firefox with no setup.");
+console.log("");
diff --git a/scripts/seed-dev.ts b/scripts/seed-dev.ts
new file mode 100755
index 0000000..5428713
--- /dev/null
+++ b/scripts/seed-dev.ts
@@ -0,0 +1,135 @@
+#!/usr/bin/env bun
+/**
+ * Seeds a local development account, session and claimed system.
+ *
+ * Claiming normally requires Discord OAuth. This exists so the management UI can
+ * be exercised locally without it — nothing more.
+ *
+ * Two properties matter:
+ *
+ * 1. It refuses to run against a production configuration. This is development
+ * data and must never be mistaken for a real account.
+ *
+ * 2. The system's identifiers are READ FROM PLURALKIT rather than invented, so
+ * a seeded row satisfies the same invariant a real claim does: the stored
+ * external id is the one the source returned. Hard-coding it produced a row
+ * whose address resolved to a system PluralKit does not have — the page 404d
+ * while the id URL worked, which took a while to understand.
+ *
+ * It contains no secrets and depends on no particular person's account: the
+ * system to seed is given explicitly.
+ */
+
+import { createHash, randomBytes, randomUUID } from "node:crypto";
+import { Database } from "bun:sqlite";
+
+if (process.env["NODE_ENV"] === "production") {
+ console.error("seed-dev: refusing to run with NODE_ENV=production.");
+ process.exit(1);
+}
+
+const hid = process.env["SEED_HID"] ?? process.argv[2];
+if (!hid) {
+ console.error(
+ [
+ "seed-dev: which PluralKit system should be seeded?",
+ "",
+ " bun scripts/seed-dev.ts <system-id>",
+ " SEED_HID=<system-id> bun scripts/seed-dev.ts",
+ "",
+ "Use any system whose information is public — your own is easiest.",
+ "The id is the 5-6 character one PluralKit shows, e.g. from `pk;system`.",
+ ].join("\n"),
+ );
+ process.exit(1);
+}
+
+const databasePath = process.env["DATABASE_PATH"] ?? "./apps/api/data/pkviewer.db";
+const userAgent = `pkviewer/dev-seed (+${process.env["PK_USER_AGENT_CONTACT"] ?? "https://github.com/OWNER/pkviewer"})`;
+
+const response = await fetch(`https://api.pluralkit.me/v2/systems/${encodeURIComponent(hid)}`, {
+ headers: { "User-Agent": userAgent },
+});
+if (!response.ok) {
+ console.error(
+ `seed-dev: PluralKit returned ${response.status} for "${hid}". ` +
+ "Check the id, and that the system is publicly visible.",
+ );
+ process.exit(1);
+}
+const pkSystem = (await response.json()) as { id: string; uuid: string; name: string | null };
+
+let db: Database;
+try {
+ db = new Database(databasePath);
+} catch {
+ console.error(
+ `seed-dev: could not open ${databasePath}. Start the app once (bun run dev) so ` +
+ "migrations create it, or set DATABASE_PATH.",
+ );
+ process.exit(1);
+}
+db.exec("PRAGMA foreign_keys = ON");
+
+const tableExists = db
+ .query("SELECT name FROM sqlite_master WHERE type='table' AND name='accounts'")
+ .get();
+if (!tableExists) {
+ console.error("seed-dev: the database has no schema yet. Run `bun run migrate` first.");
+ process.exit(1);
+}
+
+const now = Date.now();
+const accountId = randomUUID();
+db.query("INSERT INTO accounts (id, created_at) VALUES (?,?)").run(accountId, now);
+
+// A fabricated snowflake, so seeding never ties development data to a real
+// Discord account.
+const discordId = String(100000000000000000n + BigInt(Math.floor(Math.random() * 1e17)));
+db.query(
+ "INSERT INTO discord_identities (discord_user_id, account_id, username, linked_at) VALUES (?,?,?,?)",
+).run(discordId, accountId, "dev-seed", now);
+
+const existing = db
+ .query("SELECT id FROM systems WHERE pk_system_uuid = ?")
+ .get(pkSystem.uuid) as { id: string } | null;
+const systemId = existing?.id ?? randomUUID();
+if (!existing) {
+ db.query(
+ "INSERT INTO systems (id, pk_system_uuid, pk_system_hid, claimed_at, created_at) VALUES (?,?,?,?,?)",
+ ).run(systemId, pkSystem.uuid, pkSystem.id, now, now);
+}
+db.query(
+ "INSERT OR IGNORE INTO grants (account_id, subject_type, subject_id, role, granted_at) VALUES (?,'system',?,'owner',?)",
+).run(accountId, systemId, now);
+
+// Sessions are stored hashed; only this run ever sees the token itself.
+const token = randomBytes(32).toString("base64url");
+db.query(
+ "INSERT INTO sessions (id, account_id, created_at, idle_expires_at, abs_expires_at) VALUES (?,?,?,?,?)",
+).run(
+ createHash("sha256").update(token, "utf8").digest("hex"),
+ accountId,
+ now,
+ now + 7 * 86_400_000,
+ now + 30 * 86_400_000,
+);
+db.close();
+
+const appOrigin = process.env["PUBLIC_APP_ORIGIN"] ?? "http://app.localhost:3000";
+
+console.log(
+ [
+ "",
+ ` Seeded ${pkSystem.name ?? pkSystem.id} (${pkSystem.id}) as a claimed system.`,
+ "",
+ " Set this cookie on the app origin, then open /manage:",
+ "",
+ ` document.cookie = "__Host-pkv_session=${token}; path=/; secure"`,
+ "",
+ ` ${appOrigin}/manage`,
+ "",
+ " Development data only. Delete the database file to start over.",
+ "",
+ ].join("\n"),
+);
diff --git a/tsconfig.base.json b/tsconfig.base.json
new file mode 100644
index 0000000..b91cb9e
--- /dev/null
+++ b/tsconfig.base.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "lib": ["ES2023"],
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "types": ["bun"],
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "noImplicitOverride": true,
+ "noFallthroughCasesInSwitch": true,
+ "exactOptionalPropertyTypes": true,
+ "verbatimModuleSyntax": true,
+ "skipLibCheck": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "noEmit": true,
+ "allowImportingTsExtensions": true
+ }
+}