Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(relay): automatically deploy behind existing nginx
MagicLizi95ad4f74098c
diff --git a/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.tsindex a91d325d1f..78577123cb 100644--- a/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts@@ -29,7 +29,9 @@ const mocks = vi.hoisted(() => ({}));vi.mock('electron', () => ({ app: { getAppPath: () => appPath } }));-vi.mock('../../logger.js', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) }));+vi.mock('../../logger.js', () => ({+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),+}));vi.mock('../../remote-ssh/index.js', () => ({ensureRemoteHostReady: mocks.ensureReady,getRemoteSshPool: () => ({@@ -38,7 +40,11 @@ vi.mock('../../remote-ssh/index.js', () => ({mocks.commands.push({ label: options.label, command });if (options.label === 'relay-deploy-upload') {const { createHash } = await import('node:crypto');- return { stdout: `SHA ${createHash('sha256').update(options.input!).digest('hex')}\n`, stderr: '', exitCode: 0 };+ return {+ stdout: `SHA ${createHash('sha256').update(options.input!).digest('hex')}\n`,+ stderr: '',+ exitCode: 0,+ };}const respond = mocks.responses[options.label];return respond ? respond(command) : { stdout: '', stderr: '', exitCode: 0 };@@ -91,8 +97,7 @@ describe('deployRelayToServer', () => {'relay-deploy-probe': () => ok(PROBE_SUDO),'relay-deploy-runtime': () => ok('NODE_READY v24.22.1\n'),'relay-deploy-configure': () => ok('INITIALIZED\nCONFIGURED\n'),- 'relay-deploy-status': () =>- ok(`ACTIVE active\nSTATUS {"certificate":{"state":"ready","identifier":"203.0.113.10"}}\n`),+ 'relay-deploy-status': () => ok(`ACTIVE active\nSTATUS {"certificate":{"state":"ready","identifier":"203.0.113.10"}}\n`),};vi.stubGlobal('fetch',@@ -117,8 +122,13 @@ describe('deployRelayToServer', () => {});it.each([- ['no root or passwordless sudo', { 'relay-deploy-probe': () => ok(PROBE_SUDO.replace('ROOT sudo', 'ROOT none')) }, 'NEEDS_ROOT', undefined],- ['port 80 used by another program', { 'relay-deploy-inspect': () => ok('BUSY 80 nginx\n') }, 'PORT_BUSY', '80 nginx'],+ [+ 'no root or passwordless sudo',+ { 'relay-deploy-probe': () => ok(PROBE_SUDO.replace('ROOT sudo', 'ROOT none')) },+ 'NEEDS_ROOT',+ undefined,+ ],+ ['port 80 used by another program', { 'relay-deploy-inspect': () => ok('BUSY 80 apache2\n') }, 'PORT_BUSY', '80 apache2'],['a relay owned by someone else',{ 'relay-deploy-inspect': () => ok(`STATE 2 ${init.relayId} ${'R'.repeat(43)}\n`) },@@ -144,6 +154,39 @@ describe('deployRelayToServer', () => {expect(configured).toBe(code === 'CERTIFICATE_FAILED');});+ // 2026-10-29: 用户要求已有 Nginx 时自动部署,而不是让用户停网站或复制配置。+ // 缺口:旧入口对 BUSY 80 nginx 一律返回 PORT_BUSY。最小输入:两个端口均为 Nginx。+ // tier: unit;检查生产入口的结果、自动选择和失败后的恢复请求。+ it('automatically deploys behind the existing Nginx and restores it if verification fails', async () => {+ mocks.responses['relay-deploy-inspect'] = () => ok('BUSY 80 nginx\nBUSY 443 nginx\nBUSY 443 nginx\n');+ mocks.responses['relay-deploy-nginx-prepare'] = () =>+ ok('{"event":"nginx","port":47822,"challengePort":47823,"existingCertificate":false}\n');+ const success = await run();+ expect(success.error).toBeNull();+ expect(mocks.commands.some((c) => c.label === 'relay-deploy-nginx-activate')).toBe(true);+ expect(mocks.commands.some((c) => c.label === 'relay-deploy-nginx-commit')).toBe(true);+ const configure = mocks.commands.find((c) => c.label === 'relay-deploy-configure')!;+ // 远端命令的参数协议:复用 Nginx 后只允许中转监听回环地址及探测出的空闲端口。+ expect(configure.command).toContain("'203.0.113.10' '127.0.0.1' 'https://203.0.113.10'");+ expect(configure.command).toContain("'nginx-acme' '47822' '47823'");+ mocks.commands = [];+ vi.mocked(fetch).mockResolvedValue(new Response('{}', { status: 502 }));+ const failed = await run();+ expect(failed.error).toMatchObject({ code: 'NOT_REACHABLE' });+ expect(mocks.commands.some((c) => c.label === 'relay-deploy-nginx-rollback')).toBe(true);+ expect(mocks.commands.some((c) => c.label === 'relay-deploy-nginx-commit')).toBe(false);+ });++ it('uses the existing trusted HTTPS certificate without waiting for a new certificate', async () => {+ mocks.responses['relay-deploy-inspect'] = () => ok('BUSY 80 nginx\nBUSY 443 nginx\n');+ mocks.responses['relay-deploy-nginx-prepare'] = () =>+ ok('{"event":"nginx","port":47820,"challengePort":47821,"existingCertificate":true}\n');+ const { error } = await run();+ expect(error).toBeNull();+ expect(mocks.commands.some(c => c.label === 'relay-deploy-status')).toBe(false);+ expect(mocks.commands.find(c => c.label === 'relay-deploy-configure')!.command).toContain("'nginx-existing' '47820' '47821'");+ });+it('replaces a foreign relay only when asked to', async () => {mocks.responses['relay-deploy-inspect'] = () => ok(`STATE 2 other-relay ${'R'.repeat(43)}\n`);const { error } = await run({ replaceExisting: true });@@ -161,21 +204,26 @@ describe('deployRelayToServer', () => {['unknown', false],])('rechecks retained data after restoring Node: %s', async (state, matches) => {let inspections = 0;- mocks.responses['relay-deploy-inspect'] = () =>- ok(`STATE ${++inspections === 1 ? 'unknown' : state}\n`);+ mocks.responses['relay-deploy-inspect'] = () => ok(`STATE ${++inspections === 1 ? 'unknown' : state}\n`);const { error } = await run();- expect(mocks.commands.some(c => c.label === 'relay-deploy-runtime')).toBe(true);+ expect(mocks.commands.some((c) => c.label === 'relay-deploy-runtime')).toBe(true);expect(inspections).toBe(2);if (matches) expect(error).toBeNull();else expect(error).toMatchObject({ code: 'RELAY_MISMATCH' });- expect(mocks.commands.some(c => c.label === 'relay-deploy-upload')).toBe(matches);- expect(mocks.commands.some(c => c.label === 'relay-deploy-configure')).toBe(matches);+ expect(mocks.commands.some((c) => c.label === 'relay-deploy-upload')).toBe(matches);+ expect(mocks.commands.some((c) => c.label === 'relay-deploy-configure')).toBe(matches);});it('does not access another account’s SSH connection after the owner changes while connecting', async () => {let current = true;- mocks.ensureReady.mockImplementationOnce(async () => { current = false; });- const { error } = await run({ assertCurrent: () => { if (!current) throw new Error('owner changed'); } });+ mocks.ensureReady.mockImplementationOnce(async () => {+ current = false;+ });+ const { error } = await run({+ assertCurrent: () => {+ if (!current) throw new Error('owner changed');+ },+ });expect(error).toMatchObject({ message: 'owner changed' });expect(mocks.commands).toEqual([]);});@@ -184,14 +232,22 @@ describe('deployRelayToServer', () => {// 最小输入:同一 SSH 主机的 STATE 属于另一主人;tier: unit,观察没有卸载写操作。it('refuses uninstall when the server belongs to another relay owner', async () => {mocks.responses['relay-deploy-inspect'] = () => ok(`STATE 2 ${init.relayId} ${'R'.repeat(43)}\n`);- await expect(uninstallRelayFromServer('my-vps', init, true, () => {})).rejects.toMatchObject({ code: 'RELAY_MISMATCH' });- expect(mocks.commands.some(c => c.label === 'relay-deploy-uninstall')).toBe(false);+ await expect(uninstallRelayFromServer('my-vps', init, true, () => {})).rejects.toMatchObject({+ code: 'RELAY_MISMATCH',+ });+ expect(mocks.commands.some((c) => c.label === 'relay-deploy-uninstall')).toBe(false);});it('uninstalls a matching relay and rejects an identity changed before deletion', async () => {mocks.responses['relay-deploy-inspect'] = () => ok(`STATE 2 ${init.relayId} ${init.ownerPublicKey}\n`);await expect(uninstallRelayFromServer('my-vps', init, true, () => {})).resolves.toBeUndefined();- mocks.responses['relay-deploy-uninstall'] = () => ({ stdout: 'RELAY_MISMATCH\n', stderr: '', exitCode: 22 });- await expect(uninstallRelayFromServer('my-vps', init, true, () => {})).rejects.toMatchObject({ code: 'RELAY_MISMATCH' });+ mocks.responses['relay-deploy-uninstall'] = () => ({+ stdout: 'RELAY_MISMATCH\n',+ stderr: '',+ exitCode: 22,+ });+ await expect(uninstallRelayFromServer('my-vps', init, true, () => {})).rejects.toMatchObject({+ code: 'RELAY_MISMATCH',+ });});});diff --git a/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts b/apps/desktop/src/main/device-link/selfHostedRelayDeploy.tsindex f604620fd5..f057e72e27 100644--- a/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts+++ b/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts@@ -7,7 +7,7 @@* /opt/cindy-relay/relay.mjs 与 Cindy 内运行的同一个中转内核(单文件)* /var/lib/cindy-relay 中转数据(设备档案、证书),属 cindy-relay 系统用户,0700* cindy-relay.service systemd 服务,只放行绑定 80/443 的权限- * 证书由中转自己向 Let's Encrypt 申请并续期(IP 用 6 天短期证书,域名用常规证书)。+ * 自动复用正在使用 80/443 的 Nginx;已有可信证书时沿用,否则由中转申请并续期后同步给 Nginx。** 主人身份(中转 ID、主人凭证、主人密钥)只在这台电脑生成与保存;交给服务器的只有凭证哈希、* 主人公钥与主人证书。命令里不出现任何秘密,也不把服务器输出写进日志。@@ -171,6 +171,7 @@ if command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1; then echoconst INSPECT_SCRIPT = `NODE=${INSTALL_DIR}/node/bin/nodeSTATE=${DATA_DIR}/relay-state.json+if [ -f /etc/cindy-relay/nginx/state.json ]; then echo "NGINX_MANAGED yes"; fiif [ -x "$NODE" ]; then echo "NODE $("$NODE" --version 2>/dev/null)"; fiif [ -f "$STATE" ]; thenif [ -x "$NODE" ]; then@@ -226,7 +227,7 @@ echo "SHA $(sha256sum ${INSTALL_DIR}/relay.mjs.new | cut -d' ' -f1)"const CONFIGURE_SCRIPT = `set -e-ADDRESS="$1"; LISTEN="$2"; PUBLIC_URL="$3"; REPLACE="$4"; ACME_DIRECTORY="$5"; shift 5+ADDRESS="$1"; LISTEN="$2"; PUBLIC_URL="$3"; REPLACE="$4"; ACME_DIRECTORY="$5"; MODE="$6"; PORT="$7"; CHALLENGE_PORT="$8"; shift 8NODE=${INSTALL_DIR}/node/bin/nodeif ! id cindy-relay >/dev/null 2>&1; thenuseradd --system --home-dir ${DATA_DIR} --no-create-home --shell /usr/sbin/nologin cindy-relay 2>/dev/null \\@@ -243,7 +244,14 @@ fichown -R cindy-relay:cindy-relay ${DATA_DIR}rm -f ${DATA_DIR}/status.jsonEXTRA=""-if [ -n "$ACME_DIRECTORY" ]; then EXTRA=" --acme-directory $ACME_DIRECTORY"; fi+CAPS=""+if [ "$MODE" = nginx-existing ]; then+ EXTRA=" --trust-proxy"+else+ EXTRA=" --acme-identifier $ADDRESS --acme-http-port $CHALLENGE_PORT"+ if [ -n "$ACME_DIRECTORY" ]; then EXTRA="$EXTRA --acme-directory $ACME_DIRECTORY"; fi+fi+if [ "$MODE" = direct ]; then CAPS=CAP_NET_BIND_SERVICE; ficat > /etc/systemd/system/cindy-relay.service <<UNIT[Unit]Description=Cindy self-hosted relay@@ -254,11 +262,11 @@ Wants=network-online.targetType=simpleUser=cindy-relayGroup=cindy-relay-ExecStart=$NODE ${INSTALL_DIR}/relay.mjs serve --data ${DATA_DIR} --host $LISTEN --port 443 --public-url $PUBLIC_URL --acme-identifier $ADDRESS --acme-http-port 80$EXTRA+ExecStart=$NODE ${INSTALL_DIR}/relay.mjs serve --data ${DATA_DIR} --host $LISTEN --port $PORT --public-url $PUBLIC_URL$EXTRARestart=alwaysRestartSec=5-AmbientCapabilities=CAP_NET_BIND_SERVICE-CapabilityBoundingSet=CAP_NET_BIND_SERVICE+AmbientCapabilities=$CAPS+CapabilityBoundingSet=$CAPSNoNewPrivileges=trueProtectSystem=strictProtectHome=true@@ -281,6 +289,46 @@ systemctl restart cindy-relayecho "CONFIGURED"`;+const NGINX_SCRIPT = `+set -e+ACTION="$1"; shift+NODE=${INSTALL_DIR}/node/bin/node+BUNDLE=${INSTALL_DIR}/relay.mjs+if [ -f ${INSTALL_DIR}/relay.mjs.new ]; then BUNDLE=${INSTALL_DIR}/relay.mjs.new; fi+if [ "$ACTION" != commit ]; then "$NODE" "$BUNDLE" nginx --action "$ACTION" "$@"; fi+if [ "$ACTION" = rollback ]; then+ systemctl daemon-reload+ if [ -f /etc/systemd/system/cindy-relay.service ]; then systemctl restart cindy-relay+ else systemctl stop cindy-relay >/dev/null 2>&1 || true; fi+ if [ ! -f /etc/cindy-relay/nginx/state.json ]; then+ systemctl disable --now cindy-relay-nginx.timer >/dev/null 2>&1 || true+ rm -f /etc/systemd/system/cindy-relay-nginx.timer /etc/systemd/system/cindy-relay-nginx.service+ fi+fi+if [ "$ACTION" = commit ]; then+ cat > /etc/systemd/system/cindy-relay-nginx.service <<UNIT+[Unit]+Description=Apply renewed Cindy relay certificate to Nginx+[Service]+Type=oneshot+ExecStart=$NODE ${INSTALL_DIR}/relay.mjs nginx --action renew+UMask=0077+UNIT+ cat > /etc/systemd/system/cindy-relay-nginx.timer <<UNIT+[Unit]+Description=Check Cindy relay Nginx certificate+[Timer]+OnBootSec=1min+OnUnitActiveSec=5min+[Install]+WantedBy=timers.target+UNIT+ systemctl daemon-reload+ systemctl enable --now cindy-relay-nginx.timer >/dev/null 2>&1+ "$NODE" "$BUNDLE" nginx --action commit+fi+`;+const STATUS_SCRIPT = `echo "ACTIVE $(systemctl is-active cindy-relay 2>/dev/null)"if [ -f ${DATA_DIR}/status.json ]; then echo "STATUS $(cat ${DATA_DIR}/status.json)"; fi@@ -294,6 +342,12 @@ NODE=${INSTALL_DIR}/node/bin/nodeSTATE=${DATA_DIR}/relay-state.jsonif [ ! -x "$NODE" ] || [ ! -f "$STATE" ]; then echo "RELAY_MISMATCH"; exit 22; fi"$NODE" -e 'try{const s=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"));if(s.relayId!==process.argv[2]||s.ownerPublicKey!==process.argv[3])process.exit(22)}catch{process.exit(22)}' "$STATE" "$2" "$3" || { echo "RELAY_MISMATCH"; exit 22; }+if [ -f /etc/cindy-relay/nginx/state.json ]; then+ systemctl stop cindy-relay-nginx.timer cindy-relay-nginx.service >/dev/null 2>&1 || true+ "$NODE" ${INSTALL_DIR}/relay.mjs nginx --action remove+ systemctl disable cindy-relay-nginx.timer >/dev/null 2>&1 || true+ rm -f /etc/systemd/system/cindy-relay-nginx.timer /etc/systemd/system/cindy-relay-nginx.service+fisystemctl disable --now cindy-relay >/dev/null 2>&1 || truerm -f /etc/systemd/system/cindy-relay.servicesystemctl daemon-reload >/dev/null 2>&1 || true@@ -344,7 +398,11 @@ async function waitForCertificate(remote: Remote): Promise<void> {const active = first(lines, 'ACTIVE');let certificate: { state?: string; error?: string } | undefined;try {- certificate = (JSON.parse(first(lines, 'STATUS') ?? '{}') as { certificate?: { state?: string; error?: string } }).certificate;+ certificate = (+ JSON.parse(first(lines, 'STATUS') ?? '{}') as {+ certificate?: { state?: string; error?: string };+ }+ ).certificate;} catch {certificate = undefined;}@@ -366,7 +424,9 @@ async function verifyReachable(baseUrl: string, relayId: string): Promise<void>let lastError = '';for (let attempt = 0; attempt < 4; attempt++) {try {- const res = await fetch(`${baseUrl}/api/device-link/relay/info`, { signal: AbortSignal.timeout(10_000) });+ const res = await fetch(`${baseUrl}/api/device-link/relay/info`, {+ signal: AbortSignal.timeout(10_000),+ });const body = (await res.json()) as { relayId?: string };if (res.ok && body.relayId === relayId) return;lastError = `unexpected response (${res.status})`;@@ -378,6 +438,43 @@ async function verifyReachable(baseUrl: string, relayId: string): Promise<void>throw new RelayDeployError('NOT_REACHABLE', lastError.slice(0, 300));}+async function existingHttpsCertificate(baseUrl: string): Promise<boolean> {+ try {+ // 只验证 HTTPS 信任、地址与有效期;站点的 404/403 同样可以证明 TLS 可用。+ const response = await fetch(baseUrl, {+ method: 'HEAD',+ redirect: 'manual',+ signal: AbortSignal.timeout(10_000),+ });+ await response.body?.cancel();+ return true;+ } catch {+ return false;+ }+}++async function nginxAction(remote: Remote, action: string, args: string[] = []): Promise<Record<string, unknown>> {+ const result = await remote.root(NGINX_SCRIPT, [action, ...args], {+ label: `relay-deploy-nginx-${action}`,+ timeoutMs: 120_000,+ });+ const event = result.stdout+ .trim()+ .split('\n')+ .reverse()+ .find((line) => line.startsWith('{'));+ let parsed: Record<string, unknown> = {};+ try {+ parsed = JSON.parse(event ?? '{}') as Record<string, unknown>;+ } catch {+ /* handled below */+ }+ if (result.exitCode !== 0 || parsed.event === 'error') {+ throw new RelayDeployError('NGINX_FAILED', typeof parsed.message === 'string' ? parsed.message.slice(0, 300) : undefined);+ }+ return parsed;+}+/** 部署或升级:服务器上已有本机主人的中转时保留数据,只换程序与配置。 */export async function deployRelayToServer(params: DeployParams): Promise<{ relayVersion: string }> {const bundlePath = resolveRelayBundlePath();@@ -389,8 +486,9 @@ export async function deployRelayToServer(params: DeployParams): Promise<{ relayparams.onStep('check');const inspected = parseLines((await remote.root(INSPECT_SCRIPT, [], { label: 'relay-deploy-inspect' })).stdout);- const busy = inspected.get('BUSY') ?? [];- if (busy.length > 0) throw new RelayDeployError('PORT_BUSY', busy.join(', '));+ const busy = [...new Set(inspected.get('BUSY') ?? [])];+ if (busy.some((line) => !/^(80|443) nginx$/.test(line))) throw new RelayDeployError('PORT_BUSY', busy.join(', '));+ const useNginx = busy.length > 0 || first(inspected, 'NGINX_MANAGED') === 'yes';const state = first(inspected, 'STATE');const assertExistingIdentity = (existingState: string) => {const [, relayId, ownerPublicKey] = existingState.split(' ');@@ -420,7 +518,11 @@ export async function deployRelayToServer(params: DeployParams): Promise<{ relayparams.onStep('upload');const uploaded = expectOk(- await remote.root(UPLOAD_SCRIPT, [], { input: bundle, timeoutMs: 120_000, label: 'relay-deploy-upload' }),+ await remote.root(UPLOAD_SCRIPT, [], {+ input: bundle,+ timeoutMs: 120_000,+ label: 'relay-deploy-upload',+ }),'DEPLOY_FAILED',);if (first(uploaded, 'SHA') !== createHash('sha256').update(bundle).digest('hex')) {@@ -430,33 +532,79 @@ export async function deployRelayToServer(params: DeployParams): Promise<{ relayparams.onStep('configure');const init = params.init;const initArgs = [- '--name', init.name,- '--owner-user', init.ownerUserId,- '--owner-device', init.ownerDeviceId,- '--owner-device-name', init.ownerDeviceName,- '--owner-credential-hash', init.ownerCredentialHash,- '--relay-id', init.relayId,- '--owner-public-key', init.ownerPublicKey,- '--owner-cert', Buffer.from(JSON.stringify(init.ownerCert)).toString('base64url'),+ '--name',+ init.name,+ '--owner-user',+ init.ownerUserId,+ '--owner-device',+ init.ownerDeviceId,+ '--owner-device-name',+ init.ownerDeviceName,+ '--owner-credential-hash',+ init.ownerCredentialHash,+ '--relay-id',+ init.relayId,+ '--owner-public-key',+ init.ownerPublicKey,+ '--owner-cert',+ Buffer.from(JSON.stringify(init.ownerCert)).toString('base64url'),];const acmeDirectory = process.env.CINDY_RELAY_ACME_DIRECTORY ?? '';- const configured = await remote.root(- CONFIGURE_SCRIPT,- [params.address, ipv6 ? '::' : '0.0.0.0', params.baseUrl, params.replaceExisting ? '1' : '0', acmeDirectory, ...initArgs],- { timeoutMs: 180_000, label: 'relay-deploy-configure' },- );- const configureLines = expectOk(configured, 'DEPLOY_FAILED');- log.info('relay configured on server', {- initialized: configureLines.has('INITIALIZED'),- firewall: (configureLines.get('FIREWALL') ?? []).join(',') || 'none',- });+ let mode = 'direct';+ let port = 443;+ let challengePort = 80;+ let nginxPrepared = false;+ try {+ if (useNginx) {+ const args = ['--address', params.address];+ if (ipv6) args.push('--ipv6');+ if (await existingHttpsCertificate(params.baseUrl)) args.push('--existing-certificate');+ const prepared = await nginxAction(remote, 'prepare', args);+ nginxPrepared = true;+ if (!Number.isInteger(prepared.port) || !Number.isInteger(prepared.challengePort)) throw new RelayDeployError('NGINX_FAILED');+ mode = prepared.existingCertificate ? 'nginx-existing' : 'nginx-acme';+ port = prepared.port as number;+ challengePort = prepared.challengePort as number;+ }+ const configured = await remote.root(+ CONFIGURE_SCRIPT,+ [+ params.address,+ useNginx ? '127.0.0.1' : ipv6 ? '::' : '0.0.0.0',+ params.baseUrl,+ params.replaceExisting ? '1' : '0',+ acmeDirectory,+ mode,+ String(port),+ String(challengePort),+ ...initArgs,+ ],+ { timeoutMs: 180_000, label: 'relay-deploy-configure' },+ );+ const configureLines = expectOk(configured, 'DEPLOY_FAILED');+ log.info('relay configured on server', {+ initialized: configureLines.has('INITIALIZED'),+ firewall: (configureLines.get('FIREWALL') ?? []).join(',') || 'none',+ });- params.onStep('certificate');- await waitForCertificate(remote);+ params.onStep('certificate');+ if (mode !== 'nginx-existing') await waitForCertificate(remote);+ if (useNginx) await nginxAction(remote, 'activate');- params.onStep('verify');- await verifyReachable(params.baseUrl, init.relayId);- return { relayVersion: RELAY_VERSION };+ params.onStep('verify');+ await verifyReachable(params.baseUrl, init.relayId);+ if (useNginx) await nginxAction(remote, 'commit');+ return { relayVersion: RELAY_VERSION };+ } catch (error) {+ if (nginxPrepared) {+ try {+ await nginxAction(remote, 'rollback');+ } catch {+ throw new RelayDeployError('NGINX_FAILED', 'Nginx rollback could not be completed; server configuration backup retained');+ }+ }+ throw error;+ }}export async function uninstallRelayFromServer(@@ -472,7 +620,9 @@ export async function uninstallRelayFromServer(const [, relayId, ownerPublicKey] = (first(inspected, 'STATE') ?? '').split(' ');if (relayId !== identity.relayId || ownerPublicKey !== identity.ownerPublicKey) throw new RelayDeployError('RELAY_MISMATCH');onStep('configure');- const result = await remote.root(UNINSTALL_SCRIPT, [removeData ? '1' : '0', identity.relayId, identity.ownerPublicKey], { label: 'relay-deploy-uninstall' });+ const result = await remote.root(UNINSTALL_SCRIPT, [removeData ? '1' : '0', identity.relayId, identity.ownerPublicKey], {+ label: 'relay-deploy-uninstall',+ });if (parseLines(result.stdout).has('RELAY_MISMATCH')) throw new RelayDeployError('RELAY_MISMATCH');expectOk(result, 'DEPLOY_FAILED');}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 6b7b0db19f..0291171796 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5693,7 +5693,8 @@"SSH_FAILED": "Can't connect to the server. Check its SSH settings under Remote.","NEEDS_ROOT": "This needs the root account, or an account that can use sudo without a password. Cindy never asks for your server password.","UNSUPPORTED_SYSTEM": "Only 64-bit Linux with systemd (x64 / arm64) is supported, and curl or wget must be installed.",- "PORT_BUSY": "Port 80 or 443 on the server is used by another program, such as a web server. Stop it first, or use another server.",+ "PORT_BUSY": "Another service is using port 80 or 443 and can't be configured automatically. Existing Nginx is handled automatically; check other services using these ports.",+ "NGINX_FAILED": "Nginx configuration couldn't be completed, so deployment stopped. See the details for the reason.","DOWNLOAD_FAILED": "The server couldn't download the runtime from the official source or the mirror. Check that the server can reach the internet.","RELAY_MISMATCH": "This server already has a relay that wasn't deployed from this computer. You can remove it and redeploy.","CERTIFICATE_FAILED": "Couldn't get an HTTPS certificate. Usually port 80 isn't allowed in the cloud security group, or the domain doesn't point to this server yet. Fix that, then retry.",@@ -5710,7 +5711,7 @@"deploy": {"title": "Deploy to my server","hint": "Install the relay on your own Linux server so your phone and devices on other networks can connect. Cindy installs it over the SSH connection set up under Remote, gets an HTTPS certificate and renews it automatically.",- "requirements": "Requires 64-bit Linux with systemd, root or passwordless sudo, ports 80 and 443 not used by another program, and TCP 80 and 443 allowed in your cloud provider's security group or firewall.",+ "requirements": "Requires 64-bit Linux with systemd, root or passwordless sudo, and TCP 80 and 443 allowed in your cloud security group or firewall. Cindy automatically checks and configures existing Nginx.","noHosts": "No servers yet. Add an SSH host under Remote, then come back to deploy.","server": "Server","address": "Address",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex a20c19c298..1ee421a5af 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5662,7 +5662,8 @@"SSH_FAILED": "サーバーに接続できません。「リモート」でこのサーバーの SSH 設定を確認してください。","NEEDS_ROOT": "root アカウント、またはパスワードなしで sudo を使えるアカウントが必要です。Cindy がサーバーのパスワードを求めることはありません。","UNSUPPORTED_SYSTEM": "対応しているのは systemd のある 64 ビット Linux(x64 / arm64)のみで、curl または wget が必要です。",- "PORT_BUSY": "サーバーの 80 または 443 ポートを他のプログラム(Web サーバーなど)が使っています。停止するか、別のサーバーを使ってください。",+ "PORT_BUSY": "ポート 80 または 443 を使用中のサービスに自動接続できません。既存の Nginx は自動で設定されます。ほかにポートを使用しているサービスを確認してください。",+ "NGINX_FAILED": "Nginx の設定を完了できなかったため、デプロイを停止しました。詳しい理由を確認してください。","DOWNLOAD_FAILED": "サーバーが実行環境をダウンロードできませんでした(公式ソースとミラーの両方で失敗)。サーバーがインターネットに接続できるか確認してください。","RELAY_MISMATCH": "このサーバーには、このコンピュータ以外からデプロイされたリレーがあります。削除して再デプロイできます。","CERTIFICATE_FAILED": "HTTPS 証明書を取得できませんでした。多くの場合、クラウドのセキュリティグループで 80 ポートが許可されていないか、ドメインがまだこのサーバーを指していません。対処してから再試行してください。",@@ -5679,7 +5680,7 @@"deploy": {"title": "自分のサーバーにデプロイ","hint": "リレーを自分の Linux サーバーにインストールすると、スマホや別のネットワークのデバイスからも接続できます。Cindy は「リモート」で設定した SSH 接続でインストールし、HTTPS 証明書を自動で取得・更新します。",- "requirements": "必要なもの:systemd のある 64 ビット Linux、root またはパスワードなしの sudo、他のプログラムが使っていない 80 と 443 ポート、クラウドのセキュリティグループやファイアウォールでの TCP 80 と 443 の許可。",+ "requirements": "systemd のある 64 ビット Linux、root またはパスワードなしの sudo、クラウドのセキュリティグループやファイアウォールでの TCP 80 と 443 の許可が必要です。既存の Nginx は Cindy が自動で確認・設定します。","noHosts": "使えるサーバーがまだありません。「リモート」で SSH ホストを追加してから戻ってきてください。","server": "サーバー","address": "アクセス用アドレス",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 5951a45b49..586beb4510 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5662,7 +5662,8 @@"SSH_FAILED": "서버에 연결할 수 없습니다. 원격에서 이 서버의 SSH 설정을 확인하세요.","NEEDS_ROOT": "root 계정이나 암호 없이 sudo를 쓸 수 있는 계정이 필요합니다. Cindy는 서버 암호를 묻지 않습니다.","UNSUPPORTED_SYSTEM": "systemd가 있는 64비트 Linux(x64 / arm64)만 지원하며, curl 또는 wget이 필요합니다.",- "PORT_BUSY": "서버의 80 또는 443 포트를 다른 프로그램(예: 웹 서버)이 사용 중입니다. 먼저 중지하거나 다른 서버를 사용하세요.",+ "PORT_BUSY": "80 또는 443 포트를 사용하는 서비스에 자동으로 연결할 수 없습니다. 기존 Nginx는 자동으로 설정됩니다. 해당 포트를 사용하는 다른 서비스를 확인하세요.",+ "NGINX_FAILED": "Nginx 설정을 완료하지 못해 배포를 중단했습니다. 자세한 이유를 확인하세요.","DOWNLOAD_FAILED": "서버가 실행 환경을 내려받지 못했습니다(공식 소스와 미러 모두 실패). 서버가 인터넷에 연결되는지 확인하세요.","RELAY_MISMATCH": "이 서버에는 이 컴퓨터가 배포하지 않은 중계가 이미 있습니다. 지우고 다시 배포할 수 있습니다.","CERTIFICATE_FAILED": "HTTPS 인증서를 발급받지 못했습니다. 대개 클라우드 보안 그룹에서 80 포트를 허용하지 않았거나 도메인이 아직 이 서버를 가리키지 않기 때문입니다. 해결한 뒤 다시 시도하세요.",@@ -5679,7 +5680,7 @@"deploy": {"title": "내 서버에 배포","hint": "중계를 내 Linux 서버에 설치하면 휴대폰과 다른 네트워크의 기기도 연결할 수 있습니다. Cindy는 원격에서 설정한 SSH 연결로 설치하고, HTTPS 인증서를 자동으로 발급받아 만료 전에 갱신합니다.",- "requirements": "필요 조건: systemd가 있는 64비트 Linux, root 또는 암호 없는 sudo, 다른 프로그램이 쓰지 않는 80·443 포트, 클라우드 보안 그룹이나 방화벽에서 TCP 80·443 허용.",+ "requirements": "systemd가 있는 64비트 Linux, root 또는 암호 없는 sudo, 클라우드 보안 그룹이나 방화벽에서 TCP 80·443 허용이 필요합니다. 기존 Nginx는 Cindy가 자동으로 확인하고 설정합니다.","noHosts": "사용할 수 있는 서버가 없습니다. 원격에서 SSH 호스트를 추가한 뒤 다시 오세요.","server": "서버","address": "접속 주소",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 3484b7c9c1..1ce8cf4dd6 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5662,7 +5662,8 @@"SSH_FAILED": "连不上服务器。请在「远程」里检查这台服务器的 SSH 设置。","NEEDS_ROOT": "需要 root 账号,或这个账号能免密码使用 sudo。Cindy 不会索要服务器密码。","UNSUPPORTED_SYSTEM": "目前只支持带 systemd 的 64 位 Linux(x64 / arm64),并且需要 curl 或 wget。",- "PORT_BUSY": "服务器的 80 或 443 端口已被其他程序占用(例如网站服务)。请先停用它,或换一台服务器。",+ "PORT_BUSY": "服务器的 80 或 443 端口被其他服务占用,暂时无法自动接入。已有 Nginx 会自动配置,请检查占用端口的其他服务。",+ "NGINX_FAILED": "未能完成 Nginx 配置,部署已停止。请查看详细原因。","DOWNLOAD_FAILED": "服务器下载运行环境失败(官方源和国内镜像都没成功)。请检查服务器能否访问外网。","RELAY_MISMATCH": "这台服务器上已有一个不是这台电脑部署的中转。可以清除它后重新部署。","CERTIFICATE_FAILED": "申请 HTTPS 证书失败。通常是云服务器安全组没有放行 80 端口,或域名还没解析到这台服务器。处理后点重试。",@@ -5679,7 +5680,7 @@"deploy": {"title": "部署到我的服务器","hint": "把中转装到你自己的 Linux 服务器上,手机和不在同一网络的设备都能连。Cindy 通过「远程」里配置的 SSH 连接安装,并自动申请 HTTPS 证书、到期前自动续期。",- "requirements": "需要:64 位 Linux(带 systemd)、root 或免密 sudo,服务器的 80 和 443 端口没被其他程序占用,并在云服务器控制台的安全组或防火墙里放行 TCP 80 和 443。",+ "requirements": "需要:64 位 Linux(带 systemd)、root 或免密 sudo,并在云服务器安全组或防火墙里放行 TCP 80 和 443。Cindy 会自动检查并配置已有的 Nginx。","noHosts": "还没有可用的服务器。先在「远程」里添加 SSH 主机,再回来部署。","server": "服务器","address": "访问地址",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 12830d5a10..1c1b25618d 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -5662,7 +5662,8 @@"SSH_FAILED": "連不上伺服器。請在「遠端」裡檢查這台伺服器的 SSH 設定。","NEEDS_ROOT": "需要 root 帳號,或這個帳號能免密碼使用 sudo。Cindy 不會索取伺服器密碼。","UNSUPPORTED_SYSTEM": "目前只支援含 systemd 的 64 位元 Linux(x64 / arm64),並且需要 curl 或 wget。",- "PORT_BUSY": "伺服器的 80 或 443 連接埠已被其他程式佔用(例如網站服務)。請先停用它,或換一台伺服器。",+ "PORT_BUSY": "伺服器的 80 或 443 連接埠被其他服務佔用,暫時無法自動接入。現有 Nginx 會自動設定,請檢查佔用連接埠的其他服務。",+ "NGINX_FAILED": "未能完成 Nginx 設定,部署已停止。請查看詳細原因。","DOWNLOAD_FAILED": "伺服器下載執行環境失敗(官方來源和鏡像都沒成功)。請檢查伺服器能否連上外網。","RELAY_MISMATCH": "這台伺服器上已有一個不是這台電腦部署的中繼。可以清除它後重新部署。","CERTIFICATE_FAILED": "申請 HTTPS 憑證失敗。通常是雲端主機安全群組沒有放行 80 連接埠,或網域還沒解析到這台伺服器。處理後點重試。",@@ -5679,7 +5680,7 @@"deploy": {"title": "部署到我的伺服器","hint": "把中繼裝到你自己的 Linux 伺服器上,手機和不在同一網路的裝置都能連。Cindy 透過「遠端」裡設定的 SSH 連線安裝,並自動申請 HTTPS 憑證、到期前自動續期。",- "requirements": "需要:64 位元 Linux(含 systemd)、root 或免密碼 sudo,伺服器的 80 和 443 連接埠沒被其他程式佔用,並在雲端主機控制台的安全群組或防火牆裡放行 TCP 80 和 443。",+ "requirements": "需要:64 位元 Linux(含 systemd)、root 或免密碼 sudo,並在雲端伺服器安全群組或防火牆裡開放 TCP 80 和 443。Cindy 會自動檢查並設定現有的 Nginx。","noHosts": "還沒有可用的伺服器。先在「遠端」裡新增 SSH 主機,再回來部署。","server": "伺服器","address": "存取位址",diff --git a/apps/desktop/src/shared/selfHostedRelay.ts b/apps/desktop/src/shared/selfHostedRelay.tsindex 30f5900c1f..1b539d5f5f 100644--- a/apps/desktop/src/shared/selfHostedRelay.ts+++ b/apps/desktop/src/shared/selfHostedRelay.ts@@ -70,6 +70,7 @@ export type RelayDeployErrorCode =| 'UNSUPPORTED_SYSTEM'/** 80 或 443 端口被其他程序占用。 */| 'PORT_BUSY'+ | 'NGINX_FAILED'/** 下载运行环境失败(官方源与国内镜像都失败,或校验不符)。 */| 'DOWNLOAD_FAILED'/** 服务器上已有不属于这台电脑的中转。 */diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 981ae31172..1c7bf46717 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -292,6 +292,12 @@ stream 匹配后才处理;信令不进入业务可靠 FIFO,也不走直连### 自建中转同步维护+服务器部署的 Nginx 自动接入使用中转 bundle `0.3.0`(`nginx` 为 SSH 部署内部 CLI)。公网仍使用+原有 HTTPS/WSS 地址、`CindyRelay` 认证、媒体签名地址及 v1 设备协议;不新增跨端帧、能力位或权限。+已部署 `0.2.0` 的通信行为继续兼容,需要自动配置 Nginx 时由现有升级入口上传新 bundle。+Desktop/Mobile 继续共用原客户端,无须更改服务端;验证入口见+[`self-hosted-relay-plan.md §15.3`](../self-hosted-relay-plan.md#153-第-3-步设备签名一键部署到服务器远程管理2026-10-28)。+**硬性要求:凡 Device Link 的改动会影响自建中转,必须在同一次改动中完成必要的同步适配、兼容处理与验证。缺少这些内容视为未完成,不得只完成官方中转路径后把自建中转留到后续。**diff --git a/docs/self-hosted-relay-plan.md b/docs/self-hosted-relay-plan.mdindex f797b261c1..7e4a8e3dc6 100644--- a/docs/self-hosted-relay-plan.md+++ b/docs/self-hosted-relay-plan.md@@ -82,7 +82,7 @@| 方式 | 做法 | 手机能否加入 | 典型场景 || --- | --- | --- | --- |-| 自动证书 | 内核用 ACME 向 Let's Encrypt 申请并自动续期。<br>有域名时用域名证书。<br>没有域名时用 **IP 地址证书**:2026-01-15 正式提供,有效期约 6 天,需要自动续期([公告](https://letsencrypt.org/2026/01/15/6day-and-ip-general-availability))。<br>验证方式用 `tls-alpn-01`,只要求公网能访问 443 | 能 | A 的默认方式;B 中有公网 IP 的电脑 |+| 自动证书 | 内核用 ACME 向 Let's Encrypt 申请并自动续期。<br>有域名时用域名证书。<br>没有域名时用 **IP 地址证书**:2026-01-15 正式提供,有效期约 6 天,需要自动续期([公告](https://letsencrypt.org/2026/01/15/6day-and-ip-general-availability))。<br>实际实现使用 `http-01`,公网 80 提供验证,443 提供 HTTPS | 能 | A 的默认方式;B 中有公网 IP 的电脑 || 前置代理提供 | 内核只在 `127.0.0.1` 上明文监听。<br>TLS 由用户自己的 nginx、Caddy、frp、内网穿透服务或 Tailscale serve 等提供 | 取决于前置代理的证书是否受信任 | B 的常见情况;服务器上 443 已被别的网站占用时 || 自签名 + 指纹固定 | 内核生成自签名证书,加入链接里附带证书指纹,电脑端按指纹校验 | **不能**(需要原生改动),界面直接说明 | B,只连自己的几台电脑 |@@ -91,7 +91,7 @@IP 证书的注意点:- 有效期只有约 6 天,内核大约每 3 天续期一次。续期失败时,管理状态里显示证书剩余时间,并提醒主人。-- 申请证书需要支持 ACME profile(`shortlived`)和 `tls-alpn-01` 的客户端,选型在实现时确定。+- 申请 IP 证书使用 ACME profile(`shortlived`)与 `http-01`,实现见 `packages/device-link-relay/src/acme.ts`。### 2.3 管理:主人凭证@@ -555,6 +555,16 @@ App 内不加扫码组件:加一个会改变原生指纹,需要冷更。- systemd 服务以 `cindy-relay` 用户运行,只放行绑定低端口的权限;`ProtectSystem=strict`,只能写数据目录。- 主人身份(中转 ID、主人凭证、主人密钥)只在这台电脑生成;服务器只拿到凭证哈希、主人公钥和主人证书。- 身份在动服务器之前就记进部署记录:中途失败重试,用的还是同一份身份,不会和服务器上已初始化的数据冲突。+- 已有 Nginx 的自动接入(2026-10-29,服务器 bundle `0.3.0`):+ - 沿用同一个部署入口,自动判断 80/443 的占用者;原生 Nginx 自动接入,其他程序不停止、不接管。+ - 从运行中的 master 与 `nginx -T` 找到实际配置,不要求用户选安装目录或复制配置。+ - 访问地址已有可信 HTTPS 时沿用原证书管理,中转仅在回环地址提供 HTTP;否则中转在回环地址申请、续期证书,Nginx 转发 HTTP-01 验证并提供公网 HTTPS。+ - 自动探测空闲回环端口,代理 REST、WebSocket 与媒体流;保留站点根路径与常见 ACME webroot 的其他验证文件。填写 IP 时自动设置无 SNI 握手所需的默认证书,域名网站仍使用自己的证书。+ - 配置、备份与导出的证书仅存在服务器的 `/etc/cindy-relay/nginx` 私有目录;`nginx -t` 通过后平滑重载。证书按代写入私有目录,systemd timer 每 5 分钟检查并原子切换引用。+ - 验证成功才提交事务;失败或 SSH 中断后重试自动恢复。恢复检测到管理员并发修改时保留备份并停止,不能覆盖新修改。卸载撤销本次补丁,不停止 Nginx。+ - 不支持安全解析的配置(例如没有精确地址的正则站点名、复杂的自定义 ACME 处理器或多个 master)明确失败,不猜测、不覆盖。+ - 实现:`packages/device-link-relay/src/nginx.ts`;回归:同目录 `__tests__/nginx.test.ts` 与 Desktop `selfHostedRelayDeploy.test.ts`;真实 Nginx 验证:`pnpm --filter @cindy/device-link-relay run interop:nginx`(Docker 内运行,不访问用户服务器)。+ - 已验证:中转内核 26 例、Desktop 部署与运行时 22 例及两包类型检查通过。真实 Nginx 容器覆盖仅 HTTP、仅 HTTPS、原网站域名证书、其他 ACME 客户端、REST、WebSocket、大于 1 MB 的上传、证书轮换、升级回滚、已有 HTTPS 复用和卸载恢复。测试使用容器内临时证书,生产 CA 签发和真实云服务器部署仍未验证。- 服务器上已有不属于这台电脑的中转时停下(`RELAY_MISMATCH`),由用户选择清掉重新部署。**远程管理**(设置 → 远程连接 → 中转服务):@@ -623,7 +633,7 @@ App 内不加扫码组件:加一个会改变原生指纹,需要冷更。1. 使用含本次代码的桌面开发版,在「设置 → 远程」配置自己的 Linux SSH 主机。2. 打开「设置 → 远程连接 → 中转服务 → 部署到我的服务器」,选主机、核对访问地址,开始部署。- 主机需支持 systemd,并具备 root 或免密 sudo;80/443 端口不能被其他服务占用,云安全组需放行这两个端口。+ 主机需支持 systemd,并具备 root 或免密 sudo;80/443 端口需空闲或由原生 Nginx 使用,部署时自动接入 Nginx,云安全组需放行这两个端口。3. 等待部署完成并自动切换后,点击「添加设备」。另一台新版电脑粘贴链接,手机用含本次 JS 改动的开发版扫码。在主人电脑核对配对码并同意,再测试设备列表、远程消息、图片和断线重连。4. 切回官方中转,核对原有连接恢复,服务器中转仍继续运行;可以再点击「改用这个中转」。diff --git a/packages/device-link-relay/package.json b/packages/device-link-relay/package.jsonindex 164d6c9646..1387b3e7db 100644--- a/packages/device-link-relay/package.json+++ b/packages/device-link-relay/package.json@@ -14,6 +14,7 @@"typecheck": "tsc --noEmit","test": "vitest run","interop": "tsx scripts/run-interop.ts",+ "interop:nginx": "node build.mjs && tsx scripts/nginx-interop.ts","bundle": "node build.mjs"},"author": {diff --git a/packages/device-link-relay/scripts/nginx-interop.ts b/packages/device-link-relay/scripts/nginx-interop.tsnew file mode 100644index 0000000000..9858bfdc6e--- /dev/null+++ b/packages/device-link-relay/scripts/nginx-interop.ts@@ -0,0 +1,407 @@+/** 手动集成验证:pnpm --filter @cindy/device-link-relay run interop:nginx。+ * Docker 内运行真实 Nginx、CLI、中转、TLS/WS/媒体;不连接用户服务器,不读取本机凭证。+ * 容器与构建目录仅属于本次验证,结束时精确清理。证书只在容器的临时文件系统生成。+ */+import assert from 'node:assert/strict';+import { execFileSync, spawn } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import fs from 'node:fs';+import https from 'node:https';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import WebSocket from 'ws';+import { createRelaySigningKey, issueRelayDeviceCert } from '@cindy/device-link';+import { nodeRelayAuthCrypto } from '@cindy/device-link/node-relay-crypto';+import { createDeviceCredential, initializeRelay, startRelayServer } from '../src/index';+import { startChallengeServer } from '../src/certificates';++function command(file: string, args: string[]) {+ return execFileSync(file, args, {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: 60_000,+ });+}++async function retry<T>(check: () => Promise<T>, accepted: (value: T) => boolean): Promise<T> {+ const deadline = Date.now() + 10_000;+ while (Date.now() < deadline) {+ try {+ const value = await check();+ if (accepted(value)) return value;+ } catch {+ /* Nginx graceful reload */+ }+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ throw new Error('Nginx interop condition timed out');+}++async function inside() {+ const dataDir = '/var/lib/cindy-relay';+ const main = '/etc/nginx/nginx.conf';+ const site = '/etc/nginx/conf.d/website.conf';+ fs.mkdirSync('/tmp/website', { recursive: true });+ fs.mkdirSync('/tmp/acme/.well-known/acme-challenge', { recursive: true });+ fs.writeFileSync('/tmp/acme/.well-known/acme-challenge/other-client', 'other-client-proof');+ function certificate(name: string, san: string) {+ const dir = `/tmp/${name}`;+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(`${dir}/openssl.cnf`, '[req]\ndistinguished_name = dn\n[dn]\n');+ command('openssl', [+ 'req',+ '-config',+ `${dir}/openssl.cnf`,+ '-x509',+ '-newkey',+ 'rsa:2048',+ '-nodes',+ '-days',+ '2',+ '-keyout',+ `${dir}/key.pem`,+ '-out',+ `${dir}/cert.pem`,+ '-subj',+ '/CN=Cindy interop',+ '-addext',+ `subjectAltName=${san}`,+ ]);+ return {+ key: fs.readFileSync(`${dir}/key.pem`, 'utf8'),+ cert: fs.readFileSync(`${dir}/cert.pem`, 'utf8'),+ };+ }+ const websiteMaterial = certificate('website-tls', 'DNS:website.example.test');+ const initialMain =+ 'user nobody nogroup; worker_processes 1; pid /tmp/nginx.pid; events { worker_connections 128; } http { access_log off; include /etc/nginx/conf.d/website.conf; }\n';+ const initialSite = `server { listen 80 default_server; server_name website.example.test;+ location / { return 200 "website-home"; }+ location ^~ /.well-known/acme-challenge/ { root /tmp/acme; try_files $uri =404; }+ }+ server { listen 443 ssl default_server; server_name _;+ ssl_certificate /tmp/website-tls/cert.pem; ssl_certificate_key /tmp/website-tls/key.pem;+ location / { return 200 "website-home"; }+ }\n`;+ fs.writeFileSync(main, initialMain);+ fs.writeFileSync(site, initialSite);+ const nginx = spawn('nginx', ['-c', main, '-g', 'daemon off;'], {+ stdio: 'ignore',+ });+ await retry(+ () => fetch('http://127.0.0.1').then((r) => r.text()),+ (value) => value === 'website-home',+ );+ const cli = (action: string, flags: string[] = []): Record<string, any> =>+ JSON.parse(command(process.execPath, ['/tmp/relay.mjs', 'nginx', '--action', action, ...flags]).trim());+ const prepare = (existing = false) => cli('prepare', ['--address', '127.0.0.1', ...(existing ? ['--existing-certificate'] : [])]);+ const owner = createDeviceCredential();+ const ownerKey = createRelaySigningKey(nodeRelayAuthCrypto);+ const relayId = randomUUID();+ await initializeRelay({+ dataDir,+ name: 'Nginx interop',+ ownerUserId: 'interop-owner',+ ownerDeviceId: 'owner-pc',+ ownerDeviceName: 'PC',+ ownerCredentialHash: owner.credentialHash,+ relayId,+ ownerPublicKey: ownerKey.publicKey,+ ownerCert: issueRelayDeviceCert(nodeRelayAuthCrypto, ownerKey.seed, {+ relayId,+ deviceId: 'owner-pc',+ publicKey: ownerKey.publicKey,+ role: 'owner',+ issuedAt: Date.now(),+ }),+ });+ let material = certificate('relay-one', 'IP:127.0.0.1');+ const saveMaterial = () => {+ fs.mkdirSync(`${dataDir}/tls`, { recursive: true, mode: 0o700 });+ fs.writeFileSync(`${dataDir}/tls/material.json`, JSON.stringify(material), {+ mode: 0o600,+ });+ };+ const get = (pathname: string, method = 'GET', body?: Buffer, headers: Record<string, string> = {}) =>+ new Promise<{ status: number; body: Buffer }>((resolve, reject) => {+ const req = https.request(`https://127.0.0.1${pathname}`, { method, ca: material.cert, agent: false, headers }, (res) => {+ const chunks: Buffer[] = [];+ res.on('data', (chunk) => chunks.push(chunk));+ res.on('end', () => resolve({ status: res.statusCode!, body: Buffer.concat(chunks) }));+ });+ req.on('error', reject);+ req.end(body);+ });+ let relay: Awaited<ReturnType<typeof startRelayServer>> | undefined;+ let challenge: Awaited<ReturnType<typeof startChallengeServer>> | undefined;+ try {+ fs.writeFileSync(site, initialSite.slice(initialSite.indexOf('server { listen 443')));+ command('nginx', ['-t']);+ process.kill(nginx.pid!, 'SIGHUP');+ const httpsOnly = prepare();+ challenge = await startChallengeServer({+ host: '127.0.0.1',+ port: httpsOnly.challengePort,+ challenges: new Map([['https-only', 'https-only-proof']]),+ });+ await retry(+ () => fetch('http://127.0.0.1/.well-known/acme-challenge/https-only').then((r) => r.text()),+ (value) => value === 'https-only-proof',+ );+ cli('rollback');+ await challenge.close();+ challenge = undefined;+ fs.writeFileSync(site, initialSite);+ command('nginx', ['-t']);+ process.kill(nginx.pid!, 'SIGHUP');+ const plan = prepare();+ challenge = await startChallengeServer({+ host: '127.0.0.1',+ port: plan.challengePort,+ challenges: new Map([['cindy-token', 'cindy-proof']]),+ });+ await retry(+ () => fetch('http://127.0.0.1/.well-known/acme-challenge/cindy-token').then((r) => r.text()),+ (value) => value === 'cindy-proof',+ );+ await retry(+ () => fetch('http://127.0.0.1/.well-known/acme-challenge/other-client').then((r) => r.text()),+ (value) => value === 'other-client-proof',+ );+ saveMaterial();+ relay = await startRelayServer({+ dataDir,+ host: '127.0.0.1',+ port: plan.port,+ tls: material,+ publicUrl: 'https://127.0.0.1',+ });+ cli('activate');+ await retry(+ () => get('/api/device-link/relay/info'),+ (value) => value.status === 200,+ );+ assert.equal(JSON.parse((await get('/api/device-link/relay/info')).body.toString()).relayId, relayId);+ assert.equal((await get('/')).body.toString(), 'website-home');+ const originalWebsite = await new Promise<string>((resolve, reject) => {+ const req = https.get(+ {+ hostname: '127.0.0.1',+ servername: 'website.example.test',+ headers: { Host: 'website.example.test' },+ ca: websiteMaterial.cert,+ agent: false,+ },+ (res) => {+ let body = '';+ res.on('data', (chunk) => {+ body += chunk;+ });+ res.on('end', () => resolve(body));+ },+ );+ req.on('error', reject);+ });+ assert.equal(originalWebsite, 'website-home');+ cli('commit');+ const socket = new WebSocket('wss://127.0.0.1/api/device-link/ws', {+ ca: material.cert,+ headers: { Authorization: `CindyRelay ${owner.credential}` },+ });+ await new Promise<void>((resolve, reject) => {+ socket.once('open', resolve);+ socket.once('error', reject);+ });+ socket.close();+ const bytes = Buffer.alloc(1_100_000, 42);+ const auth = {+ Authorization: `CindyRelay ${owner.credential}`,+ 'Content-Type': 'application/json',+ };+ const upload = await get(+ '/api/device-link/media/presign-put',+ 'POST',+ Buffer.from(+ JSON.stringify({+ size: bytes.length,+ ext: 'bin',+ contentType: 'application/octet-stream',+ }),+ ),+ auth,+ );+ assert.equal(upload.status, 200);+ const { putUrl } = JSON.parse(upload.body.toString());+ assert.equal(+ (await get(new URL(putUrl).pathname + new URL(putUrl).search, 'PUT', bytes, { 'Content-Type': 'application/octet-stream' })).status,+ 200,+ );+ console.log('[nginx-interop] IP TLS, REST, authenticated WebSocket, >1 MB upload, original website and other ACME client passed');+ material = certificate('relay-two', 'IP:127.0.0.1');+ saveMaterial();+ relay.updateTls(material);+ cli('renew');+ await retry(+ () => get('/api/device-link/relay/info'),+ (value) => value.status === 200,+ );+ prepare();+ cli('rollback');+ await retry(+ () => get('/api/device-link/relay/info'),+ (value) => value.status === 200,+ );+ cli('remove');+ assert.equal(fs.readFileSync(main, 'utf8'), initialMain);+ assert.equal(fs.readFileSync(site, 'utf8'), initialSite);+ await relay.close();+ relay = undefined;+ await challenge.close();+ challenge = undefined;+ // 已有可信 HTTPS 时:保留原证书管理,中转自动改为回环 HTTP。+ fs.writeFileSync('/tmp/website-tls/cert.pem', material.cert);+ fs.writeFileSync('/tmp/website-tls/key.pem', material.key);+ command('nginx', ['-t']);+ process.kill(nginx.pid!, 'SIGHUP');+ const existing = prepare(true);+ assert.equal(existing.existingCertificate, true);+ relay = await startRelayServer({+ dataDir,+ host: '127.0.0.1',+ port: existing.port,+ publicUrl: 'https://127.0.0.1',+ });+ cli('activate');+ cli('commit');+ await retry(+ () => get('/api/device-link/relay/info'),+ (value) => value.status === 200,+ );+ cli('remove');+ assert.equal(fs.readFileSync(site, 'utf8'), initialSite);+ await relay.close();+ relay = undefined;+ const httpOnlySite = initialSite.slice(0, initialSite.indexOf('server { listen 443'));+ fs.writeFileSync(site, httpOnlySite);+ command('nginx', ['-t']);+ process.kill(nginx.pid!, 'SIGHUP');+ const httpOnly = prepare();+ relay = await startRelayServer({ dataDir, host: '127.0.0.1', port: httpOnly.port, tls: material, publicUrl: 'https://127.0.0.1' });+ cli('activate');+ cli('commit');+ await retry(+ () => get('/api/device-link/relay/info'),+ (value) => value.status === 200,+ );+ assert.equal((await get('/')).body.toString(), 'website-home');+ cli('remove');+ assert.equal(fs.readFileSync(site, 'utf8'), httpOnlySite);+ console.log('[nginx-interop] HTTP-only and HTTPS-only installations passed');+ console.log('[nginx-interop] renewal, interrupted deployment rollback, existing HTTPS reuse and exact uninstall restoration passed');+ } finally {+ await relay?.close();+ await challenge?.close();+ nginx.kill('SIGQUIT');+ }+}++async function docker() {+ const esbuild = await import('esbuild');+ const packageRoot = fileURLToPath(new URL('../', import.meta.url));+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-nginx-interop-'));+ const container = `cindy-nginx-interop-${randomUUID()}`;+ const sources: string[] = [];+ let started = false;+ try {+ await esbuild.build({+ entryPoints: [fileURLToPath(import.meta.url)],+ bundle: true,+ platform: 'node',+ target: 'node22',+ format: 'esm',+ outfile: path.join(temp, 'nginx-interop.mjs'),+ external: ['esbuild', 'bufferutil', 'utf-8-validate'],+ banner: {+ js: "import {createRequire} from 'node:module';const require=createRequire(import.meta.url);",+ },+ });+ fs.copyFileSync(path.join(packageRoot, 'dist', 'relay.mjs'), path.join(temp, 'relay.mjs'));+ command('docker', ['run', '-d', '--name', container, '--label', 'cindy-test=nginx-interop', 'node:22-slim', 'sleep', 'infinity']);+ started = true;+ console.log('[nginx-interop] isolated container started; loading tools from official images');+ command('docker', [+ 'exec',+ container,+ 'mkdir',+ '-p',+ '/etc/nginx/conf.d',+ '/var/log/nginx',+ '/var/cache/nginx',+ '/usr/sbin',+ '/opt/cindy-test',+ ]);+ // 不在测试中访问软件源或安装系统包;从官方镜像复制工具及其依赖,使用独立 musl 搜索路径。+ // 这些文件全部在本次容器内,不修改宿主环境;三个镜像缓存后可完全离线复跑。+ const stage = (image: string, binary: string, name: string) => {+ const source = command('docker', ['create', '--label', 'cindy-test=nginx-interop', image]).trim();+ sources.push(source);+ const listing = command('docker', ['run', '--rm', '--entrypoint', 'ldd', image, binary]);+ const loader = /^\s*(\/lib\/ld-musl-\S+)/m.exec(listing)?.[1];+ if (!loader) throw new Error('Expected an Alpine musl tool image');+ const libraries = [...new Set([...listing.matchAll(/=> (\/\S+)/g)].map((m) => m[1]))];+ const resolvedLibraries = command('docker', [+ 'run',+ '--rm',+ '--entrypoint',+ 'sh',+ image,+ '-c',+ 'for library do readlink -f "$library"; done',+ 'libraries',+ ...libraries,+ ])+ .trim()+ .split('\n');+ const folder = path.join(temp, `${name}-libs`);+ fs.mkdirSync(folder);+ for (const [index, library] of libraries.entries())+ command('docker', ['cp', `${source}:${resolvedLibraries[index]}`, path.join(folder, path.posix.basename(library))]);+ command('docker', ['cp', '-L', `${source}:${binary}`, path.join(temp, name)]);+ command('docker', ['cp', folder, `${container}:/opt/cindy-test/`]);+ command('docker', ['cp', path.join(temp, name), `${container}:/opt/cindy-test/${name}`]);+ if (name === 'nginx') {+ command('docker', ['cp', '-L', `${source}:${loader}`, path.join(temp, 'musl-loader')]);+ command('docker', ['cp', path.join(temp, 'musl-loader'), `${container}:${loader}`]);+ const arch = path.posix.basename(loader).slice('ld-musl-'.length, -'.so.1'.length);+ command('docker', [+ 'exec',+ container,+ 'node',+ '-e',+ `require('node:fs').writeFileSync('/etc/ld-musl-${arch}.path','/opt/cindy-test/nginx-libs');require('node:fs').symlinkSync('/opt/cindy-test/nginx','/usr/sbin/nginx')`,+ ]);+ }+ };+ stage('nginx:alpine', '/usr/sbin/nginx', 'nginx');+ stage('certbot/certbot:latest', '/usr/bin/openssl', 'openssl');+ const opensslWrapper = path.join(temp, 'openssl-wrapper');+ fs.writeFileSync(opensslWrapper, '#!/bin/sh\nLD_LIBRARY_PATH=/opt/cindy-test/openssl-libs exec /opt/cindy-test/openssl "$@"\n');+ command('docker', ['cp', opensslWrapper, `${container}:/usr/local/bin/openssl`]);+ command('docker', ['exec', container, 'chmod', '755', '/usr/local/bin/openssl']);+ command('docker', ['cp', path.join(temp, 'relay.mjs'), `${container}:/tmp/relay.mjs`]);+ command('docker', ['cp', path.join(temp, 'nginx-interop.mjs'), `${container}:/tmp/nginx-interop.mjs`]);+ execFileSync('docker', ['exec', container, 'node', '/tmp/nginx-interop.mjs', '--inside'], { stdio: 'inherit', timeout: 120_000 });+ } finally {+ for (const source of sources) execFileSync('docker', ['rm', '-f', source], { stdio: 'ignore' });+ if (started) execFileSync('docker', ['rm', '-f', container], { stdio: 'ignore' });+ const resolved = path.resolve(temp);+ if (path.dirname(resolved) === path.resolve(os.tmpdir()) && path.basename(resolved).startsWith('cindy-nginx-interop-'))+ fs.rmSync(resolved, { recursive: true, force: true });+ }+}++(process.argv.includes('--inside') ? inside() : docker()).catch((error) => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/packages/device-link-relay/src/__tests__/nginx.test.ts b/packages/device-link-relay/src/__tests__/nginx.test.tsnew file mode 100644index 0000000000..9e00cf6246--- /dev/null+++ b/packages/device-link-relay/src/__tests__/nginx.test.ts@@ -0,0 +1,272 @@+/**+ * 测试价值+ * - 生产入口:manageNginx 的 prepare/activate/renew/rollback/remove;观察实际写出的配置与恢复结果。+ * - 规则依据:2026-10-29 用户要求自动兼容 Nginx;不得停用已有网站、覆盖其他人的配置或破坏证书续期。+ * - 现有覆盖缺口:Desktop SSH fake 只覆盖调度,未执行远端配置事务。+ * - 最小输入:带默认网站的 80/443 配置、同一个块监听两端口、校验失败及中途断开。+ * - tier:unit。文件系统/进程为内存适配,独立 CLI 的真实 Nginx 验证另在 Docker 执行。+ * - 实测耗时:单独运行本文件 0.41 秒(8 例,2026-10-29)。+ */+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ files: new Map<string, string>(),+ tests: 0,+ failTest: 0,+ signals: [] as number[],+ masterPid: '123',+}));+const missing = () => Object.assign(new Error('not found'), { code: 'ENOENT' });+vi.mock('node:fs', () => ({+ default: {+ statSync: (file: string) => {+ if (!h.files.has(file)) throw missing();+ return {+ size: Buffer.byteLength(h.files.get(file)!),+ mode: 0o100644,+ uid: 0,+ gid: 0,+ };+ },+ existsSync: (file: string) => h.files.has(file),+ readFileSync: (file: string) => {+ if (!h.files.has(file)) throw missing();+ return h.files.get(file)!;+ },+ realpathSync: (file: string) => file,+ writeFileSync: (file: string, value: string) => {+ h.files.set(file, value);+ },+ renameSync: (from: string, to: string) => {+ h.files.set(to, h.files.get(from)!);+ h.files.delete(from);+ },+ chownSync: () => {},+ mkdirSync: () => {},+ rmSync: (file: string, options?: { recursive?: boolean }) => {+ for (const key of h.files.keys()) if (key === file || (options?.recursive && key.startsWith(`${file}/`))) h.files.delete(key);+ },+ readdirSync: () => [h.masterPid],+ readlinkSync: () => '/usr/sbin/nginx',+ },+}));+vi.mock('node:child_process', () => ({+ execFileSync: (binary: string, args: string[]) => {+ if (binary === 'ss') return 'LISTEN 0 511 0.0.0.0:80 0.0.0.0:*\nLISTEN 0 511 0.0.0.0:47820 0.0.0.0:*';+ if (args.includes('-T'))+ return [...h.files]+ .filter(([file]) => file.startsWith('/etc/nginx/') || file.endsWith('/http.conf'))+ .map(([file, text]) => `# configuration file ${file}:\n${text}\n`)+ .join('\n');+ if (++h.tests === h.failTest) throw new Error('invalid configuration');+ return '';+ },+}));+vi.mock('node:crypto', async (importOriginal) => ({+ ...(await importOriginal<typeof import('node:crypto')>()),+ createPrivateKey: (value: string) => value,+ X509Certificate: class {+ validTo = '2099-01-01';+ subjectAltName = 'DNS:website.example.test, DNS:www.example.test';+ subject = 'CN=website.example.test';+ constructor(private readonly cert: string) {}+ checkIP(address: string) {+ return address === '203.0.113.10';+ }+ checkHost(address: string) {+ return address === 'relay.example.test';+ }+ checkPrivateKey(key: string) {+ return this.cert === `test-cert-${key}`;+ }+ },+}));++import { manageNginx } from '../nginx';++const main = '/etc/nginx/nginx.conf';+const site = '/etc/nginx/conf.d/website.conf';+const root = '/etc/cindy-relay/nginx';+const originalMain = 'events {}\nhttp { include /etc/nginx/conf.d/*.conf; }';+const originalSite = `server { listen 80 default_server; server_name website.example.test;+ return 301 https://$host$request_uri;+ location ^~ /.well-known/acme-challenge/ { root /var/www/acme; try_files $uri =404; }+}+server { listen 443 ssl default_server; server_name website.example.test;+ ssl_certificate /website/cert.pem; ssl_certificate_key /website/key.pem;+ root /website/public; location / { try_files $uri $uri/ /index.html; }+}`;+function material(key: string) {+ h.files.set('/var/lib/cindy-relay/tls/material.json', JSON.stringify({ cert: `test-cert-${key}`, key }));+}+function prepare(existingCertificate = false) {+ return manageNginx('prepare', {+ address: '203.0.113.10',+ ipv6: true,+ existingCertificate,+ });+}++beforeEach(() => {+ h.files = new Map([+ [main, originalMain],+ [site, originalSite],+ ['/website/cert.pem', 'original-website-cert'],+ ['/site/cert.pem', 'original-website-cert'],+ ['/proc/net/tcp', '0: 00000000:0050 00000000:0000 0A\n1: 00000000:BACC 00000000:0000 0A\n'],+ ['/proc/123/cmdline', 'nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf'],+ ]);+ h.tests = 0;+ h.masterPid = '123';+ h.failTest = 0;+ h.signals = [];+ const real = process;+ vi.stubGlobal('process', {+ ...real,+ platform: 'linux',+ getuid: () => 0,+ kill: (pid: number, signal: string | number) => {+ if (signal === 0) throw Object.assign(new Error('no process'), { code: 'ESRCH' });+ h.signals.push(pid);+ },+ });+});+afterEach(() => vi.unstubAllGlobals());++it('preserves the original website and ACME webroot through certificate rotation, upgrade and removal', () => {+ const prepared = prepare();+ expect(prepared).toEqual({+ port: 47821,+ challengePort: 47822,+ existingCertificate: false,+ });+ expect(h.files.get(site)).toContain('location @cindy_relay_existing_acme { root /var/www/acme; try_files $uri =404;');+ expect(h.files.get(site)).toContain('ssl_certificate /website/cert.pem;');+ material('key-one');+ manageNginx('activate');+ manageNginx('commit');+ const beforeRenewal = h.files.get(`${root}/http.conf`)!;+ expect(beforeRenewal).toContain('root /website/public; location / { try_files $uri $uri/ /index.html; }');+ expect(beforeRenewal).toContain('proxy_pass https://127.0.0.1:47821;');+ expect(beforeRenewal).toContain('server_name 203.0.113.10;');+ material('key-two');+ h.masterPid = '456';+ h.files.set('/proc/456/cmdline', h.files.get('/proc/123/cmdline')!);+ manageNginx('renew');+ expect(h.signals.at(-1)).toBe(456);+ expect(h.files.get(`${root}/http.conf`)).not.toBe(beforeRenewal);+ prepare();+ manageNginx('activate');+ manageNginx('commit');+ manageNginx('remove');+ expect(h.files.get(main)).toBe(originalMain);+ expect(h.files.get(site)).toBe(originalSite);+ expect(h.files.has(`${root}/state.json`)).toBe(false);+});++it('keeps HTTP validation working when one server block listens on both 80 and 443', () => {+ h.files.set(+ site,+ 'server { listen 80; listen 443 ssl; server_name 203.0.113.10; ssl_certificate /site/cert.pem; ssl_certificate_key /site/key.pem; return 301 https://www.example.test$request_uri; }',+ );+ const original = h.files.get(site);+ prepare();+ expect(h.files.get(site)).toContain('proxy_pass http://127.0.0.1:47822;');+ expect(h.files.get(site)).toContain('ssl_certificate /site/cert.pem;');+ material('key-one');+ manageNginx('activate');+ expect(h.files.get(site)).toContain('ssl_certificate /site/cert.pem;');+ expect(h.files.get(site)).toContain('server_name website.example.test www.example.test;');+ expect(h.files.get(`${root}/http.conf`)).toContain('proxy_pass https://127.0.0.1:47821;');+ manageNginx('commit');+ material('key-two');+ manageNginx('renew');+ manageNginx('remove');+ expect(h.files.get(site)).toBe(original);+});++it('uses the already trusted website certificate without replacing or requesting one', () => {+ prepare(true);+ expect(h.files.get(site)).toContain('proxy_pass http://127.0.0.1:47821;');+ expect(h.files.get(site)).toContain('ssl_certificate /website/cert.pem;');+ expect(h.files.get(site)).not.toContain('cindy_relay_existing_acme');+ manageNginx('activate');+ manageNginx('commit');+ manageNginx('remove');+ expect(h.files.get(site)).toBe(originalSite);+});++it('opens HTTP validation before requesting a certificate when Nginx only serves HTTPS', () => {+ const httpsOnly = originalSite.slice(originalSite.indexOf('server { listen 443'));+ h.files.set(site, httpsOnly);+ prepare();+ const beforeCertificate = h.files.get(`${root}/http.conf`)!;+ expect(beforeCertificate).toContain('listen 80;');+ expect(beforeCertificate).toContain('proxy_pass http://127.0.0.1:47822;');+ expect(beforeCertificate).not.toContain('listen 443');+ material('key-one');+ manageNginx('activate');+ manageNginx('commit');+ manageNginx('remove');+ expect(h.files.get(site)).toBe(httpsOnly);+});++it('restores the complete original configuration after failed validation and automatically recovers an interrupted deployment', () => {+ h.failTest = 1;+ expect(() => prepare()).toThrow('previous configuration retained');+ expect(h.files.get(main)).toBe(originalMain);+ expect(h.files.get(site)).toBe(originalSite);+ h.failTest = 0;+ prepare();+ // 模拟 SSH 中断;下一次 prepare 自行撤销未提交事务,不叠加重复配置。+ prepare();+ material('key-one');+ manageNginx('activate');+ manageNginx('rollback');+ expect(h.files.get(main)).toBe(originalMain);+ expect(h.files.get(site)).toBe(originalSite);+});++it('rejects a conflicting API route before changing the site', () => {+ const conflict = 'server { listen 443 ssl; server_name 203.0.113.10; location /api/device-link/ { return 418; } }';+ h.files.set(site, conflict);+ expect(() => prepare(true)).toThrow('already serves');+ expect(h.files.get(main)).toBe(originalMain);+ expect(h.files.get(site)).toBe(conflict);+});++it('retains the backup and administrator edits made while the certificate was being requested', () => {+ prepare();+ const edited = h.files.get(site)! + '\n# administrator edit\n';+ h.files.set(site, edited);+ material('key-one');+ expect(() => manageNginx('activate')).toThrow('configuration changed');+ expect(() => manageNginx('rollback')).toThrow('configuration changed');+ expect(h.files.get(site)).toBe(edited);+ expect(h.files.has(`${root}/pending.json`)).toBe(true);+});++it('restores a separate HTTPS file after activation fails and preserves other certificate aliases on retry', () => {+ const tlsFile = '/etc/nginx/conf.d/tls.conf';+ const originalTls =+ 'server { listen 443 ssl; server_name relay.example.test www.example.test; ssl_certificate /site/cert.pem; ssl_certificate_key /site/key.pem; root /website/public; }';+ const originalHttp = 'server { listen 80; server_name relay.example.test; return 301 https://$host$request_uri; }';+ h.files.set(site, originalHttp);+ h.files.set(tlsFile, originalTls);+ const domain = () => manageNginx('prepare', { address: 'relay.example.test' });+ domain();+ material('key-one');+ h.failTest = h.tests + 1;+ expect(() => manageNginx('activate')).toThrow('previous configuration retained');+ expect(h.files.get(tlsFile)).toBe(originalTls);+ manageNginx('rollback');+ expect(h.files.get(site)).toBe(originalHttp);+ h.failTest = 0;+ domain();+ manageNginx('activate');+ expect(h.files.get(tlsFile)).toContain('server_name www.example.test;');+ expect(h.files.get(tlsFile)).toContain('ssl_certificate /site/cert.pem;');+ manageNginx('commit');+ manageNginx('remove');+ expect(h.files.get(tlsFile)).toBe(originalTls);+});diff --git a/packages/device-link-relay/src/cli.ts b/packages/device-link-relay/src/cli.tsindex 95c7544848..e9bcc15d05 100644--- a/packages/device-link-relay/src/cli.ts+++ b/packages/device-link-relay/src/cli.ts@@ -22,8 +22,9 @@ import type { RelayLogger } from './logger';import { readTlsFiles, startRelayServer } from './server';import { initializeRelay } from './store';import { RELAY_VERSION } from './version';+import { manageNginx } from './nginx';-const BOOLEAN_FLAGS = new Set(['trust-proxy']);+const BOOLEAN_FLAGS = new Set(['trust-proxy', 'ipv6', 'existing-certificate']);/** 首次申请证书失败后的重试间隔(Let's Encrypt 对同一名字每小时只允许几次失败验证)。 */const ACME_RETRY_DELAYS_MS = [60_000, 5 * 60_000, 15 * 60_000, 30 * 60_000, 60 * 60_000];const RENEWAL_CHECK_MS = 60 * 60 * 1000;@@ -122,6 +123,15 @@ async function main(): Promise<void> {emit({ event: 'version', relayVersion: RELAY_VERSION });return;}+ if (command === 'nginx') {+ const result = manageNginx(required(flags, 'action'), {+ address: flags.get('address'),+ ipv6: flags.has('ipv6'),+ existingCertificate: flags.has('existing-certificate'),+ });+ emit({ event: 'nginx', ...result });+ return;+ }if (command === 'init') {const { relayId } = await initializeRelay({dataDir: required(flags, 'data'),diff --git a/packages/device-link-relay/src/nginx.ts b/packages/device-link-relay/src/nginx.tsnew file mode 100644index 0000000000..f7b85677e0--- /dev/null+++ b/packages/device-link-relay/src/nginx.ts@@ -0,0 +1,756 @@+/**+ * SSH 部署专用的 Nginx 适配器,只由 root CLI 调用;中转进程本身不加载它。+ * 配置通过 Nginx 自己的 -T 发现,不假定发行版、安装目录或 sites-enabled 布局。+ * 只接管 /api/device-link/ 与自己的 ACME 验证,网站其余配置保留。+ */+import fs from 'node:fs';+import path from 'node:path';+import { execFileSync } from 'node:child_process';+import { createHash, createPrivateKey, randomUUID, X509Certificate } from 'node:crypto';+import { isIP } from 'node:net';++const ROOT = '/etc/cindy-relay/nginx';+const STATE = `${ROOT}/state.json`;+const PENDING = `${ROOT}/pending.json`;+const HTTP = `${ROOT}/http.conf`;+const DATA = '/var/lib/cindy-relay';+const API = '/api/device-link/';+const CHALLENGE = '/.well-known/acme-challenge/';+const BEGIN = '# BEGIN Cindy relay';+const END = '# END Cindy relay';++interface Directive {+ file: string;+ name: string;+ args: string[];+ start: number;+ end: number;+ open?: number;+ children?: Directive[];+}++export interface NginxPatch {+ file: string;+ before: string;+ after: string;+}+export interface NginxPlan {+ patches: NginxPatch[];+ activatePatches: NginxPatch[];+ /** 没有 HTTP 站点时,申请证书之前就需要启用验证入口。 */+ httpServer: string | null;+ /** 新增的 HTTPS 虚拟站点;沿用目标原来的站点内容,仅替换监听地址与证书。 */+ tlsServer: string | null;+ existingCertificate: boolean;+}++/** 解析语法与位置,不用正则改写任意 Nginx 配置;引号、注释、变量与嵌套块分别处理。 */+function parse(file: string, source: string): Directive[] {+ const tokens: Array<{ value: string; start: number; end: number }> = [];+ let i = 0;+ while (i < source.length) {+ if (/\s/.test(source[i])) {+ i++;+ continue;+ }+ if (source[i] === '#') {+ while (i < source.length && source[i] !== '\n') i++;+ continue;+ }+ const start = i;+ if ('{};'.includes(source[i])) {+ tokens.push({ value: source[i++], start, end: i });+ continue;+ }+ let value = '';+ let quote = '';+ while (i < source.length) {+ const c = source[i];+ if (c === '\\' && i + 1 < source.length) {+ value += source[i + 1];+ i += 2;+ continue;+ }+ if (quote) {+ if (c === quote) quote = '';+ else value += c;+ i++;+ continue;+ }+ if (c === '"' || c === "'") {+ quote = c;+ i++;+ continue;+ }+ if (c === '$' && source[i + 1] === '{') {+ const end = source.indexOf('}', i + 2);+ if (end < 0) throw new Error('Unclosed Nginx variable');+ value += source.slice(i, end + 1);+ i = end + 1;+ continue;+ }+ if (/\s/.test(c) || '{};#'.includes(c)) break;+ value += c;+ i++;+ }+ if (quote || i === start) throw new Error('Invalid Nginx token');+ tokens.push({ value, start, end: i });+ }+ let cursor = 0;+ function block(nested: boolean): Directive[] {+ const nodes: Directive[] = [];+ while (cursor < tokens.length && tokens[cursor].value !== '}') {+ const first = tokens[cursor++];+ const args: string[] = [];+ while (cursor < tokens.length && ![';', '{', '}'].includes(tokens[cursor].value)) args.push(tokens[cursor++].value);+ const delimiter = tokens[cursor++];+ if (!delimiter || delimiter.value === '}') throw new Error('Invalid Nginx directive');+ const node: Directive = {+ file,+ name: first.value,+ args,+ start: first.start,+ end: delimiter.end,+ };+ if (delimiter.value === '{') {+ node.open = delimiter.end;+ node.children = block(true);+ node.end = tokens[cursor - 1].end;+ }+ nodes.push(node);+ }+ if (nested && tokens[cursor++]?.value !== '}') throw new Error('Unclosed Nginx block');+ return nodes;+ }+ return block(false);+}++function escapeRegex(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++function included(pattern: string, files: Map<string, string>, main: string): string[] {+ const absolute = path.posix.resolve(path.posix.dirname(main), pattern);+ const match = new RegExp(+ `^${absolute+ .split('*')+ .map((part) => part.split('?').map(escapeRegex).join('.'))+ .join('.*')}$`,+ );+ return [...files.keys()].filter((file) => match.test(file));+}++function children(nodes: Directive[], files: Map<string, string>, main: string, seen: string[] = []): Directive[] {+ return nodes.flatMap((node) => {+ if (node.name !== 'include') return [node];+ return included(node.args[0] ?? '', files, main).flatMap((file) => {+ if (seen.includes(file)) throw new Error('Recursive Nginx include');+ return children(parse(file, files.get(file)!), files, main, [...seen, file]);+ });+ });+}++function listens(node: Directive, port: number, files: Map<string, string>, main: string): boolean {+ return children(node.children ?? [], files, main).some(+ (d) => d.name === 'listen' && (d.args[0] === String(port) || d.args[0]?.endsWith(`:${port}`)) && !d.args.includes('quic'),+ );+}++function selected(servers: Directive[], port: number, address: string, files: Map<string, string>, main: string): Directive[] {+ const candidates = servers.filter((s) => listens(s, port, files, main));+ const names = (s: Directive) =>+ children(s.children ?? [], files, main)+ .filter((d) => d.name === 'server_name')+ .flatMap((d) => d.args);+ const exact = candidates.filter((s) => names(s).some((n) => n.toLowerCase() === address.toLowerCase()));+ if (exact.length) return exact;+ const wildcard = candidates.filter((s) =>+ names(s).some(+ (n) =>+ (n.startsWith('*.') && address.endsWith(n.slice(1))) ||+ (n.endsWith('.*') && address.startsWith(n.slice(0, -1))) ||+ (n.startsWith('.') && (address === n.slice(1) || address.endsWith(n))),+ ),+ );+ if (wildcard.length) {+ // Nginx 在通配符中选最长名字;不擅自猜测 PCRE 的匹配结果。+ const score = (s: Directive) => Math.max(...names(s).map((n) => n.length));+ const longest = Math.max(...wildcard.map(score));+ return wildcard.filter((s) => score(s) === longest);+ }+ if (candidates.some((s) => names(s).some((n) => n.startsWith('~')))) throw new Error('Nginx regex server names require an exact address');+ const defaults = candidates.filter((s) =>+ children(s.children ?? [], files, main).some(+ (d) => d.name === 'listen' && d.args.some((a) => a === 'default_server' || a === 'default'),+ ),+ );+ return defaults.length ? defaults : candidates.slice(0, 1);+}++function marked(text: string): string {+ return `${BEGIN}\n${text}\n${END}`;+}++function location(port: number, tls: boolean): string {+ return `location ^~ ${API} {+ proxy_pass ${tls ? 'https' : 'http'}://127.0.0.1:${port};+ proxy_http_version 1.1;+ proxy_set_header Host $http_host;+ proxy_set_header X-Forwarded-Host $http_host;+ proxy_set_header X-Forwarded-Proto https;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection $cindy_relay_connection_upgrade;+ proxy_read_timeout 3600s;+ proxy_send_timeout 3600s;+ proxy_buffering off;+ proxy_request_buffering off;+ proxy_cache off;+ proxy_intercept_errors off;+ client_max_body_size 0;+ auth_basic off;+}`;+}++/** 从实际启用的文件生成最小补丁。before/after 也是卸载时的逆补丁,不还原整份旧文件覆盖用户后续修改。 */+export function planNginx(options: {+ main: string;+ files: Map<string, string>;+ address: string;+ port: number;+ challengePort: number;+ ipv6: boolean;+ /** 现有 HTTPS 已由宿主验证信任、地址和有效期时,直接沿用其证书管理。 */+ existingCertificate: boolean;+ certificateNames: (files: string[]) => string[];+}): NginxPlan {+ const { main, files, address, port, challengePort, ipv6 } = options;+ if (!/^[a-zA-Z0-9.:-]+$/.test(address)) throw new Error('Invalid relay address');+ const http = parse(main, files.get(main) ?? '').find((d) => d.name === 'http' && d.children);+ if (!http) throw new Error('Nginx HTTP configuration not found');+ const servers = children(http.children!, files, main).filter((d) => d.name === 'server' && d.children);+ const httpServers = selected(servers, 80, address, files, main);+ const httpsServers = selected(servers, 443, address, files, main);+ const existingCertificate = options.existingCertificate && httpsServers.length > 0;+ const patches: NginxPatch[] = [];+ const activatePatches: NginxPatch[] = [];+ const insert = (node: Directive, body: string) => {+ const before = files.get(node.file)!.slice(node.start, node.open);+ patches.push({+ file: node.file,+ before,+ after: `${before}\n${marked(body)}\n`,+ });+ };+ insert(http, `include ${HTTP};`);++ // 用整个目标 server 作定位锚点,不能只替换常见的 “server {” 或相同的 return 语句。+ // 展开其直接 include 后仅修改该站点,避免改到多站点共用的片段。+ const versions = new Map<string, string>();+ const patchServer = (server: Directive, transform: (body: string) => string, deferred = false) => {+ const key = `${server.file}:${server.start}`;+ const original = files.get(server.file)!.slice(server.start, server.end);+ const before = versions.get(key) ?? original;+ const offset = before.indexOf('{') + 1;+ let body = before.slice(offset, -1);+ const direct = parse('body', body);+ for (const d of [...direct].reverse()) {+ if (d.name !== 'include') continue;+ const expanded = children([d], files, main)+ .map((n) => files.get(n.file)!.slice(n.start, n.end))+ .join('\n');+ body = body.slice(0, d.start) + expanded + body.slice(d.end);+ }+ const after = before.slice(0, offset) + transform(body) + '}';+ versions.set(key, after);+ (deferred ? activatePatches : patches).push({+ file: server.file,+ before,+ after,+ });+ };+ const routeApi = (body: string, tls: boolean): string => {+ body = body.replaceAll(`if ($uri !~ "^${CHALLENGE}")`, 'if ($uri !~ "^/(?:api/device-link/|[.]well-known/acme-challenge/)")');+ const directives = parse('body', body);+ if (directives.some((d) => d.name === 'location' && d.args.some((a) => a.startsWith(API) || a === '/api/device-link'))) {+ throw new Error('The existing site already serves the Cindy relay API path');+ }+ for (const d of [...directives].reverse()) {+ if (d.name === 'return')+ body = body.slice(0, d.start) + `if ($uri !~ "^${API}") { ${body.slice(d.start, d.end)} }` + body.slice(d.end);+ }+ return `${body}\n${marked(location(port, tls))}\n`;+ };+ let httpServer: string | null = null;+ let tlsServer: string | null = null;+ if (existingCertificate) {+ for (const server of httpsServers) patchServer(server, (body) => routeApi(body, false));+ } else {+ const challenge = `location ^~ ${CHALLENGE} {+ proxy_pass http://127.0.0.1:${challengePort};+ proxy_set_header Host $http_host;+ proxy_intercept_errors on;+ error_page 404 = @cindy_relay_existing_acme;+}`;+ for (const server of httpServers) {+ patchServer(server, (body) => {+ const directives = parse('body', body);+ const oldChallenges = directives.filter((d) => d.name === 'location' && d.args.includes(CHALLENGE));+ if (oldChallenges.length > 1) throw new Error('Ambiguous Nginx ACME locations');+ let fallback = 'try_files $uri =404;';+ const old = oldChallenges[0];+ if (old) {+ // 常见 Certbot / 宝塔 webroot 保留为 404 fallback,Cindy 不抢走其他客户端的验证文件。+ if (old.children?.some((d) => !['root', 'try_files', 'default_type', 'allow', 'deny', 'add_header'].includes(d.name))) {+ throw new Error('The existing ACME handler cannot be preserved automatically');+ }+ fallback = body.slice(old.open, old.end - 1);+ body = body.slice(0, old.start) + body.slice(old.end);+ }+ for (const d of [...parse('body', body)].reverse()) {+ if (d.name === 'return')+ body = body.slice(0, d.start) + `if ($uri !~ "^${CHALLENGE}") { ${body.slice(d.start, d.end)} }` + body.slice(d.end);+ }+ return `${body}\n${marked(`${challenge}\nlocation @cindy_relay_existing_acme { ${fallback} }`)}\n`;+ });+ }+ if (!httpServers.length) {+ httpServer = `server {\nlisten 80;\n${ipv6 ? 'listen [::]:80;\n' : ''}server_name ${address};\n${challenge}\nlocation @cindy_relay_existing_acme { return 404; }\n}\n`;+ }++ // 使用独立虚拟站点承载新证书,不能替换多域名网站原有的证书。+ const exactTls = httpsServers.filter((s) =>+ children(s.children ?? [], files, main).some(+ (d) => d.name === 'server_name' && d.args.some((n) => n.toLowerCase() === address.toLowerCase()),+ ),+ );+ // 直接访问 IP 的 TLS 客户端常常不发 SNI。IP 证书必须用于默认握手,域名站点仍由 SNI 选择。+ // 原默认站点若只写 server_name _,从证书补出域名,保留已有 SNI 访问。+ const defaults = new Map<string, Directive>();+ for (const server of servers.filter((s) => listens(s, 443, files, main))) {+ for (const d of children(server.children ?? [], files, main)) {+ if (d.name !== 'listen' || !(d.args[0] === '443' || d.args[0]?.endsWith(':443')) || d.args.includes('quic')) continue;+ const socket = d.args[0] === '443' || d.args[0] === '*:443' ? '0.0.0.0:443' : d.args[0];+ if (!defaults.has(socket) || d.args.some((a) => a === 'default_server' || a === 'default')) defaults.set(socket, server);+ }+ }+ const displaced = isIP(address) ? new Set(defaults.values()) : new Set<Directive>();+ for (const server of new Set([...exactTls, ...displaced])) {+ const directives = children(server.children ?? [], files, main);+ let certNames: string[] = [];+ if (displaced.has(server)) {+ let certificates = directives.filter((d) => d.name === 'ssl_certificate');+ if (!certificates.length) certificates = children(http.children!, files, main).filter((d) => d.name === 'ssl_certificate');+ certNames = options+ .certificateNames(certificates.map((d) => path.posix.resolve(path.posix.dirname(main), d.args[0])))+ .filter((name) => selected(servers, 443, name, files, main).includes(server));+ }+ patchServer(+ server,+ (body) => {+ const names = parse('body', body).filter((d) => d.name === 'server_name');+ if (names.some((d) => d.args.some((name) => name.startsWith('~'))))+ throw new Error('Nginx regex server names cannot be rewritten automatically');+ const retained = [...new Set([...names.flatMap((d) => d.args), ...certNames])].filter(+ (n) => n.toLowerCase() !== address.toLowerCase(),+ );+ for (const d of [...names].reverse()) body = body.slice(0, d.start) + body.slice(d.end);+ for (const d of [...parse('body', body)].reverse()) {+ if (!displaced.has(server) || d.name !== 'listen' || !(d.args[0] === '443' || d.args[0]?.endsWith(':443'))) continue;+ body = body.slice(0, d.start) + body.slice(d.start, d.end).replace(/\bdefault_server\b|\bdefault\b/g, '') + body.slice(d.end);+ }+ return `${body}\nserver_name ${retained.length ? retained.join(' ') : '_'};\n`;+ },+ true,+ );+ }+ {+ // 从地址原来会落到的默认站点继承正文,避免把原来通过 IP 打开的网站换成空页。+ const source = httpsServers[0] ?? httpServers[0];+ let body = source ? files.get(source.file)!.slice(source.open, source.end - 1) : '';+ if (source) {+ const direct = source.children ?? [];+ if (direct.some((d) => d.name === 'include')) {+ // 展开直接 include,避免其中的证书/监听指令与新站点冲突;嵌套位置的 include 保持不动。+ body = children(direct, files, main)+ .map((d) => files.get(d.file)!.slice(d.start, d.end))+ .join('\n');+ }+ const parsed = parse('clone', body);+ for (const d of [...parsed].reverse()) {+ if (['listen', 'server_name', 'ssl_certificate', 'ssl_certificate_key', 'ssl_reject_handshake'].includes(d.name)) {+ body = body.slice(0, d.start) + body.slice(d.end);+ } else if (d.name === 'return') {+ body = body.slice(0, d.start) + `if ($uri !~ "^${API}") { ${body.slice(d.start, d.end)} }` + body.slice(d.end);+ } else if (d.name === 'location' && d.args.some((a) => a.startsWith(API)))+ throw new Error('The default site already serves the relay API path');+ }+ }+ const defaultFlag = isIP(address) ? ' default_server' : '';+ const listen = `listen 443 ssl${defaultFlag};\n${ipv6 ? `listen [::]:443 ssl${defaultFlag};\n` : ''}`;+ tlsServer = `server {\n${listen}server_name ${address};\nssl_certificate __CINDY_CERT__/fullchain.pem;\nssl_certificate_key __CINDY_CERT__/key.pem;\n${body}\n${location(port, true)}\n}\n`;+ }+ }+ return { patches, activatePatches, httpServer, tlsServer, existingCertificate };+}++interface NginxInstance {+ binary: string;+ args: string[];+ pid: number;+}+interface Saved extends NginxPlan {+ address: string;+ port: number;+ challengePort: number;+ nginx: NginxInstance;+ certDir?: string;+}+interface Snapshot {+ files: Array<{ file: string; text: string | null; mode: number }>;+ previous: Saved | null;+ expected?: Record<string, string | null>;+}++function read(file: string): string | null {+ try {+ if (fs.statSync(file).size > 4 * 1024 * 1024) throw new Error('Nginx configuration file is too large');+ return fs.readFileSync(file, 'utf8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw error;+ }+}++function write(file: string, text: string | null, mode = 0o600): void {+ if (text === null) {+ fs.rmSync(file, { force: true });+ return;+ }+ const target = fs.existsSync(file) ? fs.realpathSync(file) : file;+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });+ const temporary = `${target}.cindy-${randomUUID()}.tmp`;+ try {+ const stat = fs.existsSync(target) ? fs.statSync(target) : null;+ fs.writeFileSync(temporary, text, {+ mode: stat ? stat.mode & 0o777 : mode,+ flag: 'wx',+ });+ if (stat) fs.chownSync(temporary, stat.uid, stat.gid);+ fs.renameSync(temporary, target);+ } finally {+ fs.rmSync(temporary, { force: true });+ }+}++function run(binary: string, args: string[]): string {+ // Nginx -T 包含用户配置,只在远端内存中处理,错误输出不上传到客户端或日志。+ try {+ return execFileSync(binary, args, {+ encoding: 'utf8',+ timeout: 15_000,+ maxBuffer: 8 * 1024 * 1024,+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ } catch {+ throw new Error('Nginx configuration validation failed; previous configuration retained');+ }+}++function discover(): NginxInstance {+ const instances: NginxInstance[] = [];+ for (const entry of fs.readdirSync('/proc').filter((e) => /^\d+$/.test(e))) {+ let title: string;+ try {+ title = fs.readFileSync(`/proc/${entry}/cmdline`, 'utf8').replace(/\0/g, ' ').trim();+ } catch {+ continue;+ }+ if (!title.startsWith('nginx: master process ')) continue;+ const binary = fs.readlinkSync(`/proc/${entry}/exe`);+ const args: string[] = [];+ // -c/-p are paths; flags injected with -g are deliberately not executed as shell text.+ for (const flag of ['-c', '-p']) {+ const match = new RegExp(`(?:^|\\s)${flag}\\s+(?:"([^"]+)"|'([^']+)'|(\\S+))`).exec(title);+ if (match) args.push(flag, match[1] ?? match[2] ?? match[3]);+ }+ instances.push({ binary, args, pid: Number(entry) });+ }+ if (instances.length !== 1) throw new Error('Exactly one native Nginx master process is required');+ return instances[0];+}++function reload(nginx: NginxInstance): void {+ // 重启后 PID 会变化;每次重新定位同一安装,不能把旧 PID 当作 Nginx 的身份。+ const current = discover();+ if (current.binary !== nginx.binary || JSON.stringify(current.args) !== JSON.stringify(nginx.args))+ throw new Error('Nginx installation changed; previous configuration retained');+ run(current.binary, [...current.args, '-t']);+ process.kill(current.pid, 'SIGHUP');+}++function snapshot(files: string[], previous: Saved | null): Snapshot {+ return {+ previous: structuredClone(previous),+ files: [...new Set(files)].map((file) => ({+ file,+ text: read(file),+ mode: fs.existsSync(file) ? fs.statSync(file).mode & 0o777 : 0o600,+ })),+ };+}++function restore(saved: Snapshot): void {+ // 申请证书可能持续数分钟。若期间管理员改过站点,保留备份并停止,不能覆盖这些新修改。+ for (const f of saved.files) {+ const expected = saved.expected?.[f.file];+ const current = read(f.file);+ if (expected !== undefined && current !== expected && current !== f.text)+ throw new Error('Nginx configuration changed during deployment; backup retained');+ }+ for (const f of saved.files) write(f.file, f.text, f.mode);+ write(STATE, saved.previous ? JSON.stringify(saved.previous) : null);+}++function recordPending(): void {+ const backup = JSON.parse(read(PENDING) ?? 'null') as Snapshot | null;+ if (!backup) return;+ backup.expected = Object.fromEntries(+ backup.files.filter((f) => f.file !== '/etc/systemd/system/cindy-relay.service').map((f) => [f.file, read(f.file)]),+ );+ write(PENDING, JSON.stringify(backup));+}++function assertPendingUnchanged(): void {+ const backup = JSON.parse(read(PENDING) ?? 'null') as Snapshot | null;+ for (const [file, expected] of Object.entries(backup?.expected ?? {})) {+ if (read(file) !== expected) throw new Error('Nginx configuration changed during deployment; backup retained');+ }+}++function replacePatches(patches: NginxPatch[], reverse: boolean): void {+ for (const patch of reverse ? [...patches].reverse() : patches) {+ const before = reverse ? patch.after : patch.before;+ const after = reverse ? patch.before : patch.after;+ const text = read(patch.file);+ if (text === null || !text.includes(before) || text.indexOf(before) !== text.lastIndexOf(before)) {+ throw new Error('Nginx configuration changed; refusing to overwrite other edits');+ }+ write(+ patch.file,+ text.replace(before, () => after),+ 0o644,+ );+ }+}++function httpConfig(state: Saved, certDir?: string): string {+ const map = 'map $http_upgrade $cindy_relay_connection_upgrade { default upgrade; "" close; }\n';+ return map + (state.httpServer ?? '') + (certDir ? (state.tlsServer ?? '').replaceAll('__CINDY_CERT__', certDir) : '');+}++/** root-only CLI 生命周期。客户端不传配置文件路径、命令或证书内容。 */+export function manageNginx(+ action: string,+ options: {+ address?: string;+ ipv6?: boolean;+ existingCertificate?: boolean;+ } = {},+): {+ existingCertificate?: boolean;+ port?: number;+ challengePort?: number;+} {+ if (process.platform !== 'linux' || process.getuid?.() !== 0) throw new Error('Nginx deployment requires Linux root');+ fs.mkdirSync(ROOT, { recursive: true, mode: 0o700 });+ const lock = `${ROOT}/operation.lock`;+ try {+ if (fs.existsSync(lock)) {+ const pid = Number(read(lock));+ let active = true;+ try {+ process.kill(pid, 0);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') active = false;+ else throw error;+ }+ if (active) throw new Error('Nginx deployment is already running');+ fs.rmSync(lock);+ }+ fs.writeFileSync(lock, String(process.pid), { flag: 'wx', mode: 0o600 });+ } catch {+ throw new Error('Nginx deployment is already running');+ }+ try {+ return manageLocked(action, options);+ } finally {+ fs.rmSync(lock, { force: true });+ }+}++function manageLocked(+ action: string,+ options: { address?: string; ipv6?: boolean; existingCertificate?: boolean },+): {+ existingCertificate?: boolean;+ port?: number;+ challengePort?: number;+} {+ // SSH 中断留下的事务在下一次部署自动恢复,不要求用户手动清理配置。+ if (action === 'prepare' && read(PENDING)) manageLocked('rollback', {});+ if (action === 'renew' && read(PENDING)) return {};+ const saved = JSON.parse(read(STATE) ?? 'null') as Saved | null;+ if (action === 'prepare') {+ if (!options.address) throw new Error('Relay address required');+ const nginx = discover();+ const dump = run(nginx.binary, [...nginx.args, '-T']);+ const names = [...dump.matchAll(/^# configuration file (.+):\r?$/gm)].map((m) => m[1]);+ const main = names[0];+ if (!main) throw new Error('Nginx active configuration not found');+ const files = new Map(names.filter((f) => f !== HTTP).map((f) => [f, read(f)!]));+ // 升级时先在内存撤销上次补丁,再按当前站点重新生成;用户对其他配置的修改继续保留。+ if (saved)+ for (const p of [...saved.patches].reverse()) {+ const text = files.get(p.file);+ if (text === undefined || !text.includes(p.after)) throw new Error('Managed Nginx configuration changed');+ files.set(+ p.file,+ text.replace(p.after, () => p.before),+ );+ }+ const used = ['/proc/net/tcp', '/proc/net/tcp6'].flatMap((file) =>+ (read(file) ?? '').split('\n').flatMap((line) => {+ const fields = line.trim().split(/\s+/);+ return fields[3] === '0A' ? [Number.parseInt(fields[1].split(':')[1], 16)] : [];+ }),+ );+ let port = saved?.port ?? 47820;+ let challengePort = saved?.challengePort ?? 47821;+ if (used.includes(port) || used.includes(challengePort)) {+ port = 47820;+ while (used.includes(port) && port < 47920) port++;+ challengePort = port + 1;+ while (used.includes(challengePort) && challengePort < 47921) challengePort++;+ if (port >= 47920 || challengePort >= 47921) throw new Error('No free relay loopback ports');+ }+ const existingCertificate = !!options.existingCertificate && (!saved || saved.existingCertificate || saved.address !== options.address);+ const plan = planNginx({+ main,+ files,+ address: options.address,+ port,+ challengePort,+ ipv6: !!options.ipv6,+ existingCertificate,+ certificateNames: (certificates) =>+ certificates.flatMap((file) => {+ if (file.includes('$')) throw new Error('Dynamic Nginx certificate paths cannot be preserved automatically');+ const cert = new X509Certificate(fs.readFileSync(file));+ const names = [...(cert.subjectAltName ?? '').matchAll(/(?:^|,\s*)DNS:([a-zA-Z0-9*_.-]+)(?=,|$)/g)].map((m) => m[1]);+ const cn = /^CN=([a-zA-Z0-9*_.-]+)$/m.exec(cert.subject)?.[1];+ return names.length ? names : cn ? [cn] : [];+ }),+ });+ // 尚无证书时不能提前改动现有 HTTPS 站点的证书引用;activate 才提交这些补丁。+ const snapshotFiles = [+ ...plan.patches.map((p) => p.file),+ ...plan.activatePatches.map((p) => p.file),+ ...(saved?.patches.map((p) => p.file) ?? []),+ HTTP,+ '/etc/systemd/system/cindy-relay.service',+ ];+ const backup = snapshot(snapshotFiles, saved);+ write(PENDING, JSON.stringify(backup));+ try {+ if (saved) replacePatches(saved.patches, true);+ replacePatches(plan.patches, false);+ const state: Saved = {+ ...plan,+ address: options.address,+ port,+ challengePort,+ nginx,+ };+ write(HTTP, httpConfig(state), 0o644);+ reload(nginx);+ write(STATE, JSON.stringify(state));+ recordPending();+ return {+ existingCertificate: plan.existingCertificate,+ port,+ challengePort,+ };+ } catch (error) {+ restore(backup);+ reload(nginx);+ write(PENDING, null);+ throw error;+ }+ }+ if (action === 'rollback') {+ const pending = JSON.parse(read(PENDING) ?? 'null') as Snapshot | null;+ if (pending) {+ restore(pending);+ reload(pending.previous?.nginx ?? saved?.nginx ?? discover());+ write(PENDING, null);+ }+ return {};+ }+ if (!saved) return {};+ if (action === 'commit') {+ write(PENDING, null);+ return {};+ }+ if (action === 'remove') {+ const backup = snapshot([...saved.patches.map((p) => p.file), HTTP], saved);+ try {+ replacePatches(saved.patches, true);+ write(HTTP, '');+ reload(saved.nginx);+ } catch (error) {+ restore(backup);+ reload(saved.nginx);+ throw error;+ }+ // ROOT 是此适配器创建的固定私有目录,绝不递归清理 Nginx 的站点或证书目录。+ fs.rmSync(ROOT, { recursive: true, force: true });+ return {};+ }+ if (action !== 'activate' && action !== 'renew') throw new Error('Unknown Nginx action');+ if (action === 'activate') assertPendingUnchanged();+ if (saved.existingCertificate) return {};+ const material = JSON.parse(read(`${DATA}/tls/material.json`) ?? '{}') as {+ cert: string;+ key: string;+ };+ const cert = new X509Certificate(material.cert);+ const matches = isIP(saved.address) ? cert.checkIP(saved.address) : cert.checkHost(saved.address);+ if (!matches || !cert.checkPrivateKey(createPrivateKey(material.key)) || Date.parse(cert.validTo) <= Date.now())+ throw new Error('Relay TLS material is invalid');+ const hash = createHash('sha256').update(material.cert).update(material.key).digest('hex');+ const certDir = `${ROOT}/tls/${hash}`;+ if (saved.certDir === certDir) return {};+ const backup = snapshot([...saved.patches.map((p) => p.file), ...saved.activatePatches.map((p) => p.file), HTTP], saved);+ try {+ write(`${certDir}/fullchain.pem`, material.cert);+ write(`${certDir}/key.pem`, material.key);+ // 一代证书放在同一私有目录;配置一次性指向新一代,不能出现新 key 配旧 cert。+ if (!saved.certDir) {+ for (const patch of saved.activatePatches) {+ replacePatches([patch], false);+ }+ saved.patches.push(...saved.activatePatches);+ saved.activatePatches = [];+ }+ write(HTTP, httpConfig(saved, certDir), 0o644);+ reload(saved.nginx);+ saved.certDir = certDir;+ write(STATE, JSON.stringify(saved));+ recordPending();+ } catch (error) {+ restore(backup);+ reload(saved.nginx);+ throw error;+ }+ return {};+}diff --git a/packages/device-link-relay/src/version.ts b/packages/device-link-relay/src/version.tsindex 0f6ebb75a1..f7aa455f65 100644--- a/packages/device-link-relay/src/version.ts+++ b/packages/device-link-relay/src/version.ts@@ -1,2 +1,2 @@/** 中转程序版本:主人电脑据此提示升级服务器上的中转。改动 wire 行为时递增。 */-export const RELAY_VERSION = '0.2.0';+export const RELAY_VERSION = '0.3.0';