branding.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import 'server-only'
  2. import path from 'node:path'
  3. import { db } from '@/lib/db'
  4. import { uploadsRoot } from '@/lib/upload-root'
  5. import { installHasLicense, isCloudMode } from '@/lib/features'
  6. import {
  7. BRANDING_APP_NAME_MAX_LENGTH,
  8. SYSTEM_SETTING_KEYS,
  9. } from '@/features/admin/Schema/systemSettingsSchema'
  10. /**
  11. * What the browser calls this install: tab title, favicon, home-screen and
  12. * installed-app name and icon. Only a licensed self-hosted install may change
  13. * it; everywhere else it is TorqVoice. Documents, link previews and the rest
  14. * of the app are not touched by this.
  15. */
  16. export const DEFAULT_APP_NAME = 'TorqVoice'
  17. export type AppBranding = {
  18. name: string
  19. iconUrl: string | null
  20. /** True when the install is licensed and has a name or an icon set. */
  21. custom: boolean
  22. }
  23. const DEFAULT_BRANDING: AppBranding = { name: DEFAULT_APP_NAME, iconUrl: null, custom: false }
  24. // The root layout asks on every page, and the licence check verifies signed
  25. // tokens, so the answer is kept for a minute. Saving a branding setting clears it.
  26. const CACHE_TTL_MS = 60_000
  27. // On globalThis: Next can load this module more than once, and each copy
  28. // would otherwise keep its own stale answer.
  29. const globalForBranding = globalThis as unknown as {
  30. __appBranding?: { value: AppBranding; expiresAt: number }
  31. }
  32. /** Install-owned, never referenced by a workshop's records. */
  33. export function brandingDir(): string {
  34. return path.join(uploadsRoot(), 'system', 'branding')
  35. }
  36. export const APP_ICON_MIME_TYPES: Record<string, string> = {
  37. png: 'image/png',
  38. jpg: 'image/jpeg',
  39. jpeg: 'image/jpeg',
  40. webp: 'image/webp',
  41. avif: 'image/avif',
  42. }
  43. /**
  44. * Whether a stored icon name is a bare file name we would have written. The
  45. * setting is read from the database and joined onto a path, so anything that
  46. * could climb out of the branding directory is refused here.
  47. */
  48. export function isSafeIconFileName(value: string): boolean {
  49. if (!value || value !== path.basename(value)) return false
  50. if (value.includes('..') || value.includes('/') || value.includes('\\')) return false
  51. const ext = value.split('.').pop()?.toLowerCase() ?? ''
  52. return Object.hasOwn(APP_ICON_MIME_TYPES, ext) && value.length > ext.length + 1
  53. }
  54. /** The public URL of a stored icon; the file name doubles as a cache-buster. */
  55. export function appIconUrl(fileName: string): string {
  56. return `/api/public/app-icon?v=${encodeURIComponent(fileName)}`
  57. }
  58. async function readBranding(): Promise<AppBranding> {
  59. if (isCloudMode()) return DEFAULT_BRANDING
  60. if (!(await installHasLicense())) return DEFAULT_BRANDING
  61. const rows = await db.systemSetting.findMany({
  62. where: {
  63. key: { in: [SYSTEM_SETTING_KEYS.BRANDING_APP_NAME, SYSTEM_SETTING_KEYS.BRANDING_APP_ICON] },
  64. },
  65. select: { key: true, value: true },
  66. })
  67. const value = (key: string) => rows.find((row) => row.key === key)?.value?.trim() ?? ''
  68. const name = value(SYSTEM_SETTING_KEYS.BRANDING_APP_NAME).slice(0, BRANDING_APP_NAME_MAX_LENGTH)
  69. const icon = value(SYSTEM_SETTING_KEYS.BRANDING_APP_ICON)
  70. return {
  71. name: name || DEFAULT_APP_NAME,
  72. iconUrl: icon ? appIconUrl(icon) : null,
  73. custom: Boolean(name || icon),
  74. }
  75. }
  76. export async function getAppBranding(): Promise<AppBranding> {
  77. const cached = globalForBranding.__appBranding
  78. if (cached && cached.expiresAt > Date.now()) return cached.value
  79. let value: AppBranding
  80. try {
  81. value = await readBranding()
  82. } catch (error) {
  83. // A tab title is not worth failing a page over, and the build renders
  84. // without a database.
  85. console.error('[branding] Falling back to the default:', error)
  86. return DEFAULT_BRANDING
  87. }
  88. globalForBranding.__appBranding = { value, expiresAt: Date.now() + CACHE_TTL_MS }
  89. return value
  90. }
  91. /** Forget the cached branding, so the next page shows what was just saved. */
  92. export function invalidateAppBranding(): void {
  93. globalForBranding.__appBranding = undefined
  94. }