#!/usr/bin/env node // ───────────────────────────────────────────────────────────────────────────── // Livtec / AIDO white-label overlay for Onyx Community Edition. // // Applies all branding to a clean upstream Onyx checkout, driven entirely by // branding/branding.config.json. Re-runnable and deterministic: to upgrade Onyx, // check out the new upstream tag into ./onyx and run this script again, then // rebuild the web image. // // Usage: node branding/apply-branding.mjs [--dry-run] [--no-fetch] // // CE-ONLY: this rebrands at the open-source default level (the `|| "Onyx"` // fallbacks, hardcoded strings, logo components and favicon). It does NOT enable // or depend on Onyx's Enterprise white-label feature (enterprise-settings). // ───────────────────────────────────────────────────────────────────────────── import { readFile, writeFile, copyFile, mkdir, readdir, stat, rm } from "node:fs/promises"; import { existsSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { execFileSync } from "node:child_process"; import path from "node:path"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(__dirname, ".."); // project root const BRANDING = __dirname; // branding/ const CONFIG = JSON.parse(await readFile(path.join(BRANDING, "branding.config.json"), "utf8")); const argv = process.argv.slice(2); const DRY = argv.includes("--dry-run"); const NO_FETCH = argv.includes("--no-fetch"); const WEB = path.join(ROOT, CONFIG.upstream.webSrcRoot); // onyx/web const PUBLIC = path.join(WEB, "public"); const PUBLIC_BRANDING = path.join(PUBLIC, "branding"); const SRC = path.join(WEB, "src"); const OPAL_LOGOS = path.join(WEB, "lib/opal/src/logos"); const OPAL_ICONS = path.join(WEB, "lib/opal/src/icons"); const c = { gray: "\x1b[90m", green: "\x1b[32m", yellow: "\x1b[33m", red: "\x1b[31m", bold: "\x1b[1m", reset: "\x1b[0m" }; const log = (m) => console.log(m); const ok = (m) => log(`${c.green}✓${c.reset} ${m}`); const warn = (m) => log(`${c.yellow}!${c.reset} ${m}`); const step = (m) => log(`\n${c.bold}${m}${c.reset}`); let filesChanged = 0; let totalReplacements = 0; if (!existsSync(WEB)) { console.error(`${c.red}✗ Onyx web source not found at ${WEB}. Clone/checkout Onyx into ./onyx first.${c.reset}`); process.exit(1); } log(`${c.bold}Livtec white-label → ${CONFIG.brand.name}${c.reset} ${c.gray}(${DRY ? "dry-run" : "apply"}${NO_FETCH ? ", no-fetch" : ""})${c.reset}`); log(`${c.gray}web source: ${WEB}${c.reset}`); // ── 0. End-user i18n backport (temporary, until official Onyx i18n) ────────── // Applies PR #12558's react-i18next changes onto the pinned checkout. MUST run // before the string codemod so the patch's context lines still match the clean // upstream source; the codemod then rebrands Onyx->AIDO inside the locale JSONs. // Requires the checkout to be at i18n.baseCommit (== upstream.pinnedCommit). if (CONFIG.i18n && CONFIG.i18n.enabled) { step("0/4 End-user i18n (backport of PR #12558)"); const patchPath = path.join(ROOT, CONFIG.i18n.patch); if (!existsSync(patchPath)) { warn(`i18n patch not found at ${patchPath} — skipping`); } else { const gitApply = (extra) => execFileSync("git", ["apply", "-p1", ...extra, patchPath], { cwd: ROOT, stdio: "pipe" }); // Idempotency sentinel: the patch adds this file. If it exists the overlay was // already applied (a later branding pass may have edited the patched files, so a // reverse-check is unreliable) — skip re-applying. const sentinel = path.join(WEB, "src/lib/i18n.ts"); if (existsSync(sentinel)) { ok("i18n patch already applied (found src/lib/i18n.ts) — skipping"); } else { let applies = true; try { gitApply(["--check"]); } catch { applies = false; } if (!applies) { console.error(`${c.red}✗ i18n patch does not apply. The checkout must be at i18n.baseCommit (${CONFIG.i18n.baseCommit}). Run \`make setup\` (pinnedCommit is set to that tag), or set i18n.enabled=false.${c.reset}`); process.exit(1); } if (DRY) ok("i18n patch applies cleanly (dry-run, not written)"); else { gitApply([]); ok(`applied i18n patch — react-i18next, user UI only (Admin stays English); default language ${CONFIG.i18n.defaultLanguage}`); } } // Restrict the offered languages to CONFIG.i18n.languages and overlay the // client-editable dictionaries so translation edits persist across `make setup`. // Idempotent — safe whether the patch was just applied or already present. if (!DRY && existsSync(sentinel)) { const ALL = ["en", "es", "pt", "fr", "de"]; const keep = CONFIG.i18n.languages?.length ? CONFIG.i18n.languages : ALL; const drop = ALL.filter((l) => !keep.includes(l)); const i18nTs = path.join(WEB, "src/lib/i18n.ts"); let ts = await readFile(i18nTs, "utf8"); for (const l of drop) { ts = ts.replace(new RegExp(`^\\s*import \\w+ from "\\.\\./\\.\\./public/locales/${l}/common\\.json";\\n`, "m"), ""); ts = ts.replace(new RegExp(`^\\s*${l}: \\{ common: \\w+ \\},\\n`, "m"), ""); } await writeFile(i18nTs, ts); const settings = path.join(WEB, "src/views/SettingsPage.tsx"); let sp = await readFile(settings, "utf8"); for (const l of drop) { sp = sp.replace(new RegExp(`^\\s*[^<]*\\n`, "m"), ""); } await writeFile(settings, sp); for (const l of drop) { const d = path.join(PUBLIC, "locales", l); if (existsSync(d)) await rm(d, { recursive: true, force: true }); } let overlaid = 0; const dictDir = CONFIG.i18n.dictionaries ? path.join(ROOT, CONFIG.i18n.dictionaries) : null; if (dictDir) for (const l of keep) { const srcDict = path.join(dictDir, `${l}.json`); const destDict = path.join(PUBLIC, "locales", l, "common.json"); if (existsSync(srcDict)) { await mkdir(path.dirname(destDict), { recursive: true }); await copyFile(srcDict, destDict); overlaid++; } } ok(`languages: ${keep.join("/")} (dropped ${drop.length ? drop.join("/") : "none"}); overlaid ${overlaid} client dictionar${overlaid === 1 ? "y" : "ies"}`); } } } // ── 1. Assets: fetch brand images, repoint favicon ────────────────────────── step("1/4 Assets"); if (!DRY) await mkdir(PUBLIC_BRANDING, { recursive: true }); async function placeAsset(key) { const a = CONFIG.assets[key]; const destPublic = path.join(PUBLIC, a.dest); // onyx/web/public/branding/ const cache = path.join(BRANDING, "assets", path.basename(a.dest)); if (!NO_FETCH) { try { const res = await fetch(a.url, { signal: AbortSignal.timeout(20000) }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const buf = Buffer.from(await res.arrayBuffer()); if (buf.length < 100) throw new Error("suspiciously small"); if (!DRY) { await writeFile(destPublic, buf); await writeFile(cache, buf); // refresh offline fallback } ok(`${key}: fetched ${buf.length}b → public/${a.dest}`); return; } catch (e) { warn(`${key}: fetch failed (${e.message}); trying committed fallback`); } } if (existsSync(cache)) { if (!DRY) await copyFile(cache, destPublic); ok(`${key}: copied committed fallback → public/${a.dest}`); } else { warn(`${key}: NO asset available (no network + no fallback in branding/assets/). Drop a file at ${cache} and re-run.`); } } for (const key of Object.keys(CONFIG.assets)) { if (key.startsWith("$")) continue; await placeAsset(key); } // Repoint the default favicon: overwrite /onyx.ico so even un-patched refs work, // and update DynamicMetadata's fallback to the branded PNG. const favSrc = path.join(PUBLIC, CONFIG.assets.favicon.dest); if (existsSync(favSrc) && !DRY) { await copyFile(favSrc, path.join(PUBLIC, "onyx.ico")); ok("favicon: overwrote public/onyx.ico with branded icon"); } // ── 1b. Dockerfile base images ────────────────────────────────────────────── // Onyx's web Dockerfile bases on Docker Hardened Images (dhi.io/node:*), which need // a paid DHI subscription + `docker login dhi.io`, so `make build` fails with a // registry-login error for anyone without DHI access. Swap those FROM lines for the // equivalent public Docker Hub node images (config → build.baseImageReplacements). // No-op with a warning if the DHI bases are absent, so it stays safe if upstream // reverts or renames — same maintenance model as the logo/notification patches. step("1b Dockerfile base images"); { const dfPath = path.join(WEB, "Dockerfile"); const repl = (CONFIG.build && CONFIG.build.baseImageReplacements) || {}; const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); if (!existsSync(dfPath)) { warn("Dockerfile not found — skipping base-image swap"); } else { let df = await readFile(dfPath, "utf8"); let swapped = 0; // Longest keys first so `...-dev` is handled before its `...debian13` prefix. for (const from of Object.keys(repl).sort((a, b) => b.length - a.length)) { // Only rewrite actual `FROM` lines; drop any pinned @sha256 digest since it // won't match the public image. const re = new RegExp("^(FROM\\s+)" + esc(from) + "(@sha256:[a-f0-9]+)?", "gm"); df = df.replace(re, (_m, p1) => { swapped++; return p1 + repl[from]; }); } // The DHI runtime ran as the non-root `node` user (uid 1000); the public // slim image defaults to root. Restore non-root by setting USER before the // runtime CMD (idempotent). Only when we actually swapped to a public base. let hardened = false; if (swapped > 0 && !/^USER\s+node\b/m.test(df)) { const cmdRe = /^CMD \["node", "server\.js"\]/m; if (cmdRe.test(df)) { df = df.replace(cmdRe, 'USER node\nCMD ["node", "server.js"]'); hardened = true; } } if (swapped > 0) { if (!DRY) await writeFile(dfPath, df); ok(`swapped ${swapped} DHI base image(s) → public Docker Hub node (no docker login needed)` + (hardened ? "; set runtime USER node (non-root)" : "")); } else { warn("no dhi.io base images in Dockerfile (already public / upstream changed) — nothing to swap"); } } } // ── 2. Logo components ────────────────────────────────────────────────────── step("2/4 Logo components"); const MARK_SRC = "/" + CONFIG.assets.mark.dest; const WORDMARK_SRC = "/" + CONFIG.assets.wordmark.dest; function fillTemplate(tpl) { return tpl .replaceAll("__BRAND_NAME__", CONFIG.brand.name) .replaceAll("__MARK_SRC__", MARK_SRC) .replaceAll("__WORDMARK_SRC__", WORDMARK_SRC); } const logoInstalls = [ ["onyx-logo.tsx", path.join(OPAL_LOGOS, "onyx-logo.tsx")], ["onyx-typed.tsx", path.join(OPAL_LOGOS, "onyx-typed.tsx")], ["onyx-logo-typed.tsx", path.join(OPAL_LOGOS, "onyx-logo-typed.tsx")], ["onyx-logo.tsx", path.join(OPAL_ICONS, "onyx-logo.tsx")], // 16px icon → brand mark ]; for (const [tplName, dest] of logoInstalls) { if (!existsSync(dest)) { warn(`logo target missing (upstream moved it?): ${path.relative(WEB, dest)}`); continue; } const filled = fillTemplate(await readFile(path.join(BRANDING, "templates", tplName), "utf8")); if (!DRY) await writeFile(dest, filled); ok(`installed ${tplName} → ${path.relative(WEB, dest)}`); } // ── 2b. Targeted source patches ───────────────────────────────────────────── // Surgical, anchored edits for branding that the bulk string codemod can't reach: // an inline SVG wordmark, and backend-generated notification content that is only // rebrandable at render time in the web image. Each patch warns (does not fail) if // its anchor is missing after an upstream change — same maintenance model as logos. step("2b/4 Targeted patches"); async function patchFile(rel, edits) { const fp = path.join(SRC, rel); if (!existsSync(fp)) { warn(`patch target missing (upstream moved it?): ${rel}`); return; } let src = await readFile(fp, "utf8"); let applied = 0; for (const e of edits) { if (e.done && src.includes(e.done)) { applied++; continue; } // idempotent: already patched const present = e.find instanceof RegExp ? e.find.test(src) : src.includes(e.find); if (!present) { warn(`anchor not found in ${rel}: ${e.desc}`); continue; } src = e.find instanceof RegExp ? src.replace(e.find, e.replace) : src.split(e.find).join(e.replace); applied++; } if (applied && !DRY) await writeFile(fp, src); if (applied) ok(`patched ${rel} (${applied}/${edits.length} edit(s))`); } // (a) Error page / craft wordmark: inline SVG → AIDO image asset. const onyxTypeIcon = fillTemplate(await readFile(path.join(BRANDING, "templates", "icons-OnyxLogoTypeIcon.tsx"), "utf8")); await patchFile("components/icons/icons.tsx", [{ desc: "OnyxLogoTypeIcon inline SVG wordmark", find: /export const OnyxLogoTypeIcon = \(\{[\s\S]*?\n\};\n/, replace: onyxTypeIcon.endsWith("\n") ? onyxTypeIcon : onyxTypeIcon + "\n", }]); // (b) Notifications: their text is generated by the backend (official image we do // NOT rebuild), so rebrand/suppress it at render time. Generate a tiny runtime // helper from config, then route the notifications list through it. const N = CONFIG.notifications ?? { sanitize: true, suppressTypes: [] }; const runtime = `// AUTO-GENERATED by branding/apply-branding.mjs — do not edit by hand. // Runtime rebranding for backend-generated content (notification bell) that the // build-time codemod cannot reach. Driven by branding.config.json → notifications. const WORD_PAIRS: [string, string][] = ${JSON.stringify(Object.entries(CONFIG.rename.word))}; const SANITIZE = ${N.sanitize ? "true" : "false"}; const SUPPRESS_TYPES = new Set(${JSON.stringify(N.suppressTypes ?? [])}); export function brandText(text: T): T { if (!text || !SANITIZE) return text; let out: string = text; for (const [from, to] of WORD_PAIRS) { out = out.replace(new RegExp(\`\\\\b\${from}\\\\b\`, "g"), to); } return out as T; } export function filterBrandedNotifications< N extends { notif_type: string; title: string; description: string | null }, >(list: N[]): N[] { return list .filter((n) => !SUPPRESS_TYPES.has(n.notif_type)) .map((n) => ({ ...n, title: brandText(n.title), description: brandText(n.description) })); } `; if (!DRY) await writeFile(path.join(SRC, "lib/branding-runtime.ts"), runtime); ok(`generated lib/branding-runtime.ts (sanitize=${!!N.sanitize}, suppress=${(N.suppressTypes ?? []).length})`); await patchFile("hooks/useNotifications.ts", [ { desc: "import branding runtime", done: `import { filterBrandedNotifications } from "@/lib/branding-runtime";`, find: `import { useCallback, useMemo, useRef } from "react";`, replace: `import { useCallback, useMemo, useRef } from "react";\nimport { filterBrandedNotifications } from "@/lib/branding-runtime";`, }, { desc: "route notifications list through branding filter", done: `return filterBrandedNotifications(`, find: ` return data.flatMap((page) =>\n page.notifications.filter((notification) => {\n if (seenNotificationIds.has(notification.id)) {\n return false;\n }\n seenNotificationIds.add(notification.id);\n return true;\n })\n );`, replace: ` return filterBrandedNotifications(\n data.flatMap((page) =>\n page.notifications.filter((notification) => {\n if (seenNotificationIds.has(notification.id)) {\n return false;\n }\n seenNotificationIds.add(notification.id);\n return true;\n })\n )\n );`, }, ]); // ── 3. String codemod (user-visible references) ───────────────────────────── step("3/4 String codemod"); const literals = Object.entries(CONFIG.rename.literals); const wordPairs = Object.entries(CONFIG.rename.word); const ASSET_PATH_EDITS = [["/onyx.ico", `/${CONFIG.assets.favicon.dest}`]]; // favicon ref in DynamicMetadata const SKIP = /(\.test\.|\.spec\.|\.stories\.|__tests__|__mocks__|\/node_modules\/)/; const EXT = /\.(ts|tsx)$/; // Never rebrand these whole files (logos handled above; types declare identifiers). // branding-runtime.ts is excluded because it holds the "Onyx"→brand rename rule // itself — the word pass must not rewrite its own needle. const SKIP_FILES = new Set([ ...logoInstalls.map(([, d]) => path.resolve(d)), path.resolve(path.join(SRC, "lib/branding-runtime.ts")), ]); async function* walk(dir) { for (const e of await readdir(dir, { withFileTypes: true })) { const p = path.join(dir, e.name); if (e.isDirectory()) { yield* walk(p); continue; } if (EXT.test(e.name) && !SKIP.test(p)) yield p; } } for await (const file of walk(SRC)) { if (SKIP_FILES.has(path.resolve(file))) continue; const before = await readFile(file, "utf8"); let after = before; let n = 0; // 3a. exact-string literals (URLs etc.) — applied first for (const [from, to] of [...literals, ...ASSET_PATH_EDITS]) { if (after.includes(from)) { const parts = after.split(from); n += parts.length - 1; after = parts.join(to); } } // 3b. whole-word, case-sensitive brand name. \bOnyx\b never matches camelCase // identifiers (OnyxDocument, SvgOnyxLogo) or lowercase refs (@onyx, onyx.app). for (const [from, to] of wordPairs) { const re = new RegExp(`\\b${from.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "g"); after = after.replace(re, () => { n++; return to; }); } if (n > 0) { if (!DRY) await writeFile(file, after); filesChanged++; totalReplacements += n; if (DRY || process.env.VERBOSE) log(` ${c.gray}${path.relative(WEB, file)} (${n})${c.reset}`); } } ok(`${totalReplacements} replacement(s) across ${filesChanged} file(s)`); // 3c. Rebrand the bundled i18n dictionaries (Onyx->AIDO in every language) so the // translated UI is branded too. Only when the i18n backport is active. if (CONFIG.i18n && CONFIG.i18n.enabled && CONFIG.i18n.rebrandLocales) { const LOCALES = path.join(PUBLIC, "locales"); if (existsSync(LOCALES)) { let locN = 0, locFiles = 0; async function* walkJson(d) { for (const e of await readdir(d, { withFileTypes: true })) { const p = path.join(d, e.name); if (e.isDirectory()) yield* walkJson(p); else if (e.name.endsWith(".json")) yield p; } } for await (const file of walkJson(LOCALES)) { let s = await readFile(file, "utf8"); let m = 0; for (const [from, to] of literals) { if (s.includes(from)) { const parts = s.split(from); m += parts.length - 1; s = parts.join(to); } } for (const [from, to] of wordPairs) { const re = new RegExp(`\\b${from.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "g"); s = s.replace(re, () => { m++; return to; }); } if (m > 0) { if (!DRY) await writeFile(file, s); locN += m; locFiles++; } } ok(`rebranded i18n dictionaries: ${locN} replacement(s) across ${locFiles} locale file(s)`); } else { warn("i18n enabled but no public/locales dir found (patch may not have applied)"); } } // ── 4. Summary ────────────────────────────────────────────────────────────── step("4/4 Done"); log(`${c.green}White-label applied for ${c.bold}${CONFIG.brand.name}${c.reset}${c.green} (${CONFIG.brand.legalName}).${c.reset}`); log(`${c.gray}Next: docker compose build web_server && docker compose up -d${c.reset}`); if (DRY) warn("dry-run: no files were written.");