@wechatsync/cli 1.0.0 → 1.1.0

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.
Files changed (3) hide show
  1. package/README.md +43 -0
  2. package/dist/index.js +201 -40
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -98,6 +98,49 @@ CLI 启动后监听 WebSocket 端口,等待 Chrome 扩展连接。
98
98
  | `SYNC_WS_PORT` | WebSocket 端口 | 9527 |
99
99
  | `WECHATSYNC_TOKEN` | 安全验证 token | - |
100
100
 
101
+ ## 远程桥接
102
+
103
+ CLI 支持在服务器上运行,连接本地电脑上的 Chrome 扩展。适用于在远程开发机或 CI 环境中同步文章,同时利用本地浏览器的登录态。
104
+
105
+ ### 架构
106
+
107
+ ```
108
+ ┌─────────────────┐ ┌─────────────────────┐
109
+ │ 远程服务器 │ WebSocket │ 本地电脑 │
110
+ │ │ port 9527 │ │
111
+ │ wechatsync CLI │◄───────────────────────►│ Chrome Extension │
112
+ │ / MCP Server │ │ (浏览器登录态) │
113
+ └─────────────────┘ └─────────────────────┘
114
+ ```
115
+
116
+ ### 配置步骤
117
+
118
+ **1. 服务器端** - 正常启动 CLI 或 MCP Server:
119
+
120
+ ```bash
121
+ # CLI
122
+ WECHATSYNC_TOKEN=your-token wechatsync sync article.md -p zhihu
123
+
124
+ # MCP Server
125
+ MCP_TOKEN=your-token node packages/mcp-server/dist/index.js
126
+ ```
127
+
128
+ 服务器默认监听 `0.0.0.0:9527`(所有网络接口),远程可直接连接。
129
+
130
+ **2. 本地浏览器** - 在 Chrome 扩展设置中:
131
+
132
+ 1. 开启「同步桥接」开关
133
+ 2. 在「服务器地址」输入框填入远程地址,例如 `ws://192.168.1.100:9527`
134
+ 3. 确保 Token 与服务器端一致
135
+
136
+ 扩展会自动连接远程服务器,连接成功后即可远程同步。
137
+
138
+ ### 注意事项
139
+
140
+ - 确保服务器防火墙放行 9527 端口(可通过 `SYNC_WS_PORT` 自定义)
141
+ - Token 在传输中以明文发送,生产环境建议配合 SSH 隧道或 VPN 使用
142
+ - 每个 Token 只允许一个扩展连接
143
+
101
144
  ## Claude Code 集成
102
145
 
103
146
  安装 Skill 插件:
package/dist/index.js CHANGED
@@ -32,11 +32,9 @@ var import_fs = __toESM(require("fs"));
32
32
  var import_path = __toESM(require("path"));
33
33
 
34
34
  // ../mcp-server/dist/exports.js
35
- var import_ws = __toESM(require("ws"), 1);
35
+ var import_ws = require("ws");
36
36
  var import_http = __toESM(require("http"), 1);
