codex-endpoint-switcher 1.5.0 → 1.6.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.
package/README.md CHANGED
@@ -77,6 +77,11 @@ codex-switcher remove-access
77
77
  http://localhost:3186
78
78
  ```
79
79
 
80
+ 说明:
81
+
82
+ - 本地控制台和热更新代理默认只监听 `127.0.0.1`
83
+ - 不再暴露到局域网,避免其他设备直接访问你的本地 Key 管理接口
84
+
80
85
  ## 账号配置同步
81
86
 
82
87
  网页控制台现在支持“账号 + 密码”的同步方式。
@@ -144,6 +149,7 @@ codex-switcher sync-server
144
149
  - 如果你发布了新版本,其他用户打开控制台后会看到“发现新版本”的提示
145
150
  - 用户可以直接点 `立即更新`,程序会自动关闭、更新并重新打开
146
151
  - 也可以继续使用“复制升级命令”手动更新
152
+ - 上一次自动更新的成功或失败结果会记录到本地,下次打开控制台会显示结果
147
153
 
148
154
  也可以用 CLI 手动检查:
149
155
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-endpoint-switcher",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "用于切换 Codex URL 和 Key 的本地网页控制台与 npm CLI",
5
5
  "main": "src/main/main.js",
6
6
  "bin": {
@@ -0,0 +1,189 @@
1
+ const fs = require("node:fs/promises");
2
+ const { spawn } = require("node:child_process");
3
+
4
+ function sleep(timeoutMs) {
5
+ return new Promise((resolve) => {
6
+ setTimeout(resolve, timeoutMs);
7
+ });
8
+ }
9
+
10
+ async function appendLog(logPath, text) {
11
+ await fs.appendFile(logPath, text, "utf8");
12
+ }
13
+
14
+ async function writeState(statePath, payload) {
15
+ await fs.writeFile(statePath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
16
+ }
17
+
18
+ function runProcess(command, args, options = {}) {
19
+ return new Promise((resolve) => {
20
+ const child = spawn(command, args, {
21
+ cwd: options.cwd,
22
+ env: options.env,
23
+ stdio: ["ignore", "pipe", "pipe"],
24
+ windowsHide: true,
25
+ });
26
+
27
+ let stdout = "";
28
+ let stderr = "";
29
+
30
+ child.stdout.on("data", (chunk) => {
31
+ stdout += chunk.toString("utf8");
32
+ });
33
+
34
+ child.stderr.on("data", (chunk) => {
35
+ stderr += chunk.toString("utf8");
36
+ });
37
+
38
+ child.on("exit", (code) => {
39
+ resolve({
40
+ code: Number(code || 0),
41
+ stdout,
42
+ stderr,
43
+ });
44
+ });
45
+
46
+ child.on("error", (error) => {
47
+ resolve({
48
+ code: 1,
49
+ stdout,
50
+ stderr: `${stderr}${error instanceof Error ? error.message : String(error)}\n`,
51
+ });
52
+ });
53
+ });
54
+ }
55
+
56
+ async function reopenConsole(payload) {
57
+ return runProcess(
58
+ payload.nodePath,
59
+ [payload.reopenBinPath, "open"],
60
+ {
61
+ cwd: process.cwd(),
62
+ env: process.env,
63
+ },
64
+ );
65
+ }
66
+
67
+ async function main() {
68
+ const encodedPayload = String(process.argv[2] || "").trim();
69
+ if (!encodedPayload) {
70
+ throw new Error("缺少自动更新参数。");
71
+ }
72
+
73
+ const payload = JSON.parse(Buffer.from(encodedPayload, "base64url").toString("utf8"));
74
+ const startedAt = new Date().toISOString();
75
+
76
+ await appendLog(
77
+ payload.logPath,
78
+ `[${startedAt}] 自动更新开始,当前版本 ${payload.currentVersion}\n`,
79
+ );
80
+
81
+ await writeState(payload.statePath, {
82
+ status: "running",
83
+ packageName: payload.packageName,
84
+ requestedVersion: "latest",
85
+ currentVersion: payload.currentVersion,
86
+ startedAt,
87
+ finishedAt: "",
88
+ logPath: payload.logPath,
89
+ reopen: payload.reopen,
90
+ lastError: "",
91
+ });
92
+
93
+ await sleep(Number(payload.waitSeconds || 3) * 1000);
94
+
95
+ const installResult = await runProcess(
96
+ payload.nodePath,
97
+ [payload.npmCliPath, "install", "-g", `${payload.packageName}@latest`],
98
+ {
99
+ cwd: process.cwd(),
100
+ env: process.env,
101
+ },
102
+ );
103
+
104
+ if (installResult.stdout) {
105
+ await appendLog(payload.logPath, installResult.stdout);
106
+ }
107
+ if (installResult.stderr) {
108
+ await appendLog(payload.logPath, installResult.stderr);
109
+ }
110
+
111
+ if (installResult.code !== 0) {
112
+ const finishedAt = new Date().toISOString();
113
+ const errorMessage = `npm 安装失败,退出码:${installResult.code}`;
114
+ await appendLog(payload.logPath, `[${finishedAt}] ${errorMessage}\n`);
115
+ await writeState(payload.statePath, {
116
+ status: "failed",
117
+ packageName: payload.packageName,
118
+ requestedVersion: "latest",
119
+ currentVersion: payload.currentVersion,
120
+ startedAt,
121
+ finishedAt,
122
+ logPath: payload.logPath,
123
+ reopen: payload.reopen,
124
+ lastError: errorMessage,
125
+ });
126
+ process.exit(1);
127
+ }
128
+
129
+ let reopenResult = { code: 0, stdout: "", stderr: "" };
130
+ if (payload.reopen) {
131
+ reopenResult = await reopenConsole(payload);
132
+ if (reopenResult.stdout) {
133
+ await appendLog(payload.logPath, reopenResult.stdout);
134
+ }
135
+ if (reopenResult.stderr) {
136
+ await appendLog(payload.logPath, reopenResult.stderr);
137
+ }
138
+ }
139
+
140
+ const finishedAt = new Date().toISOString();
141
+ const finalStatus = reopenResult.code === 0 ? "succeeded" : "failed";
142
+ const lastError =
143
+ reopenResult.code === 0 ? "" : `更新已完成,但重新打开控制台失败,退出码:${reopenResult.code}`;
144
+
145
+ await appendLog(
146
+ payload.logPath,
147
+ `[${finishedAt}] ${finalStatus === "succeeded" ? "自动更新完成" : lastError}\n`,
148
+ );
149
+ await writeState(payload.statePath, {
150
+ status: finalStatus,
151
+ packageName: payload.packageName,
152
+ requestedVersion: "latest",
153
+ currentVersion: payload.currentVersion,
154
+ startedAt,
155
+ finishedAt,
156
+ logPath: payload.logPath,
157
+ reopen: payload.reopen,
158
+ lastError,
159
+ });
160
+
161
+ if (finalStatus !== "succeeded") {
162
+ process.exit(1);
163
+ }
164
+ }
165
+
166
+ main().catch(async (error) => {
167
+ const message = error instanceof Error ? error.message : String(error);
168
+ if (process.argv[2]) {
169
+ try {
170
+ const payload = JSON.parse(Buffer.from(process.argv[2], "base64url").toString("utf8"));
171
+ const finishedAt = new Date().toISOString();
172
+ await appendLog(payload.logPath, `[${finishedAt}] 自动更新异常:${message}\n`);
173
+ await writeState(payload.statePath, {
174
+ status: "failed",
175
+ packageName: payload.packageName,
176
+ requestedVersion: "latest",
177
+ currentVersion: payload.currentVersion,
178
+ startedAt: finishedAt,
179
+ finishedAt,
180
+ logPath: payload.logPath,
181
+ reopen: payload.reopen,
182
+ lastError: message,
183
+ });
184
+ } catch {
185
+ // 参数损坏时无法再写状态,直接退出。
186
+ }
187
+ }
188
+ process.exit(1);
189
+ });
package/src/main/main.js CHANGED
@@ -28,6 +28,10 @@ function registerHandlers() {
28
28
  return profileManager.listEndpoints();
29
29
  });
30
30
 
31
+ ipcMain.handle("endpoints:get", async (_event, payload) => {
32
+ return profileManager.getEndpointById(payload.id);
33
+ });
34
+
31
35
  ipcMain.handle("endpoints:current", async () => {
32
36
  return profileManager.getCurrentEndpointSummary();
33
37
  });
@@ -4,6 +4,9 @@ contextBridge.exposeInMainWorld("codexDesktop", {
4
4
  listEndpoints() {
5
5
  return ipcRenderer.invoke("endpoints:list");
6
6
  },
7
+ getEndpoint(payload) {
8
+ return ipcRenderer.invoke("endpoints:get", payload);
9
+ },
7
10
  getCurrentConfig() {
8
11
  return ipcRenderer.invoke("endpoints:current");
9
12
  },
@@ -440,12 +440,14 @@ async function backupEndpointData() {
440
440
  };
441
441
  }
442
442
 
443
- function buildEndpointResponse(endpoint, activeId) {
443
+ function buildEndpointResponse(endpoint, activeId, options = {}) {
444
+ const includeSensitive = Boolean(options.includeSensitive);
445
+
444
446
  return {
445
447
  id: endpoint.id,
446
448
  note: endpoint.note,
447
449
  url: endpoint.url,
448
- key: endpoint.key,
450
+ ...(includeSensitive ? { key: endpoint.key } : {}),
449
451
  maskedKey: maskKey(endpoint.key),
450
452
  createdAt: endpoint.createdAt,
451
453
  updatedAt: endpoint.updatedAt,
@@ -514,6 +516,23 @@ async function listEndpoints() {
514
516
  .map((endpoint) => buildEndpointResponse(endpoint, context.activeEndpointId));
515
517
  }
516
518
 
519
+ async function getEndpointById(id) {
520
+ const safeId = String(id || "").trim();
521
+ if (!safeId) {
522
+ throw new Error("缺少要读取的端点 ID。");
523
+ }
524
+
525
+ const context = await resolveActiveEndpointContext();
526
+ const endpoint = context.endpoints.find((item) => item.id === safeId);
527
+ if (!endpoint) {
528
+ throw new Error("未找到要读取的端点。");
529
+ }
530
+
531
+ return buildEndpointResponse(endpoint, context.activeEndpointId, {
532
+ includeSensitive: true,
533
+ });
534
+ }
535
+
517
536
  async function createEndpoint(payload) {
518
537
  const endpoint = validateEndpointPayload(payload);
519
538
  const endpoints = await readEndpointStore();
@@ -863,6 +882,7 @@ module.exports = {
863
882
  deleteEndpoint,
864
883
  enableProxyMode,
865
884
  exportSyncPackage,
885
+ getEndpointById,
866
886
  getCurrentEndpointSummary,
867
887
  getManagedPaths,
868
888
  getProxyTarget,
@@ -4,6 +4,8 @@ const fs = require("node:fs");
4
4
  const { spawn } = require("node:child_process");
5
5
  const packageInfo = require("../../package.json");
6
6
 
7
+ const packageRoot = path.resolve(__dirname, "../..");
8
+ const runnerEntryPath = path.join(__dirname, "auto-update-runner.js");
7
9
  const REGISTRY_BASE_URL = "https://registry.npmjs.org";
8
10
  const SUCCESS_CACHE_TTL_MS = 10 * 60 * 1000;
9
11
  const ERROR_CACHE_TTL_MS = 30 * 1000;
@@ -18,6 +20,57 @@ function getAutoUpdateLogPath() {
18
20
  return path.join(logDir, "codex-switcher-auto-update.log");
19
21
  }
20
22
 
23
+ function getAutoUpdateStatePath() {
24
+ const stateDir = path.join(os.homedir(), ".codex");
25
+ fs.mkdirSync(stateDir, { recursive: true });
26
+ return path.join(stateDir, "codex-switcher-auto-update.json");
27
+ }
28
+
29
+ function readAutoUpdateState() {
30
+ try {
31
+ const content = fs.readFileSync(getAutoUpdateStatePath(), "utf8");
32
+ const parsed = JSON.parse(content);
33
+ return parsed && typeof parsed === "object" ? parsed : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ function writeAutoUpdateState(payload) {
40
+ fs.writeFileSync(
41
+ getAutoUpdateStatePath(),
42
+ `${JSON.stringify(payload, null, 2)}\n`,
43
+ "utf8",
44
+ );
45
+ }
46
+
47
+ function resolveRuntimePaths() {
48
+ const nodePath = process.execPath;
49
+ const nodeDir = path.dirname(nodePath);
50
+ const globalRootCandidates =
51
+ process.platform === "win32"
52
+ ? [path.join(nodeDir, "node_modules")]
53
+ : [path.join(nodeDir, "../lib/node_modules"), path.join(nodeDir, "node_modules")];
54
+
55
+ const npmCliPath = globalRootCandidates
56
+ .map((basePath) => path.resolve(basePath, "npm/bin/npm-cli.js"))
57
+ .find((targetPath) => fs.existsSync(targetPath));
58
+
59
+ if (!npmCliPath) {
60
+ throw new Error("未找到当前运行时对应的 npm-cli.js,无法自动更新。");
61
+ }
62
+
63
+ const installedPackageBinPath = globalRootCandidates
64
+ .map((basePath) => path.resolve(basePath, `${packageInfo.name}/bin/codex-switcher.js`))
65
+ .find((targetPath) => fs.existsSync(targetPath));
66
+
67
+ return {
68
+ nodePath,
69
+ npmCliPath,
70
+ reopenBinPath: installedPackageBinPath || path.join(packageRoot, "bin/codex-switcher.js"),
71
+ };
72
+ }
73
+
21
74
  function sleep(timeoutMs) {
22
75
  return new Promise((resolve) => {
23
76
  setTimeout(resolve, timeoutMs);
@@ -56,6 +109,7 @@ function buildStatus(payload = {}) {
56
109
  const currentVersion = packageInfo.version;
57
110
  const latestVersion = payload.latestVersion || currentVersion;
58
111
  const hasUpdate = compareVersions(latestVersion, currentVersion) > 0;
112
+ const autoUpdateState = payload.autoUpdateState || readAutoUpdateState();
59
113
 
60
114
  return {
61
115
  packageName: packageInfo.name,
@@ -66,6 +120,7 @@ function buildStatus(payload = {}) {
66
120
  upgradeCommand: `npm install -g ${packageInfo.name}@latest`,
67
121
  releaseUrl: `https://www.npmjs.com/package/${packageInfo.name}`,
