Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-25 23:44:48 +03:00
1 parent 7a0446b573
commit 3632f2cd43
27 files changed
+3332 -97

No files matched your search

+22 -12
View File
@@ -16,18 +16,17 @@ target_include_directories(EchoionWeb PUBLIC
# EchoionCore is configured before this module and creates the header-only
# Boost:: targets from the single system Boost. Fall back to discovering them
# only if this module is ever built without Core.
if(NOT TARGET Boost::beast)
find_package(Boost 1.87 CONFIG QUIET)
foreach(_hdr asio beast system)
if(NOT TARGET Boost::${_hdr})
add_library(_web_boost_${_hdr}_hdr INTERFACE)
add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr)
target_include_directories(_web_boost_${_hdr}_hdr INTERFACE
"${Boost_INCLUDE_DIRS}")
endif()
endforeach()
endif()
# only if this module is ever built without Core. Check each target because
# aliases created by a sibling directory are not necessarily visible here.
find_package(Boost 1.87 CONFIG QUIET COMPONENTS system url)
foreach(_hdr asio beast system)
if(NOT TARGET Boost::${_hdr})
add_library(_web_boost_${_hdr}_hdr INTERFACE)
add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr)
target_include_directories(_web_boost_${_hdr}_hdr INTERFACE
"${Boost_INCLUDE_DIRS}")
endif()
endforeach()
find_package(Threads REQUIRED)
@@ -42,6 +41,7 @@ target_link_libraries(EchoionWeb
Boost::beast
Boost::asio
Boost::system
Boost::url
)
if(MSVC)
@@ -55,6 +55,16 @@ endif()
# That build output is what ships next to the runtime binary (default webRoot
# "./web", relative to the working directory) and is installed. Opt out with
# -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job).
if(BUILD_TESTS)
add_executable(echoion_web_security_tests
tests/HttpSecurityTests.cpp)
target_link_libraries(echoion_web_security_tests PRIVATE
EchoionWeb
Threads::Threads)
add_test(NAME echoion_web_security_tests
COMMAND echoion_web_security_tests)
endif()
option(ECHOION_BUILD_WEB "Build the React dashboard frontend with npm/vite" ON)
set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend")
-39
View File
@@ -894,9 +894,6 @@
"arm"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -911,9 +908,6 @@
"arm"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -928,9 +922,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -945,9 +936,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -962,9 +950,6 @@
"loong64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -979,9 +964,6 @@
"loong64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -996,9 +978,6 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1013,9 +992,6 @@
"ppc64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1030,9 +1006,6 @@
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1047,9 +1020,6 @@
"riscv64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1064,9 +1034,6 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1081,9 +1048,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1098,9 +1062,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
+2
View File
@@ -46,6 +46,8 @@ const KNOWN_DYNAMIC = new Set([
'Playback history and server insights',
'Server & Admin',
'Manage subscribers and broadcast',
'Updates',
'Runtime, Core, and plugin release control',
'RPC / API',
'Connect to Echoion programmatically',
// Sidebar NAV labels rendered via t(item.label) — same strings as HEADS
+3
View File
@@ -16,6 +16,7 @@ import { SearchView } from './views/SearchView';
import { LibraryView } from './views/LibraryView';
import { StatsView } from './views/StatsView';
import { ServerView } from './views/ServerView';
import { UpdatesView } from './views/UpdatesView';
import { RpcView } from './views/RpcView';
const HEADS: Record<string, [string, string]> = {
@@ -25,6 +26,7 @@ const HEADS: Record<string, [string, string]> = {
library: ['Library', 'Your favorites and saved playlists'],
stats: ['History & Stats', 'Playback history and server insights'],
server: ['Server & Admin', 'Manage subscribers and broadcast'],
updates: ['Updates', 'Runtime, Core, and plugin release control'],
rpc: ['RPC / API', 'Connect to Echoion programmatically'],
};
@@ -92,6 +94,7 @@ export function App() {
{s.view === 'library' && <LibraryView />}
{s.view === 'stats' && <StatsView />}
{s.view === 'server' && <ServerView />}
{s.view === 'updates' && <UpdatesView />}
{s.view === 'rpc' && <RpcView />}
<MiniPlayer />
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { Modal } from './Modal';
describe('Modal accessibility', () => {
it('labels the dialog and exposes a named close control', () => {
const html = renderToStaticMarkup(
<Modal title="Confirm update" onClose={() => {}}>
<p>Review the candidate.</p>
</Modal>
);
expect(html).toContain('role="dialog"');
expect(html).toContain('aria-modal="true"');
expect(html).toContain('aria-labelledby=');
expect(html).toContain('aria-label="Close"');
});
});
+49 -3
View File
@@ -1,5 +1,6 @@
import type { ReactNode } from 'react';
import { useEffect, useId, useRef, type KeyboardEvent, type ReactNode } from 'react';
import { CloseIcon } from './icons';
import { t } from '../i18n';
export function Modal(props: {
title: string;
@@ -8,15 +9,60 @@ export function Modal(props: {
footer?: ReactNode;
wide?: boolean;
}) {
const titleId = useId();
const modalRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const previous = document.activeElement as HTMLElement | null;
const focusable = modalRef.current?.querySelector<HTMLElement>(
'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])'
);
focusable?.focus();
return () => previous?.focus();
}, []);
function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
if (event.key === 'Escape') {
event.preventDefault();
props.onClose();
return;
}
if (event.key !== 'Tab' || !modalRef.current) return;
const focusable = Array.from(
modalRef.current.querySelectorAll<HTMLElement>(
'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])'
)
);
if (!focusable.length) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
return (
<div className="modal-backdrop" onClick={props.onClose}>
<div
ref={modalRef}
className={'modal' + (props.wide ? ' modal-wide' : '')}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
onKeyDown={onKeyDown}
onClick={(e) => e.stopPropagation()}
>
<div className="modal-head">
<h2>{props.title}</h2>
<button className="icon-btn" onClick={props.onClose}>
<h2 id={titleId}>{props.title}</h2>
<button
className="icon-btn"
aria-label={t('Close')}
onClick={props.onClose}
>
<CloseIcon />
</button>
</div>
+6 -1
View File
@@ -20,6 +20,7 @@ import {
QueueIcon,
SearchIcon,
StatsIcon,
UpdateIcon,
WatchIcon,
} from './icons';
import { t, useLanguage } from '../i18n';
@@ -31,6 +32,7 @@ const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [
{ view: 'library', icon: <HeartIcon />, label: 'Library' },
{ view: 'stats', icon: <StatsIcon />, label: 'History & Stats' },
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
{ view: 'updates', icon: <UpdateIcon />, label: 'Updates' },
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
];
@@ -66,7 +68,9 @@ export function Sidebar() {
<nav className="nav">
{NAV.filter(
(item) => item.view !== 'server' || isAdmin
(item) =>
(item.view !== 'server' && item.view !== 'updates') ||
isAdmin
).map((item) => (
<button
key={item.view}
@@ -74,6 +78,7 @@ export function Sidebar() {
'nav-item' +
(s.view === item.view ? ' active' : '')
}
aria-current={s.view === item.view ? 'page' : undefined}
onClick={() => showView(item.view)}
>
<span className="nav-ico">{item.icon}</span>
+3
View File
@@ -63,6 +63,9 @@ export const RoomsIcon = makeIcon(
export const GearIcon = makeIcon(
'M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z'
);
export const UpdateIcon = makeIcon(
'M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.96-.69 2.8l1.46 1.46A7.93 7.93 0 0020 12c0-4.42-3.58-8-8-8zm-5.31 5.2L5.23 7.74A7.93 7.93 0 004 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3c-3.31 0-6-2.69-6-6 0-1.01.25-1.96.69-2.8z'
);
export const CodeIcon = makeIcon(
'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z'
);
+145
View File
@@ -11,6 +11,7 @@ export const ru: Record<string, string> = {
'History & Stats': 'История и статистика',
'Watch Together': 'Совместный просмотр',
'Server & Admin': 'Сервер и админ',
'Updates': 'Обновления',
'RPC / API': 'RPC / API',
'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3',
'Connect': 'Подключиться',
@@ -32,8 +33,152 @@ export const ru: Record<string, string> = {
'Your favorites and saved playlists': 'Ваше избранное и сохранённые плейлисты',
'Playback history and server insights': 'История воспроизведения и статистика сервера',
'Manage subscribers and broadcast': 'Управление подписчиками и объявления',
'Runtime, Core, and plugin release control':
'Управление выпусками среды, ядра и плагинов',
'Connect to Echoion programmatically': 'Подключение к Echoion из кода',
// Updates
'Runtime bundle': 'Среда выполнения',
'Core': 'Ядро',
'Plugins': 'Плагины',
'default source': 'источник по умолчанию',
'stable': 'стабильный',
'Idle': 'Ожидание',
'Installed': 'Установлено',
'Available': 'Доступно',
'Up to date': 'Актуальная версия',
'Candidate attributes': 'Свойства кандидата',
'Unsigned': 'Без подписи',
'Signed': 'Подписано',
'Downgrade': 'Понижение версии',
'Incompatible': 'Несовместимо',
'Restart required': 'Нужен перезапуск',
'Apply {0}': 'Применить {0}',
'No update': 'Нет обновления',
'Rollback to {0}': 'Откатить до {0}',
'No rollback': 'Откат недоступен',
'Enabled': 'Включено',
'Source': 'Источник',
'Channel': 'Канал',
'{0} source': 'Источник: {0}',
'{0} channel': 'Канал: {0}',
'Auto-apply': 'Применять автоматически',
'Build default': 'Встроенное значение',
'Feed URL': 'URL ленты',
'Empty uses the release build default':
'Пустое поле использует адрес из сборки выпуска',
'Bearer token environment variable': 'Переменная окружения с Bearer-токеном',
'Secret is present in the service environment':
'Секрет присутствует в окружении службы',
'Secret is missing from the service environment':
'Секрет отсутствует в окружении службы',
'Secret presence was not reported': 'Наличие секрета не сообщено службой',
'No bearer token configured': 'Bearer-токен не настроен',
'Permit manual unsigned staging':
'Разрешить ручную подготовку обновлений без подписи',
'Ed25519 trust keys': 'Доверенные ключи Ed25519',
'Only public verification keys belong here.':
'Здесь должны находиться только открытые ключи проверки.',
'Add key': 'Добавить ключ',
'Key ID': 'ID ключа',
'Public key': 'Открытый ключ',
'Remove key {0}': 'Удалить ключ {0}',
'No custom keys; the build-injected keyring is used when available.':
'Пользовательских ключей нет; используется встроенное в сборку хранилище ключей.',
'Remove source': 'Удалить источник',
'Managed': 'Управляемый',
'Unmanaged': 'Неуправляемый',
'Apply': 'Применить',
'Rollback': 'Откатить',
'Never': 'Никогда',
'Automatic updates armed': 'Автоматические обновления активны',
'Automatic updates paused': 'Автоматические обновления приостановлены',
'Last check: {0}': 'Последняя проверка: {0}',
'Next: {0}': 'Следующая: {0}',
'Check now': 'Проверить сейчас',
'Checking…': 'Проверка…',
'Loading update state…': 'Загрузка состояния обновлений…',
'Installed plugins': 'Установленные плагины',
'Only managed plugins participate in update activation.':
'В активации обновлений участвуют только управляемые плагины.',
'managed': 'управляемых',
'No installed plugins reported': 'Установленные плагины не обнаружены',
'Update history': 'История обновлений',
'Checks, staging, activation, and rollback outcomes':
'Результаты проверок, подготовки, активации и откатов',
'When': 'Когда',
'Target': 'Цель',
'Action': 'Действие',
'Result': 'Результат',
'Recorded': 'Записано',
'No update history yet': 'История обновлений пока пуста',
'POLICY DECK': 'ПАНЕЛЬ ПОЛИТИКИ',
'Automation and trust': 'Автоматизация и доверие',
'Configure timing, independent channels, feeds, and public trust roots.':
'Настройте расписание, независимые каналы, ленты и открытые корни доверия.',
'Discard changes': 'Отменить изменения',
'Save policy': 'Сохранить политику',
'Saving…': 'Сохранение…',
'Enable the update scheduler': 'Включить планировщик обновлений',
'Check interval': 'Интервал проверки',
'Schedule jitter': 'Разброс расписания',
'Maintenance start (UTC)': 'Начало обслуживания (UTC)',
'Maintenance duration': 'Длительность обслуживания',
'Maximum runtime deferral': 'Максимальная отсрочка среды',
'Previous healthy versions retained': 'Хранимые предыдущие исправные версии',
'Component channels': 'Каналы компонентов',
'Selections remain independent; incompatible cohorts stay staged.':
'Выбор остаётся независимым; несовместимые наборы остаются подготовленными.',
'Never modify loose local plugin files':
'Никогда не изменять отдельные локальные файлы плагинов',
'Plugin channel overrides': 'Переопределения каналов плагинов',
'Pin individual managed plugins to another source or channel.':
'Назначьте отдельным управляемым плагинам другой источник или канал.',
'Add override': 'Добавить переопределение',
'No plugin overrides': 'Переопределений плагинов нет',
'Sources and trust roots': 'Источники и корни доверия',
'Secret values stay in the service environment and are never returned here.':
'Значения секретов остаются в окружении службы и никогда не возвращаются сюда.',
'Add source': 'Добавить источник',
'Confirm unsigned update': 'Подтвердите обновление без подписи',
'This artifact has no trusted signature. Type {0} to authorize this exact candidate.':
'У этого артефакта нет доверенной подписи. Введите {0}, чтобы разрешить именно этот кандидат.',
'Authorize unsigned candidate': 'Разрешить кандидат без подписи',
'Confirm downgrade': 'Подтвердите понижение версии',
'A downgrade may make saved state incompatible. Type DOWNGRADE to continue.':
'Понижение версии может сделать сохранённое состояние несовместимым. Введите DOWNGRADE для продолжения.',
'Continue with downgrade': 'Продолжить понижение версии',
'Restart Echoion': 'Перезапустить Echoion',
'Applying this update restarts Echoion after it becomes idle. Continue?':
'После перехода в режим ожидания Echoion будет перезапущен для применения обновления. Продолжить?',
'Apply and restart': 'Применить и перезапустить',
'{0} update queued': 'Обновление {0} поставлено в очередь',
'Confirm rollback': 'Подтвердите откат',
'Roll back {0} to {1}?': 'Откатить {0} до {1}?',
'Rollback queued': 'Откат поставлен в очередь',
'Enable unsigned update policy': 'Разрешить политику обновлений без подписи',
'Unsigned staging will be permitted for: {0}. Type ENABLE UNSIGNED to save this policy.':
'Подготовка без подписи будет разрешена для: {0}. Введите ENABLE UNSIGNED, чтобы сохранить политику.',
'Save unsafe policy': 'Сохранить небезопасную политику',
'Update policy saved': 'Политика обновлений сохранена',
'Add update source': 'Добавить источник обновлений',
'Use a short ID made from letters, numbers, dots, dashes, or underscores.':
'Используйте короткий ID из букв, цифр, точек, дефисов или подчёркиваний.',
'Invalid source ID': 'Недопустимый ID источника',
'That source already exists': 'Такой источник уже существует',
'Move every component off this source before removing it':
'Перед удалением переведите все компоненты на другой источник',
'Remove update source': 'Удалить источник обновлений',
'Remove source {0} and its public keys?':
'Удалить источник {0} и его открытые ключи?',
'Add plugin channel override': 'Добавить переопределение канала плагина',
'Enter the exact managed plugin ID.': 'Введите точный ID управляемого плагина.',
'That plugin override already exists':
'Переопределение для этого плагина уже существует',
'Update check completed': 'Проверка обновлений завершена',
'Update policy, trust keys, and activation controls are restricted to administrators.':
'Политика обновлений, доверенные ключи и активация доступны только администраторам.',
// Now playing
'Nothing playing': 'Ничего не играет',
'Up Next': 'Далее',
+1
View File
@@ -22,6 +22,7 @@ export type ViewName =
| 'library'
| 'stats'
| 'server'
| 'updates'
| 'rpc';
export interface AppState {
+2
View File
@@ -9,5 +9,7 @@ describe('audit RPC method mapping', () => {
expect(auditMethodName(72)).toBe('Reserved72');
expect(auditMethodName(73)).toBe('GetTeamSpeakDirectory');
expect(auditMethodName(88)).toBe('SendTeamSpeakServerMessage');
expect(auditMethodName(89)).toBe('GetUpdateStatus');
expect(auditMethodName(95)).toBe('ConfirmUnsignedUpdate');
});
});
+7
View File
@@ -94,6 +94,13 @@ const RPC_METHOD_BY_INDEX: readonly string[] = [
'SendTeamSpeakPrivateMessage',
'SendTeamSpeakChannelMessage',
'SendTeamSpeakServerMessage',
'GetUpdateStatus', // 89
'GetUpdateConfig',
'SetUpdateConfig',
'CheckForUpdates',
'ApplyUpdate',
'RollbackUpdate',
'ConfirmUnsignedUpdate', // 95
];
export function auditMethodName(method: number): string {
+1
View File
@@ -11,5 +11,6 @@ describe('dashboard routing', () => {
it('keeps the remaining flat views bookmarkable', () => {
expect(viewFromHash('#queue')).toBe('queue');
expect(viewFromHash('#server')).toBe('server');
expect(viewFromHash('#updates')).toBe('updates');
});
});
+1
View File
@@ -11,6 +11,7 @@ const VIEWS: readonly ViewName[] = [
'library',
'stats',
'server',
'updates',
'rpc',
];
+27
View File
@@ -75,6 +75,18 @@ describe('RpcClient wire contract', () => {
expect(frame.authToken).toBe('tok-abc');
});
it('sends updater requests through their append-only RPC enum names', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
rpc.call('GetUpdateStatus');
const frame = JSON.parse(ws.sent[0]);
expect(frame.method).toBe('GetUpdateStatus');
expect(JSON.parse(frame.params)).toEqual({});
});
it('resolves a call by requestId and JSON-decodes the result string', async () => {
installFakes();
const rpc = new RpcClient();
@@ -125,6 +137,21 @@ describe('RpcClient wire contract', () => {
expect(seen).toEqual([{ position: 1000, duration: 200000 }]);
});
it('dispatches the updater change event without renaming it', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const seen: unknown[] = [];
rpc.on('updates.changed', (data) => seen.push(data));
ws.receive({
event: 'updates.changed',
data: JSON.stringify({ component: 'core', state: 'staged' }),
});
expect(seen).toEqual([{ component: 'core', state: 'staged' }]);
});
it('fires the wildcard listener with event name and data', async () => {
installFakes();
const rpc = new RpcClient();
+8 -1
View File
@@ -80,7 +80,14 @@ export type RpcMethodName =
| 'RemoveTeamSpeakServerGroupMember'
| 'SendTeamSpeakPrivateMessage'
| 'SendTeamSpeakChannelMessage'
| 'SendTeamSpeakServerMessage';
| 'SendTeamSpeakServerMessage'
| 'GetUpdateStatus'
| 'GetUpdateConfig'
| 'SetUpdateConfig'
| 'CheckForUpdates'
| 'ApplyUpdate'
| 'RollbackUpdate'
| 'ConfirmUnsignedUpdate';
type Pending = {
+5 -1
View File
@@ -28,5 +28,9 @@ export class Store<T> {
}
export function useStore<T>(store: Store<T>): T {
return useSyncExternalStore(store.subscribe, () => store.get());
return useSyncExternalStore(
store.subscribe,
() => store.get(),
() => store.get()
);
}
+91
View File
@@ -0,0 +1,91 @@
import { describe, expect, it } from 'vitest';
import {
configForSave,
isValidSourceId,
normalizeUpdateConfig,
normalizeUpdateStatus,
} from './updates';
describe('update payload normalization', () => {
it('normalizes direct config and strips read-only secret presence on save', () => {
const config = normalizeUpdateConfig({
enabled: true,
checkInterval: '12h',
sources: {
private: {
url: ' https://updates.example/feed.json ',
publicKeys: [{ id: ' key-1 ', ed25519: ' abc123 ' }],
allowUnsigned: false,
bearerTokenEnv: ' UPDATE_TOKEN ',
bearerTokenPresent: true,
bearerToken: 'must-not-enter-browser-state',
},
},
runtime: { source: 'private', channel: 'stable' },
plugins: { managedOnly: false },
});
expect(config.checkInterval).toBe('12h');
expect(config.sources.private.bearerTokenPresent).toBe(true);
expect(config.sources.private).not.toHaveProperty('bearerToken');
expect(config.runtime.source).toBe('private');
expect(config.plugins.managedOnly).toBe(true);
const writable = configForSave(config);
expect(writable.sources.private).not.toHaveProperty(
'bearerTokenPresent'
);
expect(writable.sources.private.bearerTokenEnv).toBe('UPDATE_TOKEN');
expect(writable.sources.private.url).toBe(
'https://updates.example/feed.json'
);
expect(writable.sources.private.publicKeys).toEqual([
{ id: 'key-1', ed25519: 'abc123' },
]);
});
it('normalizes component candidates, plugin inventory, and history', () => {
const status = normalizeUpdateStatus({
enabled: true,
checking: false,
components: {
runtime: {
installedVersion: '1.0.0',
availableVersion: '1.1.0',
signed: false,
requiresRestart: true,
},
core: { currentVersion: '4.0.0', state: 'healthy' },
plugins: { state: 'current' },
},
pluginEntries: [
{
pluginId: 'weather',
managed: true,
installedVersion: '2.0.0',
candidate: { version: '2.1.0', signed: true },
},
],
history: [{ timestamp: 42, component: 'runtime', result: 'success' }],
});
expect(status.components.runtime.currentVersion).toBe('1.0.0');
expect(status.components.runtime.candidate).toMatchObject({
version: '1.1.0',
signed: false,
requiresRestart: true,
});
expect(status.plugins[0]).toMatchObject({
id: 'weather',
managed: true,
currentVersion: '2.0.0',
});
expect(status.history).toHaveLength(1);
});
it('accepts safe source identifiers only', () => {
expect(isValidSourceId('private-beta_2')).toBe(true);
expect(isValidSourceId('../escape')).toBe(false);
expect(isValidSourceId('has spaces')).toBe(false);
expect(isValidSourceId('')).toBe(false);
});
});
+481
View File
@@ -0,0 +1,481 @@
export type UpdateComponent = 'runtime' | 'core' | 'plugins';
export interface UpdatePublicKey {
id: string;
ed25519: string;
}
export interface UpdateSourceConfig {
url: string;
publicKeys: UpdatePublicKey[];
allowUnsigned: boolean;
bearerTokenEnv: string;
// Read-only status supplied by the server. It is stripped before save so
// the browser can never turn secret-presence metadata into configuration.
bearerTokenPresent?: boolean;
[key: string]: unknown;
}
export interface ComponentUpdatePolicy {
enabled: boolean;
source: string;
channel: string;
autoApply: boolean;
[key: string]: unknown;
}
export interface PluginOverridePolicy {
source: string;
channel: string;
autoApply: boolean;
[key: string]: unknown;
}
export interface PluginUpdatePolicy extends ComponentUpdatePolicy {
managedOnly: boolean;
overrides: Record<string, PluginOverridePolicy>;
}
export interface UpdateConfig {
enabled: boolean;
checkInterval: string;
jitter: string;
maintenanceWindowUtc: {
start: string;
duration: string;
[key: string]: unknown;
};
maxRuntimeDeferral: string;
retainHealthyVersions: number;
sources: Record<string, UpdateSourceConfig>;
runtime: ComponentUpdatePolicy;
core: ComponentUpdatePolicy;
plugins: PluginUpdatePolicy;
[key: string]: unknown;
}
export interface UpdateCandidate {
id?: string;
version: string;
channel?: string;
source?: string;
signed?: boolean;
compatible?: boolean;
downgrade?: boolean;
requiresRestart?: boolean;
cohort?: string;
message?: string;
[key: string]: unknown;
}
export interface ComponentUpdateStatus {
component: UpdateComponent;
currentVersion?: string;
state?: string;
message?: string;
channel?: string;
source?: string;
candidate?: UpdateCandidate;
rollbackVersion?: string;
lastChangedAt?: string | number;
[key: string]: unknown;
}
export interface PluginUpdateStatus {
id: string;
name?: string;
managed: boolean;
currentVersion?: string;
state?: string;
channel?: string;
source?: string;
candidate?: UpdateCandidate;
rollbackVersion?: string;
message?: string;
[key: string]: unknown;
}
export interface UpdateHistoryEntry {
timestamp?: string | number;
component?: UpdateComponent | string;
pluginId?: string;
action?: string;
version?: string;
result?: string;
message?: string;
actor?: string;
[key: string]: unknown;
}
export interface UpdateStatus {
enabled: boolean;
checking: boolean;
lastCheckAt?: string | number;
nextCheckAt?: string | number;
components: Record<UpdateComponent, ComponentUpdateStatus>;
plugins: PluginUpdateStatus[];
history: UpdateHistoryEntry[];
message?: string;
[key: string]: unknown;
}
const DEFAULT_COMPONENT_POLICY: ComponentUpdatePolicy = {
enabled: true,
source: 'official',
channel: 'stable',
autoApply: true,
};
export const DEFAULT_UPDATE_CONFIG: UpdateConfig = {
enabled: true,
checkInterval: '6h',
jitter: '30m',
maintenanceWindowUtc: {
start: '03:00',
duration: '2h',
},
maxRuntimeDeferral: '24h',
retainHealthyVersions: 2,
sources: {
official: {
url: '',
publicKeys: [],
allowUnsigned: false,
bearerTokenEnv: '',
},
},
runtime: { ...DEFAULT_COMPONENT_POLICY },
core: { ...DEFAULT_COMPONENT_POLICY },
plugins: {
...DEFAULT_COMPONENT_POLICY,
managedOnly: true,
overrides: {},
},
};
function record(value: unknown): Record<string, unknown> {
return value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
function stringValue(value: unknown, fallback = ''): string {
return typeof value === 'string' ? value : fallback;
}
function booleanValue(value: unknown, fallback: boolean): boolean {
return typeof value === 'boolean' ? value : fallback;
}
function numberValue(value: unknown, fallback: number): number {
return typeof value === 'number' && Number.isFinite(value)
? value
: fallback;
}
function unwrap(payload: unknown, key: string): Record<string, unknown> {
const outer = record(payload);
const nested = record(outer[key]);
return Object.keys(nested).length ? nested : outer;
}
function sourceFieldsWithoutSecrets(
source: Record<string, unknown>
): Record<string, unknown> {
return Object.fromEntries(
Object.entries(source).filter(([key]) => {
if (key === 'bearerTokenEnv' || key === 'bearerTokenPresent') {
return true;
}
return !/(token|secret|password|authorization|privatekey)/i.test(key);
})
);
}
function normalizeComponentPolicy(
value: unknown,
fallback: ComponentUpdatePolicy
): ComponentUpdatePolicy {
const raw = record(value);
return {
...raw,
enabled: booleanValue(raw.enabled, fallback.enabled),
source: stringValue(raw.source, fallback.source),
channel: stringValue(raw.channel, fallback.channel),
autoApply: booleanValue(raw.autoApply, fallback.autoApply),
};
}
function normalizePluginOverride(
value: unknown,
fallback: ComponentUpdatePolicy
): PluginOverridePolicy {
const raw = record(value);
return {
...raw,
source: stringValue(raw.source, fallback.source),
channel: stringValue(raw.channel, fallback.channel),
autoApply: booleanValue(raw.autoApply, fallback.autoApply),
};
}
export function normalizeUpdateConfig(payload: unknown): UpdateConfig {
const raw = unwrap(payload, 'config');
const rawSources = record(raw.sources);
const sources: Record<string, UpdateSourceConfig> = {};
for (const [id, value] of Object.entries(rawSources)) {
const source = record(value);
const safeSource = sourceFieldsWithoutSecrets(source);
const rawKeys = Array.isArray(source.publicKeys)
? source.publicKeys
: [];
sources[id] = {
...safeSource,
url: stringValue(source.url),
publicKeys: rawKeys.map((key) => {
const rawKey = record(key);
return {
id: stringValue(rawKey.id),
ed25519: stringValue(rawKey.ed25519),
};
}),
allowUnsigned: booleanValue(source.allowUnsigned, false),
bearerTokenEnv: stringValue(source.bearerTokenEnv),
...(typeof source.bearerTokenPresent === 'boolean'
? { bearerTokenPresent: source.bearerTokenPresent }
: {}),
};
}
if (!Object.keys(sources).length) {
sources.official = { ...DEFAULT_UPDATE_CONFIG.sources.official };
}
const runtime = normalizeComponentPolicy(
raw.runtime,
DEFAULT_UPDATE_CONFIG.runtime
);
const core = normalizeComponentPolicy(raw.core, DEFAULT_UPDATE_CONFIG.core);
const rawPlugins = record(raw.plugins);
const pluginBase = normalizeComponentPolicy(
rawPlugins,
DEFAULT_UPDATE_CONFIG.plugins
);
const overrides: Record<string, PluginOverridePolicy> = {};
for (const [id, value] of Object.entries(record(rawPlugins.overrides))) {
overrides[id] = normalizePluginOverride(value, pluginBase);
}
const rawWindow = record(raw.maintenanceWindowUtc);
return {
...raw,
enabled: booleanValue(raw.enabled, DEFAULT_UPDATE_CONFIG.enabled),
checkInterval: stringValue(
raw.checkInterval,
DEFAULT_UPDATE_CONFIG.checkInterval
),
jitter: stringValue(raw.jitter, DEFAULT_UPDATE_CONFIG.jitter),
maintenanceWindowUtc: {
...rawWindow,
start: stringValue(
rawWindow.start,
DEFAULT_UPDATE_CONFIG.maintenanceWindowUtc.start
),
duration: stringValue(
rawWindow.duration,
DEFAULT_UPDATE_CONFIG.maintenanceWindowUtc.duration
),
},
maxRuntimeDeferral: stringValue(
raw.maxRuntimeDeferral,
DEFAULT_UPDATE_CONFIG.maxRuntimeDeferral
),
retainHealthyVersions: numberValue(
raw.retainHealthyVersions,
DEFAULT_UPDATE_CONFIG.retainHealthyVersions
),
sources,
runtime,
core,
plugins: {
...rawPlugins,
...pluginBase,
// Loose local shared objects are never updater-owned. Keep this an
// invariant even if an older or hand-written config says otherwise.
managedOnly: true,
overrides,
},
};
}
function normalizeCandidate(value: unknown): UpdateCandidate | undefined {
const raw = record(value);
const version = stringValue(raw.version || raw.availableVersion);
if (!version) return undefined;
return {
...raw,
id: stringValue(raw.id || raw.candidateId) || undefined,
version,
channel: stringValue(raw.channel) || undefined,
source: stringValue(raw.source) || undefined,
...(typeof raw.signed === 'boolean' ? { signed: raw.signed } : {}),
...(typeof raw.compatible === 'boolean'
? { compatible: raw.compatible }
: {}),
...(typeof raw.downgrade === 'boolean'
? { downgrade: raw.downgrade }
: {}),
...(typeof raw.requiresRestart === 'boolean'
? { requiresRestart: raw.requiresRestart }
: {}),
cohort: stringValue(raw.cohort) || undefined,
message: stringValue(raw.message) || undefined,
};
}
function normalizeComponent(
component: UpdateComponent,
value: unknown
): ComponentUpdateStatus {
const raw = record(value);
const candidate =
normalizeCandidate(raw.candidate) ||
normalizeCandidate({
version: raw.availableVersion,
id: raw.candidateId,
channel: raw.availableChannel,
source: raw.availableSource,
signed: raw.signed,
compatible: raw.compatible,
downgrade: raw.downgrade,
requiresRestart: raw.requiresRestart,
});
return {
...raw,
component,
currentVersion:
stringValue(raw.currentVersion || raw.installedVersion) || undefined,
state: stringValue(raw.state || raw.status) || undefined,
message: stringValue(raw.message) || undefined,
channel: stringValue(raw.channel) || undefined,
source: stringValue(raw.source) || undefined,
candidate,
rollbackVersion: stringValue(raw.rollbackVersion) || undefined,
lastChangedAt:
typeof raw.lastChangedAt === 'string' ||
typeof raw.lastChangedAt === 'number'
? raw.lastChangedAt
: undefined,
};
}
function normalizePlugin(value: unknown): PluginUpdateStatus | null {
const raw = record(value);
const id = stringValue(raw.id || raw.pluginId);
if (!id) return null;
return {
...raw,
id,
name: stringValue(raw.name) || undefined,
managed: booleanValue(raw.managed, false),
currentVersion:
stringValue(raw.currentVersion || raw.installedVersion) || undefined,
state: stringValue(raw.state || raw.status) || undefined,
channel: stringValue(raw.channel) || undefined,
source: stringValue(raw.source) || undefined,
candidate:
normalizeCandidate(raw.candidate) ||
normalizeCandidate({
version: raw.availableVersion,
id: raw.candidateId,
signed: raw.signed,
compatible: raw.compatible,
downgrade: raw.downgrade,
requiresRestart: raw.requiresRestart,
}),
rollbackVersion: stringValue(raw.rollbackVersion) || undefined,
message: stringValue(raw.message) || undefined,
};
}
export function normalizeUpdateStatus(payload: unknown): UpdateStatus {
const raw = unwrap(payload, 'status');
const rawComponents = record(raw.components);
const pluginComponent = record(
rawComponents.plugins ||
(!Array.isArray(raw.plugins) ? raw.plugins : undefined)
);
const rawPluginEntries =
(Array.isArray(raw.pluginEntries) && raw.pluginEntries) ||
(Array.isArray(raw.managedPlugins) && raw.managedPlugins) ||
(Array.isArray(raw.plugins) && raw.plugins) ||
(Array.isArray(pluginComponent.items) && pluginComponent.items) ||
[];
const rawHistory = Array.isArray(raw.history) ? raw.history : [];
return {
...raw,
enabled: booleanValue(raw.enabled, true),
checking: booleanValue(raw.checking, false),
lastCheckAt:
typeof raw.lastCheckAt === 'string' ||
typeof raw.lastCheckAt === 'number'
? raw.lastCheckAt
: undefined,
nextCheckAt:
typeof raw.nextCheckAt === 'string' ||
typeof raw.nextCheckAt === 'number'
? raw.nextCheckAt
: undefined,
components: {
runtime: normalizeComponent(
'runtime',
rawComponents.runtime || raw.runtime
),
core: normalizeComponent('core', rawComponents.core || raw.core),
plugins: normalizeComponent('plugins', pluginComponent),
},
plugins: rawPluginEntries
.map(normalizePlugin)
.filter((plugin): plugin is PluginUpdateStatus => plugin !== null),
history: rawHistory.map((entry) => record(entry) as UpdateHistoryEntry),
message: stringValue(raw.message) || undefined,
};
}
export function configForSave(config: UpdateConfig): UpdateConfig {
const normalized = normalizeUpdateConfig(config);
const sources: Record<string, UpdateSourceConfig> = {};
for (const [id, source] of Object.entries(normalized.sources)) {
const { bearerTokenPresent: _present, ...writable } = source;
sources[id] = {
...sourceFieldsWithoutSecrets(writable),
url: source.url.trim(),
allowUnsigned: source.allowUnsigned,
bearerTokenEnv: source.bearerTokenEnv.trim(),
publicKeys: source.publicKeys
.map((key) => ({
id: key.id.trim(),
ed25519: key.ed25519.trim(),
}))
.filter((key) => key.id || key.ed25519),
};
}
return {
...normalized,
sources,
retainHealthyVersions: Math.max(
1,
Math.min(10, Math.trunc(normalized.retainHealthyVersions))
),
};
}
export function isValidSourceId(value: string): boolean {
return /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value);
}
export function cloneUpdateConfig(config: UpdateConfig): UpdateConfig {
return normalizeUpdateConfig(JSON.parse(JSON.stringify(config)));
}
+240
View File
@@ -186,6 +186,8 @@ select:focus:not(:focus-visible) { outline: none; }
.btn-ghost:hover { color: var(--text-2); background: rgba(255, 255, 255, 0.04); }
.btn-danger-ghost { background: transparent; border-color: rgba(255, 92, 92, 0.3); color: var(--red-text); }
.btn-danger-ghost:hover { background: rgba(255, 92, 92, 0.1); }
.btn-danger { background: #c8434b; color: #fff; }
.btn-danger:hover { background: #dc5059; }
/* Leave-room button: prominent but not alarming; pushed to the right of the
room header so it reads as the primary in-room action. */
.btn-leave {
@@ -685,3 +687,241 @@ select:focus:not(:focus-visible) { outline: none; }
}
.ts-markup details { margin: 0.4em 0; }
.ts-markup summary { cursor: pointer; font-weight: 600; }
/* ── Updates control plane ──────────────────────────────────────────────
The update surface keeps the dashboard's violet language, but uses a
denser instrument-panel rhythm: version rails, status lamps, and a faint
technical grid make trust and activation state scannable at a glance. */
.updates-view {
position: relative;
}
.updates-view::before {
content: ''; position: absolute; inset: -8px 0 auto; height: 250px;
pointer-events: none; opacity: .18;
background-image:
linear-gradient(rgba(124, 92, 255, .12) 1px, transparent 1px),
linear-gradient(90deg, rgba(124, 92, 255, .12) 1px, transparent 1px);
background-size: 28px 28px;
mask-image: linear-gradient(to bottom, #000, transparent);
}
.update-command-bar {
position: relative; display: flex; align-items: center;
justify-content: space-between; gap: 16px; margin-bottom: 16px;
padding: 14px 16px; border: 1px solid rgba(124, 92, 255, .23);
border-radius: 13px;
background: linear-gradient(110deg, rgba(124, 92, 255, .11), rgba(255, 255, 255, .025) 58%);
}
.update-command-state { display: flex; align-items: center; gap: 12px; min-width: 0; }
.update-command-state p { margin-top: 2px; font-size: 12px; }
.update-beacon {
width: 11px; height: 11px; border-radius: 50%; flex: none;
background: var(--faint); box-shadow: 0 0 0 6px rgba(106, 106, 120, .1);
}
.update-beacon.active {
background: var(--green);
box-shadow: 0 0 0 6px rgba(63, 208, 122, .1), 0 0 18px rgba(63, 208, 122, .4);
}
.update-live-region { min-height: 18px; color: var(--muted-2); font-size: 12px; }
.update-component-grid {
position: relative; display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px; margin: 2px 0 18px;
}
.update-component-card {
position: relative; overflow: hidden; display: flex; flex-direction: column;
min-height: 260px; padding: 16px; border: 1px solid var(--line);
border-radius: var(--radius); background: rgba(14, 14, 21, .93);
}
.update-component-card::after {
content: ''; position: absolute; right: -32px; top: -32px;
width: 110px; height: 110px; border-radius: 50%;
background: rgba(124, 92, 255, .08); filter: blur(4px);
}
.update-component-head {
position: relative; z-index: 1; display: grid;
grid-template-columns: auto 1fr auto; align-items: center; gap: 10px;
}
.update-component-head h2 { font-size: 15px; }
.update-component-head p { margin-top: 2px; font-size: 10px; }
.update-component-mark {
width: 35px; height: 35px; border-radius: 10px;
display: grid; place-items: center; font: 700 13px var(--font-mono);
color: #d7d0ff; border: 1px solid rgba(124, 92, 255, .28);
background: rgba(124, 92, 255, .13);
}
.update-component-mark.core { color: #8fe8b4; border-color: rgba(63, 208, 122, .25); background: rgba(63, 208, 122, .1); }
.update-component-mark.plugins { color: #ffe08d; border-color: rgba(255, 207, 74, .25); background: rgba(255, 207, 74, .1); }
.update-version-line {
display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
align-items: center; gap: 10px; margin: 20px 0 12px;
}
.update-version-line > div { min-width: 0; }
.update-version-line span {
display: block; color: var(--faint); font-size: 9px; font-weight: 700;
letter-spacing: .09em; text-transform: uppercase;
}
.update-version-line strong {
display: block; overflow: hidden; margin-top: 3px;
font: 700 14px var(--font-mono); text-overflow: ellipsis;
}
.update-version-arrow { color: var(--accent-text) !important; font-size: 16px !important; }
.update-badges { display: flex; flex-wrap: wrap; gap: 5px; }
.update-badge {
display: inline-flex; align-items: center; width: fit-content;
padding: 3px 7px; border-radius: 999px;
font: 700 9px var(--font-mono); letter-spacing: .03em;
text-transform: uppercase; white-space: nowrap;
color: var(--muted); border: 1px solid rgba(255, 255, 255, .08);
background: rgba(255, 255, 255, .04);
}
.update-badge.success { color: var(--green-text); border-color: rgba(63, 208, 122, .22); background: rgba(63, 208, 122, .09); }
.update-badge.warning { color: var(--yellow-text); border-color: rgba(255, 207, 74, .22); background: rgba(255, 207, 74, .09); }
.update-badge.danger { color: var(--red-text); border-color: rgba(255, 92, 92, .24); background: rgba(255, 92, 92, .09); }
.update-card-message { margin-top: 10px; color: var(--muted-2); font-size: 12px; line-height: 1.45; }
.update-card-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-top: auto; padding-top: 18px; }
.update-card-actions .btn { padding: 7px 10px; font-size: 11px; }
.updates-two-column {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: 18px; align-items: start;
}
.update-plugin-list { display: flex; flex-direction: column; }
.update-plugin-row {
display: grid; grid-template-columns: minmax(120px, 1.2fr) auto minmax(105px, .7fr) auto;
align-items: center; gap: 10px; padding: 9px 2px;
border-bottom: 1px solid var(--line);
}
.update-plugin-row:last-child { border-bottom: 0; }
.update-plugin-main { display: flex; flex-direction: column; min-width: 0; }
.update-plugin-main strong, .update-plugin-main span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.update-plugin-main span { font-size: 10px; margin-top: 2px; }
.update-plugin-version { color: var(--muted); font-size: 11px; }
.update-plugin-actions { display: flex; gap: 5px; }
.update-plugin-actions .btn { padding: 5px 8px; font-size: 10px; }
.update-history-scroll { max-height: 350px; overflow: auto; }
.update-history-table { width: 100%; border-collapse: collapse; font-size: 11px; }
.update-history-table th {
position: sticky; top: 0; z-index: 1; padding: 7px 8px;
text-align: left; color: var(--faint); background: #111119;
font-size: 9px; letter-spacing: .08em; text-transform: uppercase;
}
.update-history-table td { padding: 8px; border-bottom: 1px solid var(--line); vertical-align: middle; }
.update-history-table td:first-child { white-space: nowrap; color: var(--muted-2); }
.update-history-table td small { display: block; margin-top: 2px; color: var(--faint); font: 9px var(--font-mono); }
.update-config { margin-top: 8px; }
.update-config-title, .update-sources-head {
display: flex; align-items: flex-end; justify-content: space-between;
gap: 16px; margin: 27px 0 13px;
}
.update-config-title h2 { font-size: 22px; margin: 2px 0 3px; }
.update-kicker {
color: var(--accent-text); font: 700 9px var(--font-mono);
letter-spacing: .16em;
}
.update-automation-card { border-color: rgba(124, 92, 255, .18); }
.update-automation-grid {
display: grid; grid-template-columns: repeat(6, minmax(100px, 1fr));
gap: 12px; align-items: end;
}
.update-master-switch { grid-column: span 2; align-self: center; }
.update-field { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
.update-field > span {
color: var(--muted-2); font-size: 10px; font-weight: 700;
letter-spacing: .035em;
}
.update-field input, .update-field select, .update-override-row input,
.update-override-row select {
width: 100%; min-width: 0; color: var(--text);
background: rgba(255, 255, 255, .045); border: 1px solid var(--line);
border-radius: 9px; padding: 9px 10px; outline: none; font: inherit;
font-size: 12px;
}
.update-field input:focus, .update-field select:focus,
.update-override-row input:focus, .update-override-row select:focus {
border-color: rgba(124, 92, 255, .48);
}
.update-field select option, .update-override-row select option { color: #111; }
.update-field small { color: var(--faint); font-size: 10px; line-height: 1.35; }
.update-switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; color: var(--muted); font-size: 11px; }
.update-switch input { width: 15px; height: 15px; accent-color: var(--accent); }
.update-policy-list { display: flex; flex-direction: column; }
.update-policy-row {
display: grid; grid-template-columns: minmax(150px, .8fr) minmax(130px, .8fr) minmax(130px, 1fr) auto;
align-items: end; gap: 12px; padding: 12px 2px;
border-bottom: 1px solid var(--line);
}
.update-policy-row:last-child { border-bottom: 0; }
.update-policy-name { display: flex; flex-direction: column; gap: 6px; align-self: center; }
.update-auto-switch { min-height: 36px; align-self: end; }
.update-managed-only { margin-top: 12px; }
.update-override-list { display: flex; flex-direction: column; }
.update-override-row {
display: grid; grid-template-columns: minmax(140px, 1fr) minmax(120px, .7fr) minmax(120px, .8fr) auto auto;
align-items: center; gap: 9px; padding: 8px 0; border-bottom: 1px solid var(--line);
}
.update-override-id { overflow: hidden; text-overflow: ellipsis; }
.update-empty-inline { padding: 10px 2px; font-size: 12px; }
.update-source-list { display: flex; flex-direction: column; gap: 13px; }
.update-source-card {
min-width: 0; padding: 16px; border: 1px solid var(--line);
border-radius: var(--radius); background: var(--panel);
}
.update-source-card legend {
display: flex; align-items: center; gap: 8px; padding: 0 8px;
font-weight: 700;
}
.update-source-grid {
display: grid; grid-template-columns: minmax(240px, 1.4fr) minmax(220px, 1fr) auto;
align-items: start; gap: 12px; margin-bottom: 17px;
}
.update-unsigned-switch { min-height: 55px; align-self: end; color: var(--yellow-text); }
.update-key-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
.update-key-head p { margin-top: 2px; font-size: 11px; }
.update-key-list { display: flex; flex-direction: column; }
.update-key-row {
display: grid; grid-template-columns: minmax(130px, .45fr) minmax(220px, 1.55fr) auto;
align-items: end; gap: 8px; padding: 7px 0;
}
.update-key-remove { margin-bottom: 1px; }
.update-source-foot { display: flex; justify-content: flex-end; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--line); }
@media (max-width: 1200px) {
.update-component-grid { grid-template-columns: 1fr; }
.update-component-card { min-height: 0; }
.update-automation-grid { grid-template-columns: repeat(3, minmax(120px, 1fr)); }
.update-master-switch { grid-column: span 1; }
}
@media (max-width: 1000px) {
.updates-two-column { grid-template-columns: 1fr; }
.update-source-grid { grid-template-columns: 1fr 1fr; }
.update-unsigned-switch { grid-column: 1 / -1; min-height: auto; }
}
@media (max-width: 720px) {
.update-command-bar, .update-config-title, .update-sources-head {
align-items: stretch; flex-direction: column;
}
.update-command-bar .row-gap, .update-config-title .row-gap { justify-content: flex-end; }
.update-automation-grid, .update-source-grid { grid-template-columns: 1fr; }
.update-policy-row { grid-template-columns: 1fr 1fr; }
.update-policy-name { grid-column: 1 / -1; }
.update-override-row { grid-template-columns: 1fr 1fr; }
.update-override-id { grid-column: 1 / -1; }
.update-key-row { grid-template-columns: 1fr; padding: 11px 0; }
.update-key-remove { justify-self: start; }
.update-plugin-row { grid-template-columns: minmax(0, 1fr) auto; }
.update-plugin-version { grid-column: 1; }
.update-plugin-actions { grid-column: 2; grid-row: 2; }
}
@media (max-width: 460px) {
.update-policy-row, .update-override-row { grid-template-columns: 1fr; }
.update-policy-name, .update-override-id { grid-column: auto; }
.update-version-line { grid-template-columns: 1fr; }
.update-version-arrow { transform: rotate(90deg); width: fit-content; }
.update-history-table th:nth-child(3), .update-history-table td:nth-child(3) { display: none; }
}
@media (prefers-reduced-motion: reduce) {
.update-beacon { box-shadow: none; }
}
+24
View File
@@ -0,0 +1,24 @@
import { afterEach, describe, expect, it } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { appStore } from '../lib/app';
import { UpdatesView } from './UpdatesView';
afterEach(() => appStore.set({ identity: null }));
describe('UpdatesView authorization', () => {
it('shows an authorization guard to non-administrators', () => {
appStore.set({ identity: { nickname: 'listener', isAdmin: false } });
const html = renderToStaticMarkup(<UpdatesView />);
expect(html).toContain('Administrator authentication required');
expect(html).not.toContain('Check now');
});
it('renders the update controls only for an administrator', () => {
appStore.set({ identity: { nickname: 'operator', isAdmin: true } });
const html = renderToStaticMarkup(<UpdatesView />);
expect(html).toContain('Check now');
expect(html).toContain('Update history');
expect(html).not.toContain('Administrator authentication required');
expect(html).toContain('aria-live="polite"');
});
});
File diff suppressed because it is too large. Load diff
+98
View File
@@ -0,0 +1,98 @@
#pragma once
#include <boost/asio/ip/address.hpp>
#include <chrono>
#include <cstddef>
#include <expected>
#include <mutex>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
namespace Echoion::Web::Security
{
namespace asio = boost::asio;
class CidrBlock
{
public:
CidrBlock(asio::ip::address network, unsigned int prefixLength);
[[nodiscard]] bool contains(
const asio::ip::address& address) const noexcept;
private:
asio::ip::address network_;
unsigned int prefixLength_ = 0;
};
using ParsedCidrs = std::expected<std::vector<CidrBlock>, std::string>;
[[nodiscard]] ParsedCidrs parseTrustedProxyCidrs(
std::span<const std::string> cidrs);
[[nodiscard]] std::string effectiveClientAddress(
const asio::ip::address& immediatePeer,
std::optional<std::string_view> forwardedFor,
std::span<const CidrBlock> trustedProxies);
[[nodiscard]] bool validShortSlug(std::string_view slug) noexcept;
[[nodiscard]] bool validRedirectLocation(std::string_view location) noexcept;
class ShortLinkRateLimiter
{
public:
using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;
struct Config {
double globalRate = 200.0;
double globalBurst = 400.0;
double peerRate = 10.0;
double peerBurst = 20.0;
std::size_t maxPeers = 4096;
Clock::duration idleTimeout = std::chrono::minutes(10);
Clock::duration sweepInterval = std::chrono::minutes(1);
};
ShortLinkRateLimiter();
explicit ShortLinkRateLimiter(Config config);
[[nodiscard]] bool allow(std::string_view peer);
[[nodiscard]] bool allow(std::string_view peer, TimePoint now);
void reset();
[[nodiscard]] std::size_t trackedPeerCount() const;
private:
struct TokenBucket {
double tokens = 0.0;
TimePoint updated{};
bool initialized = false;
};
struct PeerBucket {
TokenBucket bucket;
TimePoint lastSeen{};
};
static void refill(TokenBucket& bucket, double rate, double burst,
TimePoint now) noexcept;
void evictIdle(TimePoint now, bool force);
Config config_;
mutable std::mutex mutex_;
TokenBucket global_;
std::unordered_map<std::string, PeerBucket> peers_;
TimePoint nextSweep_{};
bool sweepInitialized_ = false;
};
} // namespace Echoion::Web::Security
+42 -1
View File
@@ -1,5 +1,7 @@
#pragma once
#include "echoion/web/HttpSecurity.hpp"
#include <Void/Async/ThreadPool.hpp>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
@@ -7,13 +9,16 @@
#include <atomic>
#include <cstdint>
#include <expected>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <shared_mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
namespace Echoion::Web
{
@@ -43,6 +48,7 @@ namespace Echoion::Web
// Server-wide switch for the Now Playing video preview,
// surfaced to the browser via /config.json.
bool nowPlayingVideo = true;
std::vector<std::string> trustedProxyCidrs;
};
HttpServer();
@@ -52,6 +58,12 @@ namespace Echoion::Web
void stop();
[[nodiscard]] bool isRunning() const { return running_; }
using TrustedProxyUpdate = std::expected<void, std::string>;
[[nodiscard]] static TrustedProxyUpdate validateTrustedProxyCidrs(
const std::vector<std::string>& cidrs);
[[nodiscard]] TrustedProxyUpdate setTrustedProxyCidrs(
const std::vector<std::string>& cidrs);
// A user's avatar image, served at GET /avatar/<uid>. Installed
// by Core (which owns the TeamSpeak plugin handle); best-effort —
// nullopt yields a 404 and the UI falls back to initials. It may be
@@ -79,6 +91,25 @@ namespace Echoion::Web
dashboardProvider_ = std::move(provider);
}
enum class ShortLinkStatus {
found,
notFound,
gone,
rateLimited,
unavailable,
};
struct ShortLinkResolution {
ShortLinkStatus status = ShortLinkStatus::notFound;
std::string location;
};
using ShortLinkResolver =
std::function<ShortLinkResolution(std::string_view key)>;
void setShortLinkResolver(ShortLinkResolver resolver)
{
std::lock_guard lock(shortLinkResolverMutex_);
shortLinkResolver_ = std::move(resolver);
}
private:
void acceptLoop();
@@ -96,7 +127,12 @@ namespace Echoion::Web
// Serves one request; returns true when the connection should be
// kept open for the next request (HTTP keep-alive).
bool serveHttp(asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req);
const http::request<http::string_body>& req,
std::string_view clientAddress);
[[nodiscard]] std::string clientAddress(
const asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req) const;
[[nodiscard]] bool allowShortLinkRequest(std::string_view peer);
Config config_;
asio::io_context ioContext_;
@@ -126,6 +162,11 @@ namespace Echoion::Web
std::mutex avatarProviderMutex_;
DashboardProvider dashboardProvider_;
std::mutex dashboardProviderMutex_;
ShortLinkResolver shortLinkResolver_;
std::mutex shortLinkResolverMutex_;
mutable std::shared_mutex trustedProxyMutex_;
std::vector<Security::CidrBlock> trustedProxyNetworks_;
Security::ShortLinkRateLimiter shortLinkRateLimiter_;
};
} // namespace Echoion::Web
+351
View File
@@ -0,0 +1,351 @@
#include "echoion/web/HttpSecurity.hpp"
#include <boost/asio/ip/address_v6.hpp>
#include <boost/url/parse.hpp>
#include <boost/url/scheme.hpp>
#include <algorithm>
#include <charconv>
#include <cmath>
#include <format>
#include <stdexcept>
namespace Echoion::Web::Security
{
namespace
{
constexpr std::size_t MAX_FORWARDED_HOPS = 64;
constexpr std::size_t MAX_REDIRECT_LENGTH = 8192;
asio::ip::address
normalizeMappedAddress(const asio::ip::address& address)
{
if (address.is_v6() && address.to_v6().is_v4_mapped()) {
return asio::ip::make_address_v4(asio::ip::v4_mapped,
address.to_v6());
}
return address;
}
bool isTrusted(const asio::ip::address& address,
std::span<const CidrBlock>
trustedProxies) noexcept
{
return std::ranges::any_of(trustedProxies,
[&address](const CidrBlock& network) {
return network.contains(address);
});
}
std::string_view trimForwardedToken(std::string_view token) noexcept
{
while (!token.empty() &&
(token.front() == ' ' || token.front() == '\t')) {
token.remove_prefix(1);
}
while (!token.empty() &&
(token.back() == ' ' || token.back() == '\t')) {
token.remove_suffix(1);
}
return token;
}
} // namespace
CidrBlock::CidrBlock(asio::ip::address network, unsigned int prefixLength)
: network_(std::move(network)), prefixLength_(prefixLength)
{
}
bool CidrBlock::contains(const asio::ip::address& address) const noexcept
{
asio::ip::address candidate = address;
if (network_.is_v4() && candidate.is_v6()) {
if (!candidate.to_v6().is_v4_mapped()) {
return false;
}
candidate = asio::ip::make_address_v4(asio::ip::v4_mapped,
candidate.to_v6());
} else if (network_.is_v6() && candidate.is_v4()) {
candidate = asio::ip::make_address_v6(asio::ip::v4_mapped,
candidate.to_v4());
}
if (network_.is_v4() != candidate.is_v4()) {
return false;
}
const auto matches = [this](const auto& lhs, const auto& rhs) {
for (std::size_t index = 0; index < lhs.size(); ++index) {
const auto consumed = static_cast<unsigned int>(index * 8);
const auto remaining =
prefixLength_ > consumed ? prefixLength_ - consumed : 0U;
const auto mask = static_cast<unsigned char>(
remaining >= 8 ? 0xffU
: remaining == 0 ? 0U
: 0xffU << (8 - remaining));
if ((lhs[index] & mask) != (rhs[index] & mask)) {
return false;
}
}
return true;
};
return network_.is_v4() ? matches(network_.to_v4().to_bytes(),
candidate.to_v4().to_bytes())
: matches(network_.to_v6().to_bytes(),
candidate.to_v6().to_bytes());
}
ParsedCidrs parseTrustedProxyCidrs(std::span<const std::string> cidrs)
{
std::vector<CidrBlock> parsed;
parsed.reserve(cidrs.size());
for (std::size_t index = 0; index < cidrs.size(); ++index) {
const std::string_view cidr = cidrs[index];
const auto slash = cidr.find('/');
if (cidr.empty() || slash == 0 ||
(slash != std::string_view::npos &&
(slash + 1 == cidr.size() ||
cidr.find('/', slash + 1) != std::string_view::npos))) {
return std::unexpected(
std::format("trusted proxy CIDR #{} ('{}') is malformed",
index + 1, cidr));
}
const std::string_view addressText = cidr.substr(0, slash);
if (addressText.contains('%')) {
return std::unexpected(std::format(
"trusted proxy CIDR #{} ('{}') must not contain an IPv6 "
"scope identifier",
index + 1, cidr));
}
boost::system::error_code error;
const auto network = asio::ip::make_address(addressText, error);
if (error) {
return std::unexpected(std::format(
"trusted proxy CIDR #{} ('{}') has an invalid address",
index + 1, cidr));
}
const unsigned int maxBits = network.is_v4() ? 32U : 128U;
unsigned int prefixLength = maxBits;
if (slash != std::string_view::npos) {
const std::string_view prefix = cidr.substr(slash + 1);
const auto [end, code] = std::from_chars(
prefix.data(), prefix.data() + prefix.size(), prefixLength);
if (code != std::errc{} ||
end != prefix.data() + prefix.size() ||
prefixLength > maxBits) {
return std::unexpected(std::format(
"trusted proxy CIDR #{} ('{}') has an invalid prefix",
index + 1, cidr));
}
}
parsed.emplace_back(network, prefixLength);
}
return parsed;
}
std::string effectiveClientAddress(const asio::ip::address& immediatePeer,
std::optional<std::string_view>
forwardedFor,
std::span<const CidrBlock>
trustedProxies)
{
const auto directAddress = normalizeMappedAddress(immediatePeer);
if (!forwardedFor || !isTrusted(immediatePeer, trustedProxies)) {
return directAddress.to_string();
}
std::vector<asio::ip::address> hops;
hops.reserve(8);
std::string_view remaining = *forwardedFor;
for (;;) {
if (hops.size() == MAX_FORWARDED_HOPS) {
return directAddress.to_string();
}
const auto comma = remaining.find(',');
const auto token = trimForwardedToken(remaining.substr(0, comma));
if (token.empty() || token.contains('%')) {
return directAddress.to_string();
}
boost::system::error_code error;
auto hop = asio::ip::make_address(token, error);
if (error || (hop.is_v6() && hop.to_v6().scope_id() != 0)) {
return directAddress.to_string();
}
hops.push_back(std::move(hop));
if (comma == std::string_view::npos) {
break;
}
remaining.remove_prefix(comma + 1);
}
asio::ip::address effective = immediatePeer;
for (auto hop = hops.rbegin(); hop != hops.rend(); ++hop) {
if (!isTrusted(effective, trustedProxies)) {
break;
}
effective = *hop;
}
return normalizeMappedAddress(effective).to_string();
}
bool validShortSlug(std::string_view slug) noexcept
{
return slug.size() == 10 &&
std::ranges::all_of(slug, [](unsigned char character) {
return (character >= '0' && character <= '9') ||
(character >= 'A' && character <= 'Z') ||
(character >= 'a' && character <= 'z');
});
}
bool validRedirectLocation(std::string_view location) noexcept
{
if (location.empty() || location.size() > MAX_REDIRECT_LENGTH ||
std::ranges::any_of(location, [](unsigned char character) {
return character <= 0x20U || character >= 0x7fU;
})) {
return false;
}
const auto parsed = boost::urls::parse_uri(location);
if (!parsed) {
return false;
}
const auto& url = *parsed;
if ((url.scheme_id() != boost::urls::scheme::http &&
url.scheme_id() != boost::urls::scheme::https) ||
!url.has_authority() || url.has_userinfo() ||
url.encoded_host().empty()) {
return false;
}
if (url.has_port()) {
const auto port = url.port();
unsigned int number = 0;
const auto [end, code] =
std::from_chars(port.data(), port.data() + port.size(), number);
if (port.empty() || code != std::errc{} ||
end != port.data() + port.size() || number == 0 ||
number > 65535) {
return false;
}
}
return true;
}
ShortLinkRateLimiter::ShortLinkRateLimiter()
: ShortLinkRateLimiter(Config{})
{
}
ShortLinkRateLimiter::ShortLinkRateLimiter(Config config) : config_(config)
{
if (!std::isfinite(config_.globalRate) || config_.globalRate < 0.0 ||
!std::isfinite(config_.globalBurst) || config_.globalBurst < 1.0 ||
!std::isfinite(config_.peerRate) || config_.peerRate < 0.0 ||
!std::isfinite(config_.peerBurst) || config_.peerBurst < 1.0 ||
config_.maxPeers == 0 ||
config_.idleTimeout < Clock::duration::zero() ||
config_.sweepInterval < Clock::duration::zero()) {
throw std::invalid_argument(
"invalid short-link rate limiter settings");
}
peers_.reserve(config_.maxPeers);
}
bool ShortLinkRateLimiter::allow(std::string_view peer)
{
return allow(peer, Clock::now());
}
bool ShortLinkRateLimiter::allow(std::string_view peer, TimePoint now)
{
std::lock_guard lock(mutex_);
evictIdle(now, false);
refill(global_, config_.globalRate, config_.globalBurst, now);
if (global_.tokens < 1.0) {
return false;
}
const std::string peerKey{peer};
auto found = peers_.find(peerKey);
if (found == peers_.end()) {
if (peers_.size() >= config_.maxPeers) {
evictIdle(now, true);
}
if (peers_.size() >= config_.maxPeers) {
return false;
}
found =
peers_
.emplace(peerKey, PeerBucket{.bucket = {}, .lastSeen = now})
.first;
}
found->second.lastSeen = now;
refill(found->second.bucket, config_.peerRate, config_.peerBurst, now);
if (found->second.bucket.tokens < 1.0) {
return false;
}
// Commit both token deductions together. A peer-local rejection never
// consumes global capacity and cannot starve unrelated clients.
global_.tokens -= 1.0;
found->second.bucket.tokens -= 1.0;
return true;
}
void ShortLinkRateLimiter::reset()
{
std::lock_guard lock(mutex_);
global_ = {};
peers_.clear();
nextSweep_ = {};
sweepInitialized_ = false;
}
std::size_t ShortLinkRateLimiter::trackedPeerCount() const
{
std::lock_guard lock(mutex_);
return peers_.size();
}
void ShortLinkRateLimiter::refill(TokenBucket& bucket, double rate,
double burst, TimePoint now) noexcept
{
if (!bucket.initialized) {
bucket.tokens = burst;
bucket.updated = now;
bucket.initialized = true;
return;
}
const auto elapsed =
now > bucket.updated
? std::chrono::duration<double>(now - bucket.updated).count()
: 0.0;
bucket.tokens = std::min(burst, bucket.tokens + elapsed * rate);
bucket.updated = now;
}
void ShortLinkRateLimiter::evictIdle(TimePoint now, bool force)
{
if (!force && sweepInitialized_ && now < nextSweep_) {
return;
}
for (auto peer = peers_.begin(); peer != peers_.end();) {
const bool expired =
now >= peer->second.lastSeen &&
now - peer->second.lastSeen >= config_.idleTimeout;
if (expired) {
peer = peers_.erase(peer);
} else {
++peer;
}
}
nextSweep_ = now + config_.sweepInterval;
sweepInitialized_ = true;
}
} // namespace Echoion::Web::Security
+199 -39
View File
@@ -12,6 +12,10 @@
#include <sstream>
#include <string_view>
#if defined(__unix__) || defined(__APPLE__)
#include <sys/socket.h>
#endif
namespace Echoion::Web
{
namespace websocket = beast::websocket;
@@ -114,19 +118,77 @@ namespace Echoion::Web
from.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
to.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
}
} // namespace
HttpServer::HttpServer() = default;
HttpServer::~HttpServer() { stop(); }
HttpServer::TrustedProxyUpdate HttpServer::validateTrustedProxyCidrs(
const std::vector<std::string>& cidrs)
{
try {
auto parsed = Security::parseTrustedProxyCidrs(cidrs);
if (!parsed) {
return std::unexpected(std::move(parsed.error()));
}
return {};
} catch (const std::exception& exception) {
return std::unexpected(
std::format("failed to validate trusted proxy CIDRs: {}",
exception.what()));
}
}
HttpServer::TrustedProxyUpdate
HttpServer::setTrustedProxyCidrs(const std::vector<std::string>& cidrs)
{
try {
auto parsed = Security::parseTrustedProxyCidrs(cidrs);
if (!parsed) {
return std::unexpected(std::move(parsed.error()));
}
{
std::unique_lock lock(trustedProxyMutex_);
// A trust-policy change changes the peer identity used by the
// limiter. Reset while new address calculations are blocked,
// then publish the already-parsed policy with a no-throw swap.
shortLinkRateLimiter_.reset();
trustedProxyNetworks_.swap(*parsed);
}
return {};
} catch (const std::exception& exception) {
return std::unexpected(std::format(
"failed to update trusted proxy CIDRs: {}", exception.what()));
}
}
bool HttpServer::start(const Config& config)
{
if (running_.exchange(true)) {
if (running_.load()) {
return false;
}
config_ = config;
try {
auto trustedProxies =
Security::parseTrustedProxyCidrs(config.trustedProxyCidrs);
if (!trustedProxies) {
Void::Log::error(
"HttpServer", "{}",
std::format("Failed to start web interface: {}",
trustedProxies.error()));
return false;
}
bool expected = false;
if (!running_.compare_exchange_strong(expected, true)) {
return false;
}
config_ = config;
{
std::unique_lock lock(trustedProxyMutex_);
trustedProxyNetworks_ = std::move(*trustedProxies);
}
shortLinkRateLimiter_.reset();
ioContext_.restart();
asio::ip::tcp::endpoint endpoint(
@@ -272,26 +334,79 @@ namespace Echoion::Web
{
beast::error_code ec;
beast::flat_buffer buffer;
// Serve requests on this connection until the peer closes, an error
// occurs, or the request asks not to keep the connection alive.
while (running_.load()) {
http::request<http::string_body> req;
http::read(*socket, buffer, req, ec);
if (ec) {
return;
}
if (websocket::is_upgrade(req)) {
if (req.target() == "/rpc") {
bridgeRpc(socket, req, buffer);
}
return;
}
if (!serveHttp(*socket, req)) {
// Bound slow clients and parser memory. Every accepted connection
// serves exactly one request; browsers simply open another connection.
#if defined(__unix__) || defined(__APPLE__)
timeval timeout{.tv_sec = 5, .tv_usec = 0};
(void)::setsockopt(socket->native_handle(), SOL_SOCKET, SO_RCVTIMEO,
&timeout, sizeof(timeout));
#endif
http::request_parser<http::string_body> parser;
parser.header_limit(32 * 1024);
parser.body_limit(0);
http::read(*socket, buffer, parser, ec);
if (ec) {
return;
}
auto req = parser.release();
for (const auto& field : req) {
if (field.name_string().size() + field.value().size() > 8 * 1024) {
http::response<http::string_body> response{
http::status::request_header_fields_too_large,
req.version()};
response.set(http::field::server, "Echoion");
response.body() = "Request Header Fields Too Large";
response.prepare_payload();
response.keep_alive(false);
http::write(*socket, response, ec);
return;
}
}
if (websocket::is_upgrade(req)) {
if (req.target() == "/rpc") {
bridgeRpc(socket, req, buffer);
}
return;
}
(void)serveHttp(*socket, req, clientAddress(*socket, req));
}
std::string HttpServer::clientAddress(
const asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req) const
{
boost::system::error_code error;
const auto endpoint = socket.remote_endpoint(error);
if (error) {
return {};
}
std::optional<std::string_view> forwardedFor;
for (const auto& field : req) {
if (!beast::iequals(field.name_string(), "X-Forwarded-For")) {
continue;
}
// Multiple field-lines have ambiguous intermediary semantics.
// Ignore all of them instead of choosing an attacker-controlled
// value.
if (forwardedFor) {
forwardedFor.reset();
break;
}
forwardedFor =
std::string_view{field.value().data(), field.value().size()};
}
std::shared_lock lock(trustedProxyMutex_);
return Security::effectiveClientAddress(
endpoint.address(), forwardedFor, trustedProxyNetworks_);
}
bool HttpServer::allowShortLinkRequest(std::string_view peer)
{
return shortLinkRateLimiter_.allow(peer);
}
void HttpServer::bridgeRpc(std::shared_ptr<asio::ip::tcp::socket> browser,
@@ -315,25 +430,10 @@ namespace Echoion::Web
// Forward the browser's effective IP so the RPC server can offer
// address-based autologin. Never trust a client-supplied value; a
// reverse proxy's X-Forwarded-For (first hop) wins over the socket
// address because the proxy connects from its own host.
// X-Forwarded-For is accepted only from configured proxies and walked
// from right to left, stopping at the nearest untrusted hop.
req.erase("X-Echoion-Client-Ip");
std::string clientIp;
if (auto xff = req.find("X-Forwarded-For"); xff != req.end()) {
clientIp = std::string(xff->value());
if (auto comma = clientIp.find(','); comma != std::string::npos) {
clientIp = clientIp.substr(0, comma);
}
while (!clientIp.empty() && clientIp.front() == ' ') {
clientIp.erase(clientIp.begin());
}
}
if (clientIp.empty()) {
boost::system::error_code epEc;
if (auto ep = browser->remote_endpoint(epEc); !epEc) {
clientIp = ep.address().to_string();
}
}
const std::string clientIp = clientAddress(*browser, req);
if (!clientIp.empty()) {
req.set("X-Echoion-Client-Ip", clientIp);
}
@@ -373,7 +473,8 @@ namespace Echoion::Web
}
bool HttpServer::serveHttp(asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req)
const http::request<http::string_body>& req,
std::string_view requestAddress)
{
beast::error_code ec;
const bool isHead = req.method() == http::verb::head;
@@ -398,7 +499,7 @@ namespace Echoion::Web
if (!location.empty()) {
res.set(http::field::location, location);
}
res.keep_alive(req.keep_alive());
res.keep_alive(false);
// HEAD advertises the real Content-Length but carries no body.
res.content_length(
status == http::status::not_modified ? 0 : body.size());
@@ -468,6 +569,65 @@ namespace Echoion::Web
return !ec && req.keep_alive();
}
constexpr std::string_view kShortPrefix = "/s/";
if (target.starts_with(kShortPrefix)) {
const std::string key = target.substr(kShortPrefix.size());
if (!Security::validShortSlug(key)) {
respond(http::status::not_found, "text/plain", "Not Found",
"no-store");
return false;
}
if (!allowShortLinkRequest(requestAddress)) {
respond(http::status::too_many_requests, "text/plain",
"Too Many Requests", "no-store");
return false;
}
ShortLinkResolver resolver;
{
std::lock_guard lock(shortLinkResolverMutex_);
resolver = shortLinkResolver_;
}
const auto resolution =
resolver ? resolver(key)
: ShortLinkResolution{.status =
ShortLinkStatus::unavailable,
.location = {}};
http::status status = http::status::not_found;
switch (resolution.status) {
case ShortLinkStatus::found:
status = http::status::found;
break;
case ShortLinkStatus::gone:
status = http::status::gone;
break;
case ShortLinkStatus::rateLimited:
status = http::status::too_many_requests;
break;
case ShortLinkStatus::unavailable:
status = http::status::service_unavailable;
break;
case ShortLinkStatus::notFound:
break;
}
http::response<http::string_body> response{status, req.version()};
response.set(http::field::server, "Echoion");
response.set(http::field::cache_control, "no-store");
response.set("Referrer-Policy", "no-referrer");
response.set("X-Robots-Tag", "noindex, nofollow");
response.set("X-Content-Type-Options", "nosniff");
response.set("Content-Security-Policy", "default-src 'none'");
if (status == http::status::found &&
Security::validRedirectLocation(resolution.location)) {
response.set(http::field::location, resolution.location);
} else if (status == http::status::found) {
response.result(http::status::service_unavailable);
}
response.content_length(0);
response.keep_alive(false);
http::write(socket, response, ec);
return false;
}
// User avatar images, resolved through Core's provider (TeamSpeak
// avatar cache). Best-effort: 404 lets the UI fall back to its
// initial-letter avatars; short private caching keeps reloads cheap
+300
View File
@@ -0,0 +1,300 @@
#include "echoion/web/HttpSecurity.hpp"
#include "echoion/web/HttpServer.hpp"
#include <atomic>
#include <chrono>
#include <iostream>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace
{
using Echoion::Web::Security::ShortLinkRateLimiter;
namespace asio = boost::asio;
bool expect(bool condition, std::string_view message)
{
if (!condition) {
std::cerr << message << '\n';
}
return condition;
}
bool testShortSlugs()
{
using Echoion::Web::Security::validShortSlug;
std::string nonAscii(9, 'a');
nonAscii.push_back(static_cast<char>(0xe9));
return expect(validShortSlug("aZ019BcDeF"),
"ASCII short slug was rejected") &&
expect(!validShortSlug("aZ019BcDe_"),
"punctuation was accepted in a short slug") &&
expect(!validShortSlug("short"),
"short slug length was not enforced") &&
expect(!validShortSlug(nonAscii),
"locale-dependent non-ASCII alphanumeric was accepted");
}
bool testCidrsAndForwarding()
{
using Echoion::Web::Security::effectiveClientAddress;
using Echoion::Web::Security::parseTrustedProxyCidrs;
const std::vector<std::string> trustedTexts{"10.0.0.0/8",
"192.0.2.0/24"};
auto trusted = parseTrustedProxyCidrs(trustedTexts);
if (!expect(trusted.has_value(), "valid trusted proxy CIDRs failed")) {
return false;
}
const std::vector<std::string> invalidCidrs{"",
"10.0.0.0/",
"10.0.0.0/33",
"10.0.0.0/-1",
"10.0.0.0/+8",
"10.0.0.0/8 ",
" 10.0.0.0/8",
"2001:db8::/129",
"fe80::1%1/128",
"10.0.0.0/8/9",
"not-an-address"};
for (const auto& invalid : invalidCidrs) {
const std::vector<std::string> one{invalid};
if (!expect(!parseTrustedProxyCidrs(one),
"invalid trusted proxy CIDR was accepted: " +
invalid)) {
return false;
}
}
const std::vector<std::string> mappedV4Text{"192.0.2.0/24"};
auto mappedV4 = parseTrustedProxyCidrs(mappedV4Text);
const std::vector<std::string> mappedV6Text{"::ffff:192.0.2.0/120"};
auto mappedV6 = parseTrustedProxyCidrs(mappedV6Text);
if (!expect(mappedV4 && mappedV6,
"IPv4-mapped test networks did not parse") ||
!expect((*mappedV4)[0].contains(
asio::ip::make_address("::ffff:192.0.2.42")),
"IPv4 CIDR did not match an IPv4-mapped peer") ||
!expect(
(*mappedV6)[0].contains(asio::ip::make_address("192.0.2.42")),
"IPv4-mapped IPv6 CIDR did not match an IPv4 peer")) {
return false;
}
const auto immediate = asio::ip::make_address("10.0.0.10");
if (!expect(effectiveClientAddress(
immediate, "203.0.113.9, 198.51.100.7, 192.0.2.20",
*trusted) == "198.51.100.7",
"X-Forwarded-For was not walked from right to left") ||
!expect(effectiveClientAddress(immediate,
"203.0.113.9, 198.51.100.7",
*trusted) == "198.51.100.7",
"spoofed leftmost forwarded hop was trusted") ||
!expect(effectiveClientAddress(asio::ip::make_address("172.16.0.2"),
"203.0.113.9",
*trusted) == "172.16.0.2",
"untrusted direct peer supplied a forwarded address") ||
!expect(effectiveClientAddress(immediate,
"203.0.113.9, invalid, 192.0.2.20",
*trusted) == "10.0.0.10",
"malformed forwarded chain was partially accepted") ||
!expect(effectiveClientAddress(
asio::ip::make_address("::ffff:10.0.0.10"),
"198.51.100.7", *trusted) == "198.51.100.7",
"IPv4-mapped trusted peer was not recognized") ||
!expect(effectiveClientAddress(immediate,
"203.0.113.9, ::ffff:192.0.2.20",
*trusted) == "203.0.113.9",
"IPv4-mapped trusted intermediary was not recognized") ||
!expect(effectiveClientAddress(
asio::ip::make_address("::ffff:172.16.0.2"),
std::nullopt, *trusted) == "172.16.0.2",
"IPv4-mapped direct address was not normalized")) {
return false;
}
return true;
}
bool testRedirectLocations()
{
using Echoion::Web::Security::validRedirectLocation;
const std::vector<std::string_view> valid{
"https://example.test/watch?v=abc%201#fragment",
"HTTP://example.test/", "http://[2001:db8::1]:8080/path"};
for (const auto location : valid) {
if (!expect(validRedirectLocation(location),
"valid HTTP redirect was rejected")) {
return false;
}
}
const std::vector<std::string_view> invalid{
"",
"ftp://example.test/file",
"/relative/path",
"http:///missing-host",
"https://user@example.test/",
"https://example.test:",
"https://example.test:0/",
"https://example.test:65536/",
"https://example.test/a b"};
for (const auto location : invalid) {
if (!expect(!validRedirectLocation(location),
"unsafe redirect location was accepted")) {
return false;
}
}
for (unsigned int control = 0; control <= 0x20; ++control) {
std::string location = "https://example.test/path";
location.push_back(static_cast<char>(control));
if (!expect(!validRedirectLocation(location),
"ASCII control was accepted in redirect location")) {
return false;
}
}
for (const unsigned int control : {0x7fU, 0x80U, 0x9fU}) {
std::string location = "https://example.test/path";
location.push_back(static_cast<char>(control));
if (!expect(!validRedirectLocation(location),
"DEL/C1 control was accepted in redirect location")) {
return false;
}
}
return true;
}
bool testTrustedProxyRuntimeUpdates()
{
Echoion::Web::HttpServer server;
const std::vector<std::string> initial{"127.0.0.0/8"};
const std::vector<std::string> replacement{"::1/128"};
const std::vector<std::string> invalid{"127.0.0.1/129"};
const std::vector<std::string> none;
return expect(server.setTrustedProxyCidrs(initial).has_value(),
"initial live trusted-proxy update failed") &&
expect(server.setTrustedProxyCidrs(replacement).has_value(),
"replacement live trusted-proxy update failed") &&
expect(!server.setTrustedProxyCidrs(invalid),
"invalid live trusted-proxy update was accepted") &&
expect(server.setTrustedProxyCidrs(none).has_value(),
"clearing live trusted proxies failed");
}
bool testRateLimiterFairnessAndBounds()
{
using namespace std::chrono_literals;
const auto now = ShortLinkRateLimiter::TimePoint{} + 1s;
ShortLinkRateLimiter fair({
.globalRate = 0.0,
.globalBurst = 2.0,
.peerRate = 0.0,
.peerBurst = 1.0,
.maxPeers = 4,
.idleTimeout = 1min,
.sweepInterval = 1min,
});
if (!expect(fair.allow("peer-a", now),
"first peer request was rejected") ||
!expect(!fair.allow("peer-a", now),
"peer burst limit was not enforced") ||
!expect(fair.allow("peer-b", now),
"peer rejection consumed unrelated global capacity")) {
return false;
}
ShortLinkRateLimiter bounded({
.globalRate = 100.0,
.globalBurst = 100.0,
.peerRate = 100.0,
.peerBurst = 2.0,
.maxPeers = 2,
.idleTimeout = 100ms,
.sweepInterval = 1h,
});
if (!expect(bounded.allow("peer-a", now) &&
bounded.allow("peer-b", now),
"bounded limiter rejected initial peers") ||
!expect(!bounded.allow("peer-c", now),
"bounded limiter exceeded its peer cap") ||
!expect(bounded.trackedPeerCount() == 2,
"bounded limiter retained too many peers") ||
!expect(bounded.allow("peer-c", now + 200ms),
"idle peer entries were not evicted") ||
!expect(bounded.trackedPeerCount() <= 2,
"idle eviction broke the peer cap")) {
return false;
}
return true;
}
bool testRateLimiterConcurrency()
{
using namespace std::chrono_literals;
ShortLinkRateLimiter limiter({
.globalRate = 0.0,
.globalBurst = 100.0,
.peerRate = 0.0,
.peerBurst = 5.0,
.maxPeers = 16,
.idleTimeout = 1min,
.sweepInterval = 1min,
});
const auto now = ShortLinkRateLimiter::TimePoint{} + 1s;
std::atomic<unsigned int> allowed{0};
std::vector<std::thread> workers;
workers.reserve(32);
for (int index = 0; index < 32; ++index) {
workers.emplace_back([&] {
if (limiter.allow("one-peer", now)) {
++allowed;
}
});
}
for (auto& worker : workers) {
worker.join();
}
if (!expect(allowed.load() == 5,
"concurrent limiter admitted beyond the peer burst")) {
return false;
}
ShortLinkRateLimiter global({
.globalRate = 0.0,
.globalBurst = 7.0,
.peerRate = 0.0,
.peerBurst = 1.0,
.maxPeers = 64,
.idleTimeout = 1min,
.sweepInterval = 1min,
});
allowed = 0;
workers.clear();
for (int index = 0; index < 32; ++index) {
workers.emplace_back([&, index] {
if (global.allow("peer-" + std::to_string(index), now)) {
++allowed;
}
});
}
for (auto& worker : workers) {
worker.join();
}
return expect(allowed.load() == 7,
"concurrent limiter admitted beyond the global burst");
}
} // namespace
int main()
{
return testShortSlugs() && testCidrsAndForwarding() &&
testRedirectLocations() &&
testTrustedProxyRuntimeUpdates() &&
testRateLimiterFairnessAndBounds() &&
testRateLimiterConcurrency()
? 0
: 1;
}