feat: migrate project secrets and user-scoped colors
Lint / Lint (push) Successful in 25s
Tests / Go backend (push) Successful in 34s
Tests / Dashboard checks (push) Successful in 48s
Docker / Docker Build & Push (push) Successful in 3m29s

This commit is contained in:
Gabriel20xx committed 2026-09-15 13:22:50 +02:00
1 parent f723afa369
commit 07e25a3cf3
13 files changed
+277 -12

No files matched your search

+2 -2
View File
@@ -39,7 +39,7 @@ AuthGuard integration has three states:
Because AuthGuard doesn't know "this is CollabTable's initial account" and can't answer "have any accounts been registered yet" (it's a shared identity store other projects and other CollabTable instances may already use), the one-time setup screen is instead gated by a small local flag in Postgres, independent of AuthGuard's own state. Because AuthGuard doesn't know "this is CollabTable's initial account" and can't answer "have any accounts been registered yet" (it's a shared identity store other projects and other CollabTable instances may already use), the one-time setup screen is instead gated by a small local flag in Postgres, independent of AuthGuard's own state.
`AUTHGUARD_URL` and `CARRIERNODE_URL` are also only the bootstrap fallback: once CollabTable is registered in ProjectConfigurator's Projects workspace, ProjectConfigurator pushes both values here automatically (`PUT /api/core-services/internal`, `X-Internal-Auth`-gated with `INTERNAL_SERVICE_SECRET`) and keeps them current with no restart — see `Core/ProjectConfigurator/README.md`'s "Pushing core service info to other projects". This means `AUTHGUARD_URL` no longer needs to be set at all for a registered deployment: it stays "pending" until the first push. A push never overrides `AUTH_DISABLED=true`; it only ever retargets an already-enabled AuthGuard connection. CarrierNode isn't used by any feature here yet, but the client is wired and ready. `AUTHGUARD_URL` and `CARRIERNODE_URL` are also only the bootstrap fallback: once CollabTable is registered in ProjectConfigurator's Projects workspace, ProjectConfigurator pushes both values here automatically (`PUT /api/core-services/internal`, `X-Internal-Auth`-gated with `SECRET`) and keeps them current with no restart — see `Core/ProjectConfigurator/README.md`'s "Pushing core service info to other projects". This means `AUTHGUARD_URL` no longer needs to be set at all for a registered deployment: it stays "pending" until the first push. A push never overrides `AUTH_DISABLED=true`; it only ever retargets an already-enabled AuthGuard connection. CarrierNode isn't used by any feature here yet, but the client is wired and ready.
The device-sync API token (generated from the dashboard's Settings page, used by the Android app's `Authorization: Bearer` header for `/api/lists`, `/api/fields`, `/api/items`, `/api/sync`, and notification polling) is unrelated to AuthGuard and unaffected by whether it's configured: it's a long-lived per-account credential for a user's own devices, not a browser session, and stays entirely local to CollabTable's own Postgres. The device-sync API token (generated from the dashboard's Settings page, used by the Android app's `Authorization: Bearer` header for `/api/lists`, `/api/fields`, `/api/items`, `/api/sync`, and notification polling) is unrelated to AuthGuard and unaffected by whether it's configured: it's a long-lived per-account credential for a user's own devices, not a browser session, and stays entirely local to CollabTable's own Postgres.
@@ -49,7 +49,7 @@ The device-sync API token (generated from the dashboard's Settings page, used by
| `AUTHGUARD_URL` | No | unset (pending) | Optional bootstrap/override base URL of the AuthGuard identity service. Leaving it unset does not disable authentication — it leaves the service "pending" until ProjectConfigurator pushes a URL, failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off. | | `AUTHGUARD_URL` | No | unset (pending) | Optional bootstrap/override base URL of the AuthGuard identity service. Leaving it unset does not disable authentication — it leaves the service "pending" until ProjectConfigurator pushes a URL, failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off. |
| `AUTH_DISABLED` | No | `false` | Set `true` to disable authentication entirely (no login screen, nothing gated, every request treated as authenticated) — for local development or a standalone deployment with no AuthGuard integration at all. | | `AUTH_DISABLED` | No | `false` | Set `true` to disable authentication entirely (no login screen, nothing gated, every request treated as authenticated) — for local development or a standalone deployment with no AuthGuard integration at all. |
| `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. | | `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. |
| `INTERNAL_SERVICE_SECRET` | No | unset (push endpoint refuses every caller) | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal`. | | `SECRET` | No | unset (push endpoint refuses every caller) | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal`. |
| `PORT` | No | `8080` | HTTP listen port | | `PORT` | No | `8080` | HTTP listen port |
| `APP_VERSION` | No | `dev` | Version label shown on the dashboard's About page | | `APP_VERSION` | No | `dev` | Version label shown on the dashboard's About page |
| `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS, to mark cookies `Secure` | | `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS, to mark cookies `Secure` |
+5 -1
View File
@@ -40,7 +40,6 @@ COOKIE_SECURE=false
# still needs to be set even though AUTHGUARD_URL/CARRIERNODE_URL don't. A # still needs to be set even though AUTHGUARD_URL/CARRIERNODE_URL don't. A
# push never overrides AUTH_DISABLED=true; it only ever retargets an # push never overrides AUTH_DISABLED=true; it only ever retargets an
# already-enabled AuthGuard connection. # already-enabled AuthGuard connection.
# INTERNAL_SERVICE_SECRET=
################################################################# #################################################################
# PostgreSQL configuration # PostgreSQL configuration
@@ -64,3 +63,8 @@ SYNC_MAX_FUTURE_SKEW_MS=0
# Notification retention period in milliseconds (default: 7 days) # Notification retention period in milliseconds (default: 7 days)
NOTIF_RETENTION_MS=604800000 NOTIF_RETENTION_MS=604800000
# Required shared-service authentication secret.
SECRET=change-me-to-a-long-random-value
# Set true only for local development or a standalone deployment.
AUTH_DISABLED=false
+5 -1
View File
@@ -44,6 +44,11 @@ func main() {
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required") fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
os.Exit(1) os.Exit(1)
} }
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
if internalServiceSecret == "" {
fmt.Fprintln(os.Stderr, "SECRET environment variable is required")
os.Exit(1)
}
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
@@ -84,7 +89,6 @@ func main() {
// auth.SetAuthGuardBaseURL retargets the live AuthGuard client sharedauth.Service holds // auth.SetAuthGuardBaseURL retargets the live AuthGuard client sharedauth.Service holds
// internally on every push, so AuthGuard moving to a new URL takes effect without a restart -- it // internally on every push, so AuthGuard moving to a new URL takes effect without a restart -- it
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above). // is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
internalServiceSecret := strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET"))
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL")) carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL}) coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
coreConfig.OnUpdate(func(info coreconfig.Info) { coreConfig.OnUpdate(func(info coreconfig.Info) {
@@ -1,7 +1,7 @@
<script> <script>
import { Moon, Sun, SunMoon } from '@lucide/svelte'; import { Moon, Sun, SunMoon } from '@lucide/svelte';
import Button from '$lib/components/ui/button.svelte'; import Button from '$lib/components/ui/button.svelte';
import { SettingsDialog as SharedSettingsDialog } from '@gabriel20xx/web-ui'; import { PrimaryColorPicker, SettingsDialog as SharedSettingsDialog } from '@gabriel20xx/web-ui';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '$lib/components/ui/select'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '$lib/components/ui/select';
import { currentLanguage, languages, setLanguage } from '$lib/language.svelte.js'; import { currentLanguage, languages, setLanguage } from '$lib/language.svelte.js';
import { layoutState } from '$lib/layout.svelte.js'; import { layoutState } from '$lib/layout.svelte.js';
@@ -49,6 +49,7 @@
</div> </div>
</div> </div>
<div class="mt-5"> <div class="mt-5">
<PrimaryColorPicker projectKey="CollabTable" />
<label for="settings-language" class="mb-2 block text-sm font-medium">Language</label> <label for="settings-language" class="mb-2 block text-sm font-medium">Language</label>
<Select type="single" value={currentLanguage()} items={languageItems} onValueChange={(value) => setLanguage(value)}> <Select type="single" value={currentLanguage()} items={languageItems} onValueChange={(value) => setLanguage(value)}>
<SelectTrigger id="settings-language" class="w-full"> <SelectTrigger id="settings-language" class="w-full">
+1 -1
View File
@@ -126,7 +126,7 @@ func normalizeInfo(info Info) Info {
// Handler is the X-Internal-Auth-gated PUT /api/core-services/internal endpoint // Handler is the X-Internal-Auth-gated PUT /api/core-services/internal endpoint
// ProjectConfigurator calls to push a fresh Info: mount it at that path (see // ProjectConfigurator calls to push a fresh Info: mount it at that path (see
// ProjectConfigurator/README.md) behind a secret check for this service's own // ProjectConfigurator/README.md) behind a secret check for this service's own
// INTERNAL_SERVICE_SECRET (the same value ProjectConfigurator and CarrierNode were configured // SECRET (the same value ProjectConfigurator and CarrierNode were configured
// with - an empty secret refuses every caller, the same fail-closed default ProjectConfigurator's // with - an empty secret refuses every caller, the same fail-closed default ProjectConfigurator's
// own internal-auth-gated routes use). // own internal-auth-gated routes use).
func Handler(secret string, store *Store) http.HandlerFunc { func Handler(secret string, store *Store) http.HandlerFunc {
+1 -1
View File
@@ -44,7 +44,7 @@ coreConfig.onUpdate((info) => authClient.setBaseUrl(info.authGuardUrl));
// in your own route for PUT /api/core-services/internal: // in your own route for PUT /api/core-services/internal:
app.put('/api/core-services/internal', (req, res) => { app.put('/api/core-services/internal', (req, res) => {
if (req.get('X-Internal-Auth') !== process.env.INTERNAL_SERVICE_SECRET) { if (req.get('X-Internal-Auth') !== process.env.SECRET) {
return res.status(401).json({ error: 'internal service authentication required' }); return res.status(401).json({ error: 'internal service authentication required' });
} }
const info = coreConfig.set(req.body); const info = coreConfig.set(req.body);
@@ -12,7 +12,7 @@
* Framework-agnostic: this module has no HTTP server of its own. A service * Framework-agnostic: this module has no HTTP server of its own. A service
* wires the actual `PUT /api/core-services/internal` route in its own * wires the actual `PUT /api/core-services/internal` route in its own
* framework (Express, plain `http`, ...), gated behind its own * framework (Express, plain `http`, ...), gated behind its own
* INTERNAL_SERVICE_SECRET check the same way its other internal-service * SECRET check the same way its other internal-service
* routes already are, decodes the JSON body with `Info.fromJSON`, and calls * routes already are, decodes the JSON body with `Info.fromJSON`, and calls
* `store.set(info)` - see `Store.set`'s doc comment for a minimal Express * `store.set(info)` - see `Store.set`'s doc comment for a minimal Express
* example. * example.
@@ -118,7 +118,7 @@ export class Store {
* the other value. Returns the resulting Info. Minimal Express usage: * the other value. Returns the resulting Info. Minimal Express usage:
* *
* app.put('/api/core-services/internal', (req, res) => { * app.put('/api/core-services/internal', (req, res) => {
* if (req.get('X-Internal-Auth') !== process.env.INTERNAL_SERVICE_SECRET) { * if (req.get('X-Internal-Auth') !== process.env.SECRET) {
* return res.status(401).json({ error: 'internal service authentication required' }); * return res.status(401).json({ error: 'internal service authentication required' });
* } * }
* const info = coreConfigStore.set(Info.fromJSON(req.body)); * const info = coreConfigStore.set(Info.fromJSON(req.body));
+1 -1
View File
@@ -97,7 +97,7 @@ core_config.on_update(lambda info: auth_client.set_base_url(info.auth_guard_url)
# in your framework's route for PUT /api/core-services/internal: # in your framework's route for PUT /api/core-services/internal:
async def push_core_services(request): async def push_core_services(request):
if request.headers.get("X-Internal-Auth") != INTERNAL_SERVICE_SECRET: if request.headers.get("X-Internal-Auth") != SECRET:
raise HTTPException(status_code=401) raise HTTPException(status_code=401)
body = await request.json() body = await request.json()
info = core_config.set(CoreConfigInfo.from_json(body)) info = core_config.set(CoreConfigInfo.from_json(body))
@@ -11,7 +11,7 @@ Framework-agnostic, like the rest of this package (see the top-level
README's "HTTP framework adapters stay in each service" note): this module README's "HTTP framework adapters stay in each service" note): this module
has no HTTP server of its own. A service wires the actual has no HTTP server of its own. A service wires the actual
PUT /api/core-services/internal route in its own framework (FastAPI, PUT /api/core-services/internal route in its own framework (FastAPI,
aiohttp, ...), gated behind its own INTERNAL_SERVICE_SECRET check the same aiohttp, ...), gated behind its own SECRET check the same
way its other internal-service routes already are, decodes the JSON body way its other internal-service routes already are, decodes the JSON body
into an `Info`, and calls `Store.set(info)` -- see `Store.set`'s doc comment into an `Info`, and calls `Store.set(info)` -- see `Store.set`'s doc comment
for a minimal FastAPI example. for a minimal FastAPI example.
@@ -108,7 +108,7 @@ class Store:
@app.put("/api/core-services/internal") @app.put("/api/core-services/internal")
async def push_core_services(request: Request): async def push_core_services(request: Request):
if request.headers.get("X-Internal-Auth") != INTERNAL_SERVICE_SECRET: if request.headers.get("X-Internal-Auth") != SECRET:
raise HTTPException(status_code=401) raise HTTPException(status_code=401)
body = await request.json() body = await request.json()
info = core_config_store.set(Info.from_json(body)) info = core_config_store.set(Info.from_json(body))
@@ -1,9 +1,11 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte';
import type { Snippet } from 'svelte'; import type { Snippet } from 'svelte';
import type { NavItem } from '../types'; import type { NavItem } from '../types';
import Header from './Header.svelte'; import Header from './Header.svelte';
import NotificationStack from './NotificationStack.svelte'; import NotificationStack from './NotificationStack.svelte';
import PageHeader from './PageHeader.svelte'; import PageHeader from './PageHeader.svelte';
import { initPrimaryColor, setPrimaryColorUser } from '../primary-color.svelte';
let { let {
aboutHref, aboutHref,
@@ -52,6 +54,12 @@
item.href === '/' ? currentPath === '/' : currentPath === item.href || currentPath.startsWith(`${item.href}/`), item.href === '/' ? currentPath === '/' : currentPath === item.href || currentPath.startsWith(`${item.href}/`),
), ),
); );
$effect(() => {
setPrimaryColorUser(username);
});
onMount(() => initPrimaryColor(brand, username));
</script> </script>
<div class={`sc-root sc-app-shell ${className}`} data-theme={theme === 'system' ? undefined : theme}> <div class={`sc-root sc-app-shell ${className}`} data-theme={theme === 'system' ? undefined : theme}>
@@ -0,0 +1,115 @@
<script lang="ts">
import { onMount } from 'svelte'
import {
PRIMARY_COLOR_PALETTE,
initPrimaryColor,
primaryColorByName,
setPrimaryColor,
storedPrimaryColor,
} from '../primary-color.svelte'
let {
projectKey,
label = 'Primary color',
}: {
projectKey: string
label?: string
} = $props()
let selected = $state('')
onMount(() => {
selected = storedPrimaryColor(projectKey)
const stop = initPrimaryColor(projectKey)
return stop
})
function choose(name: string) {
selected = name
setPrimaryColor(projectKey, name)
}
</script>
<div class="sc-primary-color">
<span class="sc-label">{label}</span>
<div class="sc-primary-color-options" role="radiogroup" aria-label={label}>
<button
type="button"
role="radio"
aria-checked={selected === ''}
aria-label="Default"
title="Default"
class:sc-primary-color-selected={selected === ''}
onclick={() => choose('')}
>
<span class="sc-primary-color-default">—</span>
</button>
{#each PRIMARY_COLOR_PALETTE as color (color.name)}
<button
type="button"
role="radio"
aria-checked={selected === color.name}
aria-label={color.name}
title={color.name}
class:sc-primary-color-selected={selected === color.name}
style={'--sc-picker-color:' + color.light}
onclick={() => choose(color.name)}
>
<span></span>
</button>
{/each}
</div>
{#if selected}
<span class="sc-primary-color-name">{primaryColorByName(selected)?.name}</span>
{:else}
<span class="sc-primary-color-name">Default</span>
{/if}
</div>
<style>
.sc-primary-color {
display: grid;
gap: 0.5rem;
}
.sc-primary-color-options {
display: flex;
flex-wrap: wrap;
gap: 0.375rem;
}
.sc-primary-color-options button {
display: grid;
width: 1.75rem;
height: 1.75rem;
place-items: center;
padding: 0;
border: 1px solid var(--sc-border);
border-radius: 9999px;
background: var(--sc-surface);
cursor: pointer;
}
.sc-primary-color-options button > span {
width: 1.25rem;
height: 1.25rem;
border-radius: 9999px;
background: var(--sc-picker-color);
}
.sc-primary-color-options button:focus-visible,
.sc-primary-color-options button.sc-primary-color-selected {
outline: 2px solid var(--sc-ring);
outline-offset: 2px;
}
.sc-primary-color-default {
color: var(--sc-muted-fg);
background: transparent !important;
}
.sc-primary-color-name {
color: var(--sc-muted-fg);
font-size: 0.75rem;
}
</style>
+11
View File
@@ -12,6 +12,7 @@ export { default as NotificationStack } from './components/NotificationStack.sve
export { default as PageHeader } from './components/PageHeader.svelte'; export { default as PageHeader } from './components/PageHeader.svelte';
export { default as Pagination } from './components/Pagination.svelte'; export { default as Pagination } from './components/Pagination.svelte';
export { default as ProfileDialog } from './components/ProfileDialog.svelte'; export { default as ProfileDialog } from './components/ProfileDialog.svelte';
export { default as PrimaryColorPicker } from './components/PrimaryColorPicker.svelte';
export { default as SectionTitle } from './components/SectionTitle.svelte'; export { default as SectionTitle } from './components/SectionTitle.svelte';
export { default as SettingsDialog } from './components/SettingsDialog.svelte'; export { default as SettingsDialog } from './components/SettingsDialog.svelte';
export { default as StatusDialog } from './components/StatusDialog.svelte'; export { default as StatusDialog } from './components/StatusDialog.svelte';
@@ -19,6 +20,16 @@ export { default as StatusWidget } from './components/StatusWidget.svelte';
export { default as TotpSettings } from './components/TotpSettings.svelte'; export { default as TotpSettings } from './components/TotpSettings.svelte';
export { default as UserManagement } from './components/UserManagement.svelte'; export { default as UserManagement } from './components/UserManagement.svelte';
export { notifications, notify } from './notifications.svelte'; export { notifications, notify } from './notifications.svelte';
export {
PRIMARY_COLOR_PALETTE,
applyPrimaryColor,
initPrimaryColor,
primaryColorByName,
setPrimaryColor,
setPrimaryColorUser,
storedPrimaryColor,
} from './primary-color.svelte';
export type { PaletteColor } from './primary-color.svelte';
export type { NotificationEntry, NotificationVariant } from './notifications.svelte'; export type { NotificationEntry, NotificationVariant } from './notifications.svelte';
export type { export type {
AboutLink, AboutLink,
@@ -0,0 +1,122 @@
export type PaletteColor = { name: string; dark: string; light: string; darkFg: string }
export const PRIMARY_COLOR_PALETTE: PaletteColor[] = [
{ name: 'Vermilion', dark: '#f59080', light: '#db3e24', darkFg: '#2b110d' },
{ name: 'Tangerine', dark: '#fb923c', light: '#c2410c', darkFg: '#2b1206' },
{ name: 'Marigold', dark: '#f5b380', light: '#db7524', darkFg: '#2b1a0d' },
{ name: 'Amber', dark: '#f5ca80', light: '#b87d14', darkFg: '#2b200d' },
{ name: 'Gold', dark: '#f5e280', light: '#b89d14', darkFg: '#2b260d' },
{ name: 'Honey', dark: '#f1f580', light: '#b2b814', darkFg: '#2a2b0d' },
{ name: 'Chartreuse', dark: '#daf580', light: '#92b814', darkFg: '#242b0d' },
{ name: 'Lime', dark: '#c3f580', light: '#72b814', darkFg: '#1e2b0d' },
{ name: 'Spring Green', dark: '#abf580', light: '#51b814', darkFg: '#182b0d' },
{ name: 'Shamrock', dark: '#94f580', light: '#44db24', darkFg: '#122b0d' },
{ name: 'Emerald', dark: '#80f582', light: '#24db28', darkFg: '#0d2b0d' },
{ name: 'Jade', dark: '#80f599', light: '#24db4c', darkFg: '#0d2b13' },
{ name: 'Clover', dark: '#22c55e', light: '#16a34a', darkFg: '#052e14' },
{ name: 'Mint', dark: '#80f5bc', light: '#24db83', darkFg: '#0d2b1d' },
{ name: 'Seafoam', dark: '#80f5d4', light: '#24dba8', darkFg: '#0d2b23' },
{ name: 'Turquoise', dark: '#80f5ec', light: '#24dbce', darkFg: '#0d2b29' },
{ name: 'Aqua', dark: '#80e5f5', light: '#24c3db', darkFg: '#0d272b' },
{ name: 'Cyan', dark: '#80cef5', light: '#249edb', darkFg: '#0d212b' },
{ name: 'Sky Blue', dark: '#80b6f5', light: '#2479db', darkFg: '#0d1b2b' },
{ name: 'Cornflower', dark: '#3b82f6', light: '#2563eb', darkFg: '#0a1733' },
{ name: 'Indigo', dark: '#99a1d7', light: '#4355b9', darkFg: '#12162b' },
{ name: 'Iris', dark: '#818cf8', light: '#4f46e5', darkFg: '#12102e' },
{ name: 'Periwinkle', dark: '#9880f5', light: '#4a24db', darkFg: '#130d2b' },
{ name: 'Violet', dark: '#ae80f5', light: '#6d24db', darkFg: '#190d2b' },
{ name: 'Purple', dark: '#c580f5', light: '#9124db', darkFg: '#1f0d2b' },
{ name: 'Orchid', dark: '#dc80f5', light: '#b424db', darkFg: '#250d2b' },
{ name: 'Magenta', dark: '#f280f5', light: '#d824db', darkFg: '#2b0d2b' },
{ name: 'Fuchsia', dark: '#f580e0', light: '#db24bb', darkFg: '#2b0d26' },
{ name: 'Pink', dark: '#f580ca', light: '#db2498', darkFg: '#2b0d20' },
{ name: 'Rose', dark: '#f580b3', light: '#db2474', darkFg: '#2b0d1a' },
{ name: 'Ruby', dark: '#f5809c', light: '#db2451', darkFg: '#2b0d14' },
{ name: 'Crimson', dark: '#f58086', light: '#db242d', darkFg: '#2b0d0e' },
]
const paletteByName = Object.fromEntries(PRIMARY_COLOR_PALETTE.map((color) => [color.name, color])) as Record<
string,
PaletteColor
>
const primaryVars = ['--color-primary', '--color-accent', '--color-ring']
const foregroundVars = ['--color-primary-fg', '--color-accent-fg']
const activeUserAttribute = 'data-primary-color-user'
const activeProjects = new Set<string>()
function normalizeUserKey(userKey: string): string {
return userKey.trim().toLowerCase() || 'anonymous'
}
function activeUserKey(): string {
if (typeof document === 'undefined') return 'anonymous'
return normalizeUserKey(document.documentElement.getAttribute(activeUserAttribute) || '')
}
function storageKey(projectKey: string, userKey = activeUserKey()): string {
const project = encodeURIComponent(projectKey.trim().toLowerCase() || 'application')
const user = encodeURIComponent(normalizeUserKey(userKey))
return `primary-color:${project}:${user}`
}
function readStoredColor(projectKey: string): string {
try {
return localStorage.getItem(storageKey(projectKey)) || ''
} catch {
return ''
}
}
export function applyPrimaryColor(_projectKey: string, colorName: string): void {
if (typeof document === 'undefined') return
const color = paletteByName[colorName]
const root = document.documentElement.style
if (!color) {
for (const name of [...primaryVars, ...foregroundVars]) root.removeProperty(name)
return
}
const dark = document.documentElement.getAttribute('data-theme') === 'dark'
const primary = dark ? color.dark : color.light
const foreground = dark ? color.darkFg : '#ffffff'
for (const name of primaryVars) root.setProperty(name, primary)
for (const name of foregroundVars) root.setProperty(name, foreground)
}
export function setPrimaryColor(projectKey: string, colorName: string): void {
try {
const key = storageKey(projectKey)
if (colorName) localStorage.setItem(key, colorName)
else localStorage.removeItem(key)
} catch {
// The current page still receives the selected color if storage is unavailable.
}
applyPrimaryColor(projectKey, colorName)
}
export function setPrimaryColorUser(userKey: string): void {
if (typeof document === 'undefined') return
document.documentElement.setAttribute(activeUserAttribute, normalizeUserKey(userKey))
for (const projectKey of activeProjects) {
applyPrimaryColor(projectKey, readStoredColor(projectKey))
}
}
export function initPrimaryColor(projectKey: string, userKey = ''): () => void {
if (typeof document === 'undefined') return () => undefined
if (userKey) setPrimaryColorUser(userKey)
activeProjects.add(projectKey.trim().toLowerCase() || 'application')
const stored = readStoredColor(projectKey)
applyPrimaryColor(projectKey, stored)
const observer = new MutationObserver(() => applyPrimaryColor(projectKey, readStoredColor(projectKey)))
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] })
return () => observer.disconnect()
}
export function storedPrimaryColor(projectKey: string): string {
const stored = readStoredColor(projectKey)
return paletteByName[stored] ? stored : ''
}
export function primaryColorByName(name: string): PaletteColor | undefined {
return paletteByName[name]
}