import { createConnection } from 'node:net'; import { readFile } from 'node:fs/promises'; /** Same-user 0600 Unix channel. Never print the connect response or persist its token. */ export async function subscriptionOperation(operation: 'connect' | 'status' | 'limits' | 'stop') { const pointer = JSON.parse( await readFile('build/lekiwi-agent/subscription-session.json', 'utf8'), ) as { socket?: string; status: string }; if (!pointer.socket || pointer.status === 'closed') throw new Error('隔离订阅会话已关闭,请重新发起官方登录'); return new Promise>((resolve, reject) => { const channel = createConnection(pointer.socket!); let buffer = ''; channel.setTimeout(20000); channel.once('connect', () => channel.write(JSON.stringify(operation) + '\n')); channel.on('data', (chunk) => { buffer += String(chunk); if (buffer.length > 16384) { channel.destroy(); reject(new Error('订阅管理响应过大')); return; } if (buffer.includes('\n')) { try { const result = JSON.parse(buffer.split('\n')[0]) as Record; if (result.error) reject(new Error('订阅管理请求失败')); else resolve(result); } catch { reject(new Error('订阅管理响应非法')); } channel.end(); } }); channel.once('timeout', () => { channel.destroy(); reject(new Error('订阅管理请求超时')); }); channel.once('error', () => reject(new Error('无法连接隔离订阅会话'))); channel.once('end', () => { if (!buffer.includes('\n')) reject(new Error('订阅管理连接提前关闭')); }); }); }