dsh-mobile 0.4.2 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -3
- package/CONTRIBUTORS.md +53 -0
- package/README.en.md +50 -20
- package/README.md +48 -20
- package/bin/dsh-mobile-funnel-linux-arm64 +0 -0
- package/bin/dsh-mobile-funnel-linux-x64 +0 -0
- package/docs/CLOUDFLARE_TUNNEL.en.md +2 -2
- package/docs/CLOUDFLARE_TUNNEL.md +2 -2
- package/lib/cli.js.map +1 -1
- package/lib/client.js +6 -6
- package/lib/client.js.map +1 -1
- package/lib/index.d.mts +63 -15
- package/lib/index.mjs +599 -148
- package/lib/index.mjs.map +1 -1
- package/package.json +11 -8
package/lib/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":["execFile","execFile","execFile"],"sources":["../src/exec-file.ts","../src/private-file.ts","../src/managed-setup.ts","../src/lan-setup.ts","../src/extensions.ts","../src/cli.ts"],"sourcesContent":["import { execFile, type ExecFileOptions } from 'node:child_process'\n\n/** Capture both output streams even when a desktop host wraps execFile without Node's promisify metadata. */\nexport function execFileText(\n file: string,\n args: readonly string[],\n options: Omit<ExecFileOptions, 'encoding'> & { encoding?: 'utf8' } = {},\n): Promise<{ stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n execFile(file, [...args], { windowsHide: true, ...options, encoding: 'utf8' }, (error, stdout, stderr) => {\n if (error !== null) { reject(error); return }\n if (typeof stdout !== 'string' || typeof stderr !== 'string') {\n reject(new Error('subprocess returned invalid text output'))\n return\n }\n resolve({ stdout, stderr })\n })\n })\n}\n","import { chmod } from 'node:fs/promises'\nimport { execFileText as execFile } from './exec-file.js'\n\nlet userSidTask: Promise<string> | undefined\n\nasync function currentWindowsUserSid(): Promise<string> {\n userSidTask ??= execFile('whoami.exe', ['/user', '/fo', 'csv', '/nh'], {\n encoding: 'utf8',\n windowsHide: true,\n timeout: 10_000,\n }).then(({ stdout }) => {\n const match = /,\"(S-\\d(?:-\\d+)+)\"\\s*$/u.exec(stdout.trim())\n if (match?.[1] === undefined) throw new Error('unable to resolve the current Windows user SID')\n return match[1]\n }).catch((error: unknown) => {\n userSidTask = undefined\n throw error\n })\n return userSidTask\n}\n\n/** Restrict a sensitive regular file to the current user and Windows administrators. */\nexport async function restrictPrivateFile(file: string, mode = 0o600): Promise<void> {\n await chmod(file, mode)\n if (process.platform !== 'win32') return\n const userSid = await currentWindowsUserSid()\n await execFile('icacls.exe', [\n file,\n '/inheritance:r',\n '/grant:r',\n `*${userSid}:(F)`,\n '*S-1-5-18:(F)',\n '*S-1-5-32-544:(F)',\n '/remove:g',\n '*S-1-1-0',\n '*S-1-5-11',\n '*S-1-5-32-545',\n ], { encoding: 'utf8', windowsHide: true, timeout: 10_000 })\n}\n","import {\n X509Certificate,\n createPrivateKey,\n createPublicKey,\n} from 'node:crypto'\nimport { execFileText as execFile } from './exec-file.js'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { networkInterfaces, type NetworkInterfaceInfo } from 'node:os'\nimport { basename, dirname, join } from 'node:path'\nimport { generate } from 'selfsigned'\nimport { restrictPrivateFile } from './private-file.js'\n\n/** One active private IPv4 address tied to a stable operating-system interface name. */\nexport interface LanNetwork {\n readonly name: string\n readonly address: string\n readonly cidr: string\n}\n\n/** Versioned setup that survives DHCP address changes on the selected interface. */\nexport interface ManagedSetup {\n readonly version: 2\n readonly networkInterface: string\n readonly listenPort: number\n /** Legacy setup snapshot retained for file compatibility; the active WebServer port wins at runtime. */\n readonly upstreamOrigin: string\n readonly tls: {\n readonly mode: 'managed'\n readonly caCertFile: string\n readonly caKeyFile: string\n readonly certFile: string\n readonly keyFile: string\n }\n}\n\ntype InterfaceTable = NodeJS.Dict<NetworkInterfaceInfo[]>\ntype RouteCommand = (file: string, args: readonly string[]) => Promise<string>\n\nconst VIRTUAL_INTERFACE_MARKERS = [\n 'bridge', 'docker', 'hyper-v', 'mihomo', 'radmin', 'tailscale', 'tap', 'tun',\n 'utun', 'vbox', 'veth', 'virtual', 'vmware', 'vpn', 'vethernet', 'wsl', 'zerotier',\n]\n\n/** Route inspection is advisory; never let a system command hold setup open indefinitely. */\nconst ROUTE_COMMAND_TIMEOUT_MS = 5_000\n\nfunction requiredString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.length === 0) throw new Error(`${name} must be a non-empty string`)\n return value\n}\n\n/** Validate the durable managed setup before it controls network and filesystem operations. */\nexport function parseManagedSetup(value: unknown): ManagedSetup {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error('mobile setup file must be an object')\n }\n const record = value as Record<string, unknown>\n if (record.version !== 2 || Reflect.ownKeys(record)\n .some(key => typeof key !== 'string' || !['version', 'networkInterface', 'listenPort', 'upstreamOrigin', 'tls'].includes(key))) {\n throw new Error('mobile setup file has an unsupported format')\n }\n if (!Number.isSafeInteger(record.listenPort) || (record.listenPort as number) < 1024\n || (record.listenPort as number) > 65535) {\n throw new Error('mobile setup listenPort must be from 1024 through 65535')\n }\n if (typeof record.tls !== 'object' || record.tls === null || Array.isArray(record.tls)) {\n throw new Error('mobile setup tls must be an object')\n }\n const tls = record.tls as Record<string, unknown>\n if (tls.mode !== 'managed' || Reflect.ownKeys(tls)\n .some(key => typeof key !== 'string' || !['mode', 'caCertFile', 'caKeyFile', 'certFile', 'keyFile'].includes(key))) {\n throw new Error('mobile setup tls has an unsupported format')\n }\n return Object.freeze({\n version: 2,\n networkInterface: requiredString(record.networkInterface, 'mobile setup networkInterface'),\n listenPort: record.listenPort as number,\n upstreamOrigin: requiredString(record.upstreamOrigin, 'mobile setup upstreamOrigin'),\n tls: Object.freeze({\n mode: 'managed',\n caCertFile: requiredString(tls.caCertFile, 'mobile setup tls.caCertFile'),\n caKeyFile: requiredString(tls.caKeyFile, 'mobile setup tls.caKeyFile'),\n certFile: requiredString(tls.certFile, 'mobile setup tls.certFile'),\n keyFile: requiredString(tls.keyFile, 'mobile setup tls.keyFile'),\n }),\n })\n}\n\nfunction privateIpv4(value: string): boolean {\n const parts = value.split('.').map(Number)\n return parts.length === 4 && parts.every(part => Number.isInteger(part) && part >= 0 && part <= 255)\n && (parts[0] === 10\n || (parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31)\n || (parts[0] === 192 && parts[1] === 168))\n}\n\nfunction networkCidr(address: string, cidr: string): string {\n const prefix = Number(cidr.slice(cidr.lastIndexOf('/') + 1))\n const value = address.split('.').reduce((total, part) => ((total << 8) | Number(part)) >>> 0, 0)\n const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0\n const network = (value & mask) >>> 0\n return `${[24, 16, 8, 0].map(shift => (network >>> shift) & 255).join('.')}/${String(prefix)}`\n}\n\n/** List current private IPv4 candidates with their interface identity. */\nexport function availableLanNetworks(table: InterfaceTable = networkInterfaces()): LanNetwork[] {\n const candidates = Object.entries(table).flatMap(([name, entries]) => (entries ?? [])\n .filter(entry => entry.family === 'IPv4' && !entry.internal && privateIpv4(entry.address) && entry.cidr !== null)\n .map(entry => ({ name, address: entry.address, cidr: networkCidr(entry.address, entry.cidr!) })))\n return [...new Map(candidates.map(entry => [`${entry.name}\\0${entry.address}`, entry])).values()]\n}\n\nfunction likelyVirtualInterface(name: string): boolean {\n const normalized = name.toLowerCase().replaceAll(/[^a-z0-9]+/gu, ' ')\n return VIRTUAL_INTERFACE_MARKERS.some(marker => normalized.includes(marker.replaceAll('-', ' ')))\n || /^(?:br|wg)\\d*\\b/u.test(normalized)\n}\n\nasync function runRouteCommand(file: string, args: readonly string[]): Promise<string> {\n const result = await execFile(file, [...args], { encoding: 'utf8', timeout: ROUTE_COMMAND_TIMEOUT_MS })\n return result.stdout\n}\n\nfunction uniqueLines(output: string): string[] {\n return [...new Set(output.split(/\\r?\\n/gu).map(line => line.trim()).filter(Boolean))]\n}\n\n/** Return operating-system default-route interfaces in routing preference order. */\nexport async function preferredLanInterfaceNames(\n platform: NodeJS.Platform = process.platform,\n run: RouteCommand = runRouteCommand,\n): Promise<string[]> {\n try {\n if (platform === 'win32') {\n const script = [\n \"$routes = Get-NetRoute -AddressFamily IPv4 -DestinationPrefix '0.0.0.0/0' -ErrorAction Stop\",\n \"$ranked = $routes | Where-Object { $_.State -eq 'Alive' -and $_.NextHop -ne '0.0.0.0' } | ForEach-Object {\",\n ' $route = $_',\n ' $adapter = Get-NetAdapter -InterfaceIndex $route.InterfaceIndex -ErrorAction SilentlyContinue',\n ' $ip = Get-NetIPInterface -AddressFamily IPv4 -InterfaceIndex $route.InterfaceIndex -ErrorAction SilentlyContinue',\n \" if ($adapter -and $ip -and $adapter.Status -eq 'Up' -and $adapter.HardwareInterface -eq $true -and $adapter.Virtual -ne $true) {\",\n ' [pscustomobject]@{ Name = $route.InterfaceAlias; Metric = [int]$route.RouteMetric + [int]$ip.InterfaceMetric }',\n ' }',\n '}',\n '$ranked | Sort-Object Metric | Select-Object -ExpandProperty Name -Unique',\n ].join('; ')\n return uniqueLines(await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]))\n }\n if (platform === 'linux') {\n const routes = uniqueLines(await run('ip', ['-o', '-4', 'route', 'show', 'default']))\n .map(line => ({\n name: /(?:^|\\s)dev\\s+(\\S+)/u.exec(line)?.[1],\n metric: Number(/(?:^|\\s)metric\\s+(\\d+)/u.exec(line)?.[1] ?? 0),\n }))\n .filter((route): route is { name: string; metric: number } => route.name !== undefined\n && !likelyVirtualInterface(route.name))\n .sort((left, right) => left.metric - right.metric)\n return [...new Set(routes.map(route => route.name))]\n }\n if (platform === 'darwin') {\n const name = /^\\s*interface:\\s*(\\S+)\\s*$/mu.exec(await run('route', ['-n', 'get', 'default']))?.[1]\n return name === undefined || likelyVirtualInterface(name) ? [] : [name]\n }\n } catch {\n // Route discovery is advisory; deterministic candidate checks below remain the fallback.\n }\n return []\n}\n\n/** Select an active LAN, optionally by address or by a previously saved interface name. */\nexport function selectLanNetwork(\n requestedAddress?: string,\n requestedInterface?: string,\n table?: InterfaceTable,\n preferredInterfaces: readonly string[] = [],\n): LanNetwork {\n const candidates = availableLanNetworks(table)\n if (requestedAddress !== undefined) {\n const match = candidates.find(candidate => candidate.address === requestedAddress)\n if (match === undefined) throw new Error(`--address ${requestedAddress} is not an active private LAN address`)\n return match\n }\n if (requestedInterface !== undefined) {\n const matches = candidates.filter(candidate => candidate.name === requestedInterface)\n if (matches.length === 1) return matches[0]!\n if (matches.length === 0) {\n throw new Error(`saved LAN interface ${JSON.stringify(requestedInterface)} is not connected`)\n }\n throw new Error(`saved LAN interface ${JSON.stringify(requestedInterface)} has more than one private IPv4 address`)\n }\n if (candidates.length === 1) return candidates[0]!\n if (candidates.length === 0) throw new Error('no active private LAN address was found; connect to Wi-Fi or Ethernet')\n for (const name of preferredInterfaces) {\n const matches = candidates.filter(candidate => candidate.name === name)\n if (matches.length === 1) return matches[0]!\n }\n const physicalCandidates = candidates.filter(candidate => !likelyVirtualInterface(candidate.name))\n if (physicalCandidates.length === 1) return physicalCandidates[0]!\n throw new Error(`more than one LAN address is active; rerun with --address and one of: ${candidates.map(entry => `${entry.name}=${entry.address}`).join(', ')}`)\n}\n\nfunction assertMatchingCa(certPem: string, keyPem: string): X509Certificate {\n const certificate = new X509Certificate(certPem)\n if (!certificate.ca || certificate.subject !== certificate.issuer\n || !certificate.verify(certificate.publicKey)) {\n throw new Error('managed TLS CA must be a self-signed CA certificate')\n }\n const privatePublic = createPublicKey(createPrivateKey(keyPem)).export({ format: 'der', type: 'spki' })\n const certificatePublic = certificate.publicKey.export({ format: 'der', type: 'spki' })\n if (!privatePublic.equals(certificatePublic)) throw new Error('managed TLS CA certificate and key do not match')\n if (Date.parse(certificate.validFrom) > Date.now() || Date.parse(certificate.validTo) <= Date.now()) {\n throw new Error('managed TLS CA certificate is not currently valid')\n }\n return certificate\n}\n\nasync function atomicWrite(file: string, contents: string | Uint8Array): Promise<void> {\n const directory = dirname(file)\n await mkdir(directory, { recursive: true, mode: 0o700 })\n const temporary = join(directory, `.${basename(file)}.${process.pid}.tmp`)\n await writeFile(temporary, contents, { mode: 0o600 })\n await rename(temporary, file)\n await restrictPrivateFile(file)\n}\n\n/** Create a long-lived CA or migrate the legacy self-signed server certificate as that CA. */\nexport async function ensureManagedCa(\n setup: ManagedSetup['tls'],\n legacy?: { readonly certFile: string; readonly keyFile: string },\n): Promise<X509Certificate> {\n let certPem: string | undefined\n let keyPem: string | undefined\n try {\n [certPem, keyPem] = await Promise.all([readFile(setup.caCertFile, 'utf8'), readFile(setup.caKeyFile, 'utf8')])\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n let migrated = false\n if (legacy !== undefined) {\n try {\n [certPem, keyPem] = await Promise.all([readFile(legacy.certFile, 'utf8'), readFile(legacy.keyFile, 'utf8')])\n assertMatchingCa(certPem, keyPem)\n migrated = true\n } catch (legacyError) {\n if ((legacyError as NodeJS.ErrnoException).code !== 'ENOENT') throw legacyError\n }\n }\n if (!migrated) {\n const now = new Date()\n const notAfter = new Date(now)\n notAfter.setFullYear(notAfter.getFullYear() + 5)\n const generated = await generate([{ name: 'commonName', value: 'DeepSeek Harness Mobile CA' }], {\n keyType: 'ec',\n curve: 'P-256',\n algorithm: 'sha256',\n notBeforeDate: new Date(now.getTime() - 5 * 60_000),\n notAfterDate: notAfter,\n extensions: [\n { name: 'basicConstraints', cA: true, critical: true },\n { name: 'keyUsage', digitalSignature: true, keyCertSign: true, cRLSign: true, critical: true },\n ],\n })\n certPem = generated.cert\n keyPem = generated.private\n }\n if (certPem === undefined || keyPem === undefined) throw new Error('managed TLS CA creation did not produce key material')\n await Promise.all([atomicWrite(setup.caCertFile, certPem), atomicWrite(setup.caKeyFile, keyPem)])\n }\n if (certPem === undefined || keyPem === undefined) throw new Error('managed TLS CA creation did not produce key material')\n await Promise.all([restrictPrivateFile(setup.caCertFile), restrictPrivateFile(setup.caKeyFile)])\n return assertMatchingCa(certPem, keyPem)\n}\n\n/** Sign and atomically install a server leaf for the interface's current address. */\nexport async function refreshManagedServerCertificate(setup: ManagedSetup, address: string): Promise<void> {\n await Promise.all([restrictPrivateFile(setup.tls.caCertFile), restrictPrivateFile(setup.tls.caKeyFile)])\n const [caCert, caKey] = await Promise.all([\n readFile(setup.tls.caCertFile, 'utf8'),\n readFile(setup.tls.caKeyFile, 'utf8'),\n ])\n assertMatchingCa(caCert, caKey)\n const now = new Date()\n const notAfter = new Date(now)\n notAfter.setDate(notAfter.getDate() + 397)\n const server = await generate([{ name: 'commonName', value: 'DeepSeek Harness Mobile' }], {\n keyType: 'ec',\n curve: 'P-256',\n algorithm: 'sha256',\n notBeforeDate: new Date(now.getTime() - 5 * 60_000),\n notAfterDate: notAfter,\n ca: { cert: caCert, key: caKey },\n extensions: [\n { name: 'basicConstraints', cA: false, critical: true },\n { name: 'keyUsage', digitalSignature: true, critical: true },\n { name: 'extKeyUsage', serverAuth: true },\n { name: 'subjectAltName', altNames: [{ type: 7, ip: address }] },\n ],\n })\n await Promise.all([\n atomicWrite(setup.tls.certFile, server.cert),\n atomicWrite(setup.tls.keyFile, server.private),\n ])\n}\n\n/** Resolve the saved interface to the ordinary gateway config consumed by the Host plugin. */\nexport async function materializeManagedSetup(\n setup: ManagedSetup,\n table?: InterfaceTable,\n): Promise<Record<string, unknown>> {\n const network = selectLanNetwork(undefined, setup.networkInterface, table)\n await refreshManagedServerCertificate(setup, network.address)\n const ca = new X509Certificate(await readFile(setup.tls.caCertFile, 'utf8'))\n return {\n publicOrigin: `https://${network.address}:${String(setup.listenPort)}`,\n listenHost: network.address,\n allowedCidrs: [network.cidr],\n instanceId: ca.fingerprint256.replaceAll(':', '').toLowerCase(),\n pairingCaFile: setup.tls.caCertFile,\n tls: {\n mode: 'provided',\n certFile: setup.tls.certFile,\n keyFile: setup.tls.keyFile,\n },\n }\n}\n","import { execFileText as execFile } from './exec-file.js'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join } from 'node:path'\nimport {\n ensureManagedCa,\n refreshManagedServerCertificate,\n type LanNetwork,\n type ManagedSetup,\n} from './managed-setup.js'\nimport { restrictPrivateFile } from './private-file.js'\n\nconst FIREWALL_TCP_RULE = 'DSH Mobile HTTPS'\nconst FIREWALL_UDP_RULE = 'DSH Mobile Discovery'\n\n/** Files and active address produced by one explicit LAN setup confirmation. */\nexport interface ManagedLanSetupResult {\n readonly setup: ManagedSetup\n readonly network: LanNetwork\n readonly origin: string\n readonly androidCertificate: string\n}\n\n/** Inputs required to prepare the managed LAN listener without starting it. */\nexport interface ManagedLanSetupOptions {\n readonly setupFile: string\n readonly controlFile: string\n readonly network: LanNetwork\n readonly listenPort: number\n readonly dshPort: number\n readonly configureFirewall: boolean\n}\n\nasync function runElevatedPowerShell(script: string): Promise<void> {\n const encoded = Buffer.from(script, 'utf16le').toString('base64')\n const launch = [\n \"$ErrorActionPreference = 'Stop'; $process = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru\",\n ` -ArgumentList @('-NoProfile','-NonInteractive','-EncodedCommand','${encoded}')`,\n '; exit $process.ExitCode',\n ].join(' ')\n await execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', launch], { windowsHide: true })\n}\n\n/** Install the two Windows inbound rules used by the managed LAN listener. */\nexport async function configureWindowsFirewall(port: number): Promise<void> {\n if (process.platform !== 'win32') return\n const script = [\n \"$ErrorActionPreference = 'Stop'\",\n `Get-NetFirewallRule -DisplayName '${FIREWALL_TCP_RULE}' -ErrorAction SilentlyContinue | Remove-NetFirewallRule`,\n `Get-NetFirewallRule -DisplayName '${FIREWALL_UDP_RULE}' -ErrorAction SilentlyContinue | Remove-NetFirewallRule`,\n `New-NetFirewallRule -DisplayName '${FIREWALL_TCP_RULE}' -Direction Inbound -Action Allow -Protocol TCP -LocalPort ${String(port)} -RemoteAddress LocalSubnet -Profile Any | Out-Null`,\n `New-NetFirewallRule -DisplayName '${FIREWALL_UDP_RULE}' -Direction Inbound -Action Allow -Protocol UDP -LocalPort ${String(port)} -RemoteAddress LocalSubnet -Profile Any | Out-Null`,\n ].join('; ')\n await runElevatedPowerShell(script)\n}\n\n/** Remove only the two Windows firewall rules owned by DSH Mobile. */\nexport async function removeWindowsFirewall(): Promise<void> {\n if (process.platform !== 'win32') return\n await runElevatedPowerShell([\n \"$ErrorActionPreference = 'Stop'\",\n `Get-NetFirewallRule -DisplayName '${FIREWALL_TCP_RULE}' -ErrorAction SilentlyContinue | Remove-NetFirewallRule`,\n `Get-NetFirewallRule -DisplayName '${FIREWALL_UDP_RULE}' -ErrorAction SilentlyContinue | Remove-NetFirewallRule`,\n ].join('; '))\n}\n\n/** Generate private TLS material and persist a managed setup selected by the user. */\nexport async function prepareManagedLanSetup(options: ManagedLanSetupOptions): Promise<ManagedLanSetupResult> {\n if (!isAbsolute(options.setupFile) || !isAbsolute(options.controlFile)) {\n throw new Error('managed LAN setup paths must be absolute')\n }\n if (!Number.isSafeInteger(options.listenPort) || options.listenPort < 1024 || options.listenPort > 65535) {\n throw new Error('managed LAN listenPort must be from 1024 through 65535')\n }\n if (!Number.isSafeInteger(options.dshPort) || options.dshPort < 1024 || options.dshPort > 65535) {\n throw new Error('managed LAN dshPort must be from 1024 through 65535')\n }\n const directory = dirname(options.setupFile)\n const tlsDirectory = join(directory, 'tls')\n await mkdir(tlsDirectory, { recursive: true, mode: 0o700 })\n const managedTls: ManagedSetup['tls'] = {\n mode: 'managed',\n caCertFile: join(tlsDirectory, 'ca.pem'),\n caKeyFile: join(tlsDirectory, 'ca-key.pem'),\n certFile: join(tlsDirectory, 'server-cert.pem'),\n keyFile: join(tlsDirectory, 'server-key.pem'),\n }\n const ca = await ensureManagedCa(managedTls, {\n certFile: join(tlsDirectory, 'cert.pem'),\n keyFile: join(tlsDirectory, 'key.pem'),\n })\n const setup: ManagedSetup = {\n version: 2,\n networkInterface: options.network.name,\n listenPort: options.listenPort,\n upstreamOrigin: `http://127.0.0.1:${String(options.dshPort)}`,\n tls: managedTls,\n }\n await refreshManagedServerCertificate(setup, options.network.address)\n const androidCertificate = join(tlsDirectory, 'dsh-mobile-ca.cer')\n await writeFile(androidCertificate, ca.raw, { mode: 0o600 })\n await Promise.all([\n ...Object.values(managedTls).filter(value => value !== 'managed').map(file => restrictPrivateFile(file)),\n restrictPrivateFile(androidCertificate),\n ])\n if (options.configureFirewall) await configureWindowsFirewall(options.listenPort)\n await Promise.all([\n writeFile(options.setupFile, `${JSON.stringify({\n ...setup,\n tls: Object.fromEntries(Object.entries(setup.tls)\n .map(([key, value]) => [key, typeof value === 'string' ? value.replaceAll('\\\\', '/') : value])),\n }, null, 2)}\\n`, { mode: 0o600 }),\n writeFile(options.controlFile, '{\"version\":1,\"enabled\":true}\\n', { mode: 0o600 }),\n ])\n await Promise.all([restrictPrivateFile(options.setupFile), restrictPrivateFile(options.controlFile)])\n return Object.freeze({\n setup: Object.freeze(setup),\n network: Object.freeze({ ...options.network }),\n origin: `https://${options.network.address}:${String(options.listenPort)}`,\n androidCertificate,\n })\n}\n","import { createHash } from 'node:crypto'\nimport type { Dirent } from 'node:fs'\nimport { lstat, mkdir, opendir, readFile, realpath } from 'node:fs/promises'\nimport { basename, isAbsolute, join, relative, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { Service, type Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport { finished, type Readable } from 'node:stream'\n\n/** Maximum sizes enforced at the local-extension filesystem boundary. */\nexport const EXTENSION_LIMITS = Object.freeze({\n manifest: 64 * 1024,\n script: 1024 * 1024,\n css: 512 * 1024,\n asset: 8 * 1024 * 1024,\n assetFiles: 256,\n assetBytes: 32 * 1024 * 1024,\n assetDepth: 8,\n})\n\n/** A misbehaving host activation must not wedge the local watcher forever. */\nconst HOST_ACTIVATION_TIMEOUT_MS = 5_000\n\n/** The previous Host outlives the hidden-page refresh interval and one timed refresh. */\nconst RETIRED_GENERATION_TTL_MS = 10 * 60_000\n\n/** Extension teardown is advisory and must never stop watcher progress. */\nconst HOST_TEARDOWN_TIMEOUT_MS = 2_000\n\nasync function withActivationTimeout<T>(promise: Promise<T>, id: string, signal: AbortSignal): Promise<T> {\n let timer: NodeJS.Timeout | undefined\n let onAbort: (() => void) | undefined\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new MobileExtensionError('host_load_timeout', `extension ${id} activation timed out`, 500)), HOST_ACTIVATION_TIMEOUT_MS)\n }),\n new Promise<never>((_, reject) => {\n const abort = (): void => { reject(new MobileExtensionError('host_activation_closed', `extension ${id} activation is closed`, 409)) }\n if (signal.aborted) abort()\n else { onAbort = abort; signal.addEventListener('abort', abort, { once: true }) }\n }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)\n }\n}\n\n/** A controlled business failure returned by an extension action or route. */\nexport class MobileExtensionError extends Error {\n constructor(readonly code: string, message: string, readonly status = 400) {\n super(message)\n this.name = 'MobileExtensionError'\n }\n}\n\n/** One host-side action exposed by an extension. */\ntype CallableActionInput = (value?: never, options?: never) => unknown\n\nexport interface MobileHostAction {\n /** A callable Schemastery schema or an adapter exposing parse(). */\n readonly input?: CallableActionInput | { parse(value: unknown): unknown }\n readonly run: (context: MobileActionContext, input: unknown) => unknown | Promise<unknown>\n}\n\n/** Context supplied to a host action. */\nexport interface MobileActionContext {\n readonly signal: AbortSignal\n readonly deviceId: string\n}\n\n/** Safe request values supplied to a host route. */\nexport interface MobileRouteRequest {\n readonly method: string\n readonly pathname: string\n readonly query: Readonly<URLSearchParams>\n readonly headers: Readonly<Record<string, string>>\n readonly body: Uint8Array\n readonly signal: AbortSignal\n readonly deviceId: string\n}\n\n/** Values an extension route may return; status is a final HTTP code from 200 through 599. */\nexport interface MobileRouteResponse {\n readonly status?: number\n readonly contentType?: string\n readonly headers?: Readonly<Record<string, string>>\n readonly body: string | Uint8Array | Readable\n}\n\n/** One host-side route exposed by an extension. */\nexport interface MobileHostRoute {\n readonly method: string\n readonly path: string\n readonly kind?: 'exact' | 'prefix'\n readonly handle: (request: MobileRouteRequest) => MobileRouteResponse | Promise<MobileRouteResponse>\n}\n\n/** Metadata shared by local and npm-provided extensions. */\nexport interface MobileExtensionManifest {\n readonly schemaVersion: 1\n readonly id: string\n readonly name: string\n readonly version: string\n readonly description?: string\n}\n\n/** Definition registered by a normal Cordis plugin. */\nexport interface MobileExtensionDefinition extends MobileExtensionManifest {\n readonly actions?: Readonly<Record<string, MobileHostAction>>\n readonly routes?: readonly MobileHostRoute[]\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n mobileAccess: MobileAccessService\n }\n}\n\n/** A local extension manifest read from extension.json. */\nexport interface LocalExtensionManifest extends MobileExtensionManifest {}\n\n/** Public snapshot sent to the mobile browser. */\nexport interface MobileExtensionClientEntry extends MobileExtensionManifest {\n readonly generation?: string\n readonly scriptUrl?: string\n readonly styleUrl?: string\n readonly assetsUrl?: string\n}\n\ninterface LocalAssetSnapshot {\n readonly body: Buffer\n readonly digest: string\n readonly name: string\n}\n\n/** Small status summary used by the desktop mobile-access card. */\nexport interface MobileExtensionStatus {\n readonly loaded: number\n readonly failed: number\n}\n\ninterface ActiveLocalExtension {\n readonly manifest: LocalExtensionManifest\n readonly directory: string\n readonly scriptBody?: Buffer\n readonly styleBody?: Buffer\n readonly assets: ReadonlyMap<string, LocalAssetSnapshot>\n readonly host: MobileExtensionDefinition\n readonly controller: AbortController\n readonly cleanups: readonly (() => void | Promise<void>)[]\n readonly digest: string\n}\n\ninterface RegisteredExtension {\n readonly definition: MobileExtensionDefinition\n readonly dispose: () => void\n}\n\ninterface RetiredLocalExtension {\n readonly active: ActiveLocalExtension\n readonly timer: NodeJS.Timeout\n}\n\ntype HostApi = {\n readonly manifest: LocalExtensionManifest\n readonly context: Context\n readonly schema: typeof z\n readonly signal: AbortSignal\n action(name: string, spec: MobileHostAction): void\n route(spec: MobileHostRoute): void\n effect(setup: () => void | (() => void | Promise<void>) | Promise<void | (() => void | Promise<void>)>): void\n}\n\ntype LocalHostModule = { readonly default?: (api: HostApi) => void | Promise<void> }\n\n/** Validate user-facing extension text without allowing control characters. */\nfunction text(value: unknown, field: string, maximum: number, required: boolean): string | undefined {\n if (value === undefined && !required) return undefined\n if (typeof value !== 'string' || (required && value.length === 0) || value.length > maximum\n || /[\\u0000-\\u001f\\u007f]/u.test(value)) throw new MobileExtensionError('invalid_manifest', `${field} is invalid`)\n return value\n}\n\n/** Validate a stable extension id. */\nexport function assertExtensionId(value: unknown): string {\n if (typeof value !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/u.test(value)) {\n throw new MobileExtensionError('invalid_manifest', 'extension id is invalid')\n }\n return value\n}\n\n/** Validate a manifest from JSON or a plugin definition. */\nexport function parseExtensionManifest(value: unknown): LocalExtensionManifest {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new MobileExtensionError('invalid_manifest', 'extension.json must be an object')\n }\n const record = value as Record<string, unknown>\n if (record.schemaVersion !== 1) throw new MobileExtensionError('invalid_manifest', 'unsupported extension schema')\n const id = assertExtensionId(record.id)\n const name = text(record.name, 'name', 120, true) as string\n const version = text(record.version, 'version', 64, true) as string\n const description = text(record.description, 'description', 500, false)\n for (const key of Reflect.ownKeys(record)) {\n if (!['schemaVersion', 'id', 'name', 'version', 'description'].includes(String(key))) {\n throw new MobileExtensionError('invalid_manifest', 'extension.json has unknown fields')\n }\n }\n return Object.freeze({ schemaVersion: 1, id, name, version, ...(description === undefined ? {} : { description }) })\n}\n\nfunction normalizeRelativePath(value: string, field: string): string {\n if (value.length === 0 || value.includes('\\0') || isAbsolute(value)) throw new MobileExtensionError('invalid_extension_path', `${field} is invalid`)\n const normalized = value.replaceAll('\\\\', '/')\n if (normalized.split('/').some(part => part === '' || part === '.' || part === '..')) {\n throw new MobileExtensionError('invalid_extension_path', `${field} escapes extension directory`)\n }\n return normalized\n}\n\nasync function regularFile(path: string, maximum: number, field: string): Promise<{ readonly path: string; readonly size: number }> {\n let info\n try { info = await lstat(path) } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw new MobileExtensionError('invalid_extension', `${field} is missing`)\n throw error\n }\n if (!info.isFile() || info.isSymbolicLink() || info.size > maximum) {\n throw new MobileExtensionError('invalid_extension', `${field} must be a regular file within its size limit`)\n }\n return { path, size: info.size }\n}\n\nasync function containedPath(root: string, relativePath: string, maximum: number, field: string): Promise<{ readonly path: string; readonly size: number }> {\n const normalized = normalizeRelativePath(relativePath, field)\n const target = resolve(root, normalized)\n const rootReal = await realpath(root)\n const targetReal = await realpath(target)\n const relation = relative(rootReal, targetReal)\n if (relation === '' || relation.startsWith('..') || isAbsolute(relation)) throw new MobileExtensionError('invalid_extension_path', `${field} escapes extension directory`)\n return regularFile(targetReal, maximum, field)\n}\n\nasync function optionalFile(root: string, name: string, maximum: number, field: string): Promise<string | undefined> {\n try {\n return (await containedPath(root, name, maximum, field)).path\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n if (error instanceof MobileExtensionError && error.message.includes('is missing')) return undefined\n throw error\n }\n}\n\nasync function optionalBytes(root: string, name: string, maximum: number, field: string): Promise<Buffer | undefined> {\n const path = await optionalFile(root, name, maximum, field)\n return path === undefined ? undefined : readFile(path)\n}\n\nfunction assertRealPathWithin(rootReal: string, targetReal: string, field: string): void {\n const relation = relative(rootReal, targetReal)\n if (relation === '' || relation.startsWith('..') || isAbsolute(relation)) {\n throw new MobileExtensionError('invalid_extension_path', `${field} escapes extension directory`)\n }\n}\n\nasync function realExtensionRoot(directory: string): Promise<string> {\n const root = resolve(directory)\n const info = await lstat(root)\n if (!info.isDirectory() || info.isSymbolicLink()) throw new MobileExtensionError('invalid_extension', 'extension directory must be real')\n return realpath(root)\n}\n\nasync function assetSnapshot(extensionRootReal: string): Promise<ReadonlyMap<string, LocalAssetSnapshot>> {\n const assetsPath = join(extensionRootReal, 'assets')\n let assetsInfo\n try { assetsInfo = await lstat(assetsPath) } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return new Map()\n throw error\n }\n if (!assetsInfo.isDirectory() || assetsInfo.isSymbolicLink()) {\n throw new MobileExtensionError('invalid_extension', 'assets must be a real directory')\n }\n const assetsReal = await realpath(assetsPath)\n assertRealPathWithin(extensionRootReal, assetsReal, 'assets')\n const snapshots = new Map<string, LocalAssetSnapshot>()\n let totalBytes = 0\n const visit = async (directoryReal: string, prefix: string, depth: number): Promise<void> => {\n if (depth > EXTENSION_LIMITS.assetDepth) {\n throw new MobileExtensionError('invalid_extension', 'asset tree exceeds its depth limit')\n }\n assertRealPathWithin(extensionRootReal, directoryReal, 'asset directory')\n const handle = await opendir(directoryReal)\n const entries: Dirent[] = []\n try { for await (const entry of handle) entries.push(entry) }\n finally { await handle.close().catch(() => undefined) }\n entries.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)\n for (const entry of entries) {\n const path = join(directoryReal, entry.name)\n const info = await lstat(path)\n if (info.isSymbolicLink()) throw new MobileExtensionError('invalid_extension_path', 'asset escapes extension directory')\n const targetReal = await realpath(path)\n assertRealPathWithin(extensionRootReal, targetReal, 'asset')\n const key = prefix === '' ? entry.name : `${prefix}/${entry.name}`\n if (info.isDirectory()) {\n await visit(targetReal, key, depth + 1)\n continue\n }\n if (!info.isFile() || info.size > EXTENSION_LIMITS.asset) {\n throw new MobileExtensionError('invalid_extension', 'asset must be a regular file within its size limit')\n }\n const body = await readFile(targetReal)\n totalBytes += body.byteLength\n if (snapshots.size >= EXTENSION_LIMITS.assetFiles || totalBytes > EXTENSION_LIMITS.assetBytes) {\n throw new MobileExtensionError('invalid_extension', 'asset tree exceeds its aggregate limit')\n }\n snapshots.set(key, Object.freeze({ body, digest: createHash('sha256').update(body).digest('hex'), name: entry.name }))\n }\n }\n await visit(assetsReal, '', 0)\n return snapshots\n}\n\ninterface LocalExtensionFingerprint {\n readonly manifest: LocalExtensionManifest\n readonly digest: string\n readonly scriptBody?: Buffer\n readonly styleBody?: Buffer\n readonly assets: ReadonlyMap<string, LocalAssetSnapshot>\n}\n\nasync function extensionFingerprint(directory: string): Promise<LocalExtensionFingerprint> {\n const root = await realExtensionRoot(directory)\n const manifestFile = await regularFile(join(root, 'extension.json'), EXTENSION_LIMITS.manifest, 'extension.json')\n const manifestBody = await readFile(manifestFile.path)\n const manifest = parseExtensionManifest(JSON.parse(manifestBody.toString('utf8')) as unknown)\n if (manifest.id !== basename(root)) throw new MobileExtensionError('invalid_manifest', 'extension id must match its directory name')\n const [host, script, style, assets] = await Promise.all([\n optionalBytes(root, 'host.mjs', EXTENSION_LIMITS.script, 'host.mjs'),\n optionalBytes(root, 'mobile.js', EXTENSION_LIMITS.script, 'mobile.js'),\n optionalBytes(root, 'mobile.css', EXTENSION_LIMITS.css, 'mobile.css'),\n assetSnapshot(root),\n ])\n const digest = createHash('sha256').update(`manifest:${manifestBody.byteLength}:`).update(createHash('sha256').update(manifestBody).digest())\n for (const [name, body] of [['host', host], ['script', script], ['style', style]] as const) {\n digest.update(`\\0${name}:${body?.byteLength ?? -1}:`)\n if (body !== undefined) digest.update(createHash('sha256').update(body).digest())\n }\n for (const [name, asset] of assets) {\n digest.update(`\\0asset:${Buffer.byteLength(name)}:${name}:${asset.body.byteLength}:${asset.digest}`)\n }\n return {\n manifest,\n digest: digest.digest('hex'),\n assets,\n ...(script === undefined ? {} : { scriptBody: script }),\n ...(style === undefined ? {} : { styleBody: style }),\n }\n}\n\nfunction routeKey(route: MobileHostRoute): string {\n const method = route.method.toUpperCase()\n const path = normalizeRoutePath(route.path)\n return `${method} ${route.kind ?? 'exact'} ${path}`\n}\n\nfunction normalizeRoutePath(value: string): string {\n if (typeof value !== 'string' || value.length === 0 || value.length > 256\n || value.includes('?') || value.includes('#') || value.includes('\\\\') || value.includes('\\0')\n || /[\\u0000-\\u001f\\u007f]/u.test(value)) throw new MobileExtensionError('invalid_route', 'extension route path is invalid')\n const normalizedInput = value.startsWith('/') ? value : `/${value}`\n const parts = normalizedInput.split('/')\n if (parts.some(part => part === '..' || part === '.')) throw new MobileExtensionError('invalid_route', 'extension route path is invalid')\n return normalizedInput === '/' ? '/' : normalizedInput.replace(/\\/+$/u, '')\n}\n\nfunction validateDefinition(definition: MobileExtensionDefinition): MobileExtensionDefinition {\n const manifest = parseExtensionManifest({\n schemaVersion: definition.schemaVersion,\n id: definition.id,\n name: definition.name,\n version: definition.version,\n ...(definition.description === undefined ? {} : { description: definition.description }),\n })\n const actionNames = new Set<string>()\n for (const [name, action] of Object.entries(definition.actions ?? {})) {\n if (!/^[a-z][a-z0-9-]{0,63}$/u.test(name) || action === null || typeof action !== 'object' || typeof action.run !== 'function' || actionNames.has(name)) {\n throw new MobileExtensionError('invalid_action', `invalid action ${name}`)\n }\n actionNames.add(name)\n }\n const routeNames = new Set<string>()\n const routes = (definition.routes ?? []).map(route => {\n if (route === null || typeof route !== 'object' || typeof route.handle !== 'function') throw new MobileExtensionError('invalid_route', 'invalid extension route')\n const method = route.method.toUpperCase()\n if (!['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) throw new MobileExtensionError('invalid_route', 'unsupported extension route method')\n const normalized: MobileHostRoute = { ...route, method, path: normalizeRoutePath(route.path) }\n const key = routeKey(normalized)\n if (routeNames.has(key)) throw new MobileExtensionError('duplicate_route', `duplicate route ${key}`)\n routeNames.add(key)\n return normalized\n })\n return Object.freeze({ ...manifest, ...(definition.actions === undefined ? {} : { actions: Object.freeze({ ...definition.actions }) }), ...(routes.length === 0 ? {} : { routes: Object.freeze(routes) }) })\n}\n\ninterface CombinedSignalLifetime {\n readonly signal: AbortSignal\n readonly cleanup: () => void\n}\n\nfunction combineSignalLifetime(first: AbortSignal, second: AbortSignal): CombinedSignalLifetime {\n if (first.aborted || second.aborted) {\n const aborted = new AbortController()\n aborted.abort(first.aborted ? first.reason : second.reason)\n return { signal: aborted.signal, cleanup: () => undefined }\n }\n const controller = new AbortController()\n const cleanup = (): void => {\n first.removeEventListener('abort', abortFirst)\n second.removeEventListener('abort', abortSecond)\n }\n const abortFirst = (): void => { cleanup(); controller.abort(first.reason) }\n const abortSecond = (): void => { cleanup(); controller.abort(second.reason) }\n first.addEventListener('abort', abortFirst, { once: true })\n second.addEventListener('abort', abortSecond, { once: true })\n return { signal: controller.signal, cleanup }\n}\n\n/** Validate and normalize an action input through either supported schema form. */\nfunction parseActionInput(schema: MobileHostAction['input'], input: unknown): unknown {\n if (schema === undefined) return input\n if (typeof schema === 'function') return (schema as (value: unknown) => unknown)(input)\n return schema.parse(input) ?? input\n}\n\n/** Combine two abort lifetimes without relying on AbortSignal.any in older WebViews. */\nexport function combineSignals(first: AbortSignal, second: AbortSignal): AbortSignal {\n return combineSignalLifetime(first, second).signal\n}\n\n/** Host registry and service consumed by both npm plugins and local extensions. */\nexport class MobileAccessService extends Service {\n private readonly registered = new Map<string, RegisteredExtension>()\n private readonly local = new Map<string, ActiveLocalExtension>()\n private readonly retired = new Map<string, RetiredLocalExtension>()\n private readonly failures = new Map<string, string>()\n private readonly contentListeners = new Set<() => void>()\n private contentHash = createHash('sha256').update('').digest('hex')\n private localRoot: string | undefined\n private localContext: Context | undefined\n private localTimer: NodeJS.Timeout | undefined\n private localRefreshing: Promise<void> | undefined\n private localRefreshAbort: AbortController | undefined\n private localLifecycle = 0\n private localClosed = true\n\n constructor(ctx: Context) { super(ctx, 'mobileAccess') }\n\n /** Register a normal Cordis extension and return an idempotent disposer. */\n registerExtension(definition: MobileExtensionDefinition): () => void {\n const validated = validateDefinition(definition)\n if (this.registered.has(validated.id) || this.local.has(validated.id)) throw new Error(`mobile extension id already registered: ${validated.id}`)\n const dispose = (): void => {\n const current = this.registered.get(validated.id)\n if (current?.dispose === dispose) {\n this.registered.delete(validated.id)\n this.updateContentHash()\n }\n }\n this.registered.set(validated.id, { definition: validated, dispose })\n this.updateContentHash()\n return dispose\n }\n\n /** Aggregate digest covering every registered and active local extension. */\n contentDigest(): string {\n return this.contentHash\n }\n\n /** Subscribe to committed extension generation changes. */\n onContentChanged(listener: () => void): () => void {\n this.contentListeners.add(listener)\n return () => { this.contentListeners.delete(listener) }\n }\n\n private updateContentHash(): void {\n const parts = [\n ...[...this.registered.values()].map(entry => entry.definition.id),\n ...[...this.local.values()].map(active => `${active.manifest.id}:${active.digest}`),\n ]\n const next = createHash('sha256').update(parts.sort().join('|')).digest('hex')\n if (next === this.contentHash) return\n this.contentHash = next\n for (const listener of this.contentListeners) {\n try { listener() } catch { /* One observer cannot block a committed generation. */ }\n }\n }\n\n /** Return the current client-facing manifest, deterministically sorted by id. */\n manifest(): readonly MobileExtensionClientEntry[] {\n const entries = new Map<string, MobileExtensionClientEntry>()\n for (const { definition } of this.registered.values()) entries.set(definition.id, {\n schemaVersion: 1, id: definition.id, name: definition.name, version: definition.version,\n ...(definition.description === undefined ? {} : { description: definition.description }),\n })\n for (const active of this.local.values()) entries.set(active.manifest.id, {\n ...active.manifest,\n generation: active.digest,\n ...(active.scriptBody === undefined ? {} : { scriptUrl: `/mobile-access/extensions/${active.manifest.id}/mobile.js?generation=${active.digest}` }),\n ...(active.styleBody === undefined ? {} : { styleUrl: `/mobile-access/extensions/${active.manifest.id}/mobile.css?generation=${active.digest}` }),\n assetsUrl: `/mobile-access/extensions/${active.manifest.id}/assets/`,\n })\n return [...entries.values()].sort((left, right) => left.id.localeCompare(right.id))\n }\n\n /** Return loaded and failed local extension counts without exposing host errors. */\n status(): MobileExtensionStatus {\n return Object.freeze({ loaded: this.registered.size + this.local.size, failed: this.failures.size })\n }\n\n /** Locate one active extension. */\n extension(id: string, generation?: string): MobileExtensionDefinition | ActiveLocalExtension | undefined {\n if (generation !== undefined) {\n const current = this.local.get(id)\n if (current?.digest === generation) return current\n const previous = this.retired.get(id)?.active\n return previous?.digest === generation ? previous : undefined\n }\n return this.local.get(id) ?? this.registered.get(id)?.definition\n }\n\n /** Return the active local generation signal for gateway cancellation wiring. */\n signal(id: string, generation?: string): AbortSignal | undefined {\n const extension = this.extension(id, generation)\n return extension !== undefined && 'host' in extension ? extension.controller.signal : undefined\n }\n\n /** Read a local client entry after validating that it remains inside its directory. */\n async readClientFile(id: string, kind: 'script' | 'style', signal?: AbortSignal, generation?: string): Promise<{ readonly body: Buffer; readonly digest: string }> {\n signal?.throwIfAborted()\n const selected = this.extension(id, generation)\n const active = selected !== undefined && 'host' in selected ? selected : undefined\n if (active === undefined) throw new MobileExtensionError('extension_generation_not_found', 'extension generation not found', 404)\n const snapshot = kind === 'script' ? active.scriptBody : active.styleBody\n if (snapshot === undefined) throw new MobileExtensionError('extension_asset_not_found', 'extension asset not found', 404)\n const body = Buffer.from(snapshot)\n return { body, digest: createHash('sha256').update(body).digest('hex') }\n }\n\n /** Read a generation-pinned static asset from its validated snapshot. */\n async readAsset(id: string, assetPath: string, signal?: AbortSignal, generation?: string): Promise<{ readonly body: Buffer; readonly digest: string; readonly name: string }> {\n signal?.throwIfAborted()\n const selected = this.extension(id, generation)\n const active = selected !== undefined && 'host' in selected ? selected : undefined\n if (active === undefined) throw new MobileExtensionError('extension_generation_not_found', 'extension generation not found', 404)\n const normalized = normalizeRelativePath(assetPath, 'asset')\n const asset = active.assets.get(normalized)\n if (asset === undefined) throw new MobileExtensionError('extension_asset_not_found', 'extension asset not found', 404)\n return { body: Buffer.from(asset.body), digest: asset.digest, name: asset.name }\n }\n\n /** Invoke one action after parsing its input and binding the request lifetime. */\n async invoke(id: string, actionName: string, input: unknown, context: MobileActionContext, generation?: string): Promise<unknown> {\n const extension = this.extension(id, generation)\n if (extension === undefined) throw new MobileExtensionError('extension_not_found', 'extension not found', 404)\n const definition = 'host' in extension ? extension.host : extension\n const action = definition.actions?.[actionName]\n if (action === undefined) throw new MobileExtensionError('action_not_found', 'action not found', 404)\n let parsed: unknown\n try { parsed = parseActionInput(action.input, input) } catch { throw new MobileExtensionError('invalid_action_input', 'action input is invalid', 400) }\n const lifetime = 'host' in extension ? combineSignalLifetime(extension.controller.signal, context.signal) : undefined\n const signal = lifetime?.signal ?? context.signal\n try { return await action.run({ ...context, signal }, parsed) } catch (error) {\n if (error instanceof MobileExtensionError) throw error\n throw new MobileExtensionError('extension_failed', 'extension action failed', 500)\n } finally { lifetime?.cleanup() }\n }\n\n /** Match one route and invoke it with a generation-bound abort signal. */\n async route(id: string, method: string, pathname: string, request: MobileRouteRequest, generation?: string): Promise<MobileRouteResponse> {\n const extension = this.extension(id, generation)\n if (extension === undefined) throw new MobileExtensionError('extension_not_found', 'extension not found', 404)\n const definition = 'host' in extension ? extension.host : extension\n const route = definition.routes?.find((candidate: MobileHostRoute) => {\n if (candidate.method !== method) return false\n return (candidate.kind ?? 'exact') === 'exact'\n ? candidate.path === pathname\n : pathname === candidate.path || pathname.startsWith(`${candidate.path}/`)\n })\n if (route === undefined) throw new MobileExtensionError('route_not_found', 'route not found', 404)\n const lifetime = 'host' in extension ? combineSignalLifetime(extension.controller.signal, request.signal) : undefined\n let releaseLifetime = true\n try {\n const routeRequest = lifetime === undefined ? request : { ...request, signal: lifetime.signal }\n const result = await route.handle(routeRequest)\n if (result === null || typeof result !== 'object' || typeof result.body !== 'string' && !(result.body instanceof Uint8Array) && !isReadable(result.body)) {\n throw new MobileExtensionError('invalid_route_response', 'extension returned an invalid response', 500)\n }\n if (lifetime !== undefined && isReadable(result.body)) {\n releaseLifetime = false\n releaseSignalLifetimeWhenStreamSettles(result.body, lifetime.cleanup)\n }\n return result\n } catch (error) {\n if (error instanceof MobileExtensionError) throw error\n throw new MobileExtensionError('extension_failed', 'extension route failed', 500)\n } finally { if (releaseLifetime) lifetime?.cleanup() }\n }\n\n /** Start the local directory watcher; an absent directory is intentionally inert. */\n async startLocal(root: string, context: Context): Promise<void> {\n const targetRoot = resolve(root)\n if (this.localRoot !== undefined && resolve(this.localRoot) !== targetRoot) await this.stopLocal()\n if (this.localTimer !== undefined) clearInterval(this.localTimer)\n const lifecycle = ++this.localLifecycle\n this.localRoot = targetRoot; this.localContext = context; this.localClosed = false\n await mkdir(this.localRoot, { recursive: true })\n if (this.localClosed || this.localLifecycle !== lifecycle || this.localRoot !== targetRoot || this.localContext !== context) return\n await this.refreshLocal()\n if (this.localClosed || this.localLifecycle !== lifecycle || this.localRoot !== targetRoot || this.localContext !== context) return\n this.localTimer = setInterval(() => { void this.refreshLocal() }, 2_000)\n this.localTimer.unref()\n }\n\n /** Stop the watcher and abort every local host generation. */\n async stopLocal(): Promise<void> {\n this.localClosed = true\n const lifecycle = ++this.localLifecycle\n if (this.localTimer !== undefined) clearInterval(this.localTimer)\n this.localTimer = undefined\n const refreshing = this.localRefreshing\n this.localRefreshAbort?.abort()\n const previous = [...this.local.values(), ...[...this.retired.values()].map(entry => entry.active)]\n this.local.clear()\n for (const entry of this.retired.values()) clearTimeout(entry.timer)\n this.retired.clear()\n this.failures.clear()\n this.updateContentHash()\n await Promise.allSettled([\n abortAndDisposeLocal(previous),\n ...(refreshing === undefined ? [] : [refreshing]),\n ])\n if (this.localLifecycle !== lifecycle) return\n const late = [...this.local.values(), ...[...this.retired.values()].map(entry => entry.active)]\n this.local.clear()\n for (const entry of this.retired.values()) clearTimeout(entry.timer)\n this.retired.clear()\n this.failures.clear()\n this.updateContentHash()\n await abortAndDisposeLocal(late)\n if (this.localTimer !== undefined) clearInterval(this.localTimer)\n this.localTimer = undefined\n }\n\n /** Refresh all local extensions atomically; failures keep the previous snapshot. */\n refreshLocal(): Promise<void> {\n if (this.localRefreshing !== undefined) return this.localRefreshing\n const controller = new AbortController()\n this.localRefreshAbort = controller\n const refreshing = this.stageAndCommit(controller.signal).finally(() => {\n if (this.localRefreshing === refreshing) this.localRefreshing = undefined\n if (this.localRefreshAbort === controller) this.localRefreshAbort = undefined\n })\n this.localRefreshing = refreshing\n return refreshing\n }\n\n private async stageAndCommit(signal: AbortSignal): Promise<void> {\n if (this.localClosed || signal.aborted || this.localRoot === undefined || this.localContext === undefined) return\n let names: string[] = []\n try {\n const directory = await opendir(this.localRoot)\n try { for await (const entry of directory) if (entry.isDirectory() && !entry.isSymbolicLink()) names.push(entry.name) }\n finally { await directory.close().catch(() => undefined) }\n } catch { return }\n names.sort()\n const staged: ActiveLocalExtension[] = []\n const stagedFresh: ActiveLocalExtension[] = []\n let failingName = 'local'\n try {\n for (const name of names) {\n signal.throwIfAborted()\n failingName = name\n const directory = join(this.localRoot, name)\n const fingerprint = await extensionFingerprint(directory)\n const current = this.local.get(fingerprint.manifest.id)\n const retired = this.retired.get(fingerprint.manifest.id)?.active\n const previous = current?.digest === fingerprint.digest ? current : retired?.digest === fingerprint.digest ? retired : undefined\n if (previous?.digest === fingerprint.digest) staged.push(previous)\n else {\n const fresh = await loadLocalExtension(directory, this.localContext, fingerprint, signal)\n try {\n signal.throwIfAborted()\n const confirmed = await extensionFingerprint(directory)\n if (confirmed.digest !== fingerprint.digest) {\n throw new MobileExtensionError('extension_changed_during_activation', `extension ${fingerprint.manifest.id} changed during activation`, 409)\n }\n } catch (error) {\n await abortAndDisposeLocal([fresh])\n throw error\n }\n staged.push(fresh); stagedFresh.push(fresh)\n }\n }\n if (this.localClosed || signal.aborted || this.localRoot === undefined || this.localContext === undefined) {\n await abortAndDisposeLocal(stagedFresh)\n return\n }\n const duplicate = new Set<string>()\n for (const entry of staged) {\n if (duplicate.has(entry.manifest.id) || this.registered.has(entry.manifest.id)) throw new MobileExtensionError('duplicate_extension', `duplicate extension id ${entry.manifest.id}`)\n duplicate.add(entry.manifest.id)\n }\n const previous = [...this.local.values()]\n for (const entry of staged) {\n const retired = this.retired.get(entry.manifest.id)\n if (retired?.active === entry) {\n clearTimeout(retired.timer)\n this.retired.delete(entry.manifest.id)\n }\n }\n const stagedIds = new Set(staged.map(entry => entry.manifest.id))\n const removed: ActiveLocalExtension[] = []\n for (const entry of previous) {\n if (staged.includes(entry)) continue\n if (stagedIds.has(entry.manifest.id)) {\n this.retire(entry)\n continue\n }\n removed.push(entry)\n const retired = this.retired.get(entry.manifest.id)\n if (retired !== undefined) {\n clearTimeout(retired.timer)\n this.retired.delete(entry.manifest.id)\n removed.push(retired.active)\n }\n }\n this.local.clear()\n for (const entry of staged) this.local.set(entry.manifest.id, entry)\n for (const entry of staged) this.failures.delete(entry.manifest.id)\n for (const name of names) this.failures.delete(name)\n for (const failure of this.failures.keys()) {\n if (failure !== 'local' && !names.includes(failure)) this.failures.delete(failure)\n }\n this.failures.delete('local')\n if (removed.length > 0) void abortAndDisposeLocal(removed)\n this.updateContentHash()\n } catch (error) {\n await abortAndDisposeLocal(stagedFresh)\n if (this.localClosed || signal.aborted) return\n const message = error instanceof Error ? error.message : String(error)\n this.failures.set(failingName, message)\n if (!(error instanceof MobileExtensionError)) this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error)))\n }\n }\n\n private retire(active: ActiveLocalExtension): void {\n const previous = this.retired.get(active.manifest.id)\n if (previous?.active === active) return\n if (previous !== undefined) {\n clearTimeout(previous.timer)\n this.retired.delete(active.manifest.id)\n void abortAndDisposeLocal([previous.active])\n }\n const timer = setTimeout(() => {\n const current = this.retired.get(active.manifest.id)\n if (current?.active !== active) return\n this.retired.delete(active.manifest.id)\n void abortAndDisposeLocal([active])\n }, RETIRED_GENERATION_TTL_MS)\n timer.unref()\n this.retired.set(active.manifest.id, { active, timer })\n }\n}\n\nfunction isReadable(value: unknown): value is Readable {\n return value !== null && typeof value === 'object' && typeof (value as { pipe?: unknown }).pipe === 'function'\n}\n\nfunction releaseSignalLifetimeWhenStreamSettles(stream: Readable, cleanup: () => void): void {\n let stopObserving: (() => void) | undefined\n stopObserving = finished(stream, () => {\n stopObserving?.()\n cleanup()\n })\n}\n\nfunction invokeCleanups(cleanups: readonly (() => void | Promise<void>)[]): Promise<unknown>[] {\n const pending: Promise<unknown>[] = []\n for (const cleanup of [...cleanups].reverse()) {\n try { pending.push(Promise.resolve(cleanup())) } catch { /* extension teardown cannot block the owner */ }\n }\n return pending\n}\n\nasync function settleBounded(pending: readonly Promise<unknown>[], timeoutMs: number): Promise<void> {\n if (pending.length === 0) return\n let timer: NodeJS.Timeout | undefined\n await Promise.race([\n Promise.allSettled(pending),\n new Promise<void>(resolveTimeout => { timer = setTimeout(resolveTimeout, timeoutMs) }),\n ])\n if (timer !== undefined) clearTimeout(timer)\n}\n\nasync function abortAndDisposeLocal(entries: readonly ActiveLocalExtension[]): Promise<void> {\n const pending: Promise<unknown>[] = []\n for (const entry of entries) {\n entry.controller.abort()\n pending.push(...invokeCleanups(entry.cleanups))\n }\n await settleBounded(pending, HOST_TEARDOWN_TIMEOUT_MS)\n}\n\nasync function loadLocalExtension(directory: string, context: Context, known?: LocalExtensionFingerprint, parentSignal?: AbortSignal): Promise<ActiveLocalExtension> {\n const root = await realExtensionRoot(directory)\n const manifestFile = await regularFile(join(root, 'extension.json'), EXTENSION_LIMITS.manifest, 'extension.json')\n const manifest = known?.manifest ?? parseExtensionManifest(JSON.parse(await readFile(manifestFile.path, 'utf8')) as unknown)\n if (manifest.id !== basename(root)) throw new MobileExtensionError('invalid_manifest', 'extension id must match its directory name')\n const scriptBody = known === undefined\n ? await optionalFile(root, 'mobile.js', EXTENSION_LIMITS.script, 'mobile.js').then(path => path === undefined ? undefined : readFile(path))\n : known.scriptBody\n const styleBody = known === undefined\n ? await optionalFile(root, 'mobile.css', EXTENSION_LIMITS.css, 'mobile.css').then(path => path === undefined ? undefined : readFile(path))\n : known.styleBody\n const assets = known?.assets ?? await assetSnapshot(root)\n const hostFile = await optionalFile(root, 'host.mjs', EXTENSION_LIMITS.script, 'host.mjs')\n const controller = new AbortController()\n const actions: Record<string, MobileHostAction> = {}\n const routes: MobileHostRoute[] = []\n const cleanups: (() => void | Promise<void>)[] = []\n const pendingEffects: Promise<void>[] = []\n let activationOpen = true\n const onParentAbort = (): void => { controller.abort(parentSignal?.reason) }\n if (parentSignal?.aborted === true) onParentAbort()\n else parentSignal?.addEventListener('abort', onParentAbort, { once: true })\n const ensureActivationOpen = (): void => {\n if (!activationOpen || controller.signal.aborted) throw new MobileExtensionError('host_activation_closed', `extension ${manifest.id} activation is closed`, 409)\n }\n const api: HostApi = {\n manifest,\n context,\n schema: z,\n signal: controller.signal,\n action(name, spec) { ensureActivationOpen(); if (actions[name] !== undefined) throw new MobileExtensionError('duplicate_action', `duplicate action ${name}`); actions[name] = spec },\n route(spec) { ensureActivationOpen(); routes.push(spec) },\n effect(setup) {\n ensureActivationOpen()\n const result = setup()\n if (result instanceof Promise) {\n pendingEffects.push(result.then(async cleanup => {\n if (typeof cleanup !== 'function') return\n if (activationOpen) cleanups.push(cleanup)\n else await cleanup()\n }))\n } else if (typeof result === 'function') {\n if (activationOpen) cleanups.push(result)\n else void Promise.resolve(result()).catch(() => undefined)\n }\n },\n }\n try {\n const activate = async (): Promise<void> => {\n controller.signal.throwIfAborted()\n if (hostFile !== undefined) {\n const digest = createHash('sha256').update(await readFile(hostFile)).digest('hex')\n controller.signal.throwIfAborted()\n let imported: LocalHostModule\n try { imported = await import(`${pathToFileURL(hostFile).href}?dsh_generation=${digest}`) as LocalHostModule }\n catch { throw new MobileExtensionError('host_load_failed', `could not load ${manifest.id}/host.mjs`, 500) }\n controller.signal.throwIfAborted()\n if (imported.default !== undefined) await imported.default(api)\n }\n await Promise.all(pendingEffects)\n }\n await withActivationTimeout(activate(), manifest.id, controller.signal)\n const host = validateDefinition({ ...manifest, actions, routes })\n activationOpen = false\n const digest = known?.digest ?? createHash('sha256').update(manifest.id).digest('hex')\n return Object.freeze({ manifest, directory: root, ...(scriptBody === undefined ? {} : { scriptBody }), ...(styleBody === undefined ? {} : { styleBody }), assets, host, controller, cleanups: Object.freeze(cleanups), digest })\n } catch (error) {\n activationOpen = false\n controller.abort()\n const cleanupPromises = invokeCleanups(cleanups.splice(0))\n await settleBounded([...pendingEffects, ...cleanupPromises], HOST_TEARDOWN_TIMEOUT_MS)\n throw error\n } finally {\n parentSignal?.removeEventListener('abort', onParentAbort)\n }\n}\n\n/** Construct the service in a Cordis plugin without importing DSH internals. */\nexport function createMobileAccessService(ctx: Context): MobileAccessService {\n return new MobileAccessService(ctx)\n}\n","#!/usr/bin/env node\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport { preferredLanInterfaceNames, selectLanNetwork } from './managed-setup.js'\nimport { prepareManagedLanSetup, removeWindowsFirewall } from './lan-setup.js'\nimport { assertExtensionId } from './extensions.js'\nimport { restrictPrivateFile } from './private-file.js'\n\ninterface SetupOptions {\n readonly address?: string\n readonly port: number\n readonly dshPort: number\n readonly configureFirewall: boolean\n}\n\nfunction parseOptions(args: readonly string[]): SetupOptions {\n let address: string | undefined\n let port = 3443\n let dshPort = 3080\n let configureFirewall = true\n for (let index = 0; index < args.length; index += 1) {\n const name = args[index]\n const value = args[index + 1]\n if (name === '--address' && value !== undefined) {\n address = value\n index += 1\n continue\n }\n if (name === '--port' && value !== undefined) {\n port = Number(value)\n index += 1\n continue\n }\n if (name === '--dsh-port' && value !== undefined) {\n dshPort = Number(value)\n index += 1\n continue\n }\n if (name === '--no-firewall') {\n configureFirewall = false\n continue\n }\n throw new Error(`unknown setup option: ${name ?? ''}`)\n }\n if (!Number.isSafeInteger(port) || port < 1024 || port > 65535) throw new Error('--port must be from 1024 through 65535')\n if (!Number.isSafeInteger(dshPort) || dshPort < 1024 || dshPort > 65535) throw new Error('--dsh-port must be from 1024 through 65535')\n return { ...(address === undefined ? {} : { address }), port, dshPort, configureFirewall }\n}\n\nfunction dshHome(): string {\n return resolve(process.env.DSH_HOME ?? join(homedir(), '.dsh'))\n}\n\nasync function setup(args: readonly string[]): Promise<void> {\n const options = parseOptions(args)\n const preferredInterfaces = options.address === undefined ? await preferredLanInterfaceNames() : []\n const network = selectLanNetwork(options.address, undefined, undefined, preferredInterfaces)\n const home = dshHome()\n const directory = join(home, 'mobile-access')\n await mkdir(directory, { recursive: true, mode: 0o700 })\n const customCss = join(directory, 'mobile.css')\n try {\n await readFile(customCss)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await writeFile(customCss, [\n '/* Safe mobile overrides. DSH Mobile applies saved changes on the phone automatically. */',\n ':root {',\n ' --dsh-mobile-accent: #2563eb;',\n ' --dsh-mobile-font-scale: 1;',\n ' --dsh-mobile-radius: 14px;',\n '}',\n '',\n ].join('\\n'), { mode: 0o600 })\n }\n\n const customScript = join(directory, 'mobile.js')\n try {\n await readFile(customScript)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await writeFile(customScript, [\n '/* Mount mobile-only Web features here. Saved changes are applied automatically. */',\n 'window.dshMobile.register(({ root }) => {',\n ' root.replaceChildren()',\n ' return () => root.replaceChildren()',\n '})',\n '',\n ].join('\\n'), { mode: 0o600 })\n }\n\n const extensions = join(directory, 'extensions')\n await mkdir(extensions, { recursive: true, mode: 0o700 })\n await createExtensionScaffold(extensions, 'custom', '自定义移动扩展', false)\n\n if (options.configureFirewall && process.platform === 'win32') {\n console.log('Windows will request administrator approval for two LAN-only firewall rules.')\n }\n const result = await prepareManagedLanSetup({\n setupFile: join(directory, 'setup.json'),\n controlFile: join(directory, 'control.json'),\n network,\n listenPort: options.port,\n dshPort: options.dshPort,\n configureFirewall: options.configureFirewall,\n })\n\n console.log(`DSH Mobile follows ${network.name} and is currently configured for ${result.origin}`)\n console.log(`Install this CA certificate on Android once: ${result.androidCertificate}`)\n console.log(`Ask DSH to customize the mobile Web UI and features in: ${customCss} and ${customScript}`)\n console.log(`Additional extensions live in: ${extensions}`)\n console.log('Start DSH with: dsh --profile web')\n console.log('Then open the Mobile card in the lower-left corner and create a pairing key.')\n}\n\nasync function createExtensionScaffold(root: string, id: string, name: string, refuseExisting = true): Promise<void> {\n assertExtensionId(id)\n await mkdir(root, { recursive: true, mode: 0o700 })\n const directory = join(root, id)\n try {\n await mkdir(directory, { recursive: false, mode: 0o700 })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST' && !refuseExisting) return\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new Error(`extension directory already exists: ${id}`)\n throw error\n }\n const files: Readonly<Record<string, string>> = {\n 'extension.json': `${JSON.stringify({ schemaVersion: 1, id, name, version: '0.1.0', description: '在手机端扩展 DSH' }, null, 2)}\\n`,\n 'host.mjs': `export default async function activate(api) {\\n api.action('hello', {\\n input: api.schema.object({ name: api.schema.string().max(80) }),\\n async run({ signal, deviceId }, input) {\\n void signal; void deviceId\\n return { message: \\`Hello, \\${input.name}\\` }\\n },\\n })\\n}\\n`,\n 'mobile.js': `window.dshMobile?.define?.({\\n apiVersion: 1,\\n id: '${id}',\\n activate(api) {\\n return api.ui.registerSurface({\\n id: '${id}-page', placement: 'page', label: ${JSON.stringify(name)},\\n mount(container) {\\n container.textContent = ${JSON.stringify(`这是 ${name} 的移动页面。`)}\\n return () => container.replaceChildren()\\n },\\n })\\n },\\n})\\n`,\n 'mobile.css': `/* ${name.replaceAll('*/', '* /')} 的移动端样式。保存后通常会在几秒内刷新。 */\\n`,\n }\n try {\n for (const [file, contents] of Object.entries(files)) await writeFile(join(directory, file), contents, { encoding: 'utf8', flag: 'wx', mode: 0o600 })\n } catch (error) {\n await rm(directory, { recursive: true, force: true })\n throw error\n }\n console.log(`Created extension: ${directory}`)\n}\n\nasync function extensionCommand(args: readonly string[]): Promise<void> {\n const [subcommand, id, ...rest] = args\n if (subcommand !== 'create' || id === undefined) throw new Error('usage: extension create <id> [--name <name>]')\n let name = id\n for (let index = 0; index < rest.length; index += 1) {\n if (rest[index] === '--name' && rest[index + 1] !== undefined) { name = rest[index + 1]!; index += 1; continue }\n throw new Error(`unknown extension option: ${rest[index] ?? ''}`)\n }\n if (name.length === 0 || name.length > 120 || /[\\u0000-\\u001f\\u007f]/u.test(name)) throw new Error('--name is invalid')\n await createExtensionScaffold(join(dshHome(), 'mobile-access', 'extensions'), id, name)\n}\n\nasync function purge(args: readonly string[]): Promise<void> {\n if (args.length !== 1 || args[0] !== '--yes') throw new Error('purge requires --yes')\n const home = dshHome()\n await rm(join(home, 'mobile-access'), { recursive: true, force: true })\n await removeWindowsFirewall()\n console.log('Removed DSH Mobile certificates, devices, preferences, and custom Web files.')\n}\n\nfunction help(): void {\n console.log([\n 'dsh-mobile setup [--address 192.168.x.x] [--port 3443] [--dsh-port 3080] [--no-firewall]',\n 'dsh-mobile extension create <id> [--name <name>]',\n 'dsh-mobile purge --yes',\n '',\n 'Run through the DSH profile:',\n ' dsh plugin --profile web exec dsh-mobile setup',\n ].join('\\n'))\n}\n\nasync function main(): Promise<void> {\n const [command = 'help', ...args] = process.argv.slice(2)\n if (command === 'setup') await setup(args)\n else if (command === 'extension') await extensionCommand(args)\n else if (command === 'purge') await purge(args)\n else if (command === 'help' || command === '--help' || command === '-h') help()\n else throw new Error(`unknown command: ${command}`)\n}\n\nmain().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error))\n process.exitCode = 1\n})\n"],"mappings":";;;;;;;;;;;AAGA,SAAgB,aACd,MACA,MACA,UAAqE,CAAC,GACzB;CAC7C,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,SAAS,MAAM,CAAC,GAAG,IAAI,GAAG;GAAE,aAAa;GAAM,GAAG;GAAS,UAAU;EAAO,IAAI,OAAO,QAAQ,WAAW;GACxG,IAAI,UAAU,MAAM;IAAE,OAAO,KAAK;IAAG;GAAO;GAC5C,IAAI,OAAO,WAAW,YAAY,OAAO,WAAW,UAAU;IAC5D,uBAAO,IAAI,MAAM,yCAAyC,CAAC;IAC3D;GACF;GACA,QAAQ;IAAE;IAAQ;GAAO,CAAC;EAC5B,CAAC;CACH,CAAC;AACH;;;ACfA,IAAI;AAEJ,eAAe,wBAAyC;CACtD,gBAAgBA,aAAS,cAAc;EAAC;EAAS;EAAO;EAAO;CAAK,GAAG;EACrE,UAAU;EACV,aAAa;EACb,SAAS;CACX,CAAC,CAAC,CAAC,MAAM,EAAE,aAAa;EACtB,MAAM,QAAQ,0BAA0B,KAAK,OAAO,KAAK,CAAC;EAC1D,IAAI,QAAQ,OAAO,KAAA,GAAW,MAAM,IAAI,MAAM,gDAAgD;EAC9F,OAAO,MAAM;CACf,CAA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;CACpF,MAAM,OAAO,QAAQ;CACrB,MAAM,GAAG,KAAK,MAAM,eAAe,GAAG;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;CACtE,MAAM,sBAAsB;CAC5B,QAAQ,IAAI,8EAA8E;AAC5F;AAEA,SAAS,OAAa;CACpB,QAAQ,IAAI;EACV;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI,CAAC;AACd;AAEA,eAAe,OAAsB;CACnC,MAAM,CAAC,UAAU,QAAQ,GAAG,QAAQ,QAAQ,KAAK,MAAM,CAAC;CACxD,IAAI,YAAY,SAAS,MAAM,MAAM,IAAI;MACpC,IAAI,YAAY,aAAa,MAAM,iBAAiB,IAAI;MACxD,IAAI,YAAY,SAAS,MAAM,MAAM,IAAI;MACzC,IAAI,YAAY,UAAU,YAAY,YAAY,YAAY,MAAM,KAAK;MACzE,MAAM,IAAI,MAAM,oBAAoB,SAAS;AACpD;AAEA,KAAK,CAAC,CAAC,OAAO,UAAmB;CAC/B,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;CACpE,QAAQ,WAAW;AACrB,CAAC"}
|
|
1
|
+
{"version":3,"file":"cli.js","names":["execFile","execFile","execFile"],"sources":["../src/exec-file.ts","../src/private-file.ts","../src/managed-setup.ts","../src/lan-setup.ts","../src/extensions.ts","../src/cli.ts"],"sourcesContent":["import { execFile, type ExecFileOptions } from 'node:child_process'\n\n/** Capture both output streams even when a desktop host wraps execFile without Node's promisify metadata. */\nexport function execFileText(\n file: string,\n args: readonly string[],\n options: Omit<ExecFileOptions, 'encoding'> & { encoding?: 'utf8' } = {},\n): Promise<{ stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n execFile(file, [...args], { windowsHide: true, ...options, encoding: 'utf8' }, (error, stdout, stderr) => {\n if (error !== null) { reject(error); return }\n if (typeof stdout !== 'string' || typeof stderr !== 'string') {\n reject(new Error('subprocess returned invalid text output'))\n return\n }\n resolve({ stdout, stderr })\n })\n })\n}\n","import { chmod } from 'node:fs/promises'\nimport { execFileText as execFile } from './exec-file.js'\n\nlet userSidTask: Promise<string> | undefined\n\nasync function currentWindowsUserSid(): Promise<string> {\n userSidTask ??= execFile('whoami.exe', ['/user', '/fo', 'csv', '/nh'], {\n encoding: 'utf8',\n windowsHide: true,\n timeout: 10_000,\n }).then(({ stdout }) => {\n const match = /,\"(S-\\d(?:-\\d+)+)\"\\s*$/u.exec(stdout.trim())\n if (match?.[1] === undefined) throw new Error('unable to resolve the current Windows user SID')\n return match[1]\n }).catch((error: unknown) => {\n userSidTask = undefined\n throw error\n })\n return userSidTask\n}\n\n/** Restrict a sensitive regular file to the current user and Windows administrators. */\nexport async function restrictPrivateFile(file: string, mode = 0o600): Promise<void> {\n await chmod(file, mode)\n if (process.platform !== 'win32') return\n const userSid = await currentWindowsUserSid()\n await execFile('icacls.exe', [\n file,\n '/inheritance:r',\n '/grant:r',\n `*${userSid}:(F)`,\n '*S-1-5-18:(F)',\n '*S-1-5-32-544:(F)',\n '/remove:g',\n '*S-1-1-0',\n '*S-1-5-11',\n '*S-1-5-32-545',\n ], { encoding: 'utf8', windowsHide: true, timeout: 10_000 })\n}\n","import {\n X509Certificate,\n createPrivateKey,\n createPublicKey,\n} from 'node:crypto'\nimport { execFileText as execFile } from './exec-file.js'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { networkInterfaces, type NetworkInterfaceInfo } from 'node:os'\nimport { basename, dirname, join } from 'node:path'\nimport { generate } from 'selfsigned'\nimport { restrictPrivateFile } from './private-file.js'\n\n/** One active private IPv4 address tied to a stable operating-system interface name. */\nexport interface LanNetwork {\n readonly name: string\n readonly address: string\n readonly cidr: string\n}\n\n/** Versioned setup that survives DHCP address changes on the selected interface. */\nexport interface ManagedSetup {\n readonly version: 2\n readonly networkInterface: string\n readonly listenPort: number\n /** Legacy setup snapshot retained for file compatibility; the active WebServer port wins at runtime. */\n readonly upstreamOrigin: string\n readonly tls: {\n readonly mode: 'managed'\n readonly caCertFile: string\n readonly caKeyFile: string\n readonly certFile: string\n readonly keyFile: string\n }\n}\n\ntype InterfaceTable = NodeJS.Dict<NetworkInterfaceInfo[]>\ntype RouteCommand = (file: string, args: readonly string[]) => Promise<string>\n\nconst VIRTUAL_INTERFACE_MARKERS = [\n 'bridge', 'docker', 'hyper-v', 'mihomo', 'radmin', 'tailscale', 'tap', 'tun',\n 'utun', 'vbox', 'veth', 'virtual', 'vmware', 'vpn', 'vethernet', 'wsl', 'zerotier',\n]\n\n/** Route inspection is advisory; never let a system command hold setup open indefinitely. */\nconst ROUTE_COMMAND_TIMEOUT_MS = 5_000\n\nfunction requiredString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.length === 0) throw new Error(`${name} must be a non-empty string`)\n return value\n}\n\n/** Validate the durable managed setup before it controls network and filesystem operations. */\nexport function parseManagedSetup(value: unknown): ManagedSetup {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error('mobile setup file must be an object')\n }\n const record = value as Record<string, unknown>\n if (record.version !== 2 || Reflect.ownKeys(record)\n .some(key => typeof key !== 'string' || !['version', 'networkInterface', 'listenPort', 'upstreamOrigin', 'tls'].includes(key))) {\n throw new Error('mobile setup file has an unsupported format')\n }\n if (!Number.isSafeInteger(record.listenPort) || (record.listenPort as number) < 1024\n || (record.listenPort as number) > 65535) {\n throw new Error('mobile setup listenPort must be from 1024 through 65535')\n }\n if (typeof record.tls !== 'object' || record.tls === null || Array.isArray(record.tls)) {\n throw new Error('mobile setup tls must be an object')\n }\n const tls = record.tls as Record<string, unknown>\n if (tls.mode !== 'managed' || Reflect.ownKeys(tls)\n .some(key => typeof key !== 'string' || !['mode', 'caCertFile', 'caKeyFile', 'certFile', 'keyFile'].includes(key))) {\n throw new Error('mobile setup tls has an unsupported format')\n }\n return Object.freeze({\n version: 2,\n networkInterface: requiredString(record.networkInterface, 'mobile setup networkInterface'),\n listenPort: record.listenPort as number,\n upstreamOrigin: requiredString(record.upstreamOrigin, 'mobile setup upstreamOrigin'),\n tls: Object.freeze({\n mode: 'managed',\n caCertFile: requiredString(tls.caCertFile, 'mobile setup tls.caCertFile'),\n caKeyFile: requiredString(tls.caKeyFile, 'mobile setup tls.caKeyFile'),\n certFile: requiredString(tls.certFile, 'mobile setup tls.certFile'),\n keyFile: requiredString(tls.keyFile, 'mobile setup tls.keyFile'),\n }),\n })\n}\n\nfunction privateIpv4(value: string): boolean {\n const parts = value.split('.').map(Number)\n return parts.length === 4 && parts.every(part => Number.isInteger(part) && part >= 0 && part <= 255)\n && (parts[0] === 10\n || (parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31)\n || (parts[0] === 192 && parts[1] === 168))\n}\n\nfunction networkCidr(address: string, cidr: string): string {\n const prefix = Number(cidr.slice(cidr.lastIndexOf('/') + 1))\n const value = address.split('.').reduce((total, part) => ((total << 8) | Number(part)) >>> 0, 0)\n const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0\n const network = (value & mask) >>> 0\n return `${[24, 16, 8, 0].map(shift => (network >>> shift) & 255).join('.')}/${String(prefix)}`\n}\n\n/** List current private IPv4 candidates with their interface identity. */\nexport function availableLanNetworks(table: InterfaceTable = networkInterfaces()): LanNetwork[] {\n const candidates = Object.entries(table).flatMap(([name, entries]) => (entries ?? [])\n .filter(entry => entry.family === 'IPv4' && !entry.internal && privateIpv4(entry.address) && entry.cidr !== null)\n .map(entry => ({ name, address: entry.address, cidr: networkCidr(entry.address, entry.cidr!) })))\n return [...new Map(candidates.map(entry => [`${entry.name}\\0${entry.address}`, entry])).values()]\n}\n\nfunction likelyVirtualInterface(name: string): boolean {\n const normalized = name.toLowerCase().replaceAll(/[^a-z0-9]+/gu, ' ')\n return VIRTUAL_INTERFACE_MARKERS.some(marker => normalized.includes(marker.replaceAll('-', ' ')))\n || /^(?:br|wg)\\d*\\b/u.test(normalized)\n}\n\nasync function runRouteCommand(file: string, args: readonly string[]): Promise<string> {\n const result = await execFile(file, [...args], { encoding: 'utf8', timeout: ROUTE_COMMAND_TIMEOUT_MS })\n return result.stdout\n}\n\nfunction uniqueLines(output: string): string[] {\n return [...new Set(output.split(/\\r?\\n/gu).map(line => line.trim()).filter(Boolean))]\n}\n\n/** Return operating-system default-route interfaces in routing preference order. */\nexport async function preferredLanInterfaceNames(\n platform: NodeJS.Platform = process.platform,\n run: RouteCommand = runRouteCommand,\n): Promise<string[]> {\n try {\n if (platform === 'win32') {\n const script = [\n \"$routes = Get-NetRoute -AddressFamily IPv4 -DestinationPrefix '0.0.0.0/0' -ErrorAction Stop\",\n \"$ranked = $routes | Where-Object { $_.State -eq 'Alive' -and $_.NextHop -ne '0.0.0.0' } | ForEach-Object {\",\n ' $route = $_',\n ' $adapter = Get-NetAdapter -InterfaceIndex $route.InterfaceIndex -ErrorAction SilentlyContinue',\n ' $ip = Get-NetIPInterface -AddressFamily IPv4 -InterfaceIndex $route.InterfaceIndex -ErrorAction SilentlyContinue',\n \" if ($adapter -and $ip -and $adapter.Status -eq 'Up' -and $adapter.HardwareInterface -eq $true -and $adapter.Virtual -ne $true) {\",\n ' [pscustomobject]@{ Name = $route.InterfaceAlias; Metric = [int]$route.RouteMetric + [int]$ip.InterfaceMetric }',\n ' }',\n '}',\n '$ranked | Sort-Object Metric | Select-Object -ExpandProperty Name -Unique',\n ].join('; ')\n return uniqueLines(await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]))\n }\n if (platform === 'linux') {\n const routes = uniqueLines(await run('ip', ['-o', '-4', 'route', 'show', 'default']))\n .map(line => ({\n name: /(?:^|\\s)dev\\s+(\\S+)/u.exec(line)?.[1],\n metric: Number(/(?:^|\\s)metric\\s+(\\d+)/u.exec(line)?.[1] ?? 0),\n }))\n .filter((route): route is { name: string; metric: number } => route.name !== undefined\n && !likelyVirtualInterface(route.name))\n .sort((left, right) => left.metric - right.metric)\n return [...new Set(routes.map(route => route.name))]\n }\n if (platform === 'darwin') {\n const name = /^\\s*interface:\\s*(\\S+)\\s*$/mu.exec(await run('route', ['-n', 'get', 'default']))?.[1]\n return name === undefined || likelyVirtualInterface(name) ? [] : [name]\n }\n } catch {\n // Route discovery is advisory; deterministic candidate checks below remain the fallback.\n }\n return []\n}\n\n/** Select an active LAN, optionally by address or by a previously saved interface name. */\nexport function selectLanNetwork(\n requestedAddress?: string,\n requestedInterface?: string,\n table?: InterfaceTable,\n preferredInterfaces: readonly string[] = [],\n): LanNetwork {\n const candidates = availableLanNetworks(table)\n if (requestedAddress !== undefined) {\n const match = candidates.find(candidate => candidate.address === requestedAddress)\n if (match === undefined) throw new Error(`--address ${requestedAddress} is not an active private LAN address`)\n return match\n }\n if (requestedInterface !== undefined) {\n const matches = candidates.filter(candidate => candidate.name === requestedInterface)\n if (matches.length === 1) return matches[0]!\n if (matches.length === 0) {\n throw new Error(`saved LAN interface ${JSON.stringify(requestedInterface)} is not connected`)\n }\n throw new Error(`saved LAN interface ${JSON.stringify(requestedInterface)} has more than one private IPv4 address`)\n }\n if (candidates.length === 1) return candidates[0]!\n if (candidates.length === 0) throw new Error('no active private LAN address was found; connect to Wi-Fi or Ethernet')\n for (const name of preferredInterfaces) {\n const matches = candidates.filter(candidate => candidate.name === name)\n if (matches.length === 1) return matches[0]!\n }\n const physicalCandidates = candidates.filter(candidate => !likelyVirtualInterface(candidate.name))\n if (physicalCandidates.length === 1) return physicalCandidates[0]!\n throw new Error(`more than one LAN address is active; rerun with --address and one of: ${candidates.map(entry => `${entry.name}=${entry.address}`).join(', ')}`)\n}\n\n/**\n * True when the failure came from LAN selection (the configured network is\n * gone, nothing is up, or several are) rather than from config/TLS code.\n * Callers use it to degrade (warn + stay down) instead of failing boot.\n * Pinned to the selectLanNetwork message contract — keep in sync.\n */\nexport function isNetworkSelectionError(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error ?? '')\n return message.includes('is not connected')\n || message.includes('no active private LAN address was found')\n || message.includes('more than one LAN address is active')\n || message.includes('has more than one private IPv4 address')\n || message.includes('is not an active private LAN address')\n}\n\nfunction assertMatchingCa(certPem: string, keyPem: string): X509Certificate {\n const certificate = new X509Certificate(certPem)\n if (!certificate.ca || certificate.subject !== certificate.issuer\n || !certificate.verify(certificate.publicKey)) {\n throw new Error('managed TLS CA must be a self-signed CA certificate')\n }\n const privatePublic = createPublicKey(createPrivateKey(keyPem)).export({ format: 'der', type: 'spki' })\n const certificatePublic = certificate.publicKey.export({ format: 'der', type: 'spki' })\n if (!privatePublic.equals(certificatePublic)) throw new Error('managed TLS CA certificate and key do not match')\n if (Date.parse(certificate.validFrom) > Date.now() || Date.parse(certificate.validTo) <= Date.now()) {\n throw new Error('managed TLS CA certificate is not currently valid')\n }\n return certificate\n}\n\nasync function atomicWrite(file: string, contents: string | Uint8Array): Promise<void> {\n const directory = dirname(file)\n await mkdir(directory, { recursive: true, mode: 0o700 })\n const temporary = join(directory, `.${basename(file)}.${process.pid}.tmp`)\n await writeFile(temporary, contents, { mode: 0o600 })\n await rename(temporary, file)\n await restrictPrivateFile(file)\n}\n\n/** Create a long-lived CA or migrate the legacy self-signed server certificate as that CA. */\nexport async function ensureManagedCa(\n setup: ManagedSetup['tls'],\n legacy?: { readonly certFile: string; readonly keyFile: string },\n): Promise<X509Certificate> {\n let certPem: string | undefined\n let keyPem: string | undefined\n try {\n [certPem, keyPem] = await Promise.all([readFile(setup.caCertFile, 'utf8'), readFile(setup.caKeyFile, 'utf8')])\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n let migrated = false\n if (legacy !== undefined) {\n try {\n [certPem, keyPem] = await Promise.all([readFile(legacy.certFile, 'utf8'), readFile(legacy.keyFile, 'utf8')])\n assertMatchingCa(certPem, keyPem)\n migrated = true\n } catch (legacyError) {\n if ((legacyError as NodeJS.ErrnoException).code !== 'ENOENT') throw legacyError\n }\n }\n if (!migrated) {\n const now = new Date()\n const notAfter = new Date(now)\n notAfter.setFullYear(notAfter.getFullYear() + 5)\n const generated = await generate([{ name: 'commonName', value: 'DeepSeek Harness Mobile CA' }], {\n keyType: 'ec',\n curve: 'P-256',\n algorithm: 'sha256',\n notBeforeDate: new Date(now.getTime() - 5 * 60_000),\n notAfterDate: notAfter,\n extensions: [\n { name: 'basicConstraints', cA: true, critical: true },\n { name: 'keyUsage', digitalSignature: true, keyCertSign: true, cRLSign: true, critical: true },\n ],\n })\n certPem = generated.cert\n keyPem = generated.private\n }\n if (certPem === undefined || keyPem === undefined) throw new Error('managed TLS CA creation did not produce key material')\n await Promise.all([atomicWrite(setup.caCertFile, certPem), atomicWrite(setup.caKeyFile, keyPem)])\n }\n if (certPem === undefined || keyPem === undefined) throw new Error('managed TLS CA creation did not produce key material')\n await Promise.all([restrictPrivateFile(setup.caCertFile), restrictPrivateFile(setup.caKeyFile)])\n return assertMatchingCa(certPem, keyPem)\n}\n\n/** Sign and atomically install a server leaf for the interface's current address. */\nexport async function refreshManagedServerCertificate(setup: ManagedSetup, address: string): Promise<void> {\n await Promise.all([restrictPrivateFile(setup.tls.caCertFile), restrictPrivateFile(setup.tls.caKeyFile)])\n const [caCert, caKey] = await Promise.all([\n readFile(setup.tls.caCertFile, 'utf8'),\n readFile(setup.tls.caKeyFile, 'utf8'),\n ])\n assertMatchingCa(caCert, caKey)\n const now = new Date()\n const notAfter = new Date(now)\n notAfter.setDate(notAfter.getDate() + 397)\n const server = await generate([{ name: 'commonName', value: 'DeepSeek Harness Mobile' }], {\n keyType: 'ec',\n curve: 'P-256',\n algorithm: 'sha256',\n notBeforeDate: new Date(now.getTime() - 5 * 60_000),\n notAfterDate: notAfter,\n ca: { cert: caCert, key: caKey },\n extensions: [\n { name: 'basicConstraints', cA: false, critical: true },\n { name: 'keyUsage', digitalSignature: true, critical: true },\n { name: 'extKeyUsage', serverAuth: true },\n { name: 'subjectAltName', altNames: [{ type: 7, ip: address }] },\n ],\n })\n await Promise.all([\n atomicWrite(setup.tls.certFile, server.cert),\n atomicWrite(setup.tls.keyFile, server.private),\n ])\n}\n\n/** Resolve the saved interface to the ordinary gateway config consumed by the Host plugin. */\nexport async function materializeManagedSetup(\n setup: ManagedSetup,\n table?: InterfaceTable,\n): Promise<Record<string, unknown>> {\n const network = selectLanNetwork(undefined, setup.networkInterface, table)\n await refreshManagedServerCertificate(setup, network.address)\n const ca = new X509Certificate(await readFile(setup.tls.caCertFile, 'utf8'))\n return {\n publicOrigin: `https://${network.address}:${String(setup.listenPort)}`,\n listenHost: network.address,\n allowedCidrs: [network.cidr],\n instanceId: ca.fingerprint256.replaceAll(':', '').toLowerCase(),\n pairingCaFile: setup.tls.caCertFile,\n tls: {\n mode: 'provided',\n certFile: setup.tls.certFile,\n keyFile: setup.tls.keyFile,\n },\n }\n}\n","import { execFileText as execFile } from './exec-file.js'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join } from 'node:path'\nimport {\n ensureManagedCa,\n refreshManagedServerCertificate,\n type LanNetwork,\n type ManagedSetup,\n} from './managed-setup.js'\nimport { restrictPrivateFile } from './private-file.js'\n\nconst FIREWALL_TCP_RULE = 'DSH Mobile HTTPS'\nconst FIREWALL_UDP_RULE = 'DSH Mobile Discovery'\n\n/** Files and active address produced by one explicit LAN setup confirmation. */\nexport interface ManagedLanSetupResult {\n readonly setup: ManagedSetup\n readonly network: LanNetwork\n readonly origin: string\n readonly androidCertificate: string\n}\n\n/** Inputs required to prepare the managed LAN listener without starting it. */\nexport interface ManagedLanSetupOptions {\n readonly setupFile: string\n readonly controlFile: string\n readonly network: LanNetwork\n readonly listenPort: number\n readonly dshPort: number\n readonly configureFirewall: boolean\n}\n\nasync function runElevatedPowerShell(script: string): Promise<void> {\n const encoded = Buffer.from(script, 'utf16le').toString('base64')\n const launch = [\n \"$ErrorActionPreference = 'Stop'; $process = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru\",\n ` -ArgumentList @('-NoProfile','-NonInteractive','-EncodedCommand','${encoded}')`,\n '; exit $process.ExitCode',\n ].join(' ')\n await execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', launch], { windowsHide: true })\n}\n\n/** Install the two Windows inbound rules used by the managed LAN listener. */\nexport async function configureWindowsFirewall(port: number): Promise<void> {\n if (process.platform !== 'win32') return\n const script = [\n \"$ErrorActionPreference = 'Stop'\",\n `Get-NetFirewallRule -DisplayName '${FIREWALL_TCP_RULE}' -ErrorAction SilentlyContinue | Remove-NetFirewallRule`,\n `Get-NetFirewallRule -DisplayName '${FIREWALL_UDP_RULE}' -ErrorAction SilentlyContinue | Remove-NetFirewallRule`,\n `New-NetFirewallRule -DisplayName '${FIREWALL_TCP_RULE}' -Direction Inbound -Action Allow -Protocol TCP -LocalPort ${String(port)} -RemoteAddress LocalSubnet -Profile Any | Out-Null`,\n `New-NetFirewallRule -DisplayName '${FIREWALL_UDP_RULE}' -Direction Inbound -Action Allow -Protocol UDP -LocalPort ${String(port)} -RemoteAddress LocalSubnet -Profile Any | Out-Null`,\n ].join('; ')\n await runElevatedPowerShell(script)\n}\n\n/** Remove only the two Windows firewall rules owned by DSH Mobile. */\nexport async function removeWindowsFirewall(): Promise<void> {\n if (process.platform !== 'win32') return\n await runElevatedPowerShell([\n \"$ErrorActionPreference = 'Stop'\",\n `Get-NetFirewallRule -DisplayName '${FIREWALL_TCP_RULE}' -ErrorAction SilentlyContinue | Remove-NetFirewallRule`,\n `Get-NetFirewallRule -DisplayName '${FIREWALL_UDP_RULE}' -ErrorAction SilentlyContinue | Remove-NetFirewallRule`,\n ].join('; '))\n}\n\n/** Generate private TLS material and persist a managed setup selected by the user. */\nexport async function prepareManagedLanSetup(options: ManagedLanSetupOptions): Promise<ManagedLanSetupResult> {\n if (!isAbsolute(options.setupFile) || !isAbsolute(options.controlFile)) {\n throw new Error('managed LAN setup paths must be absolute')\n }\n if (!Number.isSafeInteger(options.listenPort) || options.listenPort < 1024 || options.listenPort > 65535) {\n throw new Error('managed LAN listenPort must be from 1024 through 65535')\n }\n if (!Number.isSafeInteger(options.dshPort) || options.dshPort < 1024 || options.dshPort > 65535) {\n throw new Error('managed LAN dshPort must be from 1024 through 65535')\n }\n const directory = dirname(options.setupFile)\n const tlsDirectory = join(directory, 'tls')\n await mkdir(tlsDirectory, { recursive: true, mode: 0o700 })\n const managedTls: ManagedSetup['tls'] = {\n mode: 'managed',\n caCertFile: join(tlsDirectory, 'ca.pem'),\n caKeyFile: join(tlsDirectory, 'ca-key.pem'),\n certFile: join(tlsDirectory, 'server-cert.pem'),\n keyFile: join(tlsDirectory, 'server-key.pem'),\n }\n const ca = await ensureManagedCa(managedTls, {\n certFile: join(tlsDirectory, 'cert.pem'),\n keyFile: join(tlsDirectory, 'key.pem'),\n })\n const setup: ManagedSetup = {\n version: 2,\n networkInterface: options.network.name,\n listenPort: options.listenPort,\n upstreamOrigin: `http://127.0.0.1:${String(options.dshPort)}`,\n tls: managedTls,\n }\n await refreshManagedServerCertificate(setup, options.network.address)\n const androidCertificate = join(tlsDirectory, 'dsh-mobile-ca.cer')\n await writeFile(androidCertificate, ca.raw, { mode: 0o600 })\n await Promise.all([\n ...Object.values(managedTls).filter(value => value !== 'managed').map(file => restrictPrivateFile(file)),\n restrictPrivateFile(androidCertificate),\n ])\n if (options.configureFirewall) await configureWindowsFirewall(options.listenPort)\n await Promise.all([\n writeFile(options.setupFile, `${JSON.stringify({\n ...setup,\n tls: Object.fromEntries(Object.entries(setup.tls)\n .map(([key, value]) => [key, typeof value === 'string' ? value.replaceAll('\\\\', '/') : value])),\n }, null, 2)}\\n`, { mode: 0o600 }),\n writeFile(options.controlFile, '{\"version\":1,\"enabled\":true}\\n', { mode: 0o600 }),\n ])\n await Promise.all([restrictPrivateFile(options.setupFile), restrictPrivateFile(options.controlFile)])\n return Object.freeze({\n setup: Object.freeze(setup),\n network: Object.freeze({ ...options.network }),\n origin: `https://${options.network.address}:${String(options.listenPort)}`,\n androidCertificate,\n })\n}\n","import { createHash } from 'node:crypto'\nimport type { Dirent } from 'node:fs'\nimport { lstat, mkdir, opendir, readFile, realpath } from 'node:fs/promises'\nimport { basename, isAbsolute, join, relative, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { Service, type Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport { finished, type Readable } from 'node:stream'\n\n/** Maximum sizes enforced at the local-extension filesystem boundary. */\nexport const EXTENSION_LIMITS = Object.freeze({\n manifest: 64 * 1024,\n script: 1024 * 1024,\n css: 512 * 1024,\n asset: 8 * 1024 * 1024,\n assetFiles: 256,\n assetBytes: 32 * 1024 * 1024,\n assetDepth: 8,\n})\n\n/** A misbehaving host activation must not wedge the local watcher forever. */\nconst HOST_ACTIVATION_TIMEOUT_MS = 5_000\n\n/** The previous Host outlives the hidden-page refresh interval and one timed refresh. */\nconst RETIRED_GENERATION_TTL_MS = 10 * 60_000\n\n/** Extension teardown is advisory and must never stop watcher progress. */\nconst HOST_TEARDOWN_TIMEOUT_MS = 2_000\n\nasync function withActivationTimeout<T>(promise: Promise<T>, id: string, signal: AbortSignal): Promise<T> {\n let timer: NodeJS.Timeout | undefined\n let onAbort: (() => void) | undefined\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new MobileExtensionError('host_load_timeout', `extension ${id} activation timed out`, 500)), HOST_ACTIVATION_TIMEOUT_MS)\n }),\n new Promise<never>((_, reject) => {\n const abort = (): void => { reject(new MobileExtensionError('host_activation_closed', `extension ${id} activation is closed`, 409)) }\n if (signal.aborted) abort()\n else { onAbort = abort; signal.addEventListener('abort', abort, { once: true }) }\n }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)\n }\n}\n\n/** A controlled business failure returned by an extension action or route. */\nexport class MobileExtensionError extends Error {\n constructor(readonly code: string, message: string, readonly status = 400) {\n super(message)\n this.name = 'MobileExtensionError'\n }\n}\n\n/** One host-side action exposed by an extension. */\ntype CallableActionInput = (value?: never, options?: never) => unknown\n\nexport interface MobileHostAction {\n /** A callable Schemastery schema or an adapter exposing parse(). */\n readonly input?: CallableActionInput | { parse(value: unknown): unknown }\n readonly run: (context: MobileActionContext, input: unknown) => unknown | Promise<unknown>\n}\n\n/** Context supplied to a host action. */\nexport interface MobileActionContext {\n readonly signal: AbortSignal\n readonly deviceId: string\n}\n\n/** Safe request values supplied to a host route. */\nexport interface MobileRouteRequest {\n readonly method: string\n readonly pathname: string\n readonly query: Readonly<URLSearchParams>\n readonly headers: Readonly<Record<string, string>>\n readonly body: Uint8Array\n readonly signal: AbortSignal\n readonly deviceId: string\n}\n\n/** Values an extension route may return; status is a final HTTP code from 200 through 599. */\nexport interface MobileRouteResponse {\n readonly status?: number\n readonly contentType?: string\n readonly headers?: Readonly<Record<string, string>>\n readonly body: string | Uint8Array | Readable\n}\n\n/** One host-side route exposed by an extension. */\nexport interface MobileHostRoute {\n readonly method: string\n readonly path: string\n readonly kind?: 'exact' | 'prefix'\n readonly handle: (request: MobileRouteRequest) => MobileRouteResponse | Promise<MobileRouteResponse>\n}\n\n/** Metadata shared by local and npm-provided extensions. */\nexport interface MobileExtensionManifest {\n readonly schemaVersion: 1\n readonly id: string\n readonly name: string\n readonly version: string\n readonly description?: string\n}\n\n/** Definition registered by a normal Cordis plugin. */\nexport interface MobileExtensionDefinition extends MobileExtensionManifest {\n readonly actions?: Readonly<Record<string, MobileHostAction>>\n readonly routes?: readonly MobileHostRoute[]\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n mobileAccess: MobileAccessService\n }\n}\n\n/** A local extension manifest read from extension.json. */\nexport interface LocalExtensionManifest extends MobileExtensionManifest {}\n\n/** Public snapshot sent to the mobile browser. */\nexport interface MobileExtensionClientEntry extends MobileExtensionManifest {\n readonly generation?: string\n readonly scriptUrl?: string\n readonly styleUrl?: string\n readonly assetsUrl?: string\n}\n\ninterface LocalAssetSnapshot {\n readonly body: Buffer\n readonly digest: string\n readonly name: string\n}\n\n/** Small status summary used by the desktop mobile-access card. */\nexport interface MobileExtensionStatus {\n readonly loaded: number\n readonly failed: number\n}\n\ninterface ActiveLocalExtension {\n readonly manifest: LocalExtensionManifest\n readonly directory: string\n readonly scriptBody?: Buffer\n readonly styleBody?: Buffer\n readonly assets: ReadonlyMap<string, LocalAssetSnapshot>\n readonly host: MobileExtensionDefinition\n readonly controller: AbortController\n readonly cleanups: readonly (() => void | Promise<void>)[]\n readonly digest: string\n}\n\ninterface RegisteredExtension {\n readonly definition: MobileExtensionDefinition\n readonly dispose: () => void\n}\n\ninterface RetiredLocalExtension {\n readonly active: ActiveLocalExtension\n readonly timer: NodeJS.Timeout\n}\n\ntype HostApi = {\n readonly manifest: LocalExtensionManifest\n readonly context: Context\n readonly schema: typeof z\n readonly signal: AbortSignal\n action(name: string, spec: MobileHostAction): void\n route(spec: MobileHostRoute): void\n effect(setup: () => void | (() => void | Promise<void>) | Promise<void | (() => void | Promise<void>)>): void\n}\n\ntype LocalHostModule = { readonly default?: (api: HostApi) => void | Promise<void> }\n\n/** Validate user-facing extension text without allowing control characters. */\nfunction text(value: unknown, field: string, maximum: number, required: boolean): string | undefined {\n if (value === undefined && !required) return undefined\n if (typeof value !== 'string' || (required && value.length === 0) || value.length > maximum\n || /[\\u0000-\\u001f\\u007f]/u.test(value)) throw new MobileExtensionError('invalid_manifest', `${field} is invalid`)\n return value\n}\n\n/** Validate a stable extension id. */\nexport function assertExtensionId(value: unknown): string {\n if (typeof value !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/u.test(value)) {\n throw new MobileExtensionError('invalid_manifest', 'extension id is invalid')\n }\n return value\n}\n\n/** Validate a manifest from JSON or a plugin definition. */\nexport function parseExtensionManifest(value: unknown): LocalExtensionManifest {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new MobileExtensionError('invalid_manifest', 'extension.json must be an object')\n }\n const record = value as Record<string, unknown>\n if (record.schemaVersion !== 1) throw new MobileExtensionError('invalid_manifest', 'unsupported extension schema')\n const id = assertExtensionId(record.id)\n const name = text(record.name, 'name', 120, true) as string\n const version = text(record.version, 'version', 64, true) as string\n const description = text(record.description, 'description', 500, false)\n for (const key of Reflect.ownKeys(record)) {\n if (!['schemaVersion', 'id', 'name', 'version', 'description'].includes(String(key))) {\n throw new MobileExtensionError('invalid_manifest', 'extension.json has unknown fields')\n }\n }\n return Object.freeze({ schemaVersion: 1, id, name, version, ...(description === undefined ? {} : { description }) })\n}\n\nfunction normalizeRelativePath(value: string, field: string): string {\n if (value.length === 0 || value.includes('\\0') || isAbsolute(value)) throw new MobileExtensionError('invalid_extension_path', `${field} is invalid`)\n const normalized = value.replaceAll('\\\\', '/')\n if (normalized.split('/').some(part => part === '' || part === '.' || part === '..')) {\n throw new MobileExtensionError('invalid_extension_path', `${field} escapes extension directory`)\n }\n return normalized\n}\n\nasync function regularFile(path: string, maximum: number, field: string): Promise<{ readonly path: string; readonly size: number }> {\n let info\n try { info = await lstat(path) } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw new MobileExtensionError('invalid_extension', `${field} is missing`)\n throw error\n }\n if (!info.isFile() || info.isSymbolicLink() || info.size > maximum) {\n throw new MobileExtensionError('invalid_extension', `${field} must be a regular file within its size limit`)\n }\n return { path, size: info.size }\n}\n\nasync function containedPath(root: string, relativePath: string, maximum: number, field: string): Promise<{ readonly path: string; readonly size: number }> {\n const normalized = normalizeRelativePath(relativePath, field)\n const target = resolve(root, normalized)\n const rootReal = await realpath(root)\n const targetReal = await realpath(target)\n const relation = relative(rootReal, targetReal)\n if (relation === '' || relation.startsWith('..') || isAbsolute(relation)) throw new MobileExtensionError('invalid_extension_path', `${field} escapes extension directory`)\n return regularFile(targetReal, maximum, field)\n}\n\nasync function optionalFile(root: string, name: string, maximum: number, field: string): Promise<string | undefined> {\n try {\n return (await containedPath(root, name, maximum, field)).path\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n if (error instanceof MobileExtensionError && error.message.includes('is missing')) return undefined\n throw error\n }\n}\n\nasync function optionalBytes(root: string, name: string, maximum: number, field: string): Promise<Buffer | undefined> {\n const path = await optionalFile(root, name, maximum, field)\n return path === undefined ? undefined : readFile(path)\n}\n\nfunction assertRealPathWithin(rootReal: string, targetReal: string, field: string): void {\n const relation = relative(rootReal, targetReal)\n if (relation === '' || relation.startsWith('..') || isAbsolute(relation)) {\n throw new MobileExtensionError('invalid_extension_path', `${field} escapes extension directory`)\n }\n}\n\nasync function realExtensionRoot(directory: string): Promise<string> {\n const root = resolve(directory)\n const info = await lstat(root)\n if (!info.isDirectory() || info.isSymbolicLink()) throw new MobileExtensionError('invalid_extension', 'extension directory must be real')\n return realpath(root)\n}\n\nasync function assetSnapshot(extensionRootReal: string): Promise<ReadonlyMap<string, LocalAssetSnapshot>> {\n const assetsPath = join(extensionRootReal, 'assets')\n let assetsInfo\n try { assetsInfo = await lstat(assetsPath) } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return new Map()\n throw error\n }\n if (!assetsInfo.isDirectory() || assetsInfo.isSymbolicLink()) {\n throw new MobileExtensionError('invalid_extension', 'assets must be a real directory')\n }\n const assetsReal = await realpath(assetsPath)\n assertRealPathWithin(extensionRootReal, assetsReal, 'assets')\n const snapshots = new Map<string, LocalAssetSnapshot>()\n let totalBytes = 0\n const visit = async (directoryReal: string, prefix: string, depth: number): Promise<void> => {\n if (depth > EXTENSION_LIMITS.assetDepth) {\n throw new MobileExtensionError('invalid_extension', 'asset tree exceeds its depth limit')\n }\n assertRealPathWithin(extensionRootReal, directoryReal, 'asset directory')\n const handle = await opendir(directoryReal)\n const entries: Dirent[] = []\n try { for await (const entry of handle) entries.push(entry) }\n finally { await handle.close().catch(() => undefined) }\n entries.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)\n for (const entry of entries) {\n const path = join(directoryReal, entry.name)\n const info = await lstat(path)\n if (info.isSymbolicLink()) throw new MobileExtensionError('invalid_extension_path', 'asset escapes extension directory')\n const targetReal = await realpath(path)\n assertRealPathWithin(extensionRootReal, targetReal, 'asset')\n const key = prefix === '' ? entry.name : `${prefix}/${entry.name}`\n if (info.isDirectory()) {\n await visit(targetReal, key, depth + 1)\n continue\n }\n if (!info.isFile() || info.size > EXTENSION_LIMITS.asset) {\n throw new MobileExtensionError('invalid_extension', 'asset must be a regular file within its size limit')\n }\n const body = await readFile(targetReal)\n totalBytes += body.byteLength\n if (snapshots.size >= EXTENSION_LIMITS.assetFiles || totalBytes > EXTENSION_LIMITS.assetBytes) {\n throw new MobileExtensionError('invalid_extension', 'asset tree exceeds its aggregate limit')\n }\n snapshots.set(key, Object.freeze({ body, digest: createHash('sha256').update(body).digest('hex'), name: entry.name }))\n }\n }\n await visit(assetsReal, '', 0)\n return snapshots\n}\n\ninterface LocalExtensionFingerprint {\n readonly manifest: LocalExtensionManifest\n readonly digest: string\n readonly scriptBody?: Buffer\n readonly styleBody?: Buffer\n readonly assets: ReadonlyMap<string, LocalAssetSnapshot>\n}\n\nasync function extensionFingerprint(directory: string): Promise<LocalExtensionFingerprint> {\n const root = await realExtensionRoot(directory)\n const manifestFile = await regularFile(join(root, 'extension.json'), EXTENSION_LIMITS.manifest, 'extension.json')\n const manifestBody = await readFile(manifestFile.path)\n const manifest = parseExtensionManifest(JSON.parse(manifestBody.toString('utf8')) as unknown)\n if (manifest.id !== basename(root)) throw new MobileExtensionError('invalid_manifest', 'extension id must match its directory name')\n const [host, script, style, assets] = await Promise.all([\n optionalBytes(root, 'host.mjs', EXTENSION_LIMITS.script, 'host.mjs'),\n optionalBytes(root, 'mobile.js', EXTENSION_LIMITS.script, 'mobile.js'),\n optionalBytes(root, 'mobile.css', EXTENSION_LIMITS.css, 'mobile.css'),\n assetSnapshot(root),\n ])\n const digest = createHash('sha256').update(`manifest:${manifestBody.byteLength}:`).update(createHash('sha256').update(manifestBody).digest())\n for (const [name, body] of [['host', host], ['script', script], ['style', style]] as const) {\n digest.update(`\\0${name}:${body?.byteLength ?? -1}:`)\n if (body !== undefined) digest.update(createHash('sha256').update(body).digest())\n }\n for (const [name, asset] of assets) {\n digest.update(`\\0asset:${Buffer.byteLength(name)}:${name}:${asset.body.byteLength}:${asset.digest}`)\n }\n return {\n manifest,\n digest: digest.digest('hex'),\n assets,\n ...(script === undefined ? {} : { scriptBody: script }),\n ...(style === undefined ? {} : { styleBody: style }),\n }\n}\n\nfunction routeKey(route: MobileHostRoute): string {\n const method = route.method.toUpperCase()\n const path = normalizeRoutePath(route.path)\n return `${method} ${route.kind ?? 'exact'} ${path}`\n}\n\nfunction normalizeRoutePath(value: string): string {\n if (typeof value !== 'string' || value.length === 0 || value.length > 256\n || value.includes('?') || value.includes('#') || value.includes('\\\\') || value.includes('\\0')\n || /[\\u0000-\\u001f\\u007f]/u.test(value)) throw new MobileExtensionError('invalid_route', 'extension route path is invalid')\n const normalizedInput = value.startsWith('/') ? value : `/${value}`\n const parts = normalizedInput.split('/')\n if (parts.some(part => part === '..' || part === '.')) throw new MobileExtensionError('invalid_route', 'extension route path is invalid')\n return normalizedInput === '/' ? '/' : normalizedInput.replace(/\\/+$/u, '')\n}\n\nfunction validateDefinition(definition: MobileExtensionDefinition): MobileExtensionDefinition {\n const manifest = parseExtensionManifest({\n schemaVersion: definition.schemaVersion,\n id: definition.id,\n name: definition.name,\n version: definition.version,\n ...(definition.description === undefined ? {} : { description: definition.description }),\n })\n const actionNames = new Set<string>()\n for (const [name, action] of Object.entries(definition.actions ?? {})) {\n if (!/^[a-z][a-z0-9-]{0,63}$/u.test(name) || action === null || typeof action !== 'object' || typeof action.run !== 'function' || actionNames.has(name)) {\n throw new MobileExtensionError('invalid_action', `invalid action ${name}`)\n }\n actionNames.add(name)\n }\n const routeNames = new Set<string>()\n const routes = (definition.routes ?? []).map(route => {\n if (route === null || typeof route !== 'object' || typeof route.handle !== 'function') throw new MobileExtensionError('invalid_route', 'invalid extension route')\n const method = route.method.toUpperCase()\n if (!['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) throw new MobileExtensionError('invalid_route', 'unsupported extension route method')\n const normalized: MobileHostRoute = { ...route, method, path: normalizeRoutePath(route.path) }\n const key = routeKey(normalized)\n if (routeNames.has(key)) throw new MobileExtensionError('duplicate_route', `duplicate route ${key}`)\n routeNames.add(key)\n return normalized\n })\n return Object.freeze({ ...manifest, ...(definition.actions === undefined ? {} : { actions: Object.freeze({ ...definition.actions }) }), ...(routes.length === 0 ? {} : { routes: Object.freeze(routes) }) })\n}\n\ninterface CombinedSignalLifetime {\n readonly signal: AbortSignal\n readonly cleanup: () => void\n}\n\nfunction combineSignalLifetime(first: AbortSignal, second: AbortSignal): CombinedSignalLifetime {\n if (first.aborted || second.aborted) {\n const aborted = new AbortController()\n aborted.abort(first.aborted ? first.reason : second.reason)\n return { signal: aborted.signal, cleanup: () => undefined }\n }\n const controller = new AbortController()\n const cleanup = (): void => {\n first.removeEventListener('abort', abortFirst)\n second.removeEventListener('abort', abortSecond)\n }\n const abortFirst = (): void => { cleanup(); controller.abort(first.reason) }\n const abortSecond = (): void => { cleanup(); controller.abort(second.reason) }\n first.addEventListener('abort', abortFirst, { once: true })\n second.addEventListener('abort', abortSecond, { once: true })\n return { signal: controller.signal, cleanup }\n}\n\n/** Validate and normalize an action input through either supported schema form. */\nfunction parseActionInput(schema: MobileHostAction['input'], input: unknown): unknown {\n if (schema === undefined) return input\n if (typeof schema === 'function') return (schema as (value: unknown) => unknown)(input)\n return schema.parse(input) ?? input\n}\n\n/** Combine two abort lifetimes without relying on AbortSignal.any in older WebViews. */\nexport function combineSignals(first: AbortSignal, second: AbortSignal): AbortSignal {\n return combineSignalLifetime(first, second).signal\n}\n\n/** Host registry and service consumed by both npm plugins and local extensions. */\nexport class MobileAccessService extends Service {\n private readonly registered = new Map<string, RegisteredExtension>()\n private readonly local = new Map<string, ActiveLocalExtension>()\n private readonly retired = new Map<string, RetiredLocalExtension>()\n private readonly failures = new Map<string, string>()\n private readonly contentListeners = new Set<() => void>()\n private contentHash = createHash('sha256').update('').digest('hex')\n private localRoot: string | undefined\n private localContext: Context | undefined\n private localTimer: NodeJS.Timeout | undefined\n private localRefreshing: Promise<void> | undefined\n private localRefreshAbort: AbortController | undefined\n private localLifecycle = 0\n private localClosed = true\n\n constructor(ctx: Context) { super(ctx, 'mobileAccess') }\n\n /** Register a normal Cordis extension and return an idempotent disposer. */\n registerExtension(definition: MobileExtensionDefinition): () => void {\n const validated = validateDefinition(definition)\n if (this.registered.has(validated.id) || this.local.has(validated.id)) throw new Error(`mobile extension id already registered: ${validated.id}`)\n const dispose = (): void => {\n const current = this.registered.get(validated.id)\n if (current?.dispose === dispose) {\n this.registered.delete(validated.id)\n this.updateContentHash()\n }\n }\n this.registered.set(validated.id, { definition: validated, dispose })\n this.updateContentHash()\n return dispose\n }\n\n /** Aggregate digest covering every registered and active local extension. */\n contentDigest(): string {\n return this.contentHash\n }\n\n /** Subscribe to committed extension generation changes. */\n onContentChanged(listener: () => void): () => void {\n this.contentListeners.add(listener)\n return () => { this.contentListeners.delete(listener) }\n }\n\n private updateContentHash(): void {\n const parts = [\n ...[...this.registered.values()].map(entry => entry.definition.id),\n ...[...this.local.values()].map(active => `${active.manifest.id}:${active.digest}`),\n ]\n const next = createHash('sha256').update(parts.sort().join('|')).digest('hex')\n if (next === this.contentHash) return\n this.contentHash = next\n for (const listener of this.contentListeners) {\n try { listener() } catch { /* One observer cannot block a committed generation. */ }\n }\n }\n\n /** Return the current client-facing manifest, deterministically sorted by id. */\n manifest(): readonly MobileExtensionClientEntry[] {\n const entries = new Map<string, MobileExtensionClientEntry>()\n for (const { definition } of this.registered.values()) entries.set(definition.id, {\n schemaVersion: 1, id: definition.id, name: definition.name, version: definition.version,\n ...(definition.description === undefined ? {} : { description: definition.description }),\n })\n for (const active of this.local.values()) entries.set(active.manifest.id, {\n ...active.manifest,\n generation: active.digest,\n ...(active.scriptBody === undefined ? {} : { scriptUrl: `/mobile-access/extensions/${active.manifest.id}/mobile.js?generation=${active.digest}` }),\n ...(active.styleBody === undefined ? {} : { styleUrl: `/mobile-access/extensions/${active.manifest.id}/mobile.css?generation=${active.digest}` }),\n assetsUrl: `/mobile-access/extensions/${active.manifest.id}/assets/`,\n })\n return [...entries.values()].sort((left, right) => left.id.localeCompare(right.id))\n }\n\n /** Return loaded and failed local extension counts without exposing host errors. */\n status(): MobileExtensionStatus {\n return Object.freeze({ loaded: this.registered.size + this.local.size, failed: this.failures.size })\n }\n\n /** Locate one active extension. */\n extension(id: string, generation?: string): MobileExtensionDefinition | ActiveLocalExtension | undefined {\n if (generation !== undefined) {\n const current = this.local.get(id)\n if (current?.digest === generation) return current\n const previous = this.retired.get(id)?.active\n return previous?.digest === generation ? previous : undefined\n }\n return this.local.get(id) ?? this.registered.get(id)?.definition\n }\n\n /** Return the active local generation signal for gateway cancellation wiring. */\n signal(id: string, generation?: string): AbortSignal | undefined {\n const extension = this.extension(id, generation)\n return extension !== undefined && 'host' in extension ? extension.controller.signal : undefined\n }\n\n /** Read a local client entry after validating that it remains inside its directory. */\n async readClientFile(id: string, kind: 'script' | 'style', signal?: AbortSignal, generation?: string): Promise<{ readonly body: Buffer; readonly digest: string }> {\n signal?.throwIfAborted()\n const selected = this.extension(id, generation)\n const active = selected !== undefined && 'host' in selected ? selected : undefined\n if (active === undefined) throw new MobileExtensionError('extension_generation_not_found', 'extension generation not found', 404)\n const snapshot = kind === 'script' ? active.scriptBody : active.styleBody\n if (snapshot === undefined) throw new MobileExtensionError('extension_asset_not_found', 'extension asset not found', 404)\n const body = Buffer.from(snapshot)\n return { body, digest: createHash('sha256').update(body).digest('hex') }\n }\n\n /** Read a generation-pinned static asset from its validated snapshot. */\n async readAsset(id: string, assetPath: string, signal?: AbortSignal, generation?: string): Promise<{ readonly body: Buffer; readonly digest: string; readonly name: string }> {\n signal?.throwIfAborted()\n const selected = this.extension(id, generation)\n const active = selected !== undefined && 'host' in selected ? selected : undefined\n if (active === undefined) throw new MobileExtensionError('extension_generation_not_found', 'extension generation not found', 404)\n const normalized = normalizeRelativePath(assetPath, 'asset')\n const asset = active.assets.get(normalized)\n if (asset === undefined) throw new MobileExtensionError('extension_asset_not_found', 'extension asset not found', 404)\n return { body: Buffer.from(asset.body), digest: asset.digest, name: asset.name }\n }\n\n /** Invoke one action after parsing its input and binding the request lifetime. */\n async invoke(id: string, actionName: string, input: unknown, context: MobileActionContext, generation?: string): Promise<unknown> {\n const extension = this.extension(id, generation)\n if (extension === undefined) throw new MobileExtensionError('extension_not_found', 'extension not found', 404)\n const definition = 'host' in extension ? extension.host : extension\n const action = definition.actions?.[actionName]\n if (action === undefined) throw new MobileExtensionError('action_not_found', 'action not found', 404)\n let parsed: unknown\n try { parsed = parseActionInput(action.input, input) } catch { throw new MobileExtensionError('invalid_action_input', 'action input is invalid', 400) }\n const lifetime = 'host' in extension ? combineSignalLifetime(extension.controller.signal, context.signal) : undefined\n const signal = lifetime?.signal ?? context.signal\n try { return await action.run({ ...context, signal }, parsed) } catch (error) {\n if (error instanceof MobileExtensionError) throw error\n throw new MobileExtensionError('extension_failed', 'extension action failed', 500)\n } finally { lifetime?.cleanup() }\n }\n\n /** Match one route and invoke it with a generation-bound abort signal. */\n async route(id: string, method: string, pathname: string, request: MobileRouteRequest, generation?: string): Promise<MobileRouteResponse> {\n const extension = this.extension(id, generation)\n if (extension === undefined) throw new MobileExtensionError('extension_not_found', 'extension not found', 404)\n const definition = 'host' in extension ? extension.host : extension\n const route = definition.routes?.find((candidate: MobileHostRoute) => {\n if (candidate.method !== method) return false\n return (candidate.kind ?? 'exact') === 'exact'\n ? candidate.path === pathname\n : pathname === candidate.path || pathname.startsWith(`${candidate.path}/`)\n })\n if (route === undefined) throw new MobileExtensionError('route_not_found', 'route not found', 404)\n const lifetime = 'host' in extension ? combineSignalLifetime(extension.controller.signal, request.signal) : undefined\n let releaseLifetime = true\n try {\n const routeRequest = lifetime === undefined ? request : { ...request, signal: lifetime.signal }\n const result = await route.handle(routeRequest)\n if (result === null || typeof result !== 'object' || typeof result.body !== 'string' && !(result.body instanceof Uint8Array) && !isReadable(result.body)) {\n throw new MobileExtensionError('invalid_route_response', 'extension returned an invalid response', 500)\n }\n if (lifetime !== undefined && isReadable(result.body)) {\n releaseLifetime = false\n releaseSignalLifetimeWhenStreamSettles(result.body, lifetime.cleanup)\n }\n return result\n } catch (error) {\n if (error instanceof MobileExtensionError) throw error\n throw new MobileExtensionError('extension_failed', 'extension route failed', 500)\n } finally { if (releaseLifetime) lifetime?.cleanup() }\n }\n\n /** Start the local directory watcher; an absent directory is intentionally inert. */\n async startLocal(root: string, context: Context): Promise<void> {\n const targetRoot = resolve(root)\n if (this.localRoot !== undefined && resolve(this.localRoot) !== targetRoot) await this.stopLocal()\n if (this.localTimer !== undefined) clearInterval(this.localTimer)\n const lifecycle = ++this.localLifecycle\n this.localRoot = targetRoot; this.localContext = context; this.localClosed = false\n await mkdir(this.localRoot, { recursive: true })\n if (this.localClosed || this.localLifecycle !== lifecycle || this.localRoot !== targetRoot || this.localContext !== context) return\n await this.refreshLocal()\n if (this.localClosed || this.localLifecycle !== lifecycle || this.localRoot !== targetRoot || this.localContext !== context) return\n this.localTimer = setInterval(() => { void this.refreshLocal() }, 2_000)\n this.localTimer.unref()\n }\n\n /** Stop the watcher and abort every local host generation. */\n async stopLocal(): Promise<void> {\n this.localClosed = true\n const lifecycle = ++this.localLifecycle\n if (this.localTimer !== undefined) clearInterval(this.localTimer)\n this.localTimer = undefined\n const refreshing = this.localRefreshing\n this.localRefreshAbort?.abort()\n const previous = [...this.local.values(), ...[...this.retired.values()].map(entry => entry.active)]\n this.local.clear()\n for (const entry of this.retired.values()) clearTimeout(entry.timer)\n this.retired.clear()\n this.failures.clear()\n this.updateContentHash()\n await Promise.allSettled([\n abortAndDisposeLocal(previous),\n ...(refreshing === undefined ? [] : [refreshing]),\n ])\n if (this.localLifecycle !== lifecycle) return\n const late = [...this.local.values(), ...[...this.retired.values()].map(entry => entry.active)]\n this.local.clear()\n for (const entry of this.retired.values()) clearTimeout(entry.timer)\n this.retired.clear()\n this.failures.clear()\n this.updateContentHash()\n await abortAndDisposeLocal(late)\n if (this.localTimer !== undefined) clearInterval(this.localTimer)\n this.localTimer = undefined\n }\n\n /** Refresh all local extensions atomically; failures keep the previous snapshot. */\n refreshLocal(): Promise<void> {\n if (this.localRefreshing !== undefined) return this.localRefreshing\n const controller = new AbortController()\n this.localRefreshAbort = controller\n const refreshing = this.stageAndCommit(controller.signal).finally(() => {\n if (this.localRefreshing === refreshing) this.localRefreshing = undefined\n if (this.localRefreshAbort === controller) this.localRefreshAbort = undefined\n })\n this.localRefreshing = refreshing\n return refreshing\n }\n\n private async stageAndCommit(signal: AbortSignal): Promise<void> {\n if (this.localClosed || signal.aborted || this.localRoot === undefined || this.localContext === undefined) return\n let names: string[] = []\n try {\n const directory = await opendir(this.localRoot)\n try { for await (const entry of directory) if (entry.isDirectory() && !entry.isSymbolicLink()) names.push(entry.name) }\n finally { await directory.close().catch(() => undefined) }\n } catch { return }\n names.sort()\n const staged: ActiveLocalExtension[] = []\n const stagedFresh: ActiveLocalExtension[] = []\n let failingName = 'local'\n try {\n for (const name of names) {\n signal.throwIfAborted()\n failingName = name\n const directory = join(this.localRoot, name)\n const fingerprint = await extensionFingerprint(directory)\n const current = this.local.get(fingerprint.manifest.id)\n const retired = this.retired.get(fingerprint.manifest.id)?.active\n const previous = current?.digest === fingerprint.digest ? current : retired?.digest === fingerprint.digest ? retired : undefined\n if (previous?.digest === fingerprint.digest) staged.push(previous)\n else {\n const fresh = await loadLocalExtension(directory, this.localContext, fingerprint, signal)\n try {\n signal.throwIfAborted()\n const confirmed = await extensionFingerprint(directory)\n if (confirmed.digest !== fingerprint.digest) {\n throw new MobileExtensionError('extension_changed_during_activation', `extension ${fingerprint.manifest.id} changed during activation`, 409)\n }\n } catch (error) {\n await abortAndDisposeLocal([fresh])\n throw error\n }\n staged.push(fresh); stagedFresh.push(fresh)\n }\n }\n if (this.localClosed || signal.aborted || this.localRoot === undefined || this.localContext === undefined) {\n await abortAndDisposeLocal(stagedFresh)\n return\n }\n const duplicate = new Set<string>()\n for (const entry of staged) {\n if (duplicate.has(entry.manifest.id) || this.registered.has(entry.manifest.id)) throw new MobileExtensionError('duplicate_extension', `duplicate extension id ${entry.manifest.id}`)\n duplicate.add(entry.manifest.id)\n }\n const previous = [...this.local.values()]\n for (const entry of staged) {\n const retired = this.retired.get(entry.manifest.id)\n if (retired?.active === entry) {\n clearTimeout(retired.timer)\n this.retired.delete(entry.manifest.id)\n }\n }\n const stagedIds = new Set(staged.map(entry => entry.manifest.id))\n const removed: ActiveLocalExtension[] = []\n for (const entry of previous) {\n if (staged.includes(entry)) continue\n if (stagedIds.has(entry.manifest.id)) {\n this.retire(entry)\n continue\n }\n removed.push(entry)\n const retired = this.retired.get(entry.manifest.id)\n if (retired !== undefined) {\n clearTimeout(retired.timer)\n this.retired.delete(entry.manifest.id)\n removed.push(retired.active)\n }\n }\n this.local.clear()\n for (const entry of staged) this.local.set(entry.manifest.id, entry)\n for (const entry of staged) this.failures.delete(entry.manifest.id)\n for (const name of names) this.failures.delete(name)\n for (const failure of this.failures.keys()) {\n if (failure !== 'local' && !names.includes(failure)) this.failures.delete(failure)\n }\n this.failures.delete('local')\n if (removed.length > 0) void abortAndDisposeLocal(removed)\n this.updateContentHash()\n } catch (error) {\n await abortAndDisposeLocal(stagedFresh)\n if (this.localClosed || signal.aborted) return\n const message = error instanceof Error ? error.message : String(error)\n this.failures.set(failingName, message)\n if (!(error instanceof MobileExtensionError)) this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error)))\n }\n }\n\n private retire(active: ActiveLocalExtension): void {\n const previous = this.retired.get(active.manifest.id)\n if (previous?.active === active) return\n if (previous !== undefined) {\n clearTimeout(previous.timer)\n this.retired.delete(active.manifest.id)\n void abortAndDisposeLocal([previous.active])\n }\n const timer = setTimeout(() => {\n const current = this.retired.get(active.manifest.id)\n if (current?.active !== active) return\n this.retired.delete(active.manifest.id)\n void abortAndDisposeLocal([active])\n }, RETIRED_GENERATION_TTL_MS)\n timer.unref()\n this.retired.set(active.manifest.id, { active, timer })\n }\n}\n\nfunction isReadable(value: unknown): value is Readable {\n return value !== null && typeof value === 'object' && typeof (value as { pipe?: unknown }).pipe === 'function'\n}\n\nfunction releaseSignalLifetimeWhenStreamSettles(stream: Readable, cleanup: () => void): void {\n let stopObserving: (() => void) | undefined\n stopObserving = finished(stream, () => {\n stopObserving?.()\n cleanup()\n })\n}\n\nfunction invokeCleanups(cleanups: readonly (() => void | Promise<void>)[]): Promise<unknown>[] {\n const pending: Promise<unknown>[] = []\n for (const cleanup of [...cleanups].reverse()) {\n try { pending.push(Promise.resolve(cleanup())) } catch { /* extension teardown cannot block the owner */ }\n }\n return pending\n}\n\nasync function settleBounded(pending: readonly Promise<unknown>[], timeoutMs: number): Promise<void> {\n if (pending.length === 0) return\n let timer: NodeJS.Timeout | undefined\n await Promise.race([\n Promise.allSettled(pending),\n new Promise<void>(resolveTimeout => { timer = setTimeout(resolveTimeout, timeoutMs) }),\n ])\n if (timer !== undefined) clearTimeout(timer)\n}\n\nasync function abortAndDisposeLocal(entries: readonly ActiveLocalExtension[]): Promise<void> {\n const pending: Promise<unknown>[] = []\n for (const entry of entries) {\n entry.controller.abort()\n pending.push(...invokeCleanups(entry.cleanups))\n }\n await settleBounded(pending, HOST_TEARDOWN_TIMEOUT_MS)\n}\n\nasync function loadLocalExtension(directory: string, context: Context, known?: LocalExtensionFingerprint, parentSignal?: AbortSignal): Promise<ActiveLocalExtension> {\n const root = await realExtensionRoot(directory)\n const manifestFile = await regularFile(join(root, 'extension.json'), EXTENSION_LIMITS.manifest, 'extension.json')\n const manifest = known?.manifest ?? parseExtensionManifest(JSON.parse(await readFile(manifestFile.path, 'utf8')) as unknown)\n if (manifest.id !== basename(root)) throw new MobileExtensionError('invalid_manifest', 'extension id must match its directory name')\n const scriptBody = known === undefined\n ? await optionalFile(root, 'mobile.js', EXTENSION_LIMITS.script, 'mobile.js').then(path => path === undefined ? undefined : readFile(path))\n : known.scriptBody\n const styleBody = known === undefined\n ? await optionalFile(root, 'mobile.css', EXTENSION_LIMITS.css, 'mobile.css').then(path => path === undefined ? undefined : readFile(path))\n : known.styleBody\n const assets = known?.assets ?? await assetSnapshot(root)\n const hostFile = await optionalFile(root, 'host.mjs', EXTENSION_LIMITS.script, 'host.mjs')\n const controller = new AbortController()\n const actions: Record<string, MobileHostAction> = {}\n const routes: MobileHostRoute[] = []\n const cleanups: (() => void | Promise<void>)[] = []\n const pendingEffects: Promise<void>[] = []\n let activationOpen = true\n const onParentAbort = (): void => { controller.abort(parentSignal?.reason) }\n if (parentSignal?.aborted === true) onParentAbort()\n else parentSignal?.addEventListener('abort', onParentAbort, { once: true })\n const ensureActivationOpen = (): void => {\n if (!activationOpen || controller.signal.aborted) throw new MobileExtensionError('host_activation_closed', `extension ${manifest.id} activation is closed`, 409)\n }\n const api: HostApi = {\n manifest,\n context,\n schema: z,\n signal: controller.signal,\n action(name, spec) { ensureActivationOpen(); if (actions[name] !== undefined) throw new MobileExtensionError('duplicate_action', `duplicate action ${name}`); actions[name] = spec },\n route(spec) { ensureActivationOpen(); routes.push(spec) },\n effect(setup) {\n ensureActivationOpen()\n const result = setup()\n if (result instanceof Promise) {\n pendingEffects.push(result.then(async cleanup => {\n if (typeof cleanup !== 'function') return\n if (activationOpen) cleanups.push(cleanup)\n else await cleanup()\n }))\n } else if (typeof result === 'function') {\n if (activationOpen) cleanups.push(result)\n else void Promise.resolve(result()).catch(() => undefined)\n }\n },\n }\n try {\n const activate = async (): Promise<void> => {\n controller.signal.throwIfAborted()\n if (hostFile !== undefined) {\n const digest = createHash('sha256').update(await readFile(hostFile)).digest('hex')\n controller.signal.throwIfAborted()\n let imported: LocalHostModule\n try { imported = await import(`${pathToFileURL(hostFile).href}?dsh_generation=${digest}`) as LocalHostModule }\n catch { throw new MobileExtensionError('host_load_failed', `could not load ${manifest.id}/host.mjs`, 500) }\n controller.signal.throwIfAborted()\n if (imported.default !== undefined) await imported.default(api)\n }\n await Promise.all(pendingEffects)\n }\n await withActivationTimeout(activate(), manifest.id, controller.signal)\n const host = validateDefinition({ ...manifest, actions, routes })\n activationOpen = false\n const digest = known?.digest ?? createHash('sha256').update(manifest.id).digest('hex')\n return Object.freeze({ manifest, directory: root, ...(scriptBody === undefined ? {} : { scriptBody }), ...(styleBody === undefined ? {} : { styleBody }), assets, host, controller, cleanups: Object.freeze(cleanups), digest })\n } catch (error) {\n activationOpen = false\n controller.abort()\n const cleanupPromises = invokeCleanups(cleanups.splice(0))\n await settleBounded([...pendingEffects, ...cleanupPromises], HOST_TEARDOWN_TIMEOUT_MS)\n throw error\n } finally {\n parentSignal?.removeEventListener('abort', onParentAbort)\n }\n}\n\n/** Construct the service in a Cordis plugin without importing DSH internals. */\nexport function createMobileAccessService(ctx: Context): MobileAccessService {\n return new MobileAccessService(ctx)\n}\n","#!/usr/bin/env node\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport { preferredLanInterfaceNames, selectLanNetwork } from './managed-setup.js'\nimport { prepareManagedLanSetup, removeWindowsFirewall } from './lan-setup.js'\nimport { assertExtensionId } from './extensions.js'\nimport { restrictPrivateFile } from './private-file.js'\n\ninterface SetupOptions {\n readonly address?: string\n readonly port: number\n readonly dshPort: number\n readonly configureFirewall: boolean\n}\n\nfunction parseOptions(args: readonly string[]): SetupOptions {\n let address: string | undefined\n let port = 3443\n let dshPort = 3080\n let configureFirewall = true\n for (let index = 0; index < args.length; index += 1) {\n const name = args[index]\n const value = args[index + 1]\n if (name === '--address' && value !== undefined) {\n address = value\n index += 1\n continue\n }\n if (name === '--port' && value !== undefined) {\n port = Number(value)\n index += 1\n continue\n }\n if (name === '--dsh-port' && value !== undefined) {\n dshPort = Number(value)\n index += 1\n continue\n }\n if (name === '--no-firewall') {\n configureFirewall = false\n continue\n }\n throw new Error(`unknown setup option: ${name ?? ''}`)\n }\n if (!Number.isSafeInteger(port) || port < 1024 || port > 65535) throw new Error('--port must be from 1024 through 65535')\n if (!Number.isSafeInteger(dshPort) || dshPort < 1024 || dshPort > 65535) throw new Error('--dsh-port must be from 1024 through 65535')\n return { ...(address === undefined ? {} : { address }), port, dshPort, configureFirewall }\n}\n\nfunction dshHome(): string {\n return resolve(process.env.DSH_HOME ?? join(homedir(), '.dsh'))\n}\n\nasync function setup(args: readonly string[]): Promise<void> {\n const options = parseOptions(args)\n const preferredInterfaces = options.address === undefined ? await preferredLanInterfaceNames() : []\n const network = selectLanNetwork(options.address, undefined, undefined, preferredInterfaces)\n const home = dshHome()\n const directory = join(home, 'mobile-access')\n await mkdir(directory, { recursive: true, mode: 0o700 })\n const customCss = join(directory, 'mobile.css')\n try {\n await readFile(customCss)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await writeFile(customCss, [\n '/* Safe mobile overrides. DSH Mobile applies saved changes on the phone automatically. */',\n ':root {',\n ' --dsh-mobile-accent: #2563eb;',\n ' --dsh-mobile-font-scale: 1;',\n ' --dsh-mobile-radius: 14px;',\n '}',\n '',\n ].join('\\n'), { mode: 0o600 })\n }\n\n const customScript = join(directory, 'mobile.js')\n try {\n await readFile(customScript)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await writeFile(customScript, [\n '/* Mount mobile-only Web features here. Saved changes are applied automatically. */',\n 'window.dshMobile.register(({ root }) => {',\n ' root.replaceChildren()',\n ' return () => root.replaceChildren()',\n '})',\n '',\n ].join('\\n'), { mode: 0o600 })\n }\n\n const extensions = join(directory, 'extensions')\n await mkdir(extensions, { recursive: true, mode: 0o700 })\n await createExtensionScaffold(extensions, 'custom', '自定义移动扩展', false)\n\n if (options.configureFirewall && process.platform === 'win32') {\n console.log('Windows will request administrator approval for two LAN-only firewall rules.')\n }\n const result = await prepareManagedLanSetup({\n setupFile: join(directory, 'setup.json'),\n controlFile: join(directory, 'control.json'),\n network,\n listenPort: options.port,\n dshPort: options.dshPort,\n configureFirewall: options.configureFirewall,\n })\n\n console.log(`DSH Mobile follows ${network.name} and is currently configured for ${result.origin}`)\n console.log(`Install this CA certificate on Android once: ${result.androidCertificate}`)\n console.log(`Ask DSH to customize the mobile Web UI and features in: ${customCss} and ${customScript}`)\n console.log(`Additional extensions live in: ${extensions}`)\n console.log('Start DSH with: dsh --profile web')\n console.log('Then open the Mobile card in the lower-left corner and create a pairing key.')\n}\n\nasync function createExtensionScaffold(root: string, id: string, name: string, refuseExisting = true): Promise<void> {\n assertExtensionId(id)\n await mkdir(root, { recursive: true, mode: 0o700 })\n const directory = join(root, id)\n try {\n await mkdir(directory, { recursive: false, mode: 0o700 })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST' && !refuseExisting) return\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new Error(`extension directory already exists: ${id}`)\n throw error\n }\n const files: Readonly<Record<string, string>> = {\n 'extension.json': `${JSON.stringify({ schemaVersion: 1, id, name, version: '0.1.0', description: '在手机端扩展 DSH' }, null, 2)}\\n`,\n 'host.mjs': `export default async function activate(api) {\\n api.action('hello', {\\n input: api.schema.object({ name: api.schema.string().max(80) }),\\n async run({ signal, deviceId }, input) {\\n void signal; void deviceId\\n return { message: \\`Hello, \\${input.name}\\` }\\n },\\n })\\n}\\n`,\n 'mobile.js': `window.dshMobile?.define?.({\\n apiVersion: 1,\\n id: '${id}',\\n activate(api) {\\n return api.ui.registerSurface({\\n id: '${id}-page', placement: 'page', label: ${JSON.stringify(name)},\\n mount(container) {\\n container.textContent = ${JSON.stringify(`这是 ${name} 的移动页面。`)}\\n return () => container.replaceChildren()\\n },\\n })\\n },\\n})\\n`,\n 'mobile.css': `/* ${name.replaceAll('*/', '* /')} 的移动端样式。保存后通常会在几秒内刷新。 */\\n`,\n }\n try {\n for (const [file, contents] of Object.entries(files)) await writeFile(join(directory, file), contents, { encoding: 'utf8', flag: 'wx', mode: 0o600 })\n } catch (error) {\n await rm(directory, { recursive: true, force: true })\n throw error\n }\n console.log(`Created extension: ${directory}`)\n}\n\nasync function extensionCommand(args: readonly string[]): Promise<void> {\n const [subcommand, id, ...rest] = args\n if (subcommand !== 'create' || id === undefined) throw new Error('usage: extension create <id> [--name <name>]')\n let name = id\n for (let index = 0; index < rest.length; index += 1) {\n if (rest[index] === '--name' && rest[index + 1] !== undefined) { name = rest[index + 1]!; index += 1; continue }\n throw new Error(`unknown extension option: ${rest[index] ?? ''}`)\n }\n if (name.length === 0 || name.length > 120 || /[\\u0000-\\u001f\\u007f]/u.test(name)) throw new Error('--name is invalid')\n await createExtensionScaffold(join(dshHome(), 'mobile-access', 'extensions'), id, name)\n}\n\nasync function purge(args: readonly string[]): Promise<void> {\n if (args.length !== 1 || args[0] !== '--yes') throw new Error('purge requires --yes')\n const home = dshHome()\n await rm(join(home, 'mobile-access'), { recursive: true, force: true })\n await removeWindowsFirewall()\n console.log('Removed DSH Mobile certificates, devices, preferences, and custom Web files.')\n}\n\nfunction help(): void {\n console.log([\n 'dsh-mobile setup [--address 192.168.x.x] [--port 3443] [--dsh-port 3080] [--no-firewall]',\n 'dsh-mobile extension create <id> [--name <name>]',\n 'dsh-mobile purge --yes',\n '',\n 'Run through the DSH profile:',\n ' dsh plugin --profile web exec dsh-mobile setup',\n ].join('\\n'))\n}\n\nasync function main(): Promise<void> {\n const [command = 'help', ...args] = process.argv.slice(2)\n if (command === 'setup') await setup(args)\n else if (command === 'extension') await extensionCommand(args)\n else if (command === 'purge') await purge(args)\n else if (command === 'help' || command === '--help' || command === '-h') help()\n else throw new Error(`unknown command: ${command}`)\n}\n\nmain().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error))\n process.exitCode = 1\n})\n"],"mappings":";;;;;;;;;;;AAGA,SAAgB,aACd,MACA,MACA,UAAqE,CAAC,GACzB;CAC7C,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,SAAS,MAAM,CAAC,GAAG,IAAI,GAAG;GAAE,aAAa;GAAM,GAAG;GAAS,UAAU;EAAO,IAAI,OAAO,QAAQ,WAAW;GACxG,IAAI,UAAU,MAAM;IAAE,O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
|
package/lib/client.js
CHANGED
|
@@ -108,7 +108,7 @@ window.__ModuleLoader__.load({
|
|
|
108
108
|
ready: "Ready",
|
|
109
109
|
installed: "Installed",
|
|
110
110
|
installWithSize: "Install official component · {size} MB",
|
|
111
|
-
cpolarUnsupported: "
|
|
111
|
+
cpolarUnsupported: "Windows x64 and Linux x64/arm64 are currently supported.",
|
|
112
112
|
cpolarNotInstalled: "Not installed. A fixed version is downloaded from the official cpolar website only after you click the button below.",
|
|
113
113
|
cpolarNeedsToken: "Official component {version} is verified. Save the account token to continue.",
|
|
114
114
|
cpolarReady: "Official component {version} and the local account configuration are ready. Free temporary addresses may change after DSH or cpolar restarts; if the app cannot connect, scan the current remote QR code again.",
|
|
@@ -276,7 +276,7 @@ window.__ModuleLoader__.load({
|
|
|
276
276
|
ready: "Pronto",
|
|
277
277
|
installed: "Installato",
|
|
278
278
|
installWithSize: "Installa componente ufficiale · {size} MB",
|
|
279
|
-
cpolarUnsupported: "Attualmente
|
|
279
|
+
cpolarUnsupported: "Attualmente sono supportati Windows x64 e Linux x64/arm64.",
|
|
280
280
|
cpolarNotInstalled: "Non installato. Una versione fissa viene scaricata dal sito ufficiale cpolar solo dopo aver premuto il pulsante.",
|
|
281
281
|
cpolarNeedsToken: "Componente ufficiale {version} verificato. Salva il token account per continuare.",
|
|
282
282
|
cpolarReady: "Componente ufficiale {version} e configurazione account locale pronti. Gli indirizzi temporanei gratuiti possono cambiare dopo il riavvio di DSH o cpolar; se l’app non si connette, scansiona di nuovo il QR remoto corrente.",
|
|
@@ -446,7 +446,7 @@ window.__ModuleLoader__.load({
|
|
|
446
446
|
ready: "已就绪",
|
|
447
447
|
installed: "已安装",
|
|
448
448
|
installWithSize: "安装官方组件 · {size} MB",
|
|
449
|
-
cpolarUnsupported: "
|
|
449
|
+
cpolarUnsupported: "当前支持 Windows x64 与 Linux x64/arm64。",
|
|
450
450
|
cpolarNotInstalled: "尚未安装。只有点击下方按钮后,才会从 cpolar 官网下载固定版本。",
|
|
451
451
|
cpolarNeedsToken: "官方组件 {version} 已校验,下一步只需保存账号令牌。",
|
|
452
452
|
cpolarReady: "官方组件 {version} 与本机账号配置已就绪。免费临时地址可能在 DSH 或 cpolar 重启后变化;App 无法连接时,请重新扫描当前远程二维码。",
|
|
@@ -1164,7 +1164,7 @@ window.__ModuleLoader__.load({
|
|
|
1164
1164
|
cloudflaredBadge: "Account optional",
|
|
1165
1165
|
cloudflaredDescription: "Installs the official cloudflared client on demand. A quick tunnel needs no account and gives a temporary public address; a named tunnel uses a Cloudflare account token and keeps one hostname that survives restarts.",
|
|
1166
1166
|
prepareCloudflared: "Prepare cloudflared",
|
|
1167
|
-
cloudflaredUnsupported: "
|
|
1167
|
+
cloudflaredUnsupported: "Windows x64 and Linux x64/arm64 are currently supported.",
|
|
1168
1168
|
cloudflaredNotInstalled: "Not installed. A fixed version is downloaded from the official cloudflared release page only after you click the button below.",
|
|
1169
1169
|
cloudflaredReady: "Official component {version} is ready.",
|
|
1170
1170
|
cloudflaredQuickNote: "Quick tunnel: no Cloudflare account is needed, but Cloudflare positions quick tunnels for testing — the address is random, rate-limited, and carries no uptime guarantee. Do not rely on one for access that must stay reachable.",
|
|
@@ -1232,7 +1232,7 @@ window.__ModuleLoader__.load({
|
|
|
1232
1232
|
cloudflaredBadge: "Account facoltativo",
|
|
1233
1233
|
cloudflaredDescription: "Installa su richiesta il client cloudflared ufficiale. Il tunnel rapido non richiede account e fornisce un indirizzo pubblico temporaneo; il tunnel con nome usa il token di un account Cloudflare e mantiene un hostname stabile tra i riavvii.",
|
|
1234
1234
|
prepareCloudflared: "Prepara cloudflared",
|
|
1235
|
-
cloudflaredUnsupported: "Attualmente
|
|
1235
|
+
cloudflaredUnsupported: "Attualmente sono supportati Windows x64 e Linux x64/arm64.",
|
|
1236
1236
|
cloudflaredNotInstalled: "Non installato. Una versione fissa viene scaricata dalla pagina ufficiale di cloudflared solo dopo aver premuto il pulsante.",
|
|
1237
1237
|
cloudflaredReady: "Componente ufficiale {version} pronto.",
|
|
1238
1238
|
cloudflaredQuickNote: "Tunnel rapido: non serve un account Cloudflare, ma Cloudflare li considera pensati per i test — l’indirizzo è casuale, soggetto a limiti di frequenza e senza garanzia di disponibilità. Non usarlo per un accesso che deve restare raggiungibile.",
|
|
@@ -1300,7 +1300,7 @@ window.__ModuleLoader__.load({
|
|
|
1300
1300
|
cloudflaredBadge: "账号可选",
|
|
1301
1301
|
cloudflaredDescription: "按需安装官方 cloudflared 客户端。快速隧道无需账号,提供临时公网地址;命名隧道使用 Cloudflare 账号令牌,地址固定、重启不变。",
|
|
1302
1302
|
prepareCloudflared: "准备 cloudflared",
|
|
1303
|
-
cloudflaredUnsupported: "
|
|
1303
|
+
cloudflaredUnsupported: "当前支持 Windows x64 与 Linux x64/arm64。",
|
|
1304
1304
|
cloudflaredNotInstalled: "尚未安装。只有点击下方按钮后,才会从 cloudflared 官方发布页下载固定版本。",
|
|
1305
1305
|
cloudflaredReady: "官方组件 {version} 已就绪。",
|
|
1306
1306
|
cloudflaredQuickNote: "快速隧道:无需 Cloudflare 账号,但官方定位是测试用途 —— 地址随机、有限流、无可用性保证。请勿用于必须长期可达的访问。",
|