@yanzc/claude-pro 0.12.0 → 0.14.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/src/web/data.js CHANGED
@@ -151,6 +151,9 @@ function toolsFor(cwd) {
151
151
  return tools;
152
152
  }
153
153
 
154
+ // The built-in tools a session of the project sends the model (扩展's 内置工具): {name, description}.
155
+ export const builtinTools = (cwd) => toolsFor(cwd).map((t) => ({ name: t.name, description: String(t.description || '') }));
156
+
154
157
  // A conversation as the console shows it: its items (as the live view has them, images as {k: 'image', n}), with
155
158
  // what the list knows of it.
156
159
  export function sessionDetail(dir, id) {
@@ -158,7 +161,7 @@ export function sessionDetail(dir, id) {
158
161
  const loaded = SessionStore.load(file);
159
162
  const cwd = summarize(file).cwd;
160
163
  const ctx = { cwd: cwd || os.homedir(), projectRoot: cwd || os.homedir() };
161
- const items = transcriptItems(loaded.messages, { tools: toolsFor(cwd), ctx, cwd: ctx.cwd, limit: Infinity, images: true });
164
+ const items = transcriptItems(loaded.messages, { tools: toolsFor(cwd), ctx, cwd: ctx.cwd, limit: Infinity, images: true, turns: loaded.turns });
162
165
  const st = fs.statSync(file);
163
166
  return {
164
167
  id, dir, cwd, title: loaded.name || loaded.topic || loaded.title || '(no prompt)', name: loaded.name, topic: loaded.topic,
@@ -353,19 +356,22 @@ function traceRows(file) {
353
356
  try { e = JSON.parse(line); } catch { continue; }
354
357
  if (!e.ok && !e.output_tokens) continue;
355
358
  const usage = { input_tokens: e.input_tokens, output_tokens: e.output_tokens, cache_read_input_tokens: e.cache_read_tokens, cache_creation_input_tokens: e.cache_write_tokens };
356
- rows.push({ day: localDay(e.time), model: e.model || '?', session: e.session_id, input: e.input_tokens || 0, output: e.output_tokens || 0, cacheRead: e.cache_read_tokens || 0, cacheWrite: e.cache_write_tokens || 0, cost: costOf(e.model, usage) });
359
+ rows.push({ day: localDay(e.time), hour: new Date(e.time).getHours(), model: e.model || '?', session: e.session_id, input: e.input_tokens || 0, output: e.output_tokens || 0, cacheRead: e.cache_read_tokens || 0, cacheWrite: e.cache_write_tokens || 0, cost: costOf(e.model, usage) });
357
360
  }
358
361
  usageMemo.set(file, { mtime: st.mtimeMs, size: st.size, rows });
359
362
  return rows;
360
363
  }
361
364
 
362
- // Tokens and (where the model has a price here) cost by day, model and project, from every project's traces; and
363
- // each conversation's own total (its meta), which covers what the traces do not price.
365
+ // Tokens and (where the model has a price here) cost by day (by hour too for today alone, `days` 1), model, project
366
+ // and conversation, from every project's traces; and each conversation's own total (its meta), which covers what
367
+ // the traces do not price.
364
368
  export function usageReport({ days = 30 } = {}) {
365
369
  const since = localDay(new Date(Date.now() - (days - 1) * 86_400_000).toISOString());
366
370
  const byDay = new Map();
367
371
  const byModel = new Map();
368
372
  const byProject = new Map();
373
+ const bySession = new Map();
374
+ const byHour = new Map();
369
375
  const add = (map, key, r) => {
370
376
  const e = map.get(key) || { key, requests: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, unpriced: 0 };
371
377
  e.requests++;
@@ -387,6 +393,8 @@ export function usageReport({ days = 30 } = {}) {
387
393
  add(byDay, r.day, r);
388
394
  add(byModel, r.model, r);
389
395
  add(byProject, cwdOfDir.get(d.name) || d.name, r);
396
+ if (r.session) add(bySession, r.session, r);
397
+ if (days === 1) add(byHour, r.hour, r);
390
398
  }
391
399
  }
392
400
  }
@@ -396,12 +404,19 @@ export function usageReport({ days = 30 } = {}) {
396
404
  dayList.push(byDay.get(key) || { key, requests: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, unpriced: 0 });
397
405
  }
398
406
  const sortCost = (a, b) => b.cost - a.cost || b.requests - a.requests;
407
+ const sessionById = new Map(sessions.map((s) => [s.id, s]));
408
+ const empty = (key) => ({ key, requests: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, unpriced: 0 });
399
409
  return {
400
410
  days: dayList,
411
+ // today, hour by hour up to now
412
+ ...(days === 1 ? { hours: Array.from({ length: new Date().getHours() + 1 }, (_, h) => ({ ...(byHour.get(h) || empty(h)), key: `${String(h).padStart(2, '0')}:00` })) } : {}),
401
413
  models: [...byModel.values()].sort(sortCost),
402
414
  projects: [...byProject.values()].sort(sortCost),
403
- sessions: sessions.filter((s) => s.cost > 0).sort((a, b) => b.cost - a.cost).slice(0, 30)
404
- .map(({ id, dir, cwd, title, cost, mtime }) => ({ id, dir, cwd, title, cost, mtime })),
415
+ // the conversations that cost most in this period (a deleted one has no title, nor a page to open)
416
+ sessions: [...bySession.values()].sort(sortCost).slice(0, 30).map((e) => {
417
+ const s = sessionById.get(e.key);
418
+ return { id: e.key, dir: s?.dir || null, cwd: s?.cwd || null, title: s?.title || null, mtime: s?.mtime || null, cost: e.cost, requests: e.requests, unpriced: e.unpriced };
419
+ }),
405
420
  totalSessionCost: sessions.reduce((sum, s) => sum + s.cost, 0),
406
421
  };
407
422
  }
package/src/web/host.js CHANGED
@@ -216,10 +216,8 @@ export class SessionHost {
216
216
  // works is its work, loaded when the sessions are idle; one made while all are idle is loaded once the source has
217
217
  // been left alone for a few minutes (a few seconds when there is no session to restart).
218
218
  watch() {
219
- this.watcher = watchSource(INSTALL_DIR, (file) => {
220
- if (/^web[\\/]app\.js$/i.test(file)) return; // read from disk by every page load: nothing to restart for
221
- this.noteChange();
222
- });
219
+ // (the page too: the server serves the page it started with, so that page and API always match)
220
+ this.watcher = watchSource(INSTALL_DIR, () => this.noteChange());
223
221
  }
224
222
 
225
223
  noteChange({ now = false } = {}) {
@@ -5,12 +5,13 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content">
6
6
  <meta name="robots" content="noindex">
7
7
  <title>登录 · claude-pro 控制台</title>
8
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg">
8
9
  <style>
9
10
  :root { color-scheme: light dark; }
10
11
  *, *::before, *::after { box-sizing: border-box; }
11
12
  body { margin: 0; min-height: 100vh; min-height: 100dvh; display: grid; grid-template-columns: minmax(0, 1fr); place-items: center; padding: 16px; padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); font: 15px/1.6 system-ui, -apple-system, "Segoe UI", "Microsoft YaHei UI", "PingFang SC", sans-serif; background: #f6f7f9; color: #111827; }
12
13
  main { width: min(430px, 100%); background: #fff; border: 1px solid #e3e6eb; border-radius: 16px; padding: 28px 24px 24px; box-shadow: 0 10px 34px rgba(0, 0, 0, .07); overflow-wrap: anywhere; }
13
- .logo { width: 40px; height: 40px; border-radius: 11px; background: #d97757; color: #fff; display: grid; place-items: center; font-weight: 800; font-size: 20px; margin-bottom: 14px; }
14
+ .logo { display: block; width: 44px; height: 44px; border-radius: 12px; margin-bottom: 14px; box-shadow: 0 6px 18px rgba(194, 88, 54, .28); }
14
15
  h1 { font-size: 20px; margin: 0 0 4px; }
15
16
  p { margin: 0 0 18px; color: #6b7280; font-size: 13.5px; }
16
17
  input[type=password] { width: 100%; box-sizing: border-box; padding: 11px 13px; border: 1px solid #cfd4dc; border-radius: 10px; font: inherit; background: transparent; color: inherit; outline: none; }
@@ -34,7 +35,7 @@
34
35
  </head>
35
36
  <body>
36
37
  <main>
37
- <div class="logo">c</div>
38
+ <img class="logo" src="/favicon.svg" alt="claude-pro" width="44" height="44">
38
39
  <h1>claude-pro 控制台</h1>
39
40
  <p>这是一台电脑上的 claude-pro。输入在 claude-pro 里设置的远程访问密码。</p>
40
41
  <form id="f">
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="g" x1="8" y1="4" x2="56" y2="60" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#E58C6B"/><stop offset="1" stop-color="#BC4C2A"/></linearGradient></defs><rect width="64" height="64" rx="15" fill="url(#g)"/><path d="M43 20.8A15 15 0 1 0 43 43.2" fill="none" stroke="#fff" stroke-width="7.5" stroke-linecap="round"/><path d="M47 24L49 30L55 32L49 34L47 40L45 34L39 32L45 30Z" fill="#fff"/></svg>
package/src/web/page.html CHANGED
@@ -4,15 +4,16 @@
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content">
6
6
  <title>claude-pro 控制台</title>
7
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg">
7
8
  <link rel="stylesheet" href="/app.css">
8
9
  <script src="/app.js" defer></script>
9
10
  </head>
10
11
  <body>
11
12
  <div class="app">
12
13
  <aside class="side" id="sideDrawer">
13
- <div class="brand"><div class="brand-logo">c</div><strong>claude-pro</strong><span class="brand-tag">CONSOLE</span><span class="brand-release"><span class="brand-ver" id="brandVersion"></span><button type="button" class="brand-update hidden" id="brandUpdate" aria-label="更新">↑</button></span></div>
14
+ <div class="brand"><img class="brand-logo" src="/favicon.svg" alt="" width="28" height="28"><strong>claude-pro</strong><span class="brand-tag">CONSOLE</span><span class="brand-release"><span class="brand-ver" id="brandVersion"></span><button type="button" class="brand-update hidden" id="brandUpdate" aria-label="更新">↑</button></span></div>
14
15
  <a class="side-new" href="#/new" data-nav="new"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M12 8v8M8 12h8"/></svg>新会话</a>
15
- <div class="ws-head"><span>工作区</span><span class="ws-tools"><button type="button" class="drawer-close" id="drawerClose" aria-label="关闭菜单"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18"/></svg></button><button type="button" id="wsSearchBtn" title="搜索会话"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg></button><button type="button" id="wsRefresh" title="刷新"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"/><path d="M21 3v5h-5"/></svg></button><a href="#/new" title="新会话"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg></a></span></div>
16
+ <div class="ws-head"><span>工作区</span><span class="ws-tools"><button type="button" class="drawer-close" id="drawerClose" aria-label="关闭菜单"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18"/></svg></button><button type="button" id="wsSearchBtn" title="搜索会话"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg></button><button type="button" id="wsRefresh" title="刷新"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"/><path d="M21 3v5h-5"/></svg></button><button type="button" id="wsAddDir" title="添加工作区" aria-label="添加工作区"><svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M12 10.5v5M9.5 13h5"/></svg></button></span></div>
16
17
  <input type="search" class="ws-search hidden" id="wsSearch" placeholder="搜索会话或目录…">
17
18
  <div class="ws" id="ws"><div class="ws-empty">正在加载…</div></div>
18
19
  <!-- settings and the other pages: in the menu of the account, at the bottom -->
@@ -27,12 +28,14 @@
27
28
  <a href="#/sessions" data-nav="sessions"><svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>全部会话与回收站</a>
28
29
  <a href="#/memory" data-nav="memory"><svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20V3H6.5A2.5 2.5 0 0 0 4 5.5z"/><path d="M4 19.5A2.5 2.5 0 0 0 6.5 22H20v-5"/></svg>记忆与指令</a>
29
30
  <a href="#/usage" data-nav="usage"><svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21h18M7 17V11M12 17V6M17 17v-4"/></svg>用量</a>
31
+ <div class="menu-sep hidden" id="repoSep"></div>
32
+ <a href="#" class="hidden" id="repoLink" target="_blank" rel="noopener"><svg viewBox="0 0 24 24" width="17" height="17" fill="currentColor" aria-hidden="true"><path d="M12 2a10 10 0 0 0-3.16 19.49c.5.09.68-.22.68-.48v-1.7c-2.78.6-3.37-1.34-3.37-1.34-.45-1.16-1.11-1.47-1.11-1.47-.91-.62.07-.6.07-.6 1 .07 1.53 1.03 1.53 1.03.9 1.52 2.34 1.08 2.91.83.09-.65.35-1.09.63-1.34-2.22-.25-4.55-1.11-4.55-4.94 0-1.09.39-1.98 1.03-2.68-.1-.25-.45-1.27.1-2.64 0 0 .84-.27 2.75 1.02a9.6 9.6 0 0 1 5 0c1.91-1.29 2.75-1.02 2.75-1.02.55 1.37.2 2.39.1 2.64.64.7 1.03 1.59 1.03 2.68 0 3.84-2.34 4.68-4.57 4.93.36.31.68.92.68 1.85v2.74c0 .27.18.58.69.48A10 10 0 0 0 12 2z"/></svg>GitHub 仓库</a>
30
33
  </nav>
31
34
  <div class="remote-links hidden" id="remoteLinks"><a href="/__cp/computers">切换电脑</a><button type="button" id="logoutBtn">退出登录</button></div>
32
35
  </div>
33
- <div class="side-foot"><button type="button" class="side-me" id="sideMe" title="设置与更多" aria-haspopup="menu" aria-expanded="false"><span class="avatar" id="sideAvatar">·</span><span class="side-user" id="sideUser"></span><svg class="side-caret" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 15 6-6 6 6"/></svg></button><button type="button" class="icon-btn" id="themeToggle" title="浅色 / 深色">◐</button></div>
36
+ <div class="side-foot"><button type="button" class="side-me" id="sideMe" title="设置与更多" aria-haspopup="menu" aria-expanded="false"><span class="side-me-icon" aria-hidden="true"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="side-user">设置</span><svg class="side-caret" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 15 6-6 6 6"/></svg></button><button type="button" class="icon-btn theme-icon" id="themeToggle" title="浅色 / 深色" aria-label="切换浅色 / 深色"><svg class="sun" viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg><svg class="moon" viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg></button></div>
34
37
  </aside>
35
- <button type="button" class="mobile-menu" id="menuBtn" aria-label="菜单" aria-controls="sideDrawer" aria-expanded="false">☰</button>
38
+ <button type="button" class="mobile-menu" id="menuBtn" aria-label="菜单" aria-controls="sideDrawer" aria-expanded="false"><svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button>
36
39
  <div class="side-backdrop" id="sideBackdrop" aria-hidden="true"></div>
37
40
  <main class="main" id="main"><div class="page"><div class="empty">正在加载…</div></div></main>
38
41
  </div>
@@ -61,6 +61,30 @@ export function computerId() {
61
61
 
62
62
  export function setEnabled(on) { return writeRemote((d) => { d.enabled = Boolean(on); }); }
63
63
 
64
+ // The address's prefix: the account's 通讯号 at the gateway (<通讯号>.7bit.fun; its contacts find it by it too), asked
65
+ // for (handle null) or set with the gateway key (/v1/remote/contacts), the gateway checking the form, its reserved
66
+ // names and that no other account has it. {handle, auto, domain}; `auto`: still the one the gateway made up (cp and 6
67
+ // characters of its alphabet), not one the user chose. Throws with the gateway's words and a status for the page.
68
+ export async function addressPrefix(login, handle = null, { fetchImpl = globalThis.fetch } = {}) {
69
+ if (!login?.apiKey) throw Object.assign(new Error('远程访问需要先连接 7bit.fun'), { status: 409 });
70
+ const base = String(login.url || 'https://7bit.fun').replace(/\/+$/, '');
71
+ let r;
72
+ try {
73
+ r = await fetchImpl(`${base}/v1/remote/contacts${handle ? '/handle' : ''}`, {
74
+ method: handle ? 'POST' : 'GET',
75
+ headers: { authorization: `Bearer ${login.apiKey}`, ...(handle ? { 'content-type': 'application/json' } : {}) },
76
+ ...(handle ? { body: JSON.stringify({ handle }) } : {}),
77
+ signal: AbortSignal.timeout(15_000),
78
+ });
79
+ } catch (e) { throw Object.assign(new Error(`连不上网关:${e.message}`), { status: 502 }); }
80
+ const j = await r.json().catch(() => null);
81
+ if (!r.ok) throw Object.assign(new Error(j?.error?.message || (typeof j?.error === 'string' ? j.error : '') || `网关返回 ${r.status}`), { status: r.status === 409 || r.status === 400 ? r.status : 502 });
82
+ const now = String(j?.handle || '');
83
+ let domain = '7bit.fun';
84
+ try { domain = new URL(base).hostname; } catch { /* the default */ }
85
+ return { handle: now, auto: /^cp[a-hjkmnp-z2-9]{6}$/.test(now), domain };
86
+ }
87
+
64
88
  // ---------------------------------------------------------------- logged-in devices
65
89
 
66
90
  const hashToken = (secret) => crypto.createHash('sha256').update(secret).digest('base64url');
package/src/web/server.js CHANGED
@@ -17,9 +17,18 @@ import crypto from 'node:crypto';
17
17
  import { spawn } from 'node:child_process';
18
18
  import { fileURLToPath } from 'node:url';
19
19
  import { CONFIG_DIR, VERSION } from '../config.js';
20
+ import { machineName } from '../peers.js';
20
21
 
21
22
  const HERE = path.dirname(fileURLToPath(import.meta.url));
22
23
  const PORT = 7878;
24
+ // The project's page (package.json's repository, as a browser opens it): the console's menu links to it.
25
+ const REPO = (() => {
26
+ try {
27
+ const r = JSON.parse(fs.readFileSync(path.join(HERE, '..', '..', 'package.json'), 'utf8')).repository;
28
+ const url = String(typeof r === 'string' ? r : r?.url || '').replace(/^git\+/, '').replace(/\.git$/, '');
29
+ return /^https:\/\//.test(url) ? url : null;
30
+ } catch { return null; }
31
+ })();
23
32
  const IDLE_MS = 30 * 60_000;
24
33
  const BODY_LIMIT = 20 * 1024 * 1024;
25
34
  const COOKIE = 'cpweb';
@@ -32,12 +41,13 @@ const STATIC = {
32
41
  '/': ['page.html', 'text/html; charset=utf-8'],
33
42
  '/app.js': ['app.js', 'text/javascript; charset=utf-8'],
34
43
  '/app.css': ['app.css', 'text/css; charset=utf-8'],
44
+ '/favicon.svg': ['logo.svg', 'image/svg+xml'], // (also before 远程访问's login: its page shows it too)
35
45
  };
36
46
 
37
47
  // What the code of the console is: the version, and in a source checkout the times of its files, so that a server
38
48
  // started by older code gives way to the new one.
39
49
  export function codeStamp() {
40
- const files = ['server.js', 'api.js', 'data.js', 'remote-access.js', 'page.html', 'login.html', 'app.js', 'app.css'].map((f) => path.join(HERE, f));
50
+ const files = ['server.js', 'api.js', 'data.js', 'remote-access.js', 'page.html', 'login.html', 'app.js', 'app.css', 'logo.svg'].map((f) => path.join(HERE, f));
41
51
  files.push(path.join(HERE, '..', 'live.js'), path.join(HERE, '..', 'remote.js'), path.join(HERE, '..', 'session.js'), path.join(HERE, '..', 'config.js'), path.join(HERE, '..', 'updater.js'));
42
52
  const times = files.map((f) => { try { return Math.round(fs.statSync(f).mtimeMs); } catch { return 0; } });
43
53
  return `${VERSION}:${crypto.createHash('sha1').update(times.join(',')).digest('hex').slice(0, 10)}`;
@@ -81,6 +91,9 @@ async function serve() {
81
91
  const before = readState()?.token;
82
92
  const token = typeof before === 'string' && /^[\w-]{32}$/.test(before) ? before : crypto.randomBytes(24).toString('base64url');
83
93
  const code = codeStamp(); // the code this server runs (a later start compares it with the files as they are then)
94
+ // The page as it was when this server started: a page read from disk at every load could be newer than the API
95
+ // this process serves (an update or an edit waits for the sessions to be idle) and call routes it does not have.
96
+ const pages = Object.fromEntries(Object.values(STATIC).map(([file]) => [file, fs.readFileSync(path.join(HERE, file))]));
84
97
  const { routes, useHost } = await import('./api.js');
85
98
  const data = await import('./data.js');
86
99
  const ra = await import('./remote-access.js');
@@ -153,6 +166,8 @@ async function serve() {
153
166
  return g?.apiKey ? { url: String(g.url || process.env.CLAUDE_PRO_GATEWAY_URL || 'https://7bit.fun'), apiKey: g.apiKey } : null;
154
167
  } catch { return null; }
155
168
  }
169
+ const gatewayHandle = (handle = null) => ra.addressPrefix(gatewayLoginNow(), handle);
170
+
156
171
  function syncTunnel() {
157
172
  const want = ra.readRemote().enabled && ra.hasPassword();
158
173
  const login = want ? gatewayLoginNow() : null;
@@ -179,6 +194,10 @@ async function serve() {
179
194
  const remoteOrigin = remote ? String(req.headers['x-cpweb-origin'] || '').toLowerCase() : '';
180
195
  const ip = remote ? String(req.headers['x-cpweb-ip'] || '') : '127.0.0.1';
181
196
  try {
197
+ if (req.method === 'GET' && url.pathname === '/favicon.svg') {
198
+ res.writeHead(200, { 'content-type': 'image/svg+xml', 'cache-control': 'max-age=86400' });
199
+ return res.end(pages['logo.svg']);
200
+ }
182
201
  if (remote) {
183
202
  if (url.pathname === '/__login' && req.method === 'POST') return remoteLogin(req, res, ip, remoteOrigin);
184
203
  const session = ra.validSession(cookieOf(req, remoteCookieName(remoteOrigin)));
@@ -202,7 +221,7 @@ async function serve() {
202
221
  if (req.method === 'GET' && STATIC[url.pathname]) {
203
222
  const [file, type] = STATIC[url.pathname];
204
223
  res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store', 'content-security-policy': "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'" });
205
- return res.end(fs.readFileSync(path.join(HERE, file)));
224
+ return res.end(pages[file]);
206
225
  }
207
226
  if (!url.pathname.startsWith('/api/')) return send(res, 404, { error: 'not found' });
208
227
  const bearer = equal(String(req.headers.authorization || '').replace(/^Bearer /, ''), token);
@@ -214,7 +233,7 @@ async function serve() {
214
233
  if (!origins().has(String(req.headers.origin || '').toLowerCase())) return send(res, 403, { error: 'cross-site request refused' });
215
234
  if (req.headers['content-length'] && req.headers['content-length'] !== '0' && !/^application\/json\b/i.test(String(req.headers['content-type'] || ''))) return send(res, 415, { error: 'JSON body required' });
216
235
  }
217
- if (url.pathname === '/api/ping') return send(res, 200, { ok: true, version: VERSION, code, pid: process.pid, remote, nativeFolderPicker: !remote && process.platform === 'win32', hosted: host?.size ?? 0 });
236
+ if (url.pathname === '/api/ping') return send(res, 200, { ok: true, version: VERSION, code, pid: process.pid, machine: machineName(), repo: REPO, remote, nativeFolderPicker: !remote && process.platform === 'win32', hosted: host?.size ?? 0 });
218
237
  if (remote && url.pathname === '/api/projects/pick') return send(res, 403, { error: '远程访问请使用目录列表' });
219
238
  // a newer console was started (ensureWebServer): this one gives way once its sessions are idle
220
239
  if (url.pathname === '/api/handover' && req.method === 'POST') { host?.requestHandover(); return send(res, 200, { ok: true }); }
@@ -230,8 +249,18 @@ async function serve() {
230
249
  }
231
250
  // 远程访问's own settings: on or off, the password, the devices logged in, the recent logins
232
251
  if (url.pathname === '/api/remote' && req.method === 'GET') return send(res, 200, remoteView());
252
+ if (url.pathname === '/api/remote/handle' && req.method === 'GET') {
253
+ try { return send(res, 200, await gatewayHandle()); } catch (e) { return send(res, e.status || 502, { error: e.message }); }
254
+ }
233
255
  if (url.pathname === '/api/remote' && req.method === 'POST') {
234
256
  const body = (await readBody(req)) || {};
257
+ // the prefix chosen (the first time, or changed): set at the gateway before anything else
258
+ if (typeof body.handle === 'string' && body.handle.trim()) {
259
+ try { await gatewayHandle(body.handle.trim().toLowerCase()); } catch (e) { return send(res, e.status || 502, { error: e.message }); }
260
+ // (an open tunnel took its host when it connected: again, for the new one)
261
+ tunnel?.close();
262
+ tunnel = null;
263
+ }
235
264
  if (typeof body.password === 'string' && body.password) {
236
265
  try { ra.setPassword(body.password); } catch (e) { return send(res, 400, { error: e.message }); }
237
266
  }