37
- var WsModule = import_ws.default;
38
- var WebSocketServer = WsModule.WebSocketServer || WsModule.Server || WsModule.default?.WebSocketServer || WsModule.default?.Server;
39
- var WS_OPEN = 1;
37
+ var WS_OPEN = import_ws.WebSocket.OPEN;
40
38
  var ExtensionBridge = class {
41
39
  constructor(port = 9527, options) {
42
40
  this.port = port;
@@ -84,7 +82,7 @@ var ExtensionBridge = class {
84
82
  startServer() {
85
83
  return new Promise((resolve, reject) => {
86
84
  try {
87
- this.wss = new WebSocketServer({ port: this.port });
85
+ this.wss = new import_ws.WebSocketServer({ port: this.port });
88
86
  this.wss.on("listening", () => {
89
87
  if (!this.silent) console.error(`[Bridge] WebSocket server listening on port ${this.port}`);
90
88
  this.startHttpApi().then(resolve).catch(reject);
@@ -177,6 +175,15 @@ var ExtensionBridge = class {
177
175
  this.httpServer = null;
178
176
  }
179
177
  }
178
+ /**
179
+ * 检查 Extension 是否已连接
180
+ */
181
+ /**
182
+ * 获取当前运行模式
183
+ */
184
+ getMode() {
185
+ return this.isServerMode ? "primary" : "secondary";
186
+ }
180
187
  /**
181
188
  * 检查 Extension 是否已连接
182
189
  */
@@ -184,29 +191,83 @@ var ExtensionBridge = class {
184
191
  if (this.isServerMode) {
185
192
  return this.client !== null && this.client.readyState === WS_OPEN;
186
193
  } else {
187
- return true;
194
+ return false;
188
195
  }
189
196
  }
190
197
  /**
191
198
  * 等待 Extension 连接
192
199
  */
193
200
  waitForConnection(timeoutMs = 6e4) {
194
- if (this.isConnected()) {
195
- return Promise.resolve();
196
- }
197
- return new Promise((resolve, reject) => {
198
- const timeout = setTimeout(() => {
199
- const index = this.connectionResolvers.indexOf(resolve);
200
- if (index > -1) {
201
- this.connectionResolvers.splice(index, 1);
202
- }
203
- reject(new Error("timeout"));
204
- }, timeoutMs);
205
- this.connectionResolvers.push(() => {
206
- clearTimeout(timeout);
207
- resolve();
201
+ if (this.isServerMode) {
202
+ if (this.client !== null && this.client.readyState === WS_OPEN) {
203
+ return Promise.resolve();
204
+ }
205
+ return new Promise((resolve, reject) => {
206
+ const timeout = setTimeout(() => {
207
+ const index = this.connectionResolvers.indexOf(resolve);
208
+ if (index > -1) {
209
+ this.connectionResolvers.splice(index, 1);
210
+ }
211
+ reject(new Error("timeout"));
212
+ }, timeoutMs);
213
+ this.connectionResolvers.push(() => {
214
+ clearTimeout(timeout);
215
+ resolve();
216
+ });
208
217
  });
209
- });
218
+ } else {
219
+ return new Promise((resolve, reject) => {
220
+ const startTime = Date.now();
221
+ const pollInterval = 2e3;
222
+ let primaryReachable = false;
223
+ let promoting = false;
224
+ const poll = async () => {
225
+ if (Date.now() - startTime > timeoutMs) {
226
+ if (!primaryReachable) {
227
+ reject(new Error("timeout:unreachable"));
228
+ } else {
229
+ reject(new Error("timeout:no_extension"));
230
+ }
231
+ return;
232
+ }
233
+ const health = await this.checkPrimaryHealth();
234
+ if (health.connected) {
235
+ resolve();
236
+ return;
237
+ }
238
+ if (health.error?.includes("not reachable") && !promoting) {
239
+ promoting = true;
240
+ const promoted = await this.tryPromote();
241
+ if (promoted) {
242
+ const remaining = timeoutMs - (Date.now() - startTime);
243
+ if (remaining <= 0) {
244
+ reject(new Error("timeout:no_extension"));
245
+ return;
246
+ }
247
+ if (this.client && this.client.readyState === WS_OPEN) {
248
+ resolve();
249
+ return;
250
+ }
251
+ const promoteTimeout = setTimeout(() => {
252
+ const index = this.connectionResolvers.indexOf(resolve);
253
+ if (index > -1) this.connectionResolvers.splice(index, 1);
254
+ reject(new Error("timeout:no_extension"));
255
+ }, remaining);
256
+ this.connectionResolvers.push(() => {
257
+ clearTimeout(promoteTimeout);
258
+ resolve();
259
+ });
260
+ return;
261
+ }
262
+ promoting = false;
263
+ } else if (!health.error?.includes("not reachable")) {
264
+ primaryReachable = true;
265
+ }
266
+ setTimeout(poll, pollInterval);
267
+ };
268
+ poll();
269
+ });
270
+ }
210
271
  }
211
272
  /**
212
273
  * 检查 Primary 实例健康状态(Secondary 模式用)
@@ -249,14 +310,62 @@ var ExtensionBridge = class {
249
310
  if (this.isServerMode) {
250
311
  return this.requestInternal(method, params);
251
312
  } else {
313
+ return this.requestViaSecondary(method, params);
314
+ }
315
+ }
316
+ /**
317
+ * SECONDARY 模式请求(带重试 + 自动接管)
318
+ */
319
+ async requestViaSecondary(method, params, maxRetries = 3) {
320
+ let lastError = null;
321
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
322
+ if (this.isServerMode) {
323
+ return this.requestInternal(method, params);
324
+ }
325
+ if (attempt > 0) {
326
+ const delay = Math.min(1e3 * Math.pow(2, attempt - 1), 5e3);
327
+ if (!this.silent) console.error(`[Bridge] SECONDARY retry ${attempt}/${maxRetries} in ${delay}ms...`);
328
+ await new Promise((resolve) => setTimeout(resolve, delay));
329
+ }
252
330
  const health = await this.checkPrimaryHealth();
253
331
  if (!health.connected) {
254
- throw new Error(
255
- health.error || "Primary MCP instance not available. Please ensure only one Claude Code session is using MCP."
256
- );
332
+ if (health.error?.includes("not reachable")) {
333
+ if (!this.silent) console.error("[Bridge] PRIMARY gone during request, attempting takeover...");
334
+ const promoted = await this.tryPromote();
335
+ if (promoted) {
336
+ if (!this.client || this.client.readyState !== WS_OPEN) {
337
+ if (!this.silent) console.error("[Bridge] Waiting for Extension to reconnect...");
338
+ await this.waitForConnection(3e4);
339
+ }
340
+ return this.requestInternal(method, params);
341
+ }
342
+ }
343
+ lastError = new Error(health.error || "Primary instance not available.");
344
+ continue;
345
+ }
346
+ try {
347
+ return await this.requestViaHttp(method, params);
348
+ } catch (error) {
349
+ lastError = error;
257
350
  }
258
- return this.requestViaHttp(method, params);
259
351
  }
352
+ throw lastError;
353
+ }
354
+ /**
355
+ * 尝试接管端口,升级为 PRIMARY
356
+ */
357
+ async tryPromote() {
358
+ for (let i = 0; i < 5; i++) {
359
+ try {
360
+ await this.startServer();
361
+ this.isServerMode = true;
362
+ if (!this.silent) console.error(`[Bridge] Promoted to PRIMARY (WebSocket: ${this.port}, HTTP: ${this.port + 1})`);
363
+ return true;
364
+ } catch {
365
+ await new Promise((r) => setTimeout(r, 1e3));
366
+ }
367
+ }
368
+ return false;
260
369
  }
261
370
  /**
262
371
  * 直接通过 WebSocket 发送请求(服务器模式)
@@ -638,29 +747,81 @@ function markdownToHtml(markdown) {
638
747
  });
639
748
  return html;
640
749
  }
750
+ async function detectPortProcess(port) {
751
+ const { execSync } = await import("child_process");
752
+ try {
753
+ if (process.platform === "win32") {
754
+ const output = execSync(`netstat -ano | findstr :${port} | findstr LISTENING`, { encoding: "utf-8" });
755
+ const pid = output.trim().split(/\s+/).pop();
756
+ if (pid) {
757
+ const info = execSync(`tasklist /FI "PID eq ${pid}" /FO CSV /NH`, { encoding: "utf-8" }).trim();
758
+ return `PID ${pid} (${info.split(",")[0]?.replace(/"/g, "") || "unknown"})`;
759
+ }
760
+ } else {
761
+ const output = execSync(`lsof -i :${port} -t 2>/dev/null`, { encoding: "utf-8" }).trim();
762
+ if (output) {
763
+ const pid = output.split("\n")[0];
764
+ const cmdline = execSync(`ps -p ${pid} -o command= 2>/dev/null`, { encoding: "utf-8" }).trim();
765
+ return `PID ${pid} (${cmdline.slice(0, 60)})`;
766
+ }
767
+ }
768
+ } catch {
769
+ }
770
+ return null;
771
+ }
641
772
  async function createBridge() {
642
773
  const bridge = new ExtensionBridge(WS_PORT, { silent: true });
643
774
  const timeout = connectionTimeout;
775
+ const cleanup = () => {
776
+ bridge.stop();
777
+ process.exit(0);
778
+ };
779
+ process.on("SIGINT", cleanup);
780
+ process.on("SIGTERM", cleanup);
644
781
  const spinner = (0, import_ora.default)("\u542F\u52A8\u670D\u52A1...").start();
645
- try {
646
- await bridge.start();
782
+ await bridge.start();
783
+ if (bridge.getMode() === "secondary") {
784
+ spinner.text = "\u68C0\u6D4B\u5230\u5DF2\u6709\u5B9E\u4F8B\uFF0C\u7B49\u5F85\u5176\u5B8C\u6210\u6216\u63A5\u7BA1\u7AEF\u53E3...";
785
+ } else {
647
786
  spinner.text = "\u7B49\u5F85 Chrome Extension \u8FDE\u63A5...";
648
- } catch (error) {
649
- if (error.code === "EADDRINUSE") {
650
- spinner.fail(`\u7AEF\u53E3 ${WS_PORT} \u5DF2\u88AB\u5360\u7528`);
651
- console.log(import_chalk.default.gray("\u53EF\u80FD\u5DF2\u6709\u5176\u4ED6 wechatsync \u5B9E\u4F8B\u5728\u8FD0\u884C"));
652
- return null;
653
- }
654
- throw error;
655
787
  }
656
788
  try {
657
789
  await bridge.waitForConnection(timeout);
658
- spinner.succeed("Chrome Extension \u5DF2\u8FDE\u63A5");
790
+ spinner.succeed(
791
+ bridge.getMode() === "secondary" ? "Chrome Extension \u5DF2\u8FDE\u63A5 (\u901A\u8FC7 PRIMARY \u8F6C\u53D1)" : "Chrome Extension \u5DF2\u8FDE\u63A5"
792
+ );
659
793
  return bridge;
660
- } catch {
794
+ } catch (error) {
661
795
  spinner.stop();
662
- showInstallGuide();
663
- await promptOpenInstallPage();
796
+ const errMsg = error.message || "";
797
+ if (bridge.getMode() === "secondary") {
798
+ if (errMsg.includes("timeout:unreachable")) {
799
+ console.log();
800
+ console.log(import_chalk.default.red("\u8FDE\u63A5\u8D85\u65F6: \u7AEF\u53E3\u88AB\u5360\u7528\u4F46\u65E0\u6CD5\u4E0E\u5DF2\u6709\u5B9E\u4F8B\u901A\u8BAF"));
801
+ console.log(import_chalk.default.gray("\u53EF\u80FD\u662F\u65E7\u7684 wechatsync \u8FDB\u7A0B\u672A\u6B63\u5E38\u9000\u51FA"));
802
+ console.log();
803
+ const processInfo = await detectPortProcess(WS_PORT);
804
+ if (processInfo) {
805
+ console.log(import_chalk.default.yellow(` \u7AEF\u53E3 ${WS_PORT} \u5360\u7528\u8FDB\u7A0B: ${processInfo}`));
806
+ console.log();
807
+ }
808
+ console.log(import_chalk.default.bold("\u89E3\u51B3\u65B9\u6CD5:"));
809
+ if (process.platform === "win32") {
810
+ console.log(` 1. \u7EC8\u6B62\u65E7\u8FDB\u7A0B: ${import_chalk.default.cyan(`taskkill /F /PID <pid>`)}`);
811
+ } else {
812
+ console.log(` 1. \u7EC8\u6B62\u65E7\u8FDB\u7A0B: ${import_chalk.default.cyan(`kill $(lsof -i :${WS_PORT} -t)`)}`);
813
+ }
814
+ console.log(` 2. \u4F7F\u7528\u5176\u4ED6\u7AEF\u53E3: ${import_chalk.default.cyan(`SYNC_WS_PORT=9600 wechatsync ...`)}`);
815
+ } else {
816
+ console.log();
817
+ console.log(import_chalk.default.red("\u8FDE\u63A5\u8D85\u65F6: \u5DF2\u6709\u5B9E\u4F8B\u6B63\u5728\u8FD0\u884C\u4F46 Chrome Extension \u672A\u8FDE\u63A5"));
818
+ console.log(import_chalk.default.gray("\u8BF7\u786E\u4FDD Chrome \u6269\u5C55\u5DF2\u542F\u7528\u300C\u540C\u6B65\u6865\u63A5\u300D\u5E76\u4E14 Token \u6B63\u786E"));
819
+ }
820
+ } else {
821
+ showInstallGuide();
822
+ await promptOpenInstallPage();
823
+ }
824
+ console.log();
664
825
  bridge.stop();
665
826
  return null;
666
827
  }
@@ -835,12 +996,12 @@ program.command("auth [platform]").description("\u68C0\u67E5\u5E73\u53F0\u767B\u
835
996
  spinner.stop();
836
997
  console.log();
837
998
  if (result.isAuthenticated) {
838
- console.log(import_chalk.default.green(`\u2713 ${result.name} \u5DF2\u767B\u5F55`));
999
+ console.log(import_chalk.default.green(`\u2713 ${platform} \u5DF2\u767B\u5F55`));
839
1000
  if (result.username) {
840
1001
  console.log(` \u7528\u6237: ${import_chalk.default.cyan(result.username)}`);
841
1002
  }
842
1003
  } else {
843
- console.log(import_chalk.default.red(`\u2717 ${result.name} \u672A\u767B\u5F55`));
1004
+ console.log(import_chalk.default.red(`\u2717 ${platform} \u672A\u767B\u5F55`));
844
1005
  if (result.error) {
845
1006
  console.log(` \u9519\u8BEF: ${import_chalk.default.gray(result.error)}`);
846
1007
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wechatsync/cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "WechatSync CLI - 命令行同步文章到多个平台",
5
5
  "main": "dist/index.js",
6
6
  "bin": {