Skip to content

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

10.5 KB
Raw Blame
// Zero-dependency theme tokens, types, URL safety checks, and lightweight ThemeFile validator for browser boot entries
// (main.tsx / rail.tsx) so booting the theme runtime does not pull zod into the initial bundle.
import { SKIN_IDS } from "./app-settings-ids.ts";

/** Where a theme's files are served, same origin, behind the server's sign-in: `<prefix><themeId>/<file>`. */
export const THEME_ASSET_PREFIX = "/api/theme-assets/";
/** Opening the app with this in its address starts it without the custom theme. */
export const SAFE_LOOK_PARAM = "safe-look";

export const THEME_LIMITS = {
  cssChars: 100_000,
  assetBytes: 10 * 1024 * 1024,
  themeBytes: 40 * 1024 * 1024,
  assetsPerTheme: 40,
  themesPerPerson: 50,
} as const;

export const THEME_ID = /^[a-z0-9][a-z0-9-]{0,47}$/;
export const THEME_ASSET_NAME = /^[a-z0-9][a-z0-9_-]{0,79}\.(png|jpe?g|webp|gif|avif|svg|woff2?|ttf|otf)$/;
const ASSET_URL = /^\/api\/theme-assets\/[a-z0-9][a-z0-9-]{0,47}\/[a-z0-9][a-z0-9_-]{0,79}\.[a-z0-9]{2,5}$/;

export const THEME_ASSET_TYPES: Readonly<Record<string, string>> = {
  png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", gif: "image/gif", avif: "image/avif",
  svg: "image/svg+xml", woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf",
};

/** The app's colour tokens a theme may set, as `--color-<role>`. */
export const THEME_COLOR_ROLES = [
  "app", "panel", "frame", "raised", "raised-hover", "card", "inset", "control", "composer", "composer-ring",
  "menu", "menu-hover", "menu-active", "hairline", "edge", "scrollbar",
  "ink", "ink-secondary", "ink-tertiary", "accent", "accent-border", "accent-text", "accent-ink", "focus",
  "bubble-user", "bubble-user-ink", "success", "success-ink", "danger", "danger-ink", "warning",
] as const;
export type ThemeColorRole = (typeof THEME_COLOR_ROLES)[number];

export const THEME_ROLE_HELP: Readonly<Record<ThemeColorRole, string>> = {
  app: "the window's ground behind the chat", panel: "the sidebar", frame: "the top bar and the rail around the app",
  raised: "content surfaces", "raised-hover": "a hovered row or button", card: "cards and the bot's bubble", inset: "sunken fields",
  control: "a control on a card", composer: "the message box", "composer-ring": "the message box's outline", menu: "menus and popovers",
  "menu-hover": "a hovered menu row", "menu-active": "a chosen menu row", hairline: "borders", edge: "the line where two panes meet",
  scrollbar: "scrollbar thumbs", ink: "main text", "ink-secondary": "quieter text", "ink-tertiary": "the quietest text: hints and times",
  accent: "buttons and highlights", "accent-border": "the accent's edge", "accent-text": "links and accent text", "accent-ink": "text on the accent",
  focus: "the keyboard focus ring", "bubble-user": "your own messages", "bubble-user-ink": "text in your own messages",
  success: "done and OK", "success-ink": "text on success", danger: "errors and delete", "danger-ink": "text on danger", warning: "warnings",
};

export interface ThemeVariant {
  canvas?: string;
  accent?: string;
  colors?: Partial<Record<ThemeColorRole, string>>;
}

export interface ThemeFile {
  name: string;
  skin?: (typeof SKIN_IDS)[number] | "system";
  canvas?: string;
  accent?: string;
  colors?: Partial<Record<ThemeColorRole, string>>;
  light?: ThemeVariant;
  dark?: ThemeVariant;
  font?: string;
  css?: string;
}

export interface ThemeSummary {
  id: string;
  name: string;
  hasCss: boolean;
  assets: string[];
}
/** GET /api/themes: this person's saved themes and the one their windows wear. */
export interface ThemeList {
  active: string | null;
  themes: ThemeSummary[];
}
/** GET /api/themes/active. */
export interface ActiveTheme {
  id: string | null;
  theme: ThemeFile | null;
}
/** How many of a person's look changes are kept to go back to. */
export const LOOK_HISTORY_LIMIT = 30;
/** What one look change did: a theme made, edited or deleted while worn, a theme or built-in skin worn, back to the
 * default look, or earlier changes gone back on. */
export const LOOK_CHANGE_KINDS = ["made", "edited", "deleted", "wore", "skin", "default", "undid"] as const;
export interface LookChange {
  kind: (typeof LOOK_CHANGE_KINDS)[number];
  /** The theme's name, or the built-in skin's id. */
  name?: string;
  /** undid: how many changes it went back on. */
  count?: number;
}
/** GET /api/themes/history, newest first; POST it `{ index }` to go back to how things looked right after that change. */
export interface ThemeHistoryItem extends LookChange {
  index: number;
  at: string;
}
export const THEME_EXPORT_VERSION = 1;

export const themeAssetUrl = (themeId: string, name: string) => `${THEME_ASSET_PREFIX}${themeId}/${name}`;
export const themeAssetType = (name: string): string | undefined => THEME_ASSET_TYPES[name.slice(name.lastIndexOf(".") + 1).toLowerCase()];

/** A url() target a theme may load: an inline data: address, a fragment, or one of the theme files on this server. */
export function themeUrlAllowed(target: string): boolean {
  return /^data:/i.test(target) || target.startsWith("#") || (ASSET_URL.test(target) && !target.includes(".."));
}

