cfpilot 0.50.0 → 0.60.0-beta.1

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.
@@ -0,0 +1,890 @@
1
+ // ../edge-relay/cf-worker-relay/dashboard.html
2
+ var dashboard_default = `<!doctype html>
3
+ <html lang="zh-CN">
4
+ <head>
5
+ <meta charset="UTF-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>MobiHop \u4E91\u76D1\u6D4B\u53F0</title>
8
+ <style>
9
+ :root { color-scheme: dark; }
10
+ * { box-sizing: border-box; }
11
+ body { margin:0; font-family: system-ui, -apple-system, sans-serif; background:#0b1220; color:#e2e8f0; }
12
+ header { padding:16px 24px; border-bottom:1px solid #1e293b; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px; }
13
+ h1 { margin:0; font-size:18px; }
14
+ .sub { color:#64748b; font-size:13px; }
15
+ main { padding:24px; }
16
+ .grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(140px,1fr)); gap:12px; margin-bottom:20px; }
17
+ .card { background:#111a2e; border:1px solid #1e293b; border-radius:10px; padding:14px; }
18
+ .card .label { color:#64748b; font-size:12px; }
19
+ .card .val { font-size:24px; font-weight:600; margin-top:4px; }
20
+ .table-wrap { overflow-x:auto; -webkit-overflow-scrolling:touch; border-radius:10px; }
21
+ table { width:100%; min-width:720px; border-collapse:collapse; background:#111a2e; border:1px solid #1e293b; }
22
+ th,td { padding:10px 12px; text-align:left; font-size:13px; border-bottom:1px solid #1e293b; white-space:nowrap; }
23
+ th { color:#94a3b8; background:#0f172a; font-weight:500; }
24
+ tr:last-child td { border-bottom:none; }
25
+ .dot { display:inline-block; width:8px; height:8px; border-radius:50%; margin-right:6px; }
26
+ .dot.on { background:#22c55e; box-shadow:0 0 6px #22c55e; }
27
+ .dot.off { background:#475569; }
28
+ .mono { font-family: ui-monospace, monospace; font-size:12px; }
29
+ .err { color:#f87171; padding:12px; }
30
+ .cfg { font-size:12px; color:#64748b; display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
31
+ input { background:#0f172a; border:1px solid #334155; color:#e2e8f0; padding:6px 10px; border-radius:6px; font-size:13px; }
32
+ button { background:#2563eb; color:#fff; border:none; padding:6px 12px; border-radius:6px; cursor:pointer; font-size:13px; }
33
+ button:hover { background:#1d4ed8; }
34
+ button.ghost { background:#1e293b; }
35
+ button.ghost:hover { background:#334155; }
36
+ .auth-box { max-width:420px; margin:40px auto; background:#111a2e; border:1px solid #1e293b; border-radius:12px; padding:24px; }
37
+ .auth-box h2 { margin:0 0 6px; font-size:18px; }
38
+ .auth-box p { color:#64748b; font-size:13px; margin:0 0 16px; }
39
+ .auth-box label { display:block; font-size:12px; color:#94a3b8; margin:12px 0 4px; }
40
+ .auth-box input { width:100%; }
41
+ .auth-box .row { display:flex; gap:8px; margin-top:16px; }
42
+ .auth-box .row button { flex:1; }
43
+ .modal-backdrop { position:fixed; inset:0; background:rgba(0,0,0,.6); display:flex; align-items:center; justify-content:center; z-index:50; }
44
+ .modal { background:#111a2e; border:1px solid #1e293b; border-radius:12px; padding:24px; width:90%; max-width:420px; }
45
+ .modal h3 { margin:0 0 12px; font-size:16px; }
46
+ .modal label { display:block; font-size:12px; color:#94a3b8; margin:10px 0 4px; }
47
+ .modal input { width:100%; }
48
+ .modal .row { display:flex; gap:8px; margin-top:16px; justify-content:flex-end; }
49
+ @media (max-width: 640px) {
50
+ header { padding:12px 16px; }
51
+ main { padding:16px; }
52
+ .cfg input { width:100%; }
53
+ h1 { font-size:16px; }
54
+ .card .val { font-size:20px; }
55
+ }
56
+ </style>
57
+ </head>
58
+ <body>
59
+ <header id="hdr" style="display:none">
60
+ <div>
61
+ <h1>MobiHop \u4E91\u76D1\u6D4B\u53F0</h1>
62
+ <div class="sub">\u53EA\u8BFB\u76D1\u6D4B \xB7 \u8282\u70B9\u5FC3\u8DF3 \xB7 \u514D\u8D39\u6258\u7BA1</div>
63
+ </div>
64
+ <div class="cfg">
65
+ API: <input id="api" /> <button onclick="saveApi()">\u4FDD\u5B58</button>
66
+ <button class="ghost" onclick="openChangePw()">\u4FEE\u6539\u5BC6\u7801</button>
67
+ <button class="ghost" onclick="logout()">\u9000\u51FA</button>
68
+ </div>
69
+ </header>
70
+ <main>
71
+ <div id="view-setup" class="auth-box" style="display:none">
72
+ <h2>\u672A\u914D\u7F6E\u5BC6\u7801</h2>
73
+ <p>\u76D1\u6D4B\u53F0\u5BC6\u7801\u5C1A\u672A\u521D\u59CB\u5316\u3002\u8BF7\u901A\u8FC7\u90E8\u7F72\u811A\u672C\uFF08deploy-cf.ps1\uFF09\u8BBE\u7F6E\u767B\u5F55\u5BC6\u7801\uFF0C\u6216\u8054\u7CFB\u7BA1\u7406\u5458\u3002</p>
74
+ <p id="setup-err" class="err"></p>
75
+ </div>
76
+ <div id="view-login" class="auth-box" style="display:none">
77
+ <h2>\u767B\u5F55</h2>
78
+ <p>\u8BF7\u8F93\u5165\u76D1\u6D4B\u53F0\u5BC6\u7801\u3002</p>
79
+ <label>\u5BC6\u7801</label>
80
+ <input id="login-pw" type="password" onkeydown="if(event.key==='Enter')doLogin()" />
81
+ <div class="row"><button onclick="doLogin()">\u767B\u5F55</button></div>
82
+ <p id="login-err" class="err"></p>
83
+ </div>
84
+ <div id="view-app" style="display:none">
85
+ <div class="grid">
86
+ <div class="card"><div class="label">\u8BBE\u5907\u603B\u6570</div><div class="val" id="total">\u2014</div></div>
87
+ <div class="card"><div class="label">\u5728\u7EBF</div><div class="val" id="online">\u2014</div></div>
88
+ <div class="card"><div class="label">\u79BB\u7EBF</div><div class="val" id="offline">\u2014</div></div>
89
+ <div class="card"><div class="label">\u6700\u540E\u5237\u65B0</div><div class="val" id="refresh" style="font-size:14px">\u2014</div></div>
90
+ </div>
91
+ <div class="table-wrap">
92
+ <table>
93
+ <thead><tr><th>\u72B6\u6001</th><th>\u8BBE\u5907</th><th>Node ID</th><th>\u865A\u62DF IP</th><th>\u7248\u672C</th><th>\u6700\u540E IP</th><th>\u6700\u540E\u5FC3\u8DF3</th></tr></thead>
94
+ <tbody id="rows"><tr><td colspan="7" style="text-align:center;color:#64748b">\u52A0\u8F7D\u4E2D\u2026</td></tr></tbody>
95
+ </table>
96
+ </div>
97
+ <p id="err" class="err"></p>
98
+ </div>
99
+ </main>
100
+ <div id="modal" style="display:none"></div>
101
+ <script>
102
+ const DEFAULT_API = location.origin;
103
+ const apiInput = document.getElementById('api');
104
+ if (apiInput) apiInput.value = localStorage.getItem('monitor_api') || DEFAULT_API;
105
+ function saveApi(){ if(apiInput) localStorage.setItem('monitor_api', apiInput.value); load(); }
106
+ function apiUrl(){ const el=document.getElementById('api'); const v = el? el.value : (localStorage.getItem('monitor_api')||DEFAULT_API); return (v||DEFAULT_API).replace(/\\/+$/,''); }
107
+ function token(){ return localStorage.getItem('monitor_session') || ''; }
108
+ function setToken(t){ if(t) localStorage.setItem('monitor_session', t); else localStorage.removeItem('monitor_session'); }
109
+ function fmtTime(ms){ if(!ms) return '\u2014'; return new Date(ms).toLocaleString('zh-CN',{hour12:false}); }
110
+ function show(id){ ['view-setup','view-login','view-app'].forEach(v=>{ const e=document.getElementById(v); if(e) e.style.display = v===id?'block':'none'; }); const hdr=document.getElementById('hdr'); if(hdr) hdr.style.display = id==='view-app'?'flex':'none'; }
111
+ async function apiFetch(path, opts){ opts=opts||{}; opts.headers = Object.assign({'Content-Type':'application/json'}, opts.headers||{}); const t=token(); if(t) opts.headers['Authorization']='Bearer '+t; const r=await fetch(apiUrl()+path, opts); return r; }
112
+
113
+ async function init(){
114
+ try {
115
+ const r = await fetch(apiUrl()+'/auth/status');
116
+ const d = await r.json();
117
+ if (d.setupRequired) { show('view-setup'); }
118
+ else if (!token()) { show('view-login'); }
119
+ else { show('view-app'); load(); }
120
+ } catch(e){ document.getElementById('login-err').textContent='\u8FDE\u63A5\u5931\u8D25: '+e.message; show('view-login'); }
121
+ }
122
+
123
+ async function doSetup(){ /* disabled: password must be set via deploy script */ }
124
+
125
+ async function doLogin(){
126
+ const pw=document.getElementById('login-pw').value;
127
+ const err=document.getElementById('login-err');
128
+ err.textContent='';
129
+ try {
130
+ const r=await fetch(apiUrl()+'/auth/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({password:pw})});
131
+ const d=await r.json();
132
+ if(!r.ok){ err.textContent=d.message||'\u767B\u5F55\u5931\u8D25'; return; }
133
+ setToken(d.token); show('view-app'); load();
134
+ } catch(e){ err.textContent='\u5931\u8D25: '+e.message; }
135
+ }
136
+
137
+ async function logout(){
138
+ try { await apiFetch('/auth/logout',{method:'POST'}); } catch(e){}
139
+ setToken(''); show('view-login');
140
+ }
141
+
142
+ function openChangePw(){
143
+ const m=document.getElementById('modal');
144
+ m.style.display='flex';
145
+ m.innerHTML = \`<div class="modal">
146
+ <h3>\u4FEE\u6539\u5BC6\u7801</h3>
147
+ <label>\u65E7\u5BC6\u7801</label><input id="cp-old" type="password" />
148
+ <label>\u65B0\u5BC6\u7801\uFF08\u81F3\u5C11 8 \u4F4D\uFF09</label><input id="cp-new" type="password" />
149
+ <label>\u786E\u8BA4\u65B0\u5BC6\u7801</label><input id="cp-new2" type="password" />
150
+ <p id="cp-err" class="err"></p>
151
+ <div class="row"><button class="ghost" onclick="closeModal()">\u53D6\u6D88</button><button onclick="doChangePw()">\u786E\u8BA4</button></div>
152
+ </div>\`;
153
+ }
154
+ function closeModal(){ const m=document.getElementById('modal'); m.style.display='none'; m.innerHTML=''; }
155
+ async function doChangePw(){
156
+ const oldPw=document.getElementById('cp-old').value;
157
+ const newPw=document.getElementById('cp-new').value;
158
+ const newPw2=document.getElementById('cp-new2').value;
159
+ const err=document.getElementById('cp-err');
160
+ err.textContent='';
161
+ if(newPw.length<8){ err.textContent='\u65B0\u5BC6\u7801\u81F3\u5C11 8 \u4F4D'; return; }
162
+ if(newPw!==newPw2){ err.textContent='\u4E24\u6B21\u65B0\u5BC6\u7801\u4E0D\u4E00\u81F4'; return; }
163
+ try {
164
+ const r=await apiFetch('/auth/change-password',{method:'POST',body:JSON.stringify({oldPassword:oldPw,newPassword:newPw})});
165
+ const d=await r.json();
166
+ if(!r.ok){ err.textContent=d.message||'\u4FEE\u6539\u5931\u8D25'; return; }
167
+ closeModal();
168
+ alert('\u5BC6\u7801\u5DF2\u4FEE\u6539\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55');
169
+ logout();
170
+ } catch(e){ err.textContent='\u5931\u8D25: '+e.message; }
171
+ }
172
+
173
+ async function load(){
174
+ const err = document.getElementById('err');
175
+ err.textContent = '';
176
+ try {
177
+ const r = await apiFetch('/devices');
178
+ if(r.status===401){ setToken(''); show('view-login'); return; }
179
+ if(!r.ok) throw new Error('HTTP ' + r.status);
180
+ const data = await r.json();
181
+ const devs = data.devices || [];
182
+ document.getElementById('total').textContent = devs.length;
183
+ const on = devs.filter(d=>d.online).length;
184
+ document.getElementById('online').textContent = on;
185
+ document.getElementById('offline').textContent = devs.length - on;
186
+ document.getElementById('refresh').textContent = fmtTime(data.generatedAtMs);
187
+ const tbody = document.getElementById('rows');
188
+ if(devs.length===0){ tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#64748b">\u6682\u65E0\u8BBE\u5907\u3002\u8282\u70B9\u9700\u914D\u7F6E monitoring \u4E0A\u62A5\u3002</td></tr>'; return; }
189
+ tbody.innerHTML = devs.map(d => \`<tr>
190
+ <td><span class="dot \${d.online?'on':'off'}"></span>\${d.online?'\u5728\u7EBF':'\u79BB\u7EBF'}</td>
191
+ <td>\${d.alias||'\u2014'}</td>
192
+ <td class="mono">\${d.nodeId}</td>
193
+ <td class="mono">\${d.virtualIpv4||'\u2014'}</td>
194
+ <td>\${d.version||'\u2014'}</td>
195
+ <td class="mono">\${d.lastIp||'\u2014'}</td>
196
+ <td>\${fmtTime(d.lastSeenMs)}</td>
197
+ </tr>\`).join('');
198
+ } catch(e){ err.textContent = '\u52A0\u8F7D\u5931\u8D25: ' + e.message; }
199
+ }
200
+
201
+ init();
202
+ setInterval(()=>{ if(document.getElementById('view-app').style.display!=='none') load(); }, 15000);
203
+ </script>
204
+ </body>
205
+ </html>
206
+ `;
207
+
208
+ // ../edge-relay/cf-worker-relay/src/proto.ts
209
+ var MAGIC = 77;
210
+ var VERSION = 2;
211
+ var LEGACY_VERSION = 1;
212
+ var HEADER_LEN = 32;
213
+ var MAX_FRAME = 1400;
214
+ var MAX_WIRE_FRAME = HEADER_LEN + MAX_FRAME;
215
+ var BROADCAST_HEX = "ffffffffffffffff";
216
+ var OFF = {
217
+ magic: 0,
218
+ version: 1,
219
+ msgType: 2,
220
+ flags: 3,
221
+ ttl: 4,
222
+ /** ADR-0016:v2 中为 `key_meta`(高 4 位 key_slot / 低 4 位 qos_class),v1 必须为 0。 */
223
+ keyMeta: 5,
224
+ payloadLen: 6,
225
+ src: 8,
226
+ dst: 16,
227
+ counter: 24
228
+ };
229
+ var MESSAGE_TYPES = [1, 2, 3, 4, 5, 6, 7];
230
+ var FLAG_RELAYED = 2;
231
+ function nodeIdHex(bytes, offset) {
232
+ let out = "";
233
+ for (let i = 0; i < 8; i += 1) {
234
+ const byte = bytes[offset + i] ?? 0;
235
+ out += byte.toString(16).padStart(2, "0");
236
+ }
237
+ return out;
238
+ }
239
+ function fail(reason) {
240
+ return { ok: false, reason };
241
+ }
242
+ function parseFrame(input) {
243
+ if (input.length > MAX_WIRE_FRAME) {
244
+ return fail("oversize");
245
+ }
246
+ if (input.length < HEADER_LEN) {
247
+ return fail("short");
248
+ }
249
+ if (input[OFF.magic] !== MAGIC) {
250
+ return fail("bad_magic");
251
+ }
252
+ const version = input[OFF.version];
253
+ if (version !== VERSION && version !== LEGACY_VERSION) {
254
+ return fail("bad_version");
255
+ }
256
+ const isLegacy = version === LEGACY_VERSION;
257
+ const msgType = input[OFF.msgType] ?? 0;
258
+ if (!MESSAGE_TYPES.includes(msgType)) {
259
+ return fail("unknown_type");
260
+ }
261
+ const keyMeta = input[OFF.keyMeta] ?? 1;
262
+ if (isLegacy && keyMeta !== 0) {
263
+ return fail("reserved_nonzero");
264
+ }
265
+ const ttl = input[OFF.ttl] ?? 0;
266
+ if (ttl > 64) {
267
+ return fail("ttl_out_of_range");
268
+ }
269
+ const payloadLen = (input[OFF.payloadLen] ?? 0) << 8 | (input[OFF.payloadLen + 1] ?? 0);
270
+ if (HEADER_LEN + payloadLen !== input.length) {
271
+ return fail("length_mismatch");
272
+ }
273
+ const src = nodeIdHex(input, OFF.src);
274
+ const dst = nodeIdHex(input, OFF.dst);
275
+ return {
276
+ ok: true,
277
+ frame: {
278
+ frame: input,
279
+ msgType,
280
+ flags: input[OFF.flags] ?? 0,
281
+ ttl,
282
+ keyMeta,
283
+ keySlot: keyMeta >> 4,
284
+ qosClass: keyMeta & 15,
285
+ payloadLen,
286
+ src,
287
+ dst,
288
+ broadcast: dst === BROADCAST_HEX
289
+ }
290
+ };
291
+ }
292
+ function decideForward(parsed, senderPeerId, peerIds) {
293
+ if (parsed.ttl <= 1) {
294
+ return { kind: "drop", reason: "ttl_exhausted" };
295
+ }
296
+ if (parsed.broadcast) {
297
+ const targets = peerIds.filter((peer) => peer !== senderPeerId).slice().sort();
298
+ if (targets.length === 0) {
299
+ return { kind: "drop", reason: "no_members" };
300
+ }
301
+ return { kind: "broadcast", targets };
302
+ }
303
+ if (parsed.dst === senderPeerId) {
304
+ return { kind: "drop", reason: "self_unicast" };
305
+ }
306
+ if (!peerIds.includes(parsed.dst)) {
307
+ return { kind: "drop", reason: "unknown_target" };
308
+ }
309
+ return { kind: "unicast", target: parsed.dst };
310
+ }
311
+ function prepareForwardFrame(parsed) {
312
+ const out = parsed.frame.slice();
313
+ out[OFF.ttl] = parsed.ttl - 1;
314
+ out[OFF.flags] = parsed.flags | FLAG_RELAYED;
315
+ return out;
316
+ }
317
+ var SlidingWindow = class {
318
+ entries = [];
319
+ limits;
320
+ constructor(limits) {
321
+ if (limits.windowMs <= 0 || limits.maxBytes <= 0 || limits.maxPackets <= 0) {
322
+ throw new Error("invalid rate limits");
323
+ }
324
+ this.limits = limits;
325
+ }
326
+ prune(nowMs) {
327
+ const cutoff = nowMs - this.limits.windowMs;
328
+ while (this.entries.length > 0 && (this.entries[0]?.ts ?? nowMs) <= cutoff) {
329
+ this.entries.shift();
330
+ }
331
+ }
332
+ allow(nowMs, bytes) {
333
+ this.prune(nowMs);
334
+ let usedBytes = 0;
335
+ for (const entry of this.entries) {
336
+ usedBytes += entry.bytes;
337
+ }
338
+ const oldest = this.entries[0]?.ts;
339
+ const retryAfterMs = oldest === void 0 ? this.limits.windowMs : Math.max(0, oldest + this.limits.windowMs - nowMs);
340
+ if (usedBytes + bytes > this.limits.maxBytes) {
341
+ return { allowed: false, reason: "bytes", retryAfterMs };
342
+ }
343
+ if (this.entries.length + 1 > this.limits.maxPackets) {
344
+ return { allowed: false, reason: "packets", retryAfterMs };
345
+ }
346
+ this.entries.push({ ts: nowMs, bytes });
347
+ return { allowed: true };
348
+ }
349
+ /** 窗口内当前用量(观测 / 单测)。 */
350
+ usage(nowMs) {
351
+ this.prune(nowMs);
352
+ let bytes = 0;
353
+ for (const entry of this.entries) {
354
+ bytes += entry.bytes;
355
+ }
356
+ return { bytes, packets: this.entries.length };
357
+ }
358
+ };
359
+ function validatePeerId(raw) {
360
+ return typeof raw === "string" && /^[0-9a-f]{16}$/.test(raw);
361
+ }
362
+ function validateNetworkHash(raw) {
363
+ return typeof raw === "string" && /^[0-9a-f]{8,64}$/.test(raw);
364
+ }
365
+ function networkHashFromPath(pathname) {
366
+ const match = /^\/mesh\/([^/]+)$/.exec(pathname);
367
+ if (!match) {
368
+ return null;
369
+ }
370
+ const hash = match[1] ?? null;
371
+ return validateNetworkHash(hash) ? hash : null;
372
+ }
373
+ function roomLogPrefix(networkHash) {
374
+ return networkHash.slice(0, 4);
375
+ }
376
+
377
+ // ../edge-relay/cf-worker-relay/src/index.ts
378
+ var DEFAULT_LIMITS = {
379
+ windowMs: 1e3,
380
+ maxBytes: 1024 * 1024,
381
+ maxPackets: 2e3
382
+ };
383
+ var DEFAULT_MAX_PEERS = 512;
384
+ var MAX_PEERS_HARD_CAP = 4096;
385
+ function envInt(raw, fallback, min, max) {
386
+ const value = Number(raw);
387
+ if (!Number.isFinite(value) || value < min) {
388
+ return fallback;
389
+ }
390
+ return Math.min(Math.floor(value), max);
391
+ }
392
+ function limitsFromEnv(env) {
393
+ return {
394
+ windowMs: envInt(env.WINDOW_MS, DEFAULT_LIMITS.windowMs, 1, 6e4),
395
+ maxBytes: envInt(env.MAX_BYTES_PER_WINDOW, DEFAULT_LIMITS.maxBytes, 32, 1 << 30),
396
+ maxPackets: envInt(env.MAX_PACKETS_PER_WINDOW, DEFAULT_LIMITS.maxPackets, 1, 1e6)
397
+ };
398
+ }
399
+ function isWebSocketUpgrade(request) {
400
+ return request.headers.get("Upgrade")?.toLowerCase() === "websocket";
401
+ }
402
+ function validatedTarget(request) {
403
+ const url = new URL(request.url);
404
+ const hash = networkHashFromPath(url.pathname);
405
+ const peerId = url.searchParams.get("peer_id");
406
+ if (!hash || typeof peerId !== "string" || !validatePeerId(peerId)) {
407
+ return null;
408
+ }
409
+ return { hash, peerId };
410
+ }
411
+ var CORS = {
412
+ "Access-Control-Allow-Origin": "*",
413
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
414
+ "Access-Control-Allow-Headers": "Content-Type, X-Monitor-Token"
415
+ };
416
+ function json(data, status = 200) {
417
+ return new Response(JSON.stringify(data), {
418
+ status,
419
+ headers: { "Content-Type": "application/json", ...CORS }
420
+ });
421
+ }
422
+ async function handleHeartbeat(request, env) {
423
+ const token = request.headers.get("X-Monitor-Token") || "";
424
+ if (!env.MONITOR_TOKEN || token !== env.MONITOR_TOKEN) {
425
+ return json({ code: "unauthorized", message: "invalid monitor token" }, 401);
426
+ }
427
+ let body;
428
+ try {
429
+ body = await request.json();
430
+ } catch {
431
+ return json({ code: "bad_request", message: "invalid json" }, 400);
432
+ }
433
+ const nodeId = String(body?.node_id ?? "").trim();
434
+ if (!/^[0-9a-f]{16}$/i.test(nodeId)) {
435
+ return json({ code: "bad_request", message: "node_id must be 16 hex" }, 400);
436
+ }
437
+ const now = Date.now();
438
+ const alias = String(body?.alias ?? "").slice(0, 64);
439
+ const vip = body?.virtual_ipv4 ? String(body.virtual_ipv4).slice(0, 48) : null;
440
+ const version = body?.version ? String(body.version).slice(0, 32) : null;
441
+ const online = body?.online ? 1 : 0;
442
+ const ip = request.headers.get("CF-Connecting-IP") || null;
443
+ await env.DB.prepare(
444
+ `INSERT INTO devices (node_id, alias, virtual_ipv4, version, last_ip, online, last_seen_ms, updated_at_ms)
445
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
446
+ ON CONFLICT(node_id) DO UPDATE SET
447
+ alias=excluded.alias, virtual_ipv4=excluded.virtual_ipv4, version=excluded.version,
448
+ last_ip=excluded.last_ip, online=excluded.online,
449
+ last_seen_ms=excluded.last_seen_ms, updated_at_ms=excluded.updated_at_ms`
450
+ ).bind(nodeId, alias || null, vip, version, ip, online, now, now).run();
451
+ return json({ ok: true, node_id: nodeId, ts: now });
452
+ }
453
+ async function handleDevices(env) {
454
+ const { results } = await env.DB.prepare(
455
+ `SELECT node_id, alias, virtual_ipv4, version, last_ip, online, last_seen_ms
456
+ FROM devices ORDER BY last_seen_ms DESC`
457
+ ).all();
458
+ const now = Date.now();
459
+ const STALE_MS = 9e4;
460
+ const devices = (results || []).map((r) => ({
461
+ nodeId: r.node_id,
462
+ alias: r.alias,
463
+ virtualIpv4: r.virtual_ipv4,
464
+ version: r.version,
465
+ lastIp: r.last_ip,
466
+ online: r.online === 1 && now - (r.last_seen_ms || 0) < STALE_MS,
467
+ lastSeenMs: r.last_seen_ms
468
+ }));
469
+ return json({ devices, generatedAtMs: now });
470
+ }
471
+ var SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
472
+ function b64(bytes) {
473
+ let s = "";
474
+ for (const b of bytes) s += String.fromCharCode(b);
475
+ return btoa(s);
476
+ }
477
+ function unb64(s) {
478
+ const bin = atob(s);
479
+ const out = new Uint8Array(bin.length);
480
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
481
+ return out;
482
+ }
483
+ async function deriveHash(password, salt) {
484
+ const km = await crypto.subtle.importKey("raw", new TextEncoder().encode(password), "PBKDF2", false, [
485
+ "deriveBits"
486
+ ]);
487
+ const bits = await crypto.subtle.deriveBits(
488
+ { name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" },
489
+ km,
490
+ 256
491
+ );
492
+ return b64(new Uint8Array(bits));
493
+ }
494
+ function timingSafeEqual(a, b) {
495
+ if (a.length !== b.length) return false;
496
+ let diff = 0;
497
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
498
+ return diff === 0;
499
+ }
500
+ async function hasPassword(env) {
501
+ const row = await env.DB.prepare("SELECT password_hash FROM auth WHERE id=1").first();
502
+ return !!row?.password_hash;
503
+ }
504
+ async function getSession(request, env) {
505
+ const auth = request.headers.get("Authorization") || "";
506
+ const m = auth.match(/^Bearer\s+(.+)$/i);
507
+ const token = m ? m[1].trim() : request.headers.get("X-Monitor-Session") || "";
508
+ if (!token) return null;
509
+ const row = await env.DB.prepare(
510
+ "SELECT token, expires_at_ms FROM sessions WHERE token=?1"
511
+ ).bind(token).first();
512
+ if (!row) return null;
513
+ if (Date.now() > row.expires_at_ms) {
514
+ await env.DB.prepare("DELETE FROM sessions WHERE token=?1").bind(token).run();
515
+ return null;
516
+ }
517
+ return { token: row.token, expiresAtMs: row.expires_at_ms };
518
+ }
519
+ async function handleAuthStatus(env) {
520
+ return json({ setupRequired: !await hasPassword(env) });
521
+ }
522
+ async function handleAuthSetup(request, env) {
523
+ if (await hasPassword(env)) {
524
+ return json({ code: "conflict", message: "password already set; use change-password" }, 409);
525
+ }
526
+ let body;
527
+ try {
528
+ body = await request.json();
529
+ } catch {
530
+ return json({ code: "bad_request", message: "invalid json" }, 400);
531
+ }
532
+ const password = String(body?.password ?? "");
533
+ if (password.length < 8) {
534
+ return json({ code: "bad_request", message: "password must be at least 8 chars" }, 400);
535
+ }
536
+ const salt = crypto.getRandomValues(new Uint8Array(16));
537
+ const hash = await deriveHash(password, salt);
538
+ const now = Date.now();
539
+ await env.DB.prepare(
540
+ "INSERT INTO auth (id, password_hash, salt, updated_at_ms) VALUES (1, ?1, ?2, ?3) ON CONFLICT(id) DO NOTHING"
541
+ ).bind(hash, b64(salt), now).run();
542
+ const check = await env.DB.prepare("SELECT password_hash FROM auth WHERE id=1").first();
543
+ if (!check?.password_hash) {
544
+ return json({ code: "conflict", message: "password already set" }, 409);
545
+ }
546
+ return json({ ok: true });
547
+ }
548
+ async function handleAuthLogin(request, env) {
549
+ if (!await hasPassword(env)) {
550
+ return json({ code: "setup_required", message: "password not set" }, 412);
551
+ }
552
+ let body;
553
+ try {
554
+ body = await request.json();
555
+ } catch {
556
+ return json({ code: "bad_request", message: "invalid json" }, 400);
557
+ }
558
+ const password = String(body?.password ?? "");
559
+ const row = await env.DB.prepare("SELECT password_hash, salt FROM auth WHERE id=1").first();
560
+ if (!row) return json({ code: "internal", message: "auth row missing" }, 500);
561
+ const salt = unb64(row.salt);
562
+ const hash = await deriveHash(password, salt);
563
+ if (!timingSafeEqual(hash, row.password_hash)) {
564
+ return json({ code: "unauthorized", message: "invalid password" }, 401);
565
+ }
566
+ const token = crypto.randomUUID() + crypto.randomUUID().replace(/-/g, "");
567
+ const expires = Date.now() + SESSION_TTL_MS;
568
+ await env.DB.prepare("INSERT INTO sessions (token, created_at_ms, expires_at_ms) VALUES (?1, ?2, ?3)").bind(
569
+ token,
570
+ Date.now(),
571
+ expires
572
+ ).run();
573
+ return json({ token, expiresAtMs: expires });
574
+ }
575
+ async function handleAuthChangePassword(request, env) {
576
+ const sess = await getSession(request, env);
577
+ if (!sess) return json({ code: "unauthorized", message: "session required" }, 401);
578
+ let body;
579
+ try {
580
+ body = await request.json();
581
+ } catch {
582
+ return json({ code: "bad_request", message: "invalid json" }, 400);
583
+ }
584
+ const oldPassword = String(body?.oldPassword ?? "");
585
+ const newPassword = String(body?.newPassword ?? "");
586
+ if (newPassword.length < 8) {
587
+ return json({ code: "bad_request", message: "new password must be at least 8 chars" }, 400);
588
+ }
589
+ const row = await env.DB.prepare("SELECT password_hash, salt FROM auth WHERE id=1").first();
590
+ if (!row) return json({ code: "internal", message: "auth row missing" }, 500);
591
+ const oldHash = await deriveHash(oldPassword, unb64(row.salt));
592
+ if (!timingSafeEqual(oldHash, row.password_hash)) {
593
+ return json({ code: "unauthorized", message: "invalid old password" }, 401);
594
+ }
595
+ const newSalt = crypto.getRandomValues(new Uint8Array(16));
596
+ const newHash = await deriveHash(newPassword, newSalt);
597
+ const now = Date.now();
598
+ await env.DB.prepare(
599
+ "UPDATE auth SET password_hash=?1, salt=?2, updated_at_ms=?3 WHERE id=1"
600
+ ).bind(newHash, b64(newSalt), now).run();
601
+ await env.DB.prepare("DELETE FROM sessions WHERE token<>?1").bind(sess.token).run();
602
+ return json({ ok: true });
603
+ }
604
+ async function handleAuthLogout(request, env) {
605
+ const sess = await getSession(request, env);
606
+ if (sess) {
607
+ await env.DB.prepare("DELETE FROM sessions WHERE token=?1").bind(sess.token).run();
608
+ }
609
+ return json({ ok: true });
610
+ }
611
+ var index_default = {
612
+ async fetch(request, env) {
613
+ const url = new URL(request.url);
614
+ const path = url.pathname;
615
+ if (request.method === "OPTIONS") {
616
+ return new Response(null, { status: 204, headers: CORS });
617
+ }
618
+ if (path === "/health" && request.method === "GET") {
619
+ return json({ ok: true });
620
+ }
621
+ if (path === "/" && request.method === "GET" && !isWebSocketUpgrade(request)) {
622
+ return new Response(dashboard_default, {
623
+ headers: {
624
+ "Content-Type": "text/html; charset=utf-8",
625
+ "Cache-Control": "no-store"
626
+ }
627
+ });
628
+ }
629
+ if (path === "/auth/status" && request.method === "GET") {
630
+ try {
631
+ return await handleAuthStatus(env);
632
+ } catch (e) {
633
+ return json({ code: "internal", message: String(e?.message ?? e) }, 500);
634
+ }
635
+ }
636
+ if (path === "/auth/setup" && request.method === "POST") {
637
+ try {
638
+ return await handleAuthSetup(request, env);
639
+ } catch (e) {
640
+ return json({ code: "internal", message: String(e?.message ?? e) }, 500);
641
+ }
642
+ }
643
+ if (path === "/auth/login" && request.method === "POST") {
644
+ try {
645
+ return await handleAuthLogin(request, env);
646
+ } catch (e) {
647
+ return json({ code: "internal", message: String(e?.message ?? e) }, 500);
648
+ }
649
+ }
650
+ if (path === "/auth/change-password" && request.method === "POST") {
651
+ try {
652
+ return await handleAuthChangePassword(request, env);
653
+ } catch (e) {
654
+ return json({ code: "internal", message: String(e?.message ?? e) }, 500);
655
+ }
656
+ }
657
+ if (path === "/auth/logout" && request.method === "POST") {
658
+ try {
659
+ return await handleAuthLogout(request, env);
660
+ } catch (e) {
661
+ return json({ code: "internal", message: String(e?.message ?? e) }, 500);
662
+ }
663
+ }
664
+ if (path === "/heartbeat" && request.method === "POST") {
665
+ try {
666
+ return await handleHeartbeat(request, env);
667
+ } catch (e) {
668
+ return json({ code: "internal", message: String(e?.message ?? e) }, 500);
669
+ }
670
+ }
671
+ if (path === "/devices" && request.method === "GET") {
672
+ try {
673
+ const sess = await getSession(request, env);
674
+ if (!sess) return json({ code: "unauthorized", message: "session required" }, 401);
675
+ return await handleDevices(env);
676
+ } catch (e) {
677
+ return json({ code: "internal", message: String(e?.message ?? e) }, 500);
678
+ }
679
+ }
680
+ if (request.method !== "GET" || !isWebSocketUpgrade(request)) {
681
+ return new Response("MobiHop edge relay: WebSocket upgrade required", { status: 426 });
682
+ }
683
+ const target = validatedTarget(request);
684
+ if (!target || !validateNetworkHash(target.hash)) {
685
+ return new Response("MobiHop edge relay: invalid /mesh/<network_hash> or peer_id", {
686
+ status: 400
687
+ });
688
+ }
689
+ const stub = env.MESH_ROOM.get(env.MESH_ROOM.idFromName(target.hash));
690
+ return stub.fetch(request);
691
+ }
692
+ };
693
+ var MeshRoom = class {
694
+ state;
695
+ limits;
696
+ maxPeers;
697
+ /** peer_id → 滑动窗口(Hibernation 后重置)。 */
698
+ windows = /* @__PURE__ */ new Map();
699
+ roomHash = "";
700
+ // 计数(仅内存;Hibernation 后重置)。
701
+ forwarded = 0;
702
+ dropped = 0;
703
+ rateLimited = 0;
704
+ invalid = 0;
705
+ oversize = 0;
706
+ kicked = 0;
707
+ lastLogAt = 0;
708
+ lastDropLogAt = 0;
709
+ constructor(state, env) {
710
+ this.state = state;
711
+ this.limits = limitsFromEnv(env);
712
+ this.maxPeers = envInt(env.MAX_PEERS_PER_ROOM, DEFAULT_MAX_PEERS, 1, MAX_PEERS_HARD_CAP);
713
+ }
714
+ async fetch(request) {
715
+ if (!isWebSocketUpgrade(request)) {
716
+ return new Response("upgrade required", { status: 426 });
717
+ }
718
+ const target = validatedTarget(request);
719
+ if (!target) {
720
+ return new Response("invalid room / peer_id", { status: 400 });
721
+ }
722
+ if (this.roomHash === "") {
723
+ this.roomHash = target.hash;
724
+ } else if (this.roomHash !== target.hash) {
725
+ return new Response("room mismatch", { status: 400 });
726
+ }
727
+ const peerId = target.peerId;
728
+ const existing = this.state.getWebSockets(peerId);
729
+ for (const old of existing) {
730
+ try {
731
+ old.close(4001, "replaced by newer connection");
732
+ } catch {
733
+ }
734
+ this.kicked += 1;
735
+ }
736
+ const others = this.state.getWebSockets().length - existing.length;
737
+ if (others >= this.maxPeers) {
738
+ this.log("room_full", peerId, 0);
739
+ return new Response("room full", { status: 503 });
740
+ }
741
+ const pair = new WebSocketPair();
742
+ const client = pair[0];
743
+ const server = pair[1];
744
+ this.state.acceptWebSocket(server, [peerId]);
745
+ this.windows.set(peerId, new SlidingWindow(this.limits));
746
+ this.log("join", peerId, 0);
747
+ return new Response(null, { status: 101, webSocket: client });
748
+ }
749
+ /** 一条 WS 二进制消息 = 一个完整 MobiHop 帧(32B 头 + 载荷)。 */
750
+ webSocketMessage(ws, message) {
751
+ const sender = this.senderPeerId(ws);
752
+ if (!sender) {
753
+ this.invalid += 1;
754
+ return;
755
+ }
756
+ if (typeof message === "string") {
757
+ this.invalid += 1;
758
+ this.log("drop_invalid", sender, message.length);
759
+ return;
760
+ }
761
+ const bytes = normalizeBinary(message);
762
+ if (bytes === null) {
763
+ this.invalid += 1;
764
+ return;
765
+ }
766
+ const byteLen = bytes.byteLength;
767
+ const window = this.windows.get(sender) ?? new SlidingWindow(this.limits);
768
+ this.windows.set(sender, window);
769
+ const rate = window.allow(Date.now(), byteLen);
770
+ if (!rate.allowed) {
771
+ this.rateLimited += 1;
772
+ this.log(`rate_limited_${rate.reason}`, sender, byteLen);
773
+ return;
774
+ }
775
+ const parsed = parseFrame(bytes);
776
+ if (!parsed.ok) {
777
+ if (parsed.reason === "oversize") {
778
+ this.oversize += 1;
779
+ } else {
780
+ this.invalid += 1;
781
+ }
782
+ this.log(`drop_${parsed.reason}`, sender, byteLen);
783
+ return;
784
+ }
785
+ const decision = decideForward(parsed.frame, sender, this.peerIds());
786
+ switch (decision.kind) {
787
+ case "drop":
788
+ this.dropped += 1;
789
+ this.log(`drop_${decision.reason}`, sender, byteLen);
790
+ return;
791
+ case "unicast": {
792
+ const out = prepareForwardFrame(parsed.frame);
793
+ if (this.deliver(decision.target, out)) {
794
+ this.forwarded += 1;
795
+ this.maybeLogStats(sender, byteLen);
796
+ } else {
797
+ this.dropped += 1;
798
+ this.log("drop_target_gone", sender, byteLen);
799
+ }
800
+ return;
801
+ }
802
+ case "broadcast": {
803
+ const out = prepareForwardFrame(parsed.frame);
804
+ for (const target of decision.targets) {
805
+ if (this.deliver(target, out)) {
806
+ this.forwarded += 1;
807
+ }
808
+ }
809
+ this.maybeLogStats(sender, byteLen);
810
+ return;
811
+ }
812
+ }
813
+ }
814
+ webSocketClose(ws, code, reason, _wasClean) {
815
+ const peer = this.senderPeerId(ws);
816
+ if (peer) {
817
+ this.windows.delete(peer);
818
+ this.log("close", peer, reason.length);
819
+ try {
820
+ ws.close(code === 4001 ? 4001 : 1e3, code === 4001 ? "replaced" : "closed");
821
+ } catch {
822
+ }
823
+ }
824
+ }
825
+ webSocketError(_ws, error) {
826
+ this.invalid += 1;
827
+ this.log("error", "unknown", 0);
828
+ void error;
829
+ }
830
+ senderPeerId(ws) {
831
+ const tags = this.state.getTags(ws);
832
+ const tag = tags[0];
833
+ return tag && validatePeerId(tag) ? tag : null;
834
+ }
835
+ peerIds() {
836
+ return this.state.getWebSockets().flatMap((ws) => this.state.getTags(ws));
837
+ }
838
+ deliver(target, frame) {
839
+ const sockets = this.state.getWebSockets(target);
840
+ let sent = false;
841
+ for (const ws of sockets) {
842
+ try {
843
+ ws.send(frame);
844
+ sent = true;
845
+ } catch {
846
+ }
847
+ }
848
+ return sent;
849
+ }
850
+ /** 日志只允许 room 前 4 字符 + peer_id + 包长(绝不打印载荷 / 完整 hash)。 */
851
+ log(event, peerId, byteLen) {
852
+ const now = Date.now();
853
+ if (event.startsWith("drop_") || event.startsWith("rate_limited")) {
854
+ if (now - this.lastDropLogAt < 1e3) {
855
+ return;
856
+ }
857
+ this.lastDropLogAt = now;
858
+ }
859
+ console.log(
860
+ `[mh-edge] evt=${event} room=${roomLogPrefix(this.roomHash)} peer=${peerId} bytes=${byteLen}`
861
+ );
862
+ }
863
+ /** 每 500 个转发包输出一次计数(避免逐包日志造成费用与噪音)。 */
864
+ maybeLogStats(peerId, byteLen) {
865
+ const now = Date.now();
866
+ if (this.forwarded % 500 !== 0 || now - this.lastLogAt < 1e3) {
867
+ return;
868
+ }
869
+ this.lastLogAt = now;
870
+ console.log(
871
+ `[mh-edge] stats room=${roomLogPrefix(this.roomHash)} peer=${peerId} bytes=${byteLen} forwarded=${this.forwarded} dropped=${this.dropped} rate_limited=${this.rateLimited} invalid=${this.invalid} oversize=${this.oversize} kicked=${this.kicked}`
872
+ );
873
+ }
874
+ };
875
+ function normalizeBinary(message) {
876
+ if (message instanceof ArrayBuffer) {
877
+ return new Uint8Array(message);
878
+ }
879
+ if (ArrayBuffer.isView(message)) {
880
+ const view = message;
881
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
882
+ }
883
+ return null;
884
+ }
885
+ var WIRE_FRAME_LIMIT = MAX_WIRE_FRAME;
886
+ export {
887
+ MeshRoom,
888
+ WIRE_FRAME_LIMIT,
889
+ index_default as default
890
+ };