GCoordinator/src/client/ts/state.ts

175 lines
4.9 KiB
TypeScript

import type {
ConfigError,
ConfigWarning,
DiskSample,
MetricSample,
ProbeSample,
ServerRuntimeState,
VaultState,
} from '../../shared/ws-protocol.js';
export type RouteId =
| 'dashboard'
| 'server-detail'
| 'systems'
| 'terminal'
| 'sftp'
| 'workflows'
| 'alerts'
| 'config'
| 'vault'
| 'settings';
export interface OverviewFileEntry {
filePath: string;
entityType: string;
id?: string;
hasError: boolean;
warningCount: number;
}
export interface ConfigOverview {
files: OverviewFileEntry[];
diagnostics: { warnings: ConfigWarning[]; errors: ConfigError[] };
servers: Array<Record<string, unknown>>;
systems: Array<Record<string, unknown>>;
workflows: Array<Record<string, unknown>>;
snippets: { snippets?: Array<Record<string, unknown>> };
alerts: {
channels?: Array<Record<string, unknown>>;
rules?: Array<Record<string, unknown>>;
maintenanceWindows?: Array<Record<string, unknown>>;
};
settings: Record<string, unknown>;
}
export interface ServerEntry {
config: {
id: string;
name: string;
host: string;
port: number;
username: string;
credentialId: string;
jumpHostId?: string;
sudoCredentialId?: string;
tags: string[];
osHint: 'auto' | 'linux' | 'bsd' | 'macos';
pollIntervalSec: number;
probes: Array<Record<string, unknown>>;
enabled: boolean;
};
runtime: ServerRuntimeState;
telemetry: {
serverId: string;
os?: 'linux' | 'bsd' | 'macos';
sample?: MetricSample;
disks: DiskSample[];
probes: Record<string, ProbeSample>;
lastError?: string;
} | null;
}
export interface ClientSecuritySettings {
requireTotpOnLogin: boolean;
passwordMode: 'any' | 'all';
totpMode: 'any' | 'all';
stepUpPolicy: 'off' | 'every-action' | '5m' | '1h' | '24h' | 'session';
stepUpMethod: 'totp' | 'password' | 'both' | 'passkey';
elevateOnLogin: boolean;
keepElevationOnSafeMode: boolean;
enableEmergencySecretsBackup: boolean;
}
export interface ClientAuthRequirements {
requireTotpOnLogin: boolean;
passwordMode: 'any' | 'all';
passwordCount: number;
passwordLabels: Array<{ id: string; label: string }>;
totpMode: 'any' | 'all';
totpCount: number;
totpLabels: Array<{ id: string; label: string }>;
passkeyCount: number;
stepUpPolicy: ClientSecuritySettings['stepUpPolicy'];
stepUpMethod: ClientSecuritySettings['stepUpMethod'];
}
export interface ClientState {
bootstrapped: boolean;
authenticated: boolean;
vaultState: VaultState;
isPanicLocked: boolean;
safeMode: boolean;
defaultMobileSafeMode: boolean;
elevatedUntil: number | null;
theme: string;
route: RouteId;
selectedServerId?: string;
routeSegments?: string[];
routeQuery?: Record<string, string>;
overview: ConfigOverview | null;
security?: ClientSecuritySettings;
authRequirements?: ClientAuthRequirements;
}
export const SAFE_MODE_STORAGE_KEY = 'gcoord_device_safe_mode';
export const THEME_STORAGE_KEY = 'gcoord_theme';
export function initialDeviceSafeMode(defaultMobileSafeMode: boolean): boolean {
const stored = localStorage.getItem(SAFE_MODE_STORAGE_KEY);
if (stored === '1') return true;
if (stored === '0') return false;
return defaultMobileSafeMode && window.innerWidth < 768;
}
export function applyTheme(theme: string): void {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem(THEME_STORAGE_KEY, theme);
}
export function el<K extends keyof HTMLElementTagNameMap>(
tag: K,
attrs: Record<string, string | boolean | number | undefined> = {},
...children: Array<Node | string>
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v === undefined || v === false) continue;
if (v === true) {
node.setAttribute(k, '');
} else {
node.setAttribute(k, String(v));
}
}
for (const child of children) {
node.append(typeof child === 'string' ? document.createTextNode(child) : child);
}
return node;
}
export function fmtTime(ts: number | string | null | undefined): string {
if (!ts) return '—';
const d = new Date(ts);
return Number.isNaN(d.getTime()) ? '—' : d.toISOString().replace('T', ' ').slice(0, 19);
}
export function fmtBytesPerSec(bps: number): string {
if (!Number.isFinite(bps) || bps <= 0) return '0 B/s';
if (bps < 1024) return `${Math.round(bps)} B/s`;
if (bps < 1024 * 1024) return `${(bps / 1024).toFixed(1)} KB/s`;
return `${(bps / (1024 * 1024)).toFixed(2)} MB/s`;
}
export function fmtUptime(sec: number): string {
if (!Number.isFinite(sec) || sec <= 0) return '0m';
const d = Math.floor(sec / 86400);
const h = Math.floor((sec % 86400) / 3600);
const m = Math.floor((sec % 3600) / 60);
if (d > 0) return `${d}d ${h}h`;
if (h > 0) return `${h}h ${m}m`;
return `${m}m`;
}
export function extractErrorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}