/** Every url() argument in `text`, or null when one cannot be read cleanly. */
export function urlTargets(text: string): string[] | null {
  const lower = text.toLowerCase();
  const found: string[] = [];
  for (let at = lower.indexOf("url("); at !== -1; at = lower.indexOf("url(", at + 4)) {
    let index = at + 4;
    while (/\s/.test(text[index] ?? "")) index++;
    const quote = text[index];
    let target: string;
    if (quote === '"' || quote === "'") {
      const close = text.indexOf(quote, index + 1);
      if (close === -1) return null;
      target = text.slice(index + 1, close);
      index = close + 1;
      while (/\s/.test(text[index] ?? "")) index++;
      if (text[index] !== ")") return null;
    } else {
      const close = text.indexOf(")", index);
      if (close === -1) return null;
      target = text.slice(index, close).trim();
      if (/[\s"'(]/.test(target)) return null;
    }
    found.push(target.trim());
  }
  return found;
}

export const LOADS_BY_NAME = /image-set\(|\bimage\(|\bsrc\(/i;

/**
 * Security: whether one parsed declaration value could load a file from anywhere but this server's theme files. The
 * window drops such declarations. A value that still holds a backslash is refused whole: an escape can spell `url` or
 * `var` where a check of the text would not see it.
 */
export function themeValueLoads(value: string): boolean {
  if (value.includes("\\") || LOADS_BY_NAME.test(value)) return true;
  const targets = urlTargets(value);
  return targets === null || targets.some((target) => !themeUrlAllowed(target));
}

const HEX_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
const COLOR_RE = /^[#a-z0-9(),.%\s/+-]+$/i;
const COLOR_LOAD_RE = /url|image|src|attr/i;
const FONT_RE = /^[\w\s"',.-]*$/;
const ROLE_SET = new Set<string>(THEME_COLOR_ROLES);
const SKIN_SET = new Set<string>([...SKIN_IDS, "system"]);
const THEME_KEYS = new Set(["name", "skin", "canvas", "accent", "colors", "light", "dark", "font", "css"]);
const VARIANT_KEYS = new Set(["canvas", "accent", "colors"]);

function isPlainRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function parseHex(value: unknown): string | null {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  return HEX_RE.test(trimmed) ? trimmed : null;
}

function parseColor(value: unknown): string | null {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  if (trimmed.length < 1 || trimmed.length > 120) return null;
  if (!COLOR_RE.test(trimmed) || COLOR_LOAD_RE.test(trimmed)) return null;
  return trimmed;
}

function parseColors(value: unknown): Partial<Record<ThemeColorRole, string>> | null {
  if (!isPlainRecord(value)) return null;
  const out: Partial<Record<ThemeColorRole, string>> = {};
  for (const [key, raw] of Object.entries(value)) {
    if (!ROLE_SET.has(key)) return null;
    if (raw === undefined) continue;
    const parsed = parseColor(raw);
    if (parsed === null) return null;
    out[key as ThemeColorRole] = parsed;
  }
  return out;
}

function parseVariant(value: unknown): ThemeVariant | null {
  if (!isPlainRecord(value)) return null;
  for (const key of Object.keys(value)) {
    if (!VARIANT_KEYS.has(key)) return null;
  }
  const out: ThemeVariant = {};
  if (value.canvas !== undefined) {
    const canvas = parseHex(value.canvas);
    if (canvas === null) return null;
    out.canvas = canvas;
  }
  if (value.accent !== undefined) {
    const accent = parseHex(value.accent);
    if (accent === null) return null;
    out.accent = accent;
  }
  if (value.colors !== undefined) {
    const colors = parseColors(value.colors);
    if (colors === null) return null;
    out.colors = colors;
  }
  return out;
}

/** Zero-dependency strict validator matching `themeFileSchema` in `shared/theme.ts`. */
export function parseThemeFile(value: unknown): ThemeFile | null {
  if (!isPlainRecord(value)) return null;
  for (const key of Object.keys(value)) {
    if (!THEME_KEYS.has(key)) return null;
  }
  if (typeof value.name !== "string") return null;
  const name = value.name.trim();
  if (name.length < 1 || name.length > 60) return null;
  const out: ThemeFile = { name };
  if (value.skin !== undefined) {
    if (typeof value.skin !== "string" || !SKIN_SET.has(value.skin)) return null;
    out.skin = value.skin as ThemeFile["skin"];
  }
  if (value.canvas !== undefined) {
    const canvas = parseHex(value.canvas);
    if (canvas === null) return null;
    out.canvas = canvas;
  }
  if (value.accent !== undefined) {
    const accent = parseHex(value.accent);
    if (accent === null) return null;
    out.accent = accent;
  }
  if (value.colors !== undefined) {
    const colors = parseColors(value.colors);
    if (colors === null) return null;
    out.colors = colors;
  }
  if (value.light !== undefined) {
    const light = parseVariant(value.light);
    if (light === null) return null;
    out.light = light;
  }
  if (value.dark !== undefined) {
    const dark = parseVariant(value.dark);
    if (dark === null) return null;
    out.dark = dark;
  }
  if (value.font !== undefined) {
    if (typeof value.font !== "string") return null;
    const font = value.font.trim();
    if (font.length > 300 || !FONT_RE.test(font)) return null;
    out.font = font;
  }
  if (value.css !== undefined) {
    if (typeof value.css !== "string" || value.css.length > THEME_LIMITS.cssChars) return null;
    out.css = value.css;
  }
  return out;
}