diff --git a/packages/plugin/src/config.ts b/packages/plugin/src/config.ts new file mode 100644 index 0000000..20c1d2f --- /dev/null +++ b/packages/plugin/src/config.ts @@ -0,0 +1,422 @@ +import { hostname } from 'node:os' +import type { Volatile, VolatileSnapshot } from '@deepseek-ai/cordis' +import s from '@deepseek-ai/schemastery' +import { z } from 'zod' + +export const DEFAULT_REMOTE_SERVER_URL = 'https://dsh.r2049.cn' + +export interface Config { + enabled?: boolean + role?: 'host' | 'client' | 'both' + serverUrl?: string + /** Additional hosts or CIDR ranges that may use HTTP for a self-hosted Server. */ + httpServerAllowlist?: string[] + deviceName?: string + terminal?: { enabled?: boolean } + remoteTools?: { enabled?: boolean } + /** Where the Desktop client shows the Remote entry: beside Settings or in the account row. */ + sidebar?: { entry?: 'standard' | 'compact' } + hostControl?: { enabled?: boolean } + loopback?: { ports?: number[] } + forceRelay?: boolean + /** + * When a known peer device presents a NEW identity key after re-authorizing with the + * same account membership (e.g. the peer reinstalled the Harness), rotate the pinned + * key instead of rejecting the connection. The new key is validated against the + * account directory before this policy applies. Default: false (pin strictly). + */ + rotatePinnedPeerKey?: boolean + logLevel?: 'debug' | 'info' | 'warn' | 'error' + /** + * Send remote clients only what they need: the initial history page keeps the latest + * few messages and oversized plugin projections are dropped. Cuts the first-paint + * payload from megabytes to kilobytes on large sessions. Default: false. + */ + liteMode?: boolean + reconnect?: boolean | { + initialDelayMs?: number + maxDelayMs?: number + jitter?: number + } + /** Optional Codex domain carried by the existing authenticated Remote Plugin. */ + codex?: { + enabled?: boolean + binary?: string + } + /** Optional Cursor ACP domain carried by the existing authenticated Remote Plugin. */ + cursor?: { + enabled?: boolean + binary?: string + } + acp?: { enabled?: boolean; backends?: Array<{ id:string; enabled?: boolean; command?: string; args?: string[]; cwd?: string }>; backend?: string; command?: string; args?: string[]; cwd?: string } +} + +export interface ResolvedCodexConfig { + enabled: boolean + binary: string +} + +export interface ResolvedCursorConfig { + enabled: boolean + binary: string +} + +export interface ResolvedAcpBackendConfig { + id: string + enabled: boolean + command: string + args: string[] + cwd?: string +} + +export interface ResolvedAcpConfig { + enabled: boolean + backends: ResolvedAcpBackendConfig[] +} + +export interface ResolvedConfig { + enabled: boolean + role: 'host' | 'client' | 'both' + serverUrl?: string + httpServerAllowlist: string[] + deviceName: string + forceRelay: boolean + rotatePinnedPeerKey: boolean + logLevel: 'debug' | 'info' | 'warn' | 'error' + liteMode: boolean + reconnect: { + enabled: boolean + initialDelayMs: number + maxDelayMs: number + jitter: number + } + terminal: { enabled: boolean } + remoteTools?: { enabled: boolean } + sidebar: { entry: 'standard' | 'compact' } + hostControl?: { enabled: boolean } + loopback: { ports: number[] } + codex: ResolvedCodexConfig + cursor: ResolvedCursorConfig + acp?: ResolvedAcpConfig +} + +/** The entry's volatile Cordis config: one stable reference for the whole section. */ +export type EntryConfig = Volatile + +/** Config accepted by {@link resolveConfig}: the composition seed or a live snapshot. */ +export type ConfigInput = Config | VolatileSnapshot + +/** + * Schemastery schema for the plugin entry. On DSH 0.1.7-rc.1 and newer the + * whole section is `.volatile()` (DSH-0.1.7-RC1-04): the Loader hands `apply` + * a single live reference whose `.get()` always returns the latest committed + * value, and the settings service persists edits in the active profile's + * `cordis.patch.yml` under this entry id. On older hosts the helper above keeps + * the plain schema required by the namespace-registration API. + */ +export const entryConfigSchema = s.object({ + enabled: s.boolean(), + role: s.union(['host', 'client', 'both'] as const), + serverUrl: s.string(), + httpServerAllowlist: s.array(s.string()), + deviceName: s.string(), + terminal: s.object({ enabled: s.boolean() }), + remoteTools: s.object({ enabled: s.boolean() }), + sidebar: s.object({ entry: s.union(['standard', 'compact'] as const) }), + hostControl: s.object({ enabled: s.boolean() }), + loopback: s.object({ ports: s.array(s.number()) }), + forceRelay: s.boolean(), + rotatePinnedPeerKey: s.boolean(), + logLevel: s.union(['debug', 'info', 'warn', 'error'] as const), + liteMode: s.boolean().default(true), + reconnect: s.union([ + s.boolean(), + s.object({ + initialDelayMs: s.number(), + maxDelayMs: s.number(), + jitter: s.number(), + }), + ]), + codex: s.object({ + enabled: s.boolean(), + binary: s.string(), + }), + cursor: s.object({ + enabled: s.boolean(), + binary: s.string(), + }), + acp: s.object({ enabled: s.boolean(), backends: s.array(s.object({ id:s.string(), enabled:s.boolean(), command:s.string(), args:s.array(s.string()), cwd:s.string() })) }), +}) + +/** + * Mark the entry as live-editable when the host Schemastery supports the + * 0.1.7 volatile schema mode. Older DSH releases ship an earlier Schemastery + * where the method does not exist; their settings registry expects the plain + * schema and must still be able to import the plugin without throwing. + */ +export function withVolatileSchema(schema: T): T { + const volatile = (schema as { volatile?: unknown }).volatile + return typeof volatile === 'function' + ? (volatile as (this: T) => T).call(schema) + : schema +} + +export const Config: s = withVolatileSchema(entryConfigSchema) as unknown as s + +const reconnectSchema = z.union([ + z.boolean(), + z.object({ + initialDelayMs: z.number().int().min(100).max(60_000).optional(), + maxDelayMs: z.number().int().min(1_000).max(300_000).optional(), + jitter: z.number().min(0).max(1).optional(), + }).strict(), +]) + +const configSchema = z.object({ + enabled: z.boolean().optional(), + role: z.enum(['host', 'client', 'both']).optional(), + serverUrl: z.string().url().optional(), + httpServerAllowlist: z.array(z.string().trim().min(1).max(128)).max(64).optional(), + deviceName: z.string().trim().min(1).max(80).optional(), + terminal: z.object({ enabled: z.boolean().optional() }).strict().optional(), + remoteTools: z.object({ enabled: z.boolean().optional() }).strict().optional(), + sidebar: z.object({ entry: z.enum(['standard', 'compact']).optional() }).strict().optional(), + hostControl: z.object({ enabled: z.boolean().optional() }).strict().optional(), + loopback: z.object({ ports: z.array(z.number().int().min(1024).max(65535)).max(16).optional() }).strict().optional(), + forceRelay: z.boolean().optional(), + rotatePinnedPeerKey: z.boolean().optional(), + logLevel: z.enum(['debug', 'info', 'warn', 'error']).optional(), + liteMode: z.boolean().optional(), + reconnect: reconnectSchema.optional(), + codex: z.object({ + enabled: z.boolean().optional(), + binary: z.string().trim().min(1).max(4096).optional(), + }).strict().optional(), + cursor: z.object({ + enabled: z.boolean().optional(), + binary: z.string().trim().min(1).max(4096).optional(), + }).strict().optional(), + acp: z.object({ enabled:z.boolean().optional(), backends:z.array(z.object({ id:z.string().trim().regex(/^[a-z0-9][a-z0-9._-]{0,31}$/i), enabled:z.boolean().optional(), command:z.string().trim().min(1).max(4096).optional(), args:z.array(z.string().max(4096)).max(32).optional(), cwd:z.string().max(4096).optional() }).strict()).max(12).optional(), backend:z.string().trim().regex(/^[a-z0-9][a-z0-9._-]{0,31}$/i).optional(), command:z.string().trim().min(1).max(4096).optional(), args:z.array(z.string().max(4096)).max(32).optional(), cwd:z.string().max(4096).optional() }).strict().optional(), +}).strict() + +export function resolveConfig(input: ConfigInput = {}, env: NodeJS.ProcessEnv = process.env): ResolvedConfig { + const parsed = configSchema.parse(input) + const configuredCursorBackend = parsed.acp?.backends?.find(item => item.id === 'cursor') + const legacyCursorEnabled = parsed.acp?.backend === 'cursor' ? parsed.acp.enabled : undefined + const cursorEnabled = configuredCursorBackend?.enabled + ?? parsed.cursor?.enabled + ?? legacyCursorEnabled + ?? false + const codexBackend = parsed.acp?.backends?.find(item => item.id === 'codex') + const codexEnabled = codexBackend?.enabled ?? parsed.codex?.enabled ?? true + const acpEnabled = parsed.acp?.enabled ?? true + const reconnect = typeof parsed.reconnect === 'object' ? parsed.reconnect : {} + const configuredServerUrl = parsed.serverUrl ?? env.DSH_REMOTE_SERVER + const httpServerAllowlist = normalizeHttpServerAllowlist( + parsed.httpServerAllowlist ?? parseHttpServerAllowlistEnv(env.DSH_REMOTE_HTTP_SERVER_ALLOWLIST), + ) + const serverUrl = configuredServerUrl === undefined ? undefined : normalizeServerUrl(configuredServerUrl, httpServerAllowlist) + const initialDelayMs = reconnect.initialDelayMs ?? 4_000 + const maxDelayMs = reconnect.maxDelayMs ?? 30_000 + if (maxDelayMs < initialDelayMs) { + throw new TypeError('reconnect.maxDelayMs must be greater than or equal to reconnect.initialDelayMs') + } + return { + enabled: parsed.enabled ?? true, + role: parsed.role ?? 'host', + ...(serverUrl === undefined ? {} : { serverUrl }), + httpServerAllowlist, + deviceName: parsed.deviceName ?? env.DSH_REMOTE_DEVICE_NAME ?? hostname(), + hostControl: { enabled: parsed.hostControl?.enabled ?? true }, + terminal: { enabled: parsed.terminal?.enabled ?? (env.DSH_REMOTE_TERMINAL_ENABLED === undefined || env.DSH_REMOTE_TERMINAL_ENABLED === 'true') }, + remoteTools: { enabled: parsed.remoteTools?.enabled ?? true }, + sidebar: { entry: parsed.sidebar?.entry === 'compact' ? 'compact' : 'standard' }, + loopback: { ports: [...new Set(parsed.loopback?.ports ?? [])] }, + forceRelay: parsed.forceRelay ?? false, + rotatePinnedPeerKey: parsed.rotatePinnedPeerKey ?? false, + logLevel: parsed.logLevel ?? 'info', + liteMode: parsed.liteMode !== false, + reconnect: { + enabled: parsed.reconnect !== false, + initialDelayMs, + maxDelayMs, + jitter: reconnect.jitter ?? 0.2, + }, + codex: { + enabled: acpEnabled && codexEnabled, + binary: codexBackend?.command ?? parsed.codex?.binary ?? 'codex', + }, + cursor: { + enabled: cursorEnabled, + binary: configuredCursorBackend?.command ?? parsed.cursor?.binary ?? env.DSH_REMOTE_CURSOR_BINARY ?? env.DSH_REMOTE_ACP_BINARY ?? 'agent', + }, + acp: { + enabled: acpEnabled, + backends: [...new Set(['codex', 'cursor', 'antigravity', 'pi', 'claude', 'opencode', 'hermes', ...(parsed.acp?.backends?.filter(item => item.id !== 'kimi').map(item => item.id) ?? [])])].map(id => { + const configured = parsed.acp?.backends?.find(item => item.id === id) + const legacy = parsed.acp?.backend === id ? parsed.acp : undefined + const defaults: Record = { codex: 'codex', cursor: 'agent', antigravity: 'agy', pi: 'pi-acp', claude: 'claude-agent-acp', opencode: 'opencode', hermes: 'hermes' } + const cursorCommand = id === 'codex' ? parsed.codex?.binary : id === 'cursor' + ? parsed.cursor?.binary ?? env.DSH_REMOTE_CURSOR_BINARY ?? env.DSH_REMOTE_ACP_BINARY + : undefined + const cwd = configured?.cwd ?? legacy?.cwd + return { + id, + enabled: configured?.enabled ?? legacy?.enabled + // Hermes opts in explicitly: a Host without it installed must not spawn it by default. + ?? (id === 'codex' ? codexEnabled : id === 'cursor' ? cursorEnabled : id === 'pi' ? true : id === 'claude' ? true + : id === 'opencode' ? true : id === 'hermes' ? false : parsed.acp !== undefined), + command: configured?.command ?? legacy?.command ?? cursorCommand ?? defaults[id] ?? id, + args: id === 'codex' ? ['app-server'] : configured?.args ?? legacy?.args + ?? (id === 'pi' || id === 'claude' ? [] : id === 'hermes' ? ['acp'] + : id === 'antigravity' ? ['--input-format', 'stream-json', '--output-format', 'stream-json'] : ['acp']), + ...(cwd === undefined ? {} : { cwd }), + } + }), + }, + } +} + +const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']) + +function isPrivateIpv6(hostname: string): boolean { + const host = (hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname).toLowerCase() + if (!host.includes(':') || !/^[0-9a-f:]+$/.test(host)) return false + if (host === '::1') return true + return /^f[cd][0-9a-f]{2}:/.test(host) || /^fe[89ab][0-9a-f]:/.test(host) +} + +/** IPv4/IPv6 hosts that are only reachable on loopback, a LAN, link-local, or CGNAT/VPN networks. */ +function isPrivateNetworkHostname(hostname: string): boolean { + if (LOCAL_HOSTS.has(hostname)) return true + if (isPrivateIpv6(hostname)) return true + const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname) + if (match === null) return false + const octets = match.slice(1).map(Number) + if (octets.some(value => value > 255)) return false + const [a, b] = octets + return ( + a === 10 || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) || + (a === 169 && b === 254) || + (a === 100 && b >= 64 && b <= 127) + ) +} + +export function normalizeServerUrl(value: string, httpServerAllowlist: readonly string[] = []): string { + const url = new URL(value) + const privateHttp = url.protocol === 'http:' + && (isPrivateNetworkHostname(url.hostname) || matchesHttpServerAllowlist(url.hostname, httpServerAllowlist)) + if (url.protocol !== 'https:' && !privateHttp) { + throw new TypeError('serverUrl must use HTTPS (HTTP is allowed only for localhost or private-network addresses)') + } + if (url.username !== '' || url.password !== '') { + throw new TypeError('serverUrl must not contain credentials') + } + if (url.search !== '' || url.hash !== '') { + throw new TypeError('serverUrl must not contain query parameters or fragments') + } + if (url.pathname !== '' && url.pathname !== '/') { + throw new TypeError('serverUrl must be an origin without a path') + } + return url.origin +} + +interface ParsedIpAddress { + version: 4 | 6 + value: bigint +} + +function parseHttpServerAllowlistEnv(value: string | undefined): string[] | undefined { + if (value === undefined) return undefined + return value.split(',').map(item => item.trim()).filter(item => item !== '') +} + +function normalizeHttpServerAllowlist(values: readonly string[] | undefined): string[] { + if (values === undefined) return [] + const normalized = [...new Set(values.map(value => value.trim()).filter(value => value !== ''))] + for (const value of normalized) { + if (!isValidHttpServerAllowlistEntry(value)) { + throw new TypeError(`httpServerAllowlist contains an invalid host or CIDR: ${value}`) + } + } + return normalized +} + +function isValidHttpServerAllowlistEntry(value: string): boolean { + const slash = value.indexOf('/') + if (slash === -1) return parseIpAddress(value) !== undefined || isAllowlistedHostname(value) + if (slash !== value.lastIndexOf('/')) return false + const address = parseIpAddress(value.slice(0, slash)) + const prefix = Number(value.slice(slash + 1)) + return address !== undefined && Number.isInteger(prefix) && prefix >= 0 && prefix <= (address.version === 4 ? 32 : 128) +} + +function isAllowlistedHostname(value: string): boolean { + return value.length <= 253 + && !value.startsWith('.') + && !value.endsWith('.') + && /^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/.test(value) +} + +function matchesHttpServerAllowlist(hostname: string, allowlist: readonly string[]): boolean { + const host = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname + const address = parseIpAddress(host) + const normalizedHost = host.toLowerCase() + return allowlist.some(entry => { + const slash = entry.indexOf('/') + if (slash === -1) { + const exact = parseIpAddress(entry) + return exact === undefined ? entry.toLowerCase() === normalizedHost : address !== undefined && exact.version === address.version && exact.value === address.value + } + if (address === undefined) return false + const network = parseIpAddress(entry.slice(0, slash)) + const prefix = Number(entry.slice(slash + 1)) + if (network === undefined || network.version !== address.version) return false + const bits = network.version === 4 ? 32n : 128n + const mask = prefix === 0 ? 0n : ((1n << BigInt(prefix)) - 1n) << (bits - BigInt(prefix)) + return (network.value & mask) === (address.value & mask) + }) +} + +function parseIpAddress(value: string): ParsedIpAddress | undefined { + const normalized = value.startsWith('[') && value.endsWith(']') ? value.slice(1, -1) : value + return parseIpv4(normalized) ?? parseIpv6(normalized) +} + +function parseIpv4(value: string): ParsedIpAddress | undefined { + const parts = value.split('.') + if (parts.length !== 4 || parts.some(part => !/^\d{1,3}$/.test(part))) return undefined + const octets = parts.map(Number) + if (octets.some(octet => octet > 255)) return undefined + return { version: 4, value: octets.reduce((result, octet) => (result << 8n) | BigInt(octet), 0n) } +} + +function parseIpv6(value: string): ParsedIpAddress | undefined { + const normalized = value.toLowerCase() + if (!normalized.includes(':') || normalized.includes('%')) return undefined + const sections = normalized.split('::') + if (sections.length > 2) return undefined + const expand = (section: string): number[] | undefined => { + if (section === '') return [] + const parts = section.split(':') + const result: number[] = [] + for (const part of parts) { + if (part.includes('.')) { + const ipv4 = parseIpv4(part) + if (ipv4 === undefined) return undefined + result.push(Number((ipv4.value >> 16n) & 0xffffn), Number(ipv4.value & 0xffffn)) + } else if (/^[0-9a-f]{1,4}$/.test(part)) { + result.push(Number.parseInt(part, 16)) + } else return undefined + } + return result + } + const left = expand(sections[0]!) + const right = expand(sections.length === 2 ? sections[1]! : '') + if (left === undefined || right === undefined) return undefined + const hextets = sections.length === 2 ? [...left, ...Array(8 - left.length - right.length).fill(0), ...right] : left + if (hextets.length !== 8) return undefined + return { version: 6, value: hextets.reduce((result, hextet) => (result << 16n) | BigInt(hextet), 0n) } +}