feat(agent): inject S0 env into launchd/systemd via install CLI (S2)
- launchd writer emits <EnvironmentVariables>; systemd writer emits EnvironmentFile/Environment; originConfig zone parameterized (default 'term' preserved for relay callers). - InstallOptions threaded CLI install -> createCliDeps -> installService seam -> writers, so generated units carry BIND_HOST (defaults 127.0.0.1 for tunnel hosts), ALLOWED_ORIGINS, PORT, SHELL_PATH, IDLE_TTL, USE_TMUX. systemd rejects control chars in env values. Verified: agent typecheck+build clean; vitest 166/166 (154 baseline + 12 new).
This commit is contained in:
@@ -6,6 +6,7 @@
|
||||
import type { AgentConfig } from './config/agentConfig.js'
|
||||
import type { AgentIdentity } from './keys/identity.js'
|
||||
import type { Keystore } from './keys/keystore.js'
|
||||
import type { InstallOptions } from './service/install.js'
|
||||
import type { EnrollResult } from 'relay-contracts'
|
||||
|
||||
export type CliCommand = 'pair' | 'run' | 'status' | 'install' | 'uninstall'
|
||||
@@ -30,7 +31,9 @@ export interface CliDeps {
|
||||
generateIdentity(): AgentIdentity
|
||||
redeem(cfg: AgentConfig, code: string, id: AgentIdentity, ks: Keystore): Promise<EnrollResult>
|
||||
runTunnel(cfg: AgentConfig, ks: Keystore): Promise<number>
|
||||
installService(cfg: AgentConfig): Promise<void>
|
||||
/** Resolve per-host install inputs (S0 env incl. loopback BIND_HOST, tunnel origin) from env/flags. */
|
||||
resolveInstallOptions(): InstallOptions
|
||||
installService(cfg: AgentConfig, options: InstallOptions): Promise<void>
|
||||
uninstallService(): Promise<void>
|
||||
print(line: string): void
|
||||
}
|
||||
@@ -70,7 +73,7 @@ export async function runCli(args: CliArgs, deps: CliDeps): Promise<number> {
|
||||
ks.saveIdentity(id)
|
||||
const enroll = await deps.redeem(cfg, args.code!, id, ks)
|
||||
deps.print(`paired: host ${enroll.hostId} subdomain ${enroll.subdomain}`)
|
||||
if (args.flags['install']) await deps.installService(cfg)
|
||||
if (args.flags['install']) await deps.installService(cfg, deps.resolveInstallOptions())
|
||||
return 0
|
||||
}
|
||||
case 'run': {
|
||||
@@ -88,7 +91,7 @@ export async function runCli(args: CliArgs, deps: CliDeps): Promise<number> {
|
||||
return 0
|
||||
}
|
||||
case 'install':
|
||||
await deps.installService(cfg)
|
||||
await deps.installService(cfg, deps.resolveInstallOptions())
|
||||
return 0
|
||||
case 'uninstall':
|
||||
await deps.uninstallService()
|
||||
|
||||
@@ -17,6 +17,7 @@ import { generateIdentity } from '../keys/identity.js'
|
||||
import { redeemPairingCode } from '../enroll/pair.js'
|
||||
import { runTunnel } from '../transport/runTunnel.js'
|
||||
import {
|
||||
buildInstallOptions,
|
||||
detectPlatform,
|
||||
installService as installServiceUnit,
|
||||
uninstallService as uninstallServiceUnit,
|
||||
@@ -74,7 +75,9 @@ export function createCliDeps(): CliDeps {
|
||||
process.once('SIGINT', onSignal)
|
||||
return handle.done
|
||||
},
|
||||
installService: (cfg) => installServiceUnit(cfg, requirePlatform(), realInstallDeps()),
|
||||
resolveInstallOptions: () => buildInstallOptions(process.env),
|
||||
installService: (cfg, options) =>
|
||||
installServiceUnit(cfg, requirePlatform(), realInstallDeps(), options),
|
||||
uninstallService: () => uninstallServiceUnit(requirePlatform(), { runCommand, homedir }),
|
||||
print: (line) => {
|
||||
process.stdout.write(`${line}\n`)
|
||||
|
||||
@@ -9,16 +9,69 @@ import {
|
||||
launchdLoadCommand,
|
||||
launchdPlistPath,
|
||||
launchdUnloadCommand,
|
||||
type ServiceEnv,
|
||||
} from './launchd.js'
|
||||
import {
|
||||
buildSystemdUnit,
|
||||
systemdDisableCommand,
|
||||
systemdEnableCommand,
|
||||
systemdUnitPath,
|
||||
type SystemdUnitOptions,
|
||||
} from './systemd.js'
|
||||
import { DEFAULT_ORIGIN_ZONE, mergeOrigins, subdomainOrigin } from './originConfig.js'
|
||||
|
||||
export type ServicePlatform = 'launchd' | 'systemd'
|
||||
|
||||
/**
|
||||
* Per-host packaging inputs threaded to the unit writers (PLAN_NATIVE_TUNNEL S2). All optional so
|
||||
* existing callers (and relay callers) are unaffected — an empty object writes the historical unit.
|
||||
*/
|
||||
export interface InstallOptions {
|
||||
/** S0 env injected into the supervised process (BIND_HOST, ALLOWED_ORIGINS, PORT, …). */
|
||||
readonly env?: ServiceEnv
|
||||
/** systemd `EnvironmentFile=` path (preferred over inline for values best kept off the unit). */
|
||||
readonly envFile?: string
|
||||
/** DNS zone label for the tunnel origin (`terminal` for native-tunnel hosts, default `term`). */
|
||||
readonly zone?: string
|
||||
/** Parent domain (e.g. `yaojia.wang`); with `cfg.subdomain` derives the tunnel ALLOWED_ORIGINS. */
|
||||
readonly domain?: string
|
||||
}
|
||||
|
||||
/** S0 base-app env vars the install CLI bakes into the per-host unit, passed through verbatim. */
|
||||
const BASE_APP_ENV_KEYS = ['ALLOWED_ORIGINS', 'PORT', 'SHELL_PATH', 'IDLE_TTL', 'USE_TMUX'] as const
|
||||
|
||||
/**
|
||||
* Tunnel hosts MUST bind loopback. At the relay the device-cert mTLS is the ONLY auth gate, so a
|
||||
* default `0.0.0.0` bind (`src/config.ts`) would serve an unauth'd shell on the LAN, bypassing mTLS
|
||||
* entirely (PLAN_NATIVE_TUNNEL S0/R2). `buildInstallOptions` therefore defaults `BIND_HOST` here.
|
||||
*/
|
||||
export const TUNNEL_DEFAULT_BIND_HOST = '127.0.0.1'
|
||||
|
||||
/** Native-tunnel origin zone → `https://<subdomain>.terminal.<domain>`; overridable via TUNNEL_ZONE. */
|
||||
export const TUNNEL_ORIGIN_ZONE = 'terminal'
|
||||
|
||||
/**
|
||||
* Resolve the per-host `InstallOptions` from the process environment (PLAN_NATIVE_TUNNEL S0/S2).
|
||||
* Sources the S0 base-app env — defaulting `BIND_HOST` to loopback so a tunnel install can never
|
||||
* emit a LAN-exposed unit — plus the tunnel-origin `domain`/`zone` used to derive ALLOWED_ORIGINS.
|
||||
* Pure/immutable: `env` is a parameter, so this is unit-testable without touching real process state.
|
||||
*/
|
||||
export function buildInstallOptions(env: NodeJS.ProcessEnv): InstallOptions {
|
||||
const passthrough = Object.fromEntries(
|
||||
BASE_APP_ENV_KEYS.map((key) => [key, env[key]] as [string, string | undefined]).filter(
|
||||
(entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1].length > 0,
|
||||
),
|
||||
)
|
||||
const serviceEnv: ServiceEnv = { BIND_HOST: env.BIND_HOST || TUNNEL_DEFAULT_BIND_HOST, ...passthrough }
|
||||
const domain = env.TUNNEL_DOMAIN
|
||||
const envFile = env.AGENT_ENV_FILE
|
||||
return {
|
||||
env: serviceEnv,
|
||||
...(domain ? { domain, zone: env.TUNNEL_ZONE || TUNNEL_ORIGIN_ZONE } : {}),
|
||||
...(envFile ? { envFile } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export class RootRefusedError extends Error {
|
||||
constructor() {
|
||||
super('refusing to install the agent service as root — run as the logged-in user (least privilege)')
|
||||
@@ -42,23 +95,40 @@ export function detectPlatform(os: NodeJS.Platform): ServicePlatform | null {
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the env map injected into the unit. When a `domain` (+ `cfg.subdomain`) is supplied, the
|
||||
* tunnel origin `https://<subdomain>.<zone>.<domain>` is merged into ALLOWED_ORIGINS so the base app
|
||||
* trusts its own tunnel host — never weakening any origin the caller already provided. Immutable.
|
||||
*/
|
||||
function resolveEnv(cfg: AgentConfig, options: InstallOptions): ServiceEnv {
|
||||
const base = options.env ?? {}
|
||||
if (!options.domain || !cfg.subdomain) return base
|
||||
const origin = subdomainOrigin(cfg.subdomain, options.domain, options.zone ?? DEFAULT_ORIGIN_ZONE)
|
||||
return { ...base, ALLOWED_ORIGINS: mergeOrigins(base.ALLOWED_ORIGINS, origin) }
|
||||
}
|
||||
|
||||
/** Write + load the service unit for `platform`. Throws RootRefusedError if running as root. */
|
||||
export async function installService(
|
||||
_cfg: AgentConfig,
|
||||
cfg: AgentConfig,
|
||||
platform: ServicePlatform,
|
||||
deps: InstallDeps,
|
||||
options: InstallOptions = {},
|
||||
): Promise<void> {
|
||||
if (deps.getuid() === 0) throw new RootRefusedError()
|
||||
const bin = deps.binPath()
|
||||
const env = resolveEnv(cfg, options)
|
||||
if (platform === 'launchd') {
|
||||
const path = launchdPlistPath(deps.homedir())
|
||||
deps.writeFile(path, buildLaunchdPlist(bin))
|
||||
deps.writeFile(path, buildLaunchdPlist(bin, env))
|
||||
const { cmd, args } = launchdLoadCommand(path)
|
||||
await deps.runCommand(cmd, args)
|
||||
return
|
||||
}
|
||||
const path = systemdUnitPath(deps.homedir())
|
||||
deps.writeFile(path, buildSystemdUnit(bin, deps.username()))
|
||||
const systemdOptions: SystemdUnitOptions = options.envFile
|
||||
? { env, envFile: options.envFile }
|
||||
: { env }
|
||||
deps.writeFile(path, buildSystemdUnit(bin, deps.username(), systemdOptions))
|
||||
const { cmd, args } = systemdEnableCommand()
|
||||
await deps.runCommand(cmd, args)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
/**
|
||||
* macOS launchd plist writer — PLAN_RELAY_AGENT T17. The service runs as the LOGGED-IN USER, not
|
||||
* root (EXPLORE §4d least privilege); no secrets in the plist (key/cert stay in the keystore).
|
||||
*
|
||||
* PLAN_NATIVE_TUNNEL S2: the plist can now inject a caller-supplied per-host env map
|
||||
* (BIND_HOST, ALLOWED_ORIGINS, PORT, SHELL_PATH, IDLE_TTL, USE_TMUX, …) as a launchd
|
||||
* `<key>EnvironmentVariables</key><dict>…</dict>` block. Values are XML-escaped and keys are
|
||||
* sorted for deterministic, immutable output.
|
||||
*/
|
||||
|
||||
/** Shared env-map shape for the durable-service writers (launchd + systemd). Immutable. */
|
||||
export type ServiceEnv = Readonly<Record<string, string>>
|
||||
|
||||
const LABEL = 'com.web-terminal.agent'
|
||||
|
||||
export function launchdLabel(): string {
|
||||
@@ -12,24 +21,52 @@ export function launchdPlistPath(homedir: string): string {
|
||||
return `${homedir}/Library/LaunchAgents/${LABEL}.plist`
|
||||
}
|
||||
|
||||
/** Build the plist. ExecStart = `<bin> run`; RunAtLoad + KeepAlive (restart on failure). */
|
||||
export function buildLaunchdPlist(binPath: string): string {
|
||||
/** Escape the five XML-significant characters so env keys/values/paths are plist-safe. */
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
/** Build the `<key>EnvironmentVariables</key><dict>…</dict>` lines (empty array when env is empty). */
|
||||
function environmentVariablesBlock(env: ServiceEnv): readonly string[] {
|
||||
const entries = Object.entries(env).sort(([a], [b]) => a.localeCompare(b))
|
||||
if (entries.length === 0) return []
|
||||
const lines = [' <key>EnvironmentVariables</key>', ' <dict>']
|
||||
for (const [key, value] of entries) {
|
||||
lines.push(` <key>${escapeXml(key)}</key>`)
|
||||
lines.push(` <string>${escapeXml(value)}</string>`)
|
||||
}
|
||||
lines.push(' </dict>')
|
||||
return lines
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the plist. ExecStart = `<bin> run`; RunAtLoad + KeepAlive (restart on failure). When `env`
|
||||
* is non-empty, a launchd `EnvironmentVariables` dict is injected so the supervised process
|
||||
* receives the per-host tunnel config. Pure/immutable — returns a fresh string.
|
||||
*/
|
||||
export function buildLaunchdPlist(binPath: string, env: ServiceEnv = {}): string {
|
||||
return [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
||||
'<plist version="1.0">',
|
||||
'<dict>',
|
||||
' <key>Label</key>',
|
||||
` <string>${LABEL}</string>`,
|
||||
` <string>${escapeXml(LABEL)}</string>`,
|
||||
' <key>ProgramArguments</key>',
|
||||
' <array>',
|
||||
` <string>${binPath}</string>`,
|
||||
` <string>${escapeXml(binPath)}</string>`,
|
||||
' <string>run</string>',
|
||||
' </array>',
|
||||
' <key>RunAtLoad</key>',
|
||||
' <true/>',
|
||||
' <key>KeepAlive</key>',
|
||||
' <true/>',
|
||||
...environmentVariablesBlock(env),
|
||||
'</dict>',
|
||||
'</plist>',
|
||||
'',
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
/**
|
||||
* The ONE base-app touch-point — PLAN_RELAY_AGENT T17 (INDEX §0, EXPLORE §3 "Zero code change").
|
||||
* APPENDS `https://<subdomain>.term.<domain>` to the base app's ALLOWED_ORIGINS env (idempotent),
|
||||
* APPENDS `https://<subdomain>.<zone>.<domain>` to the base app's ALLOWED_ORIGINS env (idempotent),
|
||||
* as CONFIG — NO `src/` code edit. AUGMENTS, never weakens, the Origin/CSWSH check: existing
|
||||
* origins are always preserved (EXPLORE §3 "do not weaken the check").
|
||||
*
|
||||
* PLAN_NATIVE_TUNNEL S2: the DNS zone label is PARAMETERIZED. Relay callers keep the historical
|
||||
* `term` zone (default), while native-tunnel hosts pass `terminal` so the base app trusts
|
||||
* `https://<name>.terminal.<domain>`. The default is preserved so existing callers/tests are
|
||||
* unaffected — the zone is opt-in per call, never hard-flipped.
|
||||
*/
|
||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
|
||||
@@ -18,23 +23,40 @@ const defaultFs: OriginFsDeps = {
|
||||
write: (p, c) => writeFileSync(p, c),
|
||||
}
|
||||
|
||||
/** Compose the subdomain origin the base app must trust. */
|
||||
export function subdomainOrigin(subdomain: string, domain: string): string {
|
||||
return `https://${subdomain}.term.${domain}`
|
||||
}
|
||||
/** Default DNS zone label (relay hosts). Native-tunnel hosts pass `terminal`. */
|
||||
export const DEFAULT_ORIGIN_ZONE = 'term'
|
||||
|
||||
const KEY = 'ALLOWED_ORIGINS'
|
||||
|
||||
/** Compose the subdomain origin the base app must trust: `https://<subdomain>.<zone>.<domain>`. */
|
||||
export function subdomainOrigin(
|
||||
subdomain: string,
|
||||
domain: string,
|
||||
zone: string = DEFAULT_ORIGIN_ZONE,
|
||||
): string {
|
||||
return `https://${subdomain}.${zone}.${domain}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge `origin` into a comma-separated ALLOWED_ORIGINS value, preserving every existing origin and
|
||||
* de-duplicating. Returns the merged CSV; never removes an origin. Pure/immutable.
|
||||
*/
|
||||
export function mergeOrigins(current: string | undefined, origin: string): string {
|
||||
const origins = (current ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0)
|
||||
if (origins.includes(origin)) return origins.join(',')
|
||||
return [...origins, origin].join(',')
|
||||
}
|
||||
|
||||
function upsertOriginLine(content: string, origin: string): string {
|
||||
const lines = content.length === 0 ? [] : content.split('\n')
|
||||
let found = false
|
||||
const next = lines.map((line) => {
|
||||
if (!line.startsWith(`${KEY}=`)) return line
|
||||
found = true
|
||||
const current = line.slice(KEY.length + 1)
|
||||
const origins = current.split(',').map((s) => s.trim()).filter((s) => s.length > 0)
|
||||
if (origins.includes(origin)) return line // idempotent — already trusted
|
||||
return `${KEY}=${[...origins, origin].join(',')}`
|
||||
return `${KEY}=${mergeOrigins(line.slice(KEY.length + 1), origin)}`
|
||||
})
|
||||
if (!found) next.push(`${KEY}=${origin}`)
|
||||
return next.join('\n')
|
||||
@@ -42,15 +64,17 @@ function upsertOriginLine(content: string, origin: string): string {
|
||||
|
||||
/**
|
||||
* Idempotently append the subdomain origin to ALLOWED_ORIGINS in `baseAppEnvPath`. Never removes an
|
||||
* existing origin. Creates the file/line if absent.
|
||||
* existing origin. Creates the file/line if absent. `zone` selects the DNS zone label (default
|
||||
* preserves relay callers).
|
||||
*/
|
||||
export function ensureAllowedOrigin(
|
||||
baseAppEnvPath: string,
|
||||
subdomain: string,
|
||||
domain: string,
|
||||
fs: OriginFsDeps = defaultFs,
|
||||
zone: string = DEFAULT_ORIGIN_ZONE,
|
||||
): void {
|
||||
const origin = subdomainOrigin(subdomain, domain)
|
||||
const origin = subdomainOrigin(subdomain, domain, zone)
|
||||
const existing = fs.exists(baseAppEnvPath) ? fs.read(baseAppEnvPath) : ''
|
||||
const updated = upsertOriginLine(existing, origin)
|
||||
fs.write(baseAppEnvPath, updated.endsWith('\n') ? updated : `${updated}\n`)
|
||||
|
||||
@@ -1,9 +1,27 @@
|
||||
/**
|
||||
* Linux systemd unit writer — PLAN_RELAY_AGENT T17. Runs as the LOGGED-IN USER (never root,
|
||||
* EXPLORE §4d), restart-on-failure; no secrets in the unit (key/cert stay in the keystore).
|
||||
*
|
||||
* PLAN_NATIVE_TUNNEL S2: the unit can now inject the per-host tunnel env via an
|
||||
* `EnvironmentFile=` line (preferred — keeps values out of the world-readable unit) and/or
|
||||
* inline `Environment=` lines from a caller-supplied env map. Inline `Environment=` is emitted
|
||||
* after `EnvironmentFile=` so an explicit value overrides the file on conflict.
|
||||
*/
|
||||
import type { ServiceEnv } from './launchd.js'
|
||||
|
||||
const UNIT_NAME = 'web-terminal-agent.service'
|
||||
|
||||
/** DEL (0x7F) and everything below the printable ASCII range are rejected in env values. */
|
||||
const FIRST_PRINTABLE_ASCII = 0x20
|
||||
const DEL_CODE = 0x7f
|
||||
|
||||
export interface SystemdUnitOptions {
|
||||
/** Inline env map → one `Environment="KEY=value"` line each (keys sorted, values escaped). */
|
||||
readonly env?: ServiceEnv
|
||||
/** Path referenced by a single `EnvironmentFile=` line (preferred over inline for secrets). */
|
||||
readonly envFile?: string
|
||||
}
|
||||
|
||||
export function systemdUnitName(): string {
|
||||
return UNIT_NAME
|
||||
}
|
||||
@@ -12,8 +30,53 @@ export function systemdUnitPath(homedir: string): string {
|
||||
return `${homedir}/.config/systemd/user/${UNIT_NAME}`
|
||||
}
|
||||
|
||||
/** Build the unit. ExecStart = `<bin> run`; Restart=on-failure; User=<user> (never root). */
|
||||
export function buildSystemdUnit(binPath: string, user: string): string {
|
||||
/**
|
||||
* True if `value` contains any control character (C0 range below 0x20, or DEL 0x7F). A raw
|
||||
* newline/CR would terminate the single `Environment=` line and let the remainder inject arbitrary
|
||||
* directives into the `[Service]` section — so such values are rejected rather than escaped.
|
||||
*/
|
||||
function hasControlChar(value: string): boolean {
|
||||
for (const char of value) {
|
||||
const code = char.codePointAt(0)
|
||||
if (code === undefined) continue
|
||||
if (code < FIRST_PRINTABLE_ASCII || code === DEL_CODE) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Quote a systemd `Environment=` value: reject control chars, then double-quote escaping `\` and `"`. */
|
||||
function quoteEnvAssignment(key: string, value: string): string {
|
||||
if (hasControlChar(value)) {
|
||||
throw new Error(
|
||||
`refusing to write systemd Environment for '${key}': value contains a control character ` +
|
||||
'(newline/CR/etc.) that could corrupt the [Service] section',
|
||||
)
|
||||
}
|
||||
const escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
|
||||
return `"${key}=${escaped}"`
|
||||
}
|
||||
|
||||
/** Build the `EnvironmentFile=` / `Environment=` lines (empty array when neither is supplied). */
|
||||
function environmentLines(options: SystemdUnitOptions): readonly string[] {
|
||||
const lines: string[] = []
|
||||
if (options.envFile) lines.push(`EnvironmentFile=${options.envFile}`)
|
||||
const entries = Object.entries(options.env ?? {}).sort(([a], [b]) => a.localeCompare(b))
|
||||
for (const [key, value] of entries) {
|
||||
lines.push(`Environment=${quoteEnvAssignment(key, value)}`)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the unit. ExecStart = `<bin> run`; Restart=on-failure; User=<user> (never root). When
|
||||
* `options.env`/`options.envFile` are supplied, the per-host tunnel env is injected into the
|
||||
* `[Service]` section. Pure/immutable — returns a fresh string.
|
||||
*/
|
||||
export function buildSystemdUnit(
|
||||
binPath: string,
|
||||
user: string,
|
||||
options: SystemdUnitOptions = {},
|
||||
): string {
|
||||
return [
|
||||
'[Unit]',
|
||||
'Description=web-terminal host agent (rendezvous relay)',
|
||||
@@ -25,6 +88,7 @@ export function buildSystemdUnit(binPath: string, user: string): string {
|
||||
'Restart=on-failure',
|
||||
'RestartSec=1',
|
||||
`User=${user}`,
|
||||
...environmentLines(options),
|
||||
'',
|
||||
'[Install]',
|
||||
'WantedBy=default.target',
|
||||
|
||||
@@ -49,6 +49,7 @@ function deps(overrides: Partial<CliDeps> = {}, enrolled = false): { d: CliDeps;
|
||||
hostContentSecret: new Uint8Array([1]),
|
||||
}),
|
||||
runTunnel: async () => 0,
|
||||
resolveInstallOptions: () => ({ env: { BIND_HOST: '127.0.0.1' } }),
|
||||
installService: vi.fn(async () => {}),
|
||||
uninstallService: vi.fn(async () => {}),
|
||||
print: (l) => out.push(l),
|
||||
@@ -88,11 +89,22 @@ describe('runCli (T5)', () => {
|
||||
expect(out.join('\n')).not.toContain('PEM')
|
||||
})
|
||||
|
||||
it('pair --install installs the service', async () => {
|
||||
it('pair --install installs the service with the resolved options', async () => {
|
||||
const options = { env: { BIND_HOST: '127.0.0.1', PORT: '3000' } }
|
||||
const install = vi.fn(async () => {})
|
||||
const { d } = deps({ installService: install })
|
||||
const { d } = deps({ resolveInstallOptions: () => options, installService: install })
|
||||
await runCli(parseArgs(['pair', 'ABCD', '--install']), d)
|
||||
expect(install).toHaveBeenCalledOnce()
|
||||
expect(install).toHaveBeenCalledWith(CFG, options)
|
||||
})
|
||||
|
||||
it('install threads the resolved InstallOptions into installService (S2 env injection)', async () => {
|
||||
const options = { env: { BIND_HOST: '127.0.0.1' }, domain: 'yaojia.wang', zone: 'terminal' }
|
||||
const install = vi.fn(async () => {})
|
||||
const { d } = deps({ resolveInstallOptions: () => options, installService: install })
|
||||
const code = await runCli(parseArgs(['install']), d)
|
||||
expect(code).toBe(0)
|
||||
expect(install).toHaveBeenCalledWith(CFG, options)
|
||||
})
|
||||
|
||||
it('run before pairing fails fast', async () => {
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { AgentConfig } from '../src/config/agentConfig.js'
|
||||
import {
|
||||
RootRefusedError,
|
||||
buildInstallOptions,
|
||||
detectPlatform,
|
||||
installService,
|
||||
uninstallService,
|
||||
type InstallDeps,
|
||||
} from '../src/service/install.js'
|
||||
import { buildLaunchdPlist } from '../src/service/launchd.js'
|
||||
import { buildSystemdUnit } from '../src/service/systemd.js'
|
||||
|
||||
const CFG: AgentConfig = {
|
||||
relayUrl: 'wss://relay/agent',
|
||||
@@ -74,3 +77,193 @@ describe('installService (T17)', () => {
|
||||
expect(d.runs[0]).toEqual(['launchctl', ['unload', '/home/alice/Library/LaunchAgents/com.web-terminal.agent.plist']])
|
||||
})
|
||||
})
|
||||
|
||||
const TUNNEL_ENV = {
|
||||
BIND_HOST: '127.0.0.1',
|
||||
ALLOWED_ORIGINS: 'https://t1.terminal.yaojia.wang',
|
||||
PORT: '3000',
|
||||
} as const
|
||||
|
||||
describe('env injection into the writers (PLAN_NATIVE_TUNNEL S2)', () => {
|
||||
it('launchd: default (no options) omits the EnvironmentVariables block', async () => {
|
||||
const d = deps()
|
||||
await installService(CFG, 'launchd', d)
|
||||
const [, plist] = d.writes[0]!
|
||||
expect(plist).not.toContain('EnvironmentVariables')
|
||||
})
|
||||
|
||||
it('launchd: injects a sorted, XML-escaped EnvironmentVariables dict', async () => {
|
||||
const d = deps()
|
||||
await installService(CFG, 'launchd', d, { env: TUNNEL_ENV })
|
||||
const [, plist] = d.writes[0]!
|
||||
expect(plist).toContain('<key>EnvironmentVariables</key>')
|
||||
expect(plist).toContain('<key>BIND_HOST</key>')
|
||||
expect(plist).toContain('<string>127.0.0.1</string>')
|
||||
// keys are sorted (ALLOWED_ORIGINS before BIND_HOST before PORT)
|
||||
expect(plist.indexOf('ALLOWED_ORIGINS')).toBeLessThan(plist.indexOf('BIND_HOST'))
|
||||
expect(plist.indexOf('BIND_HOST')).toBeLessThan(plist.indexOf('>PORT<'))
|
||||
})
|
||||
|
||||
it('launchd: escapes XML-significant characters in env values', () => {
|
||||
const plist = buildLaunchdPlist('/bin/agent', { X: `a&b<c>d"e'f` })
|
||||
expect(plist).toContain('<string>a&b<c>d"e'f</string>')
|
||||
expect(plist).not.toContain('a&b<c>d')
|
||||
})
|
||||
|
||||
it('systemd: default (no options) omits Environment lines', async () => {
|
||||
const d = deps()
|
||||
await installService(CFG, 'systemd', d)
|
||||
const [, unit] = d.writes[0]!
|
||||
expect(unit).not.toContain('Environment')
|
||||
})
|
||||
|
||||
it('systemd: emits sorted, quoted Environment= lines from the env map', async () => {
|
||||
const d = deps()
|
||||
await installService(CFG, 'systemd', d, { env: TUNNEL_ENV })
|
||||
const [, unit] = d.writes[0]!
|
||||
expect(unit).toContain('Environment="BIND_HOST=127.0.0.1"')
|
||||
expect(unit).toContain('Environment="PORT=3000"')
|
||||
expect(unit.indexOf('ALLOWED_ORIGINS')).toBeLessThan(unit.indexOf('BIND_HOST'))
|
||||
})
|
||||
|
||||
it('systemd: emits EnvironmentFile= (before inline Environment) when a path is given', async () => {
|
||||
const d = deps()
|
||||
await installService(CFG, 'systemd', d, { env: TUNNEL_ENV, envFile: '/etc/web-terminal.env' })
|
||||
const [, unit] = d.writes[0]!
|
||||
expect(unit).toContain('EnvironmentFile=/etc/web-terminal.env')
|
||||
expect(unit.indexOf('EnvironmentFile=')).toBeLessThan(unit.indexOf('Environment='))
|
||||
})
|
||||
|
||||
it('systemd: escapes backslash and double-quote in Environment values', () => {
|
||||
const unit = buildSystemdUnit('/bin/agent', 'alice', { env: { X: 'a"b\\c' } })
|
||||
expect(unit).toContain('Environment="X=a\\"b\\\\c"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('tunnel-origin derivation (PLAN_NATIVE_TUNNEL S2)', () => {
|
||||
it('merges https://<subdomain>.<zone>.<domain> into ALLOWED_ORIGINS when domain is given', async () => {
|
||||
const d = deps()
|
||||
await installService(CFG, 'launchd', d, { domain: 'yaojia.wang', zone: 'terminal' })
|
||||
const [, plist] = d.writes[0]!
|
||||
expect(plist).toContain('<key>ALLOWED_ORIGINS</key>')
|
||||
expect(plist).toContain('<string>https://host-42.terminal.yaojia.wang</string>')
|
||||
})
|
||||
|
||||
it('defaults to the `term` zone when only a domain is supplied', async () => {
|
||||
const d = deps()
|
||||
await installService(CFG, 'launchd', d, { domain: 'yaojia.wang' })
|
||||
const [, plist] = d.writes[0]!
|
||||
expect(plist).toContain('<string>https://host-42.term.yaojia.wang</string>')
|
||||
})
|
||||
|
||||
it('preserves a caller-provided ALLOWED_ORIGINS and appends the tunnel origin', async () => {
|
||||
const d = deps()
|
||||
await installService(CFG, 'systemd', d, {
|
||||
env: { ALLOWED_ORIGINS: 'https://keep.me' },
|
||||
domain: 'yaojia.wang',
|
||||
zone: 'terminal',
|
||||
})
|
||||
const [, unit] = d.writes[0]!
|
||||
expect(unit).toContain('https://keep.me,https://host-42.terminal.yaojia.wang')
|
||||
})
|
||||
|
||||
it('does not derive an origin when the config has no subdomain', async () => {
|
||||
const d = deps()
|
||||
await installService({ ...CFG, subdomain: null }, 'launchd', d, { domain: 'yaojia.wang' })
|
||||
const [, plist] = d.writes[0]!
|
||||
expect(plist).not.toContain('ALLOWED_ORIGINS')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildInstallOptions — env → InstallOptions (PLAN_NATIVE_TUNNEL S0/S2)', () => {
|
||||
it('defaults BIND_HOST to loopback so a tunnel install is never LAN-exposed (S0/R2)', () => {
|
||||
const options = buildInstallOptions({})
|
||||
expect(options.env).toEqual({ BIND_HOST: '127.0.0.1' })
|
||||
})
|
||||
|
||||
it('honours an explicit BIND_HOST and passes through the S0 base-app env vars', () => {
|
||||
const options = buildInstallOptions({
|
||||
BIND_HOST: '127.0.0.2',
|
||||
PORT: '3000',
|
||||
SHELL_PATH: '/bin/zsh',
|
||||
IDLE_TTL: '86400',
|
||||
USE_TMUX: '1',
|
||||
ALLOWED_ORIGINS: 'https://keep.me',
|
||||
})
|
||||
expect(options.env).toEqual({
|
||||
BIND_HOST: '127.0.0.2',
|
||||
PORT: '3000',
|
||||
SHELL_PATH: '/bin/zsh',
|
||||
IDLE_TTL: '86400',
|
||||
USE_TMUX: '1',
|
||||
ALLOWED_ORIGINS: 'https://keep.me',
|
||||
})
|
||||
})
|
||||
|
||||
it('omits unset/empty passthrough vars', () => {
|
||||
const options = buildInstallOptions({ PORT: '', SHELL_PATH: '/bin/bash' })
|
||||
expect(options.env).toEqual({ BIND_HOST: '127.0.0.1', SHELL_PATH: '/bin/bash' })
|
||||
})
|
||||
|
||||
it('derives domain + default `terminal` zone from TUNNEL_DOMAIN', () => {
|
||||
const options = buildInstallOptions({ TUNNEL_DOMAIN: 'yaojia.wang' })
|
||||
expect(options.domain).toBe('yaojia.wang')
|
||||
expect(options.zone).toBe('terminal')
|
||||
})
|
||||
|
||||
it('lets TUNNEL_ZONE override the origin zone and carries AGENT_ENV_FILE through', () => {
|
||||
const options = buildInstallOptions({ TUNNEL_DOMAIN: 'yaojia.wang', TUNNEL_ZONE: 'term', AGENT_ENV_FILE: '/etc/wt.env' })
|
||||
expect(options.zone).toBe('term')
|
||||
expect(options.envFile).toBe('/etc/wt.env')
|
||||
})
|
||||
|
||||
it('omits domain/zone when no TUNNEL_DOMAIN is set', () => {
|
||||
const options = buildInstallOptions({})
|
||||
expect(options.domain).toBeUndefined()
|
||||
expect(options.zone).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('install CLI seam end-to-end — resolved env reaches the units (PLAN_NATIVE_TUNNEL S2)', () => {
|
||||
// Env the operator would export before `web-terminal-agent install` on a tunnel host.
|
||||
const ENV = { PORT: '3000', SHELL_PATH: '/bin/zsh', TUNNEL_DOMAIN: 'yaojia.wang' } as const
|
||||
|
||||
it('launchd: the plist carries loopback BIND_HOST + the derived tunnel ALLOWED_ORIGINS', async () => {
|
||||
const d = deps()
|
||||
await installService(CFG, 'launchd', d, buildInstallOptions(ENV))
|
||||
const [, plist] = d.writes[0]!
|
||||
expect(plist).toContain('<key>EnvironmentVariables</key>')
|
||||
expect(plist).toContain('<key>BIND_HOST</key>')
|
||||
expect(plist).toContain('<string>127.0.0.1</string>')
|
||||
expect(plist).toContain('<string>https://host-42.terminal.yaojia.wang</string>')
|
||||
expect(plist).toContain('<key>PORT</key>')
|
||||
expect(plist).not.toContain('0.0.0.0')
|
||||
})
|
||||
|
||||
it('systemd: the unit carries loopback BIND_HOST + the derived tunnel ALLOWED_ORIGINS', async () => {
|
||||
const d = deps()
|
||||
await installService(CFG, 'systemd', d, buildInstallOptions(ENV))
|
||||
const [, unit] = d.writes[0]!
|
||||
expect(unit).toContain('Environment="BIND_HOST=127.0.0.1"')
|
||||
expect(unit).toContain('Environment="ALLOWED_ORIGINS=https://host-42.terminal.yaojia.wang"')
|
||||
expect(unit).toContain('Environment="PORT=3000"')
|
||||
expect(unit).not.toContain('0.0.0.0')
|
||||
})
|
||||
})
|
||||
|
||||
describe('systemd env value hardening (LOW: control-char injection)', () => {
|
||||
it('rejects a newline in an env value so it cannot inject a [Service] directive', () => {
|
||||
expect(() => buildSystemdUnit('/bin/agent', 'alice', { env: { X: 'a\nExecStartPre=/x' } })).toThrow(
|
||||
/control character/,
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a carriage return in an env value', () => {
|
||||
expect(() => buildSystemdUnit('/bin/agent', 'alice', { env: { X: 'a\rb' } })).toThrow(/control character/)
|
||||
})
|
||||
|
||||
it('still accepts ordinary values with quotes and backslashes', () => {
|
||||
const unit = buildSystemdUnit('/bin/agent', 'alice', { env: { X: 'a"b\\c' } })
|
||||
expect(unit).toContain('Environment="X=a\\"b\\\\c"')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ensureAllowedOrigin, subdomainOrigin, type OriginFsDeps } from '../src/service/originConfig.js'
|
||||
import {
|
||||
DEFAULT_ORIGIN_ZONE,
|
||||
ensureAllowedOrigin,
|
||||
mergeOrigins,
|
||||
subdomainOrigin,
|
||||
type OriginFsDeps,
|
||||
} from '../src/service/originConfig.js'
|
||||
|
||||
function memFs(initial: string | null): { fs: OriginFsDeps; get(): string } {
|
||||
const store = { content: initial }
|
||||
@@ -41,3 +47,38 @@ describe('ensureAllowedOrigin (T17, EXPLORE §3)', () => {
|
||||
expect(get()).toContain('https://host-42.term.example.com')
|
||||
})
|
||||
})
|
||||
|
||||
describe('zone parameterization (PLAN_NATIVE_TUNNEL S2)', () => {
|
||||
it('defaults to the historical `term` zone', () => {
|
||||
expect(DEFAULT_ORIGIN_ZONE).toBe('term')
|
||||
expect(subdomainOrigin('t1', 'yaojia.wang')).toBe('https://t1.term.yaojia.wang')
|
||||
})
|
||||
|
||||
it('composes the `terminal` zone for native-tunnel hosts', () => {
|
||||
expect(subdomainOrigin('t1', 'yaojia.wang', 'terminal')).toBe('https://t1.terminal.yaojia.wang')
|
||||
})
|
||||
|
||||
it('ensureAllowedOrigin writes the caller-selected zone', () => {
|
||||
const { fs, get } = memFs('PORT=3000\n')
|
||||
ensureAllowedOrigin(PATH, 't1', 'yaojia.wang', fs, 'terminal')
|
||||
expect(get()).toContain('ALLOWED_ORIGINS=https://t1.terminal.yaojia.wang')
|
||||
expect(get()).not.toContain('.term.yaojia.wang')
|
||||
})
|
||||
})
|
||||
|
||||
describe('mergeOrigins (PLAN_NATIVE_TUNNEL S2)', () => {
|
||||
it('appends to an empty/undefined value', () => {
|
||||
expect(mergeOrigins(undefined, 'https://a.example.com')).toBe('https://a.example.com')
|
||||
expect(mergeOrigins('', 'https://a.example.com')).toBe('https://a.example.com')
|
||||
})
|
||||
|
||||
it('de-duplicates an origin already present', () => {
|
||||
expect(mergeOrigins('https://a.example.com', 'https://a.example.com')).toBe('https://a.example.com')
|
||||
})
|
||||
|
||||
it('appends a new origin, trimming whitespace, preserving existing ones', () => {
|
||||
expect(mergeOrigins(' https://a.example.com , https://b.example.com ', 'https://c.example.com')).toBe(
|
||||
'https://a.example.com,https://b.example.com,https://c.example.com',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user