68
122
  lastError: payload.lastError || "",
123
+ autoUpdateState,
69
124
  };
70
125
  }
71
126
 
@@ -131,44 +186,41 @@ async function getUpdateStatus(options = {}) {
131
186
  function scheduleAutoUpdate(options = {}) {
132
187
  const reopen = options.reopen !== false;
133
188
  const logPath = getAutoUpdateLogPath();
134
- const installCommand = `npm install -g ${packageInfo.name}@latest`;
135
- const restartCommand = reopen ? " && codex-switcher open" : "";
136
-
137
- if (process.platform === "win32") {
138
- const command =
139
- `echo [%date% %time%] 开始自动更新 ${packageInfo.name} > "${logPath}" ` +
140
- `&& timeout /t ${AUTO_UPDATE_WAIT_SECONDS} /nobreak >nul ` +
141
- `&& ${installCommand} >> "${logPath}" 2>&1` +
142
- `${restartCommand ? `${restartCommand} >> "${logPath}" 2>&1` : ""}`;
143
-
144
- const child = spawn("cmd.exe", ["/d", "/s", "/c", command], {
145
- cwd: os.homedir(),
146
- detached: true,
147
- stdio: "ignore",
148
- windowsHide: true,
149
- env: process.env,
150
- });
189
+ const statePath = getAutoUpdateStatePath();
190
+ const runtimePaths = resolveRuntimePaths();
151
191
 
152
- child.unref();
153
- return {
154
- scheduled: true,
192
+ writeAutoUpdateState({
193
+ status: "scheduled",
194
+ packageName: packageInfo.name,
195
+ requestedVersion: "latest",
196
+ currentVersion: packageInfo.version,
197
+ startedAt: new Date().toISOString(),
198
+ finishedAt: "",
199
+ logPath,
200
+ reopen,
201
+ lastError: "",
202
+ });
203
+
204
+ const payload = Buffer.from(
205
+ JSON.stringify({
155
206
  packageName: packageInfo.name,
156
207
  currentVersion: packageInfo.version,
208
+ waitSeconds: AUTO_UPDATE_WAIT_SECONDS,
157
209
  logPath,
210
+ statePath,
158
211
  reopen,
159
- };
160
- }
161
-
162
- const command =
163
- `sleep ${AUTO_UPDATE_WAIT_SECONDS}; ` +
164
- `echo "[auto-update] start ${packageInfo.name}" > "${logPath}"; ` +
165
- `${installCommand} >> "${logPath}" 2>&1` +
166
- (reopen ? ` && codex-switcher open >> "${logPath}" 2>&1` : "");
167
-
168
- const child = spawn("sh", ["-lc", command], {
212
+ nodePath: runtimePaths.nodePath,
213
+ npmCliPath: runtimePaths.npmCliPath,
214
+ reopenBinPath: runtimePaths.reopenBinPath,
215
+ }),
216
+ "utf8",
217
+ ).toString("base64url");
218
+
219
+ const child = spawn(process.execPath, [runnerEntryPath, payload], {
169
220
  cwd: os.homedir(),
170
221
  detached: true,
171
222
  stdio: "ignore",
223
+ windowsHide: true,
172
224
  env: process.env,
173
225
  });
174
226
 
@@ -178,6 +230,7 @@ function scheduleAutoUpdate(options = {}) {
178
230
  packageName: packageInfo.name,
179
231
  currentVersion: packageInfo.version,
180
232
  logPath,
233
+ statePath,
181
234
  reopen,
182
235
  };
183
236
  }
@@ -109,6 +109,7 @@
109
109
  <button id="openEndpointStoreButton" class="ghost-button">打开连接数据文件</button>
110
110
  <button id="closeAppButton" class="danger-button">关闭程序</button>
111
111
  </div>
112
+ <div id="appStatusBox" class="status-box info">控制台已就绪。</div>
112
113
  <section class="update-strip" aria-label="版本更新状态">
113
114
  <div class="update-copy">
114
115
  <span class="metric-label">版本更新</span>
@@ -116,6 +117,7 @@
116
117
  <span id="updateDetail" class="update-detail">
117
118
  当前版本 -,正在连接 npm 仓库。
118
119
  </span>
120
+ <span id="updateHistory" class="update-detail" hidden></span>
119
121
  <code id="updateCommand" class="update-command" hidden>
120
122
  npm install -g codex-endpoint-switcher@latest
121
123
  </code>
@@ -30,6 +30,9 @@ function createWebBridge() {
30
30
  listEndpoints() {
31
31
  return request("/api/endpoints");
32
32
  },
33
+ getEndpoint(payload) {
34
+ return request(`/api/endpoints/${payload.id}`);
35
+ },
33
36
  getCurrentConfig() {
34
37
  return request("/api/current");
35
38
  },
@@ -156,8 +159,13 @@ function formatDateTime(value) {
156
159
  }
157
160
 
158
161
  function setStatus(message, type = "info") {
159
- void message;
160
- void type;
162
+ const statusBox = $("#appStatusBox");
163
+ if (!statusBox) {
164
+ return;
165
+ }
166
+
167
+ statusBox.textContent = message;
168
+ statusBox.className = `status-box ${type}`;
161
169
  }
162
170
 
163
171
  function setAuthStatus(message, type = "info") {
@@ -310,14 +318,33 @@ function renderUpdateStatus() {
310
318
 
311
319
  const summary = $("#updateSummary");
312
320
  const detail = $("#updateDetail");
321
+ const history = $("#updateHistory");
313
322
  const command = $("#updateCommand");
314
323
  const copyButton = $("#copyUpdateCommandButton");
315
324
  const autoUpdateButton = $("#autoUpdateButton");
316
325
 
317
- if (!summary || !detail || !command || !copyButton || !autoUpdateButton) {
326
+ if (!summary || !detail || !history || !command || !copyButton || !autoUpdateButton) {
318
327
  return;
319
328
  }
320
329
 
330
+ history.hidden = true;
331
+ history.textContent = "";
332
+
333
+ if (update.autoUpdateState?.status) {
334
+ const autoUpdateState = update.autoUpdateState;
335
+ if (autoUpdateState.status === "succeeded") {
336
+ history.textContent = `上次自动更新已完成:${formatDateTime(autoUpdateState.finishedAt)}`;
337
+ history.hidden = false;
338
+ } else if (autoUpdateState.status === "failed") {
339
+ history.textContent =
340
+ `上次自动更新失败:${autoUpdateState.lastError || "请查看日志"}。日志:${autoUpdateState.logPath}`;
341
+ history.hidden = false;
342
+ } else if (autoUpdateState.status === "running" || autoUpdateState.status === "scheduled") {
343
+ history.textContent = "检测到自动更新任务正在执行,请稍候。";
344
+ history.hidden = false;
345
+ }
346
+ }
347
+
321
348
  command.textContent = update.upgradeCommand;
322
349
 
323
350
  if (update.hasUpdate) {
@@ -372,6 +399,23 @@ async function refreshUpdateStatus(force = false) {
372
399
  }
373
400
  }
374
401
 
402
+ async function openEditEndpoint(id, note) {
403
+ try {
404
+ setStatus(`正在加载连接:${note} ...`, "info");
405
+ const endpoint = await bridge.getEndpoint({ id });
406
+ fillForm(endpoint);
407
+ openEndpointModal();
408
+ setStatus(`正在编辑:${note}`, "info");
409
+ } catch (error) {
410
+ if (isUnauthorizedError(error)) {
411
+ await handleAccessRevoked(error.message);
412
+ return;
413
+ }
414
+
415
+ setStatus(`读取连接失败:${error.message}`, "error");
416
+ }
417
+ }
418
+
375
419
  function createEndpointCard(endpoint) {
376
420
  const card = document.createElement("article");
377
421
  card.className = `profile-card ${endpoint.isActive ? "active" : ""}`;
@@ -417,8 +461,7 @@ function createEndpointCard(endpoint) {
417
461
  editButton.className = "ghost-button";
418
462
  editButton.textContent = "编辑";
419
463
  editButton.addEventListener("click", () => {
420
- fillForm(endpoint);
421
- openEndpointModal();
464
+ openEditEndpoint(endpoint.id, endpoint.note);
422
465
  });
423
466
 
424
467
  const deleteButton = document.createElement("button");
package/src/web/server.js CHANGED
@@ -61,6 +61,14 @@ function createApp() {
61
61
  }),
62
62
  );
63
63
 
64
+ app.get(
65
+ "/api/endpoints/:id",
66
+ wrapAsync(async (req) => {
67
+ await ensureConsoleAccess();
68
+ return profileManager.getEndpointById(req.params.id);
69
+ }),
70
+ );
71
+
64
72
  app.post(
65
73
  "/api/endpoints",
66
74
  wrapAsync(async (req) => {
@@ -253,10 +261,11 @@ function createApp() {
253
261
 
254
262
  function startServer(options = {}) {
255
263
  const port = Number(options.port || process.env.PORT || 3186);
264
+ const host = options.host || process.env.HOST || "127.0.0.1";
256
265
  const app = createApp();
257
266
  const proxyServer = createProxyServer();
258
267
  const proxyPort = profileManager.proxyPort;
259
- const webServer = app.listen(port, () => {
268
+ const webServer = app.listen(port, host, () => {
260
269
  const url = `http://localhost:${port}`;
261
270
  console.log(`Codex 网页控制台已启动:${url}`);
262
271
  console.log(`Codex 热更新代理已启动:${profileManager.proxyBaseUrl}`);
@@ -266,7 +275,7 @@ function startServer(options = {}) {
266
275
  }
267
276
  });
268
277
 
269
- proxyServer.listen(proxyPort);
278
+ proxyServer.listen(proxyPort, host);
270
279
  warmUpCurrentTarget().catch(() => {
271
280
  // 预热失败不阻断服务启动,真正请求时仍会走自动重试。
272
281
  });