phone-lens 0.3.5

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/lib/index.js ADDED
@@ -0,0 +1,1494 @@
1
+ import { join } from "node:path";
2
+ import { Service } from "@deepseek-ai/cordis";
3
+ import z from "@deepseek-ai/schemastery";
4
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
5
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
6
+ import { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
7
+ import { createServer } from "node:http";
8
+ import { readFile, readdir, stat, unlink } from "node:fs/promises";
9
+ import { WebSocketServer } from "ws";
10
+ import QRCode from "qrcode";
11
+ import * as os from "node:os";
12
+ import { homedir } from "node:os";
13
+ import { env } from "node:process";
14
+
15
+ //#region src/config.ts
16
+ /** Coerce an unknown config object (cordis patch row / CLI overrides) into LensConfig. */
17
+ function normalizeConfig(raw) {
18
+ const r = raw ?? {};
19
+ const server = r.server ?? {};
20
+ const limits = r.limits ?? {};
21
+ const pairing = r.pairing ?? {};
22
+ const preview = r.preview ?? {};
23
+ const inject = r.inject ?? {};
24
+ const target = r.target ?? {};
25
+ const app = r.app ?? {};
26
+ const GITEE_APK = "https://gitee.com/qianfengbingtang/phone-lens/releases/download/v0.2.0/app-release.apk";
27
+ const GITHUB_APK = "https://github.com/yxqfg/phone-lens/releases/latest/download/app-release.apk";
28
+ const giteeUrl = typeof app.giteeUrl === "string" && app.giteeUrl ? app.giteeUrl : GITEE_APK;
29
+ const allowed = Array.isArray(limits.allowedTypes) ? limits.allowedTypes.filter((t) => typeof t === "string") : void 0;
30
+ const mode = inject.mode === "steer" ? "steer" : "followup";
31
+ return {
32
+ server: {
33
+ host: typeof server.host === "string" && server.host ? server.host : "0.0.0.0",
34
+ port: Number.isInteger(server.port) && server.port > 0 && server.port < 65536 ? server.port : 8791
35
+ },
36
+ limits: {
37
+ maxUploadBytes: positiveInt(limits.maxUploadBytes, 10 * 1024 * 1024),
38
+ allowedTypes: allowed && allowed.length > 0 ? allowed : ["image/jpeg", "image/png"],
39
+ uploadsPerMinute: positiveInt(limits.uploadsPerMinute, 10),
40
+ previewFrameMaxBytes: positiveInt(limits.previewFrameMaxBytes, 512 * 1024),
41
+ maxStoredUploads: positiveInt(limits.maxStoredUploads, 200)
42
+ },
43
+ pairing: { codeTtlMs: positiveInt(pairing.codeTtlMs, 15 * 60 * 1e3) },
44
+ preview: {
45
+ maxWidth: positiveInt(preview.maxWidth, 854),
46
+ maxHeight: positiveInt(preview.maxHeight, 480),
47
+ fps: clampInt(preview.fps, 1, 30, 10),
48
+ jpegQuality: clampInt(preview.jpegQuality, 20, 95, 70)
49
+ },
50
+ inject: {
51
+ mode,
52
+ notePrefix: typeof inject.notePrefix === "string" ? inject.notePrefix : "[手机拍照]"
53
+ },
54
+ target: {
55
+ mode: target.mode === "pinned" ? "pinned" : "latest",
56
+ pinnedSessionId: typeof target.pinnedSessionId === "string" && target.pinnedSessionId ? target.pinnedSessionId : null
57
+ },
58
+ app: {
59
+ giteeUrl,
60
+ githubUrl: typeof app.githubUrl === "string" && app.githubUrl ? app.githubUrl : GITHUB_APK,
61
+ downloadUrl: typeof app.downloadUrl === "string" && app.downloadUrl ? app.downloadUrl : giteeUrl
62
+ }
63
+ };
64
+ }
65
+ function positiveInt(value, fallback) {
66
+ return Number.isInteger(value) && value > 0 ? value : fallback;
67
+ }
68
+ function clampInt(value, min, max, fallback) {
69
+ if (!Number.isInteger(value)) return fallback;
70
+ const n = value;
71
+ return Math.min(max, Math.max(min, n));
72
+ }
73
+
74
+ //#endregion
75
+ //#region src/inject/host-sink.ts
76
+ /**
77
+
78
+ * Phase 2 delivery seam: turns a stored image into a durable dsh user message
79
+
80
+ * attached to the current/last-active session, so the model sees it on the
81
+
82
+ * next turn.
83
+
84
+ *
85
+
86
+ * The active session is tracked from live agent events (inbox inserts and
87
+
88
+ * `running` status flips). With no live session the image stays stored but
89
+
90
+ * no delivery occurs — a real state, not an error.
91
+
92
+ */
93
+ var HostDeliverySink = class {
94
+ lastActiveId = null;
95
+ agents = new Map();
96
+ constructor(config, log) {
97
+ this.config = config;
98
+ this.log = log;
99
+ }
100
+ /** Track an agent that appeared / got input. Call from ctx event handlers. */
101
+ track(agent) {
102
+ const id = agent.id ?? String(agent.session.id);
103
+ this.agents.set(id, agent);
104
+ this.lastActiveId = id;
105
+ this.log("info", `tracking agent ${id} (active target)`);
106
+ }
107
+ /** Forget a disposed agent. */
108
+ untrack(agent) {
109
+ const id = agent.id ?? String(agent.session.id);
110
+ this.agents.delete(id);
111
+ if (this.lastActiveId === id) this.lastActiveId = this.agents.keys().next().value ?? null;
112
+ }
113
+ /** The session an upload targets right now, if any. */
114
+ resolve() {
115
+ if (this.config.target.mode === "pinned" && this.config.target.pinnedSessionId) {
116
+ const pinned = [...this.agents.values()].find((a) => String(a.session.id) === this.config.target.pinnedSessionId);
117
+ if (pinned) return pinned;
118
+ this.log("warn", `pinned session ${this.config.target.pinnedSessionId} has no live agent`);
119
+ }
120
+ return (this.lastActiveId ? this.agents.get(this.lastActiveId) : null) ?? null;
121
+ }
122
+ async deliver(admitted, note, mode) {
123
+ const agent = this.resolve();
124
+ if (!agent) return {
125
+ ok: false,
126
+ sessionId: null,
127
+ mode: "none",
128
+ reason: "no active session"
129
+ };
130
+ try {
131
+ const content = [{
132
+ type: "text",
133
+ text: note ?? this.config.inject.notePrefix
134
+ }, {
135
+ type: "image",
136
+ attachment: admitted.ref
137
+ }];
138
+ const message = createUserMessage({
139
+ content,
140
+ source: {
141
+ kind: "plugin",
142
+ plugin: "phone-lens"
143
+ }
144
+ });
145
+ this.log("info", `delivering image (${admitted.ref.attachmentId}) to session ${agent.session.id} via ${mode}`);
146
+ if (mode === "steer") agent.steer(message);
147
+ else agent.followup(message);
148
+ return {
149
+ ok: true,
150
+ sessionId: String(agent.session.id),
151
+ mode
152
+ };
153
+ } catch (e) {
154
+ this.log("warn", `delivery failed: ${String(e)}`);
155
+ return {
156
+ ok: false,
157
+ sessionId: null,
158
+ mode: "none",
159
+ reason: String(e)
160
+ };
161
+ }
162
+ }
163
+ };
164
+
165
+ //#endregion
166
+ //#region src/inject/target.ts
167
+ /**
168
+
169
+ * Resolves the session an upload should be injected into.
170
+
171
+ *
172
+
173
+ * Phase 1: pure config view, no live agents (the agent-event wiring that
174
+
175
+ * feeds `latest` lands in Phase 2 — see architecture.md §2 D4).
176
+
177
+ */
178
+ var TargetTracker = class {
179
+ constructor(config) {
180
+ this.config = config;
181
+ }
182
+ /** The session an incoming image would target right now, if any. */
183
+ resolve() {
184
+ if (this.config.target.mode === "pinned" && this.config.target.pinnedSessionId) return {
185
+ sessionId: this.config.target.pinnedSessionId,
186
+ title: "(pinned)",
187
+ active: true,
188
+ running: false
189
+ };
190
+ return null;
191
+ }
192
+ /** Choosable targets for GET /targets. */
193
+ list() {
194
+ const pinned = this.resolve();
195
+ return pinned ? [pinned] : [];
196
+ }
197
+ mode() {
198
+ return this.config.target.mode;
199
+ }
200
+ };
201
+
202
+ //#endregion
203
+ //#region src/store/pairing.ts
204
+ /** One-shot pairing-code lifecycle: create / verify / burn, with TTL. */
205
+ var PairingStore = class {
206
+ code = null;
207
+ createdAt = 0;
208
+ expiresAt = 0;
209
+ used = false;
210
+ constructor(ttlMs) {
211
+ this.ttlMs = ttlMs;
212
+ }
213
+ /** Current live code, or a freshly minted one. */
214
+ current() {
215
+ const now = Date.now();
216
+ if (this.code === null || this.used || now >= this.expiresAt) this.mint(now);
217
+ return {
218
+ code: this.code,
219
+ expiresAt: this.expiresAt
220
+ };
221
+ }
222
+ /** Force a fresh code (manual refresh). Invalidates the previous one. */
223
+ refresh() {
224
+ this.mint(Date.now());
225
+ return {
226
+ code: this.code,
227
+ expiresAt: this.expiresAt
228
+ };
229
+ }
230
+ /**
231
+
232
+ * Verify a submitted code and burn it on success.
233
+
234
+ * Constant-time compare; expired codes read as invalid.
235
+
236
+ */
237
+ verify(submitted) {
238
+ if (this.code === null || this.used) return {
239
+ ok: false,
240
+ reason: "invalid"
241
+ };
242
+ const now = Date.now();
243
+ if (now >= this.expiresAt) return {
244
+ ok: false,
245
+ reason: "expired"
246
+ };
247
+ const a = Buffer.from(submitted);
248
+ const b = Buffer.from(this.code);
249
+ const same = a.length === b.length && timingSafeEqual(a, b);
250
+ if (!same) return {
251
+ ok: false,
252
+ reason: "invalid"
253
+ };
254
+ this.used = true;
255
+ return { ok: true };
256
+ }
257
+ mint(now) {
258
+ this.code = String(randomInt(0, 1e8)).padStart(8, "0");
259
+ this.createdAt = now;
260
+ this.expiresAt = now + this.ttlMs;
261
+ this.used = false;
262
+ }
263
+ };
264
+ /** Mint a per-device token. Only its SHA-256 may be persisted. */
265
+ function mintDeviceToken() {
266
+ return randomBytes(32).toString("hex");
267
+ }
268
+ function hashToken(token) {
269
+ return createHash("sha256").update(token).digest("hex");
270
+ }
271
+ /** Constant-time token-hash comparison. */
272
+ function tokenHashMatches(recordHash, presentedToken) {
273
+ const a = Buffer.from(recordHash, "hex");
274
+ const b = Buffer.from(hashToken(presentedToken), "hex");
275
+ return a.length === b.length && a.length > 0 && timingSafeEqual(a, b);
276
+ }
277
+
278
+ //#endregion
279
+ //#region src/store/devices.ts
280
+ /**
281
+
282
+ * Paired-device registry, persisted as JSON under the plugin data dir.
283
+
284
+ * Records carry token HASHES only; the raw token exists solely in the
285
+
286
+ * pairing response and the phone's secure storage.
287
+
288
+ */
289
+ var DeviceStore = class {
290
+ devices = new Map();
291
+ file;
292
+ dirty = false;
293
+ constructor(dataDir) {
294
+ mkdirSync(dataDir, { recursive: true });
295
+ this.file = join(dataDir, "devices.json");
296
+ this.load();
297
+ }
298
+ load() {
299
+ if (!existsSync(this.file)) return;
300
+ try {
301
+ const raw = JSON.parse(readFileSync(this.file, "utf8"));
302
+ for (const d of raw.devices ?? []) if (typeof d?.deviceId === "string" && typeof d?.tokenHash === "string") this.devices.set(d.deviceId, {
303
+ ...d,
304
+ name: d.name ?? "unknown",
305
+ model: d.model ?? "",
306
+ firstPairedAt: d.firstPairedAt ?? Date.now(),
307
+ lastSeenAt: d.lastSeenAt ?? 0
308
+ });
309
+ } catch {}
310
+ }
311
+ persist() {
312
+ const tmp = `${this.file}.tmp`;
313
+ writeFileSync(tmp, JSON.stringify({
314
+ version: 1,
315
+ devices: [...this.devices.values()]
316
+ }, null, 2), "utf8");
317
+ renameSync(tmp, this.file);
318
+ }
319
+ /** Register/re-register a device, uniquifying the name against others. */
320
+ upsert(record) {
321
+ const prior = this.devices.get(record.deviceId);
322
+ const full = {
323
+ ...record,
324
+ name: this.uniquifyName(record.deviceId, record.name),
325
+ firstPairedAt: prior?.firstPairedAt ?? Date.now(),
326
+ lastSeenAt: Date.now()
327
+ };
328
+ this.devices.set(record.deviceId, full);
329
+ this.dirty = true;
330
+ this.persist();
331
+ return full;
332
+ }
333
+ /** Make a display name unique among other devices (x, x (2), x (3), …). */
334
+ uniquifyName(deviceId, name) {
335
+ const others = [...this.devices.values()].map((d) => d.name).filter((n, i, arr) => arr.indexOf(n) === i);
336
+ const base = name.trim() || "Android 设备";
337
+ if (!others.includes(base)) return base;
338
+ for (let n = 2;; n++) {
339
+ const candidate = `${base} (${n})`;
340
+ if (!others.includes(candidate)) return candidate;
341
+ }
342
+ }
343
+ /** Rename a device (user-editable in the web UI); returns the updated record. */
344
+ rename(deviceId, name) {
345
+ const record = this.devices.get(deviceId);
346
+ if (!record) return null;
347
+ record.name = name.trim() || record.name;
348
+ this.dirty = true;
349
+ this.persist();
350
+ return record;
351
+ }
352
+ /** Authenticate deviceId + token; refreshes lastSeenAt on success. */
353
+ authenticate(deviceId, token) {
354
+ const record = this.devices.get(deviceId);
355
+ if (!record) return null;
356
+ if (!tokenHashMatches(record.tokenHash, token)) return null;
357
+ record.lastSeenAt = Date.now();
358
+ this.dirty = true;
359
+ return record;
360
+ }
361
+ remove(deviceId) {
362
+ const had = this.devices.delete(deviceId);
363
+ if (had) this.persist();
364
+ return had;
365
+ }
366
+ list() {
367
+ return [...this.devices.values()].sort((a, b) => b.lastSeenAt - a.lastSeenAt);
368
+ }
369
+ count() {
370
+ return this.devices.size;
371
+ }
372
+ };
373
+
374
+ //#endregion
375
+ //#region src/types.ts
376
+ const ERROR_CODES = {
377
+ AUTH_REQUIRED: "AUTH_REQUIRED",
378
+ PAIR_CODE_INVALID: "PAIR_CODE_INVALID",
379
+ PAIR_CODE_EXPIRED: "PAIR_CODE_EXPIRED",
380
+ RATE_LIMITED: "RATE_LIMITED",
381
+ TYPE_NOT_ALLOWED: "TYPE_NOT_ALLOWED",
382
+ TOO_LARGE: "TOO_LARGE",
383
+ BAD_MAGIC: "BAD_MAGIC",
384
+ STORE_FAILED: "STORE_FAILED",
385
+ NO_TARGET: "NO_TARGET",
386
+ NO_CAMERA: "NO_CAMERA",
387
+ CAPTURE_TIMEOUT: "CAPTURE_TIMEOUT",
388
+ LOOPBACK_ONLY: "LOOPBACK_ONLY",
389
+ BAD_REQUEST: "BAD_REQUEST",
390
+ INTERNAL: "INTERNAL"
391
+ };
392
+
393
+ //#endregion
394
+ //#region src/inject/admit.ts
395
+ /** Magic-byte whitelist check — never trust Content-Type alone. */
396
+ function magicMatches(mediaType, head) {
397
+ if (mediaType === "image/jpeg") return head.length >= 3 && head[0] === 255 && head[1] === 216 && head[2] === 255;
398
+ if (mediaType === "image/png") return head.length >= 4 && head[0] === 137 && head[1] === 80 && head[2] === 78 && head[3] === 71;
399
+ return false;
400
+ }
401
+ /**
402
+
403
+ * Persist one image through the durable attachment seam.
404
+
405
+ * Falls back to a content-addressed file when the dsh attachments service is
406
+
407
+ * not mounted (standalone dev / unusual profile), so uploads never vanish.
408
+
409
+ */
410
+ async function admitImage(input, attachments, fallbackDir) {
411
+ if (attachments) {
412
+ const refs = await attachments.saveImages([{
413
+ data: input.data,
414
+ mediaType: input.mediaType,
415
+ name: input.name
416
+ }]);
417
+ const ref = refs[0];
418
+ if (!ref) throw new Error("attachment store returned no reference");
419
+ return {
420
+ ref,
421
+ storage: "attachments"
422
+ };
423
+ }
424
+ const ext = input.mediaType === "image/png" ? "png" : "jpg";
425
+ const digest = createHash("sha1").update(input.data).digest("hex").slice(0, 16);
426
+ mkdirSync(fallbackDir, { recursive: true });
427
+ const filePath = join(fallbackDir, `${digest}-${input.name.replace(/[^\w.-]+/g, "_") || "image"}.${ext}`);
428
+ writeFileSync(filePath, input.data);
429
+ return {
430
+ ref: {
431
+ attachmentId: `file:${digest}`,
432
+ mediaType: input.mediaType,
433
+ bytes: input.data.byteLength,
434
+ width: 0,
435
+ height: 0,
436
+ name: input.name
437
+ },
438
+ storage: "file",
439
+ filePath
440
+ };
441
+ }
442
+
443
+ //#endregion
444
+ //#region src/server/qr.ts
445
+ /** Enumerate LAN IPv4 candidates: private ranges first, virtual/tethering included. */
446
+ function lanAddresses() {
447
+ const out = [];
448
+ for (const [iface, addrs] of Object.entries(os.networkInterfaces())) for (const addr of addrs ?? []) {
449
+ if (addr.family !== "IPv4" || addr.internal) continue;
450
+ out.push({
451
+ ip: addr.address,
452
+ iface
453
+ });
454
+ }
455
+ const rank = (ip) => {
456
+ if (ip.startsWith("192.168.")) return 0;
457
+ if (ip.startsWith("172.")) return 1;
458
+ if (ip.startsWith("10.")) return 2;
459
+ return 3;
460
+ };
461
+ return out.sort((a, b) => rank(a.ip) - rank(b.ip) || a.ip.localeCompare(b.ip));
462
+ }
463
+ /** Build the full pairing payload + rendered QR (data URL for browsers, ASCII for terminals). */
464
+ async function buildPairingQr(code, expiresAt, config, originOverride) {
465
+ const addrs = lanAddresses();
466
+ const host = originOverride ?? addrs[0]?.ip ?? "127.0.0.1";
467
+ const port = config.server.port;
468
+ const payload = `lensmate://pair?v=1&host=${encodeURIComponent(host)}&port=${port}&code=${code}`;
469
+ const urls = (addrs.length > 0 ? addrs : [{
470
+ ip: "127.0.0.1",
471
+ iface: "loopback"
472
+ }]).map((a) => `http://${a.ip}:${port}`);
473
+ const [pngDataUrl, ascii] = await Promise.all([QRCode.toDataURL(payload, {
474
+ errorCorrectionLevel: "M",
475
+ margin: 2,
476
+ width: 320
477
+ }), QRCode.toString(payload, {
478
+ type: "terminal",
479
+ small: true
480
+ })]);
481
+ return {
482
+ code,
483
+ expiresAt,
484
+ payload,
485
+ urls,
486
+ pngDataUrl,
487
+ ascii
488
+ };
489
+ }
490
+
491
+ //#endregion
492
+ //#region src/server/static-view.ts
493
+ /**
494
+
495
+ * The standalone fallback viewfinder page, served at /view.html (loopback only).
496
+
497
+ * Same protocol as the future Web UI overlay: WS /ws/view frames + capture control.
498
+
499
+ * Picture-in-Picture turns it into a true always-on-top mini window.
500
+
501
+ */
502
+ const VIEW_HTML = `<!doctype html>
503
+ <html lang="zh-CN">
504
+ <head>
505
+ <meta charset="utf-8">
506
+ <meta name="viewport" content="width=device-width, initial-scale=1">
507
+ <title>PhoneLens 直连取景</title>
508
+ <style>
509
+ :root { color-scheme: dark; }
510
+ * { box-sizing: border-box; }
511
+ body { margin: 0; font: 13px/1.5 system-ui, "Segoe UI", "Microsoft YaHei", sans-serif;
512
+ background: #101418; color: #dfe7ee; display: flex; flex-direction: column; height: 100vh; }
513
+ header { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: #171d24; border-bottom: 1px solid #232c36; }
514
+ header h1 { font-size: 13px; margin: 0; font-weight: 600; }
515
+ #dot { width: 9px; height: 9px; border-radius: 50%; background: #e5484d; transition: background .2s; }
516
+ #dot.on { background: #46a758; }
517
+ #fps { margin-left: auto; color: #7d8da0; font-variant-numeric: tabular-nums; }
518
+ main { flex: 1; display: flex; min-height: 0; }
519
+ #stage { flex: 1; display: flex; align-items: center; justify-content: center; background: #0b0e11; position: relative; min-width: 0; }
520
+ canvas { max-width: 100%; max-height: 100%; object-fit: contain; background: #000; }
521
+ #hint { position: absolute; color: #7d8da0; }
522
+ aside { width: 240px; border-left: 1px solid #232c36; padding: 12px; overflow: auto; }
523
+ aside h2 { font-size: 12px; margin: 0 0 8px; color: #9fb0c3; text-transform: uppercase; letter-spacing: .08em; }
524
+ #qrimg { width: 100%; image-rendering: pixelated; background: #fff; padding: 8px; border-radius: 8px; }
525
+ .row { display: flex; gap: 6px; align-items: center; margin: 6px 0; }
526
+ .row code { background: #1d242d; padding: 2px 8px; border-radius: 6px; letter-spacing: .12em; font-size: 15px; }
527
+ .row a { color: #3b7cb5; text-decoration: none; }
528
+ .row a:hover { text-decoration: underline; }
529
+ button { background: #1f2937; border: 1px solid #2f3b48; color: #dfe7ee; padding: 6px 10px; border-radius: 8px; cursor: pointer; font-size: 12px; }
530
+ button:hover { background: #28323e; }
531
+ button:disabled { opacity: .45; cursor: default; }
532
+ #shoot { padding: 10px; font-size: 14px; background: #2a5d8f; border-color: #3b7cb5; }
533
+ #pip { display: none; }
534
+ #log { margin-top: 10px; font-size: 12px; color: #8fa1b5; max-height: 160px; overflow: auto; }
535
+ #log div { padding: 2px 0; border-bottom: 1px dashed #202832; }
536
+ #log .ok { color: #58b368; } #log .err { color: #e5696e; }
537
+ </style>
538
+ </head>
539
+ <body>
540
+ <header>
541
+ <div id="dot"></div><h1>PhoneLens 直连取景</h1>
542
+ <span id="dev"></span>
543
+ <span id="fps"></span><span id="age"></span>
544
+ </header>
545
+ <main>
546
+ <div id="stage"><canvas width="854" height="480"></canvas><div id="hint">等待手机连接…</div></div>
547
+ <aside>
548
+ <h2>配对</h2>
549
+ <img id="qrimg" alt="配对二维码">
550
+ <div class="row"><code id="paircode"></code><button id="refresh">刷新</button></div>
551
+ <div class="row" id="urls"></div>
552
+ <div class="row"><a href="https://github.com/yxqfg/phone-lens/releases/latest/download/app-release.apk" target="_blank" rel="noopener">📱 手机还没装 App?点此下载(Android APK)</a></div>
553
+ <h2 style="margin-top:14px">快门</h2>
554
+ <div class="row">
555
+ <button id="shoot" disabled>◉ 拍照并注入</button>
556
+ <button id="pip">置顶小窗</button>
557
+ </div>
558
+ <div id="log"></div>
559
+ </aside>
560
+ </main>
561
+ <video id="pipvid" muted playsinline style="display:none"></video>
562
+ <script>
563
+ 'use strict';
564
+ const $ = (id) => document.getElementById(id);
565
+ const canvas = $('stage').querySelector('canvas');
566
+ const ctx2d = canvas.getContext('2d');
567
+ const logEl = $('log');
568
+ let lastFrameAt = 0, frames = 0, fpsTimer = 0, pendingShot = null;
569
+ let streamRotation = 0;
570
+
571
+ function log(msg, cls) {
572
+ const d = document.createElement('div');
573
+ if (cls) d.className = cls;
574
+ d.textContent = new Date().toLocaleTimeString() + ' ' + msg;
575
+ logEl.prepend(d);
576
+ while (logEl.childElementCount > 50) logEl.lastChild.remove();
577
+ }
578
+
579
+ async function refreshQr() {
580
+ try {
581
+ const r = await fetch('/qr.json');
582
+ const j = await r.json();
583
+ $('qrimg').src = j.pngDataUrl;
584
+ $('paircode').textContent = j.code;
585
+ $('urls').innerHTML = (j.urls || []).map(u => '<span style="color:#7d8da0">' + u + '</span>').join('<br>');
586
+ } catch (e) { log('二维码加载失败: ' + e.message, 'err'); }
587
+ }
588
+ $('refresh').onclick = () => { wsSend({ type: 'refresh_pairing' }); setTimeout(refreshQr, 150); };
589
+
590
+ function drawFrame(buf) {
591
+ const blob = new Blob([buf], { type: 'image/jpeg' });
592
+ const url = URL.createObjectURL(blob);
593
+ const img = new Image();
594
+ img.onload = () => {
595
+ const r = ((streamRotation % 360) + 360) % 360;
596
+ const swap = r === 90 || r === 270;
597
+ const w = swap ? img.height : img.width;
598
+ const h = swap ? img.width : img.height;
599
+ if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
600
+ ctx2d.save();
601
+ ctx2d.translate(w / 2, h / 2);
602
+ ctx2d.rotate(r * Math.PI / 180);
603
+ ctx2d.drawImage(img, -img.width / 2, -img.height / 2);
604
+ ctx2d.restore();
605
+ URL.revokeObjectURL(url);
606
+ $('hint').style.display = 'none';
607
+ frames++;
608
+ const now = performance.now();
609
+ if (now - fpsTimer >= 1000) { $('fps').textContent = (frames * 1000 / (now - fpsTimer)).toFixed(1) + ' fps'; frames = 0; fpsTimer = now; }
610
+ lastFrameAt = now;
611
+ };
612
+ img.src = url;
613
+ }
614
+
615
+ let ws = null;
616
+ function connect() {
617
+ const proto = location.protocol === 'https:' ? 'wss' : 'ws';
618
+ ws = new WebSocket(proto + '://' + location.host + '/ws/view');
619
+ ws.binaryType = 'arraybuffer';
620
+ ws.onopen = () => { log('已连接'); refreshQr(); };
621
+ ws.onclose = () => { $('dot').className = ''; setTimeout(connect, 1500); };
622
+ ws.onerror = () => {};
623
+ ws.onmessage = (ev) => {
624
+ if (ev.data instanceof ArrayBuffer) { drawFrame(ev.data); return; }
625
+ const m = JSON.parse(ev.data);
626
+ switch (m.type) {
627
+ case 'meta':
628
+ $('dot').className = m.camera.connected ? 'on' : '';
629
+ $('dev').textContent = m.camera.name || (m.camera.connected ? '已连接' : '未连接');
630
+ $('shoot').disabled = !m.camera.connected;
631
+ if (m.camera.rotation !== undefined) streamRotation = m.camera.rotation;
632
+ $('hint').style.display = m.camera.connected ? 'none' : '';
633
+ break;
634
+ case 'frame_meta':
635
+ if (m.rotation !== undefined) streamRotation = m.rotation;
636
+ break;
637
+ case 'device':
638
+ $('dot').className = m.online ? 'on' : '';
639
+ $('dev').textContent = m.online ? (m.name || '已连接') : '未连接';
640
+ $('shoot').disabled = !m.online;
641
+ $('hint').style.display = m.online ? 'none' : '';
642
+ $('hint').textContent = '等待手机连接…';
643
+ break;
644
+ case 'capture_pending':
645
+ pendingShot = m.captureId;
646
+ log('快门已触发' + (m.note ? '(' + m.note + ')' : '') + '…');
647
+ break;
648
+ case 'injected':
649
+ pendingShot = null;
650
+ if (m.ok) log('已注入会话 ' + (m.sessionId || '').slice(0, 8) + (m.name ? ' · ' + m.name : ''), 'ok');
651
+ else log('入库成功,注入未完成: ' + (m.reason || ''), 'err');
652
+ break;
653
+ case 'upload':
654
+ log('图片已入库 ' + (m.name || ''), 'ok');
655
+ break;
656
+ case 'error':
657
+ log('错误 ' + m.code + (m.message ? ': ' + m.message : ''), 'err');
658
+ break;
659
+ }
660
+ };
661
+ }
662
+ function wsSend(obj) { if (ws && ws.readyState === 1) ws.send(JSON.stringify(obj)); }
663
+
664
+ $('shoot').onclick = () => wsSend({ type: 'capture', note: '' });
665
+
666
+ // PiP: mirror the canvas into a video stream, then request Picture-in-Picture.
667
+ $('pip').onclick = async () => {
668
+ try {
669
+ const stream = canvas.captureStream(10);
670
+ const v = $('pipvid');
671
+ v.srcObject = stream;
672
+ await v.play();
673
+ await v.requestPictureInPicture();
674
+ } catch (e) { log('画中画失败: ' + e.message, 'err'); }
675
+ };
676
+
677
+ setInterval(() => {
678
+ if (document.pictureInPictureElement) return;
679
+ if (performance.now() - lastFrameAt > 4000 && lastFrameAt > 0) $('hint').style.display = '';
680
+ $('age').textContent = lastFrameAt > 0 ? ' · ' + ((performance.now() - lastFrameAt) / 1000).toFixed(1) + 's前' : '';
681
+ }, 1000);
682
+ if (document.pictureInPictureEnabled) $('pip').style.display = '';
683
+
684
+ connect();
685
+ </script>
686
+ </body>
687
+ </html>
688
+ `;
689
+
690
+ //#endregion
691
+ //#region src/server/auth.ts
692
+ /** Sliding-window rate limiter (in-memory; resets with the process). */
693
+ var RateLimiter = class {
694
+ hits = new Map();
695
+ constructor(windowMs, max) {
696
+ this.windowMs = windowMs;
697
+ this.max = max;
698
+ }
699
+ /** Record one hit and report whether the key is still within budget. */
700
+ allow(key) {
701
+ const now = Date.now();
702
+ const cutoff = now - this.windowMs;
703
+ const list = (this.hits.get(key) ?? []).filter((t) => t > cutoff);
704
+ if (list.length >= this.max) {
705
+ this.hits.set(key, list);
706
+ return false;
707
+ }
708
+ list.push(now);
709
+ this.hits.set(key, list);
710
+ return true;
711
+ }
712
+ };
713
+ const LOOPBACK = new Set([
714
+ "127.0.0.1",
715
+ "::1",
716
+ "::ffff:127.0.0.1"
717
+ ]);
718
+ /** Whether the connection originates from this machine (loopback). */
719
+ function isLoopback(req) {
720
+ const addr = req.socket.remoteAddress ?? "";
721
+ return LOOPBACK.has(addr);
722
+ }
723
+ /**
724
+
725
+ * CORS for the dsh Web UI page (served on another loopback port) so it can
726
+
727
+ * fetch /qr.json and /status from this receiver. Only same-machine origins
728
+
729
+ * are echoed — a foreign page must not read the pairing code, and its
730
+
731
+ * cross-origin JSON POST fails the preflight we never answer.
732
+
733
+ */
734
+ function corsFor(req) {
735
+ const origin = req.headers.origin;
736
+ if (typeof origin !== "string" || origin === "") return {};
737
+ try {
738
+ const u = new URL(origin);
739
+ const host = u.hostname.replace(/^\[|\]$/g, "");
740
+ if (u.protocol === "http:" && LOOPBACK.has(host)) return {
741
+ "access-control-allow-origin": origin,
742
+ "access-control-allow-methods": "GET, POST, OPTIONS",
743
+ "access-control-allow-headers": "content-type, x-lm-device, x-lm-token",
744
+ "access-control-max-age": "600"
745
+ };
746
+ } catch {}
747
+ return {};
748
+ }
749
+ /** Extract a stable client key for rate limiting. */
750
+ function clientKey(req) {
751
+ return req.socket.remoteAddress ?? "unknown";
752
+ }
753
+ /** Read the device auth headers, if present. */
754
+ function deviceAuth(req) {
755
+ const deviceId = req.headers["x-lm-device"];
756
+ const token = req.headers["x-lm-token"];
757
+ if (typeof deviceId !== "string" || typeof token !== "string" || !deviceId || !token) return null;
758
+ return {
759
+ deviceId,
760
+ token
761
+ };
762
+ }
763
+ /** Query-string parser (URLSearchParams handles plus-encoding for notes). */
764
+ function queryOf(req) {
765
+ const url = new URL(req.url ?? "/", "http://phone-lens.local");
766
+ return url.searchParams;
767
+ }
768
+
769
+ //#endregion
770
+ //#region src/server/http.ts
771
+ /** Boot the receiver: HTTP routes + two websocket endpoints. */
772
+ async function startLensServer(deps) {
773
+ const { config, pairing, devices, hub, targets, sink, log } = deps;
774
+ const pairLimiter = new RateLimiter(6e4, 10);
775
+ const uploadLimiter = new RateLimiter(6e4, config.limits.uploadsPerMinute);
776
+ let currentCameraDeviceId = null;
777
+ const injectionBox = { last: null };
778
+ const server = createServer((req, res) => {
779
+ handle(deps, req, res, {
780
+ pairLimiter,
781
+ uploadLimiter,
782
+ getCurrentCamera: () => currentCameraDeviceId,
783
+ noteInjection: (receipt, attachmentId) => {
784
+ injectionBox.last = {
785
+ at: Date.now(),
786
+ sessionId: receipt.sessionId,
787
+ attachmentId,
788
+ ok: receipt.ok
789
+ };
790
+ },
791
+ getLastInjection: () => injectionBox.last
792
+ }).catch((error) => {
793
+ log("error", `request failed: ${String(error)}`);
794
+ if (!res.headersSent) sendJson(res, 500, { error: {
795
+ code: ERROR_CODES.INTERNAL,
796
+ message: String(error)
797
+ } });
798
+ else res.destroy();
799
+ });
800
+ });
801
+ const wss = new WebSocketServer({
802
+ noServer: true,
803
+ maxPayload: config.limits.previewFrameMaxBytes * 4
804
+ });
805
+ server.on("upgrade", (req, socket, head) => {
806
+ const url = new URL(req.url ?? "/", "http://phone-lens.local");
807
+ const done = (status, message) => {
808
+ socket.write(`HTTP/1.1 ${status} ${message}\r\nConnection: close\r\n\r\n`);
809
+ socket.destroy();
810
+ };
811
+ if (url.pathname === "/ws/camera") {
812
+ const q = url.searchParams;
813
+ const deviceId = q.get("deviceId") ?? "";
814
+ const token = q.get("token") ?? "";
815
+ const record = devices.authenticate(deviceId, token);
816
+ if (!record) return done(401, "Unauthorized");
817
+ wss.handleUpgrade(req, socket, head, (ws) => {
818
+ currentCameraDeviceId = record.deviceId;
819
+ hub.attachCamera(record.deviceId, ws, record.name);
820
+ });
821
+ return;
822
+ }
823
+ if (url.pathname === "/ws/view") {
824
+ if (!isLoopback(req)) return done(403, "Forbidden");
825
+ wss.handleUpgrade(req, socket, head, (ws) => hub.attachView(ws, {
826
+ onRefreshPairing: () => pairing.refresh(),
827
+ onRenameDevice: (deviceId, name) => {
828
+ const updated = devices.rename(deviceId, name);
829
+ if (updated) hub.renameDevice(deviceId, updated.name);
830
+ }
831
+ }));
832
+ return;
833
+ }
834
+ done(404, "Not Found");
835
+ });
836
+ const heartbeat = setInterval(() => hub.pingAll(), 2e4);
837
+ await new Promise((resolve, reject) => {
838
+ server.once("error", reject);
839
+ server.listen(config.server.port, config.server.host, () => resolve());
840
+ });
841
+ log("info", `phone-lens listening on ${config.server.host}:${config.server.port} (paired devices: ${devices.count()})`);
842
+ return {
843
+ port: config.server.port,
844
+ dispose: async () => {
845
+ clearInterval(heartbeat);
846
+ hub.detachAll();
847
+ for (const client of wss.clients) client.terminate();
848
+ await new Promise((resolve) => server.close(() => resolve()));
849
+ }
850
+ };
851
+ }
852
+ async function handle(deps, req, res, ctx) {
853
+ const { config, pairing, devices, hub, targets, sink, log } = deps;
854
+ const url = new URL(req.url ?? "/", "http://phone-lens.local");
855
+ const path = url.pathname.replace(/\/+$/, "") || "/";
856
+ const method = req.method ?? "GET";
857
+ const loop = isLoopback(req);
858
+ const cors = corsFor(req);
859
+ if (method === "OPTIONS") {
860
+ res.writeHead(204, cors);
861
+ res.end();
862
+ return;
863
+ }
864
+ if (method === "GET" && path === "/info") return sendJson(res, 200, {
865
+ name: "PhoneLens 直连取景",
866
+ version: "0.3.5",
867
+ requiresPairing: true
868
+ }, cors);
869
+ if (!loop && (path === "/" || path === "/view.html" || path === "/qr.json" || path === "/qr.png" || path === "/app-qr.json")) return sendError(res, 403, ERROR_CODES.LOOPBACK_ONLY, "preview surface is loopback-only");
870
+ if (method === "GET" && (path === "/" || path === "/view.html")) {
871
+ res.writeHead(200, {
872
+ "content-type": "text/html; charset=utf-8",
873
+ "cache-control": "no-store"
874
+ });
875
+ res.end(VIEW_HTML);
876
+ return;
877
+ }
878
+ if (method === "GET" && path === "/qr.json") {
879
+ const { code, expiresAt } = pairing.current();
880
+ const qr = await buildPairingQr(code, expiresAt, config);
881
+ return sendJson(res, 200, {
882
+ code: qr.code,
883
+ expiresAt: qr.expiresAt,
884
+ payload: qr.payload,
885
+ urls: qr.urls,
886
+ pngDataUrl: qr.pngDataUrl
887
+ }, {
888
+ ...cors,
889
+ "cache-control": "no-store"
890
+ });
891
+ }
892
+ if (method === "GET" && path === "/qr.png") {
893
+ const { code, expiresAt } = pairing.current();
894
+ const qr = await buildPairingQr(code, expiresAt, config);
895
+ const b64 = qr.pngDataUrl.slice(qr.pngDataUrl.indexOf(",") + 1);
896
+ res.writeHead(200, {
897
+ "content-type": "image/png",
898
+ "cache-control": "no-store"
899
+ });
900
+ res.end(Buffer.from(b64, "base64"));
901
+ return;
902
+ }
903
+ if (method === "GET" && path === "/app-qr.json") {
904
+ const target = config.app.downloadUrl || config.app.giteeUrl;
905
+ const pngDataUrl = await QRCode.toDataURL(target, {
906
+ errorCorrectionLevel: "M",
907
+ margin: 2,
908
+ width: 320
909
+ });
910
+ return sendJson(res, 200, {
911
+ url: target,
912
+ gitee: config.app.giteeUrl,
913
+ github: config.app.githubUrl,
914
+ pngDataUrl
915
+ }, {
916
+ ...cors,
917
+ "cache-control": "no-store"
918
+ });
919
+ }
920
+ if (method === "POST" && path === "/pair") {
921
+ const body = await readJsonBody(req, 4096);
922
+ const code = str(body?.code);
923
+ const device = body?.device ?? {};
924
+ const deviceId = str(device.id);
925
+ const name = str(device.name) ?? "unnamed device";
926
+ const model = str(device.model) ?? "";
927
+ if (!code || !deviceId) return sendError(res, 400, ERROR_CODES.BAD_REQUEST, "code and device.id are required");
928
+ const verdict = pairing.verify(code);
929
+ if (!verdict.ok) {
930
+ if (!ctx.pairLimiter.allow(clientKey(req))) return sendError(res, 429, ERROR_CODES.RATE_LIMITED, "too many pairing attempts");
931
+ return sendError(res, 401, verdict.reason === "expired" ? ERROR_CODES.PAIR_CODE_EXPIRED : ERROR_CODES.PAIR_CODE_INVALID, `pairing code ${verdict.reason}`);
932
+ }
933
+ const token = mintDeviceToken();
934
+ devices.upsert({
935
+ deviceId,
936
+ name,
937
+ model,
938
+ tokenHash: hashToken(token)
939
+ });
940
+ log("info", `paired device "${name}" (${deviceId.slice(0, 8)})`);
941
+ return sendJson(res, 200, {
942
+ token,
943
+ serverInfo: {
944
+ preview: config.preview,
945
+ limits: config.limits
946
+ }
947
+ });
948
+ }
949
+ const auth = loop ? { ok: true } : deviceAuth(req) && devices.authenticate(deviceAuth(req).deviceId, deviceAuth(req).token) ? { ok: true } : { ok: false };
950
+ if (!auth.ok) return sendError(res, 401, ERROR_CODES.AUTH_REQUIRED, "pair this device first");
951
+ if (method === "POST" && path === "/upload") {
952
+ const q = queryOf(req);
953
+ if (!ctx.uploadLimiter.allow(loop ? "loopback" : clientKey(req))) return sendError(res, 429, ERROR_CODES.RATE_LIMITED, "upload rate exceeded");
954
+ const mediaType = (req.headers["content-type"] ?? "").split(";")[0].trim();
955
+ if (!config.limits.allowedTypes.includes(mediaType)) return sendError(res, 415, ERROR_CODES.TYPE_NOT_ALLOWED, `allowed: ${config.limits.allowedTypes.join(", ")}`);
956
+ const declared = Number(req.headers["content-length"] ?? "0");
957
+ if (declared > config.limits.maxUploadBytes) return sendError(res, 413, ERROR_CODES.TOO_LARGE, `> ${config.limits.maxUploadBytes} bytes`);
958
+ const { buf, truncated } = await readRawBody(req, config.limits.maxUploadBytes);
959
+ if (truncated) return sendError(res, 413, ERROR_CODES.TOO_LARGE, `> ${config.limits.maxUploadBytes} bytes`);
960
+ if (!magicMatches(mediaType, buf)) return sendError(res, 415, ERROR_CODES.BAD_MAGIC, "bytes do not match the declared type");
961
+ const captureId = q.get("captureId");
962
+ const note = q.get("note") ?? (captureId ? hub.noteFor(captureId) : void 0);
963
+ if (captureId) hub.consumeCapture(captureId);
964
+ const name = (q.get("name") ?? `shot_${new Date().toISOString().replace(/[:.]/g, "-")}.${mediaType === "image/png" ? "png" : "jpg"}`).slice(0, 120);
965
+ let admitted;
966
+ try {
967
+ admitted = await admitImage({
968
+ data: buf,
969
+ mediaType,
970
+ name
971
+ }, deps.attachments(), deps.fallbackDir);
972
+ } catch (error) {
973
+ log("error", `admit failed: ${String(error)}`);
974
+ return sendError(res, 500, ERROR_CODES.STORE_FAILED, String(error));
975
+ }
976
+ log("info", `stored ${name} (${buf.byteLength}B) → ${admitted.storage}:${admitted.ref.attachmentId}`);
977
+ if (admitted.storage === "file") await pruneUploads(deps.fallbackDir, config.limits.maxStoredUploads).catch((error) => log("warn", `upload pruning failed: ${String(error)}`));
978
+ const pendingPath = join(deps.pendingDir, `${admitted.ref.attachmentId}.jpg`);
979
+ try {
980
+ mkdirSync(deps.pendingDir, { recursive: true });
981
+ writeFileSync(pendingPath, buf);
982
+ log("info", `staged for composer: ${pendingPath}`);
983
+ } catch (error) {
984
+ log("warn", `staging failed: ${String(error)}`);
985
+ }
986
+ hub.broadcastToViews({
987
+ type: "pending_image",
988
+ attachmentId: admitted.ref.attachmentId,
989
+ name
990
+ });
991
+ return sendJson(res, 200, {
992
+ ok: true,
993
+ attachmentId: admitted.ref.attachmentId,
994
+ width: admitted.ref.width,
995
+ height: admitted.ref.height,
996
+ bytes: admitted.ref.bytes,
997
+ storage: admitted.storage,
998
+ delivered: null,
999
+ deliverReason: "staged-in-composer"
1000
+ });
1001
+ }
1002
+ if (method === "GET" && path.startsWith("/pending/") && loop) {
1003
+ const id = path.slice(9).split("/")[0] ?? "";
1004
+ const file = join(deps.pendingDir, `${id}.jpg`);
1005
+ try {
1006
+ const data = await readFile(file);
1007
+ res.writeHead(200, {
1008
+ "content-type": "image/jpeg",
1009
+ "cache-control": "no-store",
1010
+ ...cors
1011
+ });
1012
+ res.end(data);
1013
+ return;
1014
+ } catch {
1015
+ return sendError(res, 404, ERROR_CODES.BAD_REQUEST, "pending image not found");
1016
+ }
1017
+ }
1018
+ if (method === "GET" && path === "/status") {
1019
+ const cameraDeviceId = ctx.getCurrentCamera();
1020
+ return sendJson(res, 200, {
1021
+ devices: devices.list().map((d) => ({
1022
+ id: d.deviceId,
1023
+ name: d.name,
1024
+ model: d.model,
1025
+ online: d.deviceId === cameraDeviceId,
1026
+ streaming: d.deviceId === cameraDeviceId,
1027
+ lastSeenAt: d.lastSeenAt
1028
+ })),
1029
+ camera: hub.stats(),
1030
+ preview: config.preview,
1031
+ target: {
1032
+ mode: targets.mode(),
1033
+ sessionId: targets.resolve()?.sessionId ?? null
1034
+ },
1035
+ lastInjection: ctx.getLastInjection()
1036
+ }, cors);
1037
+ }
1038
+ if (method === "GET" && path === "/targets") return sendJson(res, 200, {
1039
+ targets: targets.list(),
1040
+ default: targets.resolve()?.sessionId ?? null
1041
+ }, cors);
1042
+ if (method === "POST" && path === "/capture" && loop) {
1043
+ const captureId = randomUUID();
1044
+ const ok = hub.requestCapture(captureId, queryOf(req).get("note") ?? void 0);
1045
+ if (!ok) return sendError(res, 409, ERROR_CODES.NO_CAMERA, "no camera uplink connected");
1046
+ return sendJson(res, 202, { captureId });
1047
+ }
1048
+ return sendError(res, 404, ERROR_CODES.BAD_REQUEST, `no route ${method} ${path}`);
1049
+ }
1050
+ function sendJson(res, status, body, extraHeaders) {
1051
+ res.writeHead(status, {
1052
+ "content-type": "application/json; charset=utf-8",
1053
+ ...extraHeaders ?? {}
1054
+ });
1055
+ res.end(JSON.stringify(body));
1056
+ }
1057
+ function sendError(res, status, code, message) {
1058
+ sendJson(res, status, { error: {
1059
+ code,
1060
+ message
1061
+ } });
1062
+ }
1063
+ function str(v) {
1064
+ return typeof v === "string" ? v : void 0;
1065
+ }
1066
+ async function readJsonBody(req, limit) {
1067
+ const { buf } = await readRawBody(req, limit);
1068
+ try {
1069
+ return JSON.parse(buf.toString("utf8"));
1070
+ } catch {
1071
+ return null;
1072
+ }
1073
+ }
1074
+ function readRawBody(req, maxBytes) {
1075
+ return new Promise((resolve, reject) => {
1076
+ const chunks = [];
1077
+ let size = 0;
1078
+ let truncated = false;
1079
+ req.on("data", (chunk) => {
1080
+ size += chunk.byteLength;
1081
+ if (size > maxBytes) {
1082
+ truncated = true;
1083
+ chunks.length = 0;
1084
+ req.destroy();
1085
+ resolve({
1086
+ buf: Buffer.alloc(0),
1087
+ truncated
1088
+ });
1089
+ return;
1090
+ }
1091
+ chunks.push(chunk);
1092
+ });
1093
+ req.on("end", () => resolve({
1094
+ buf: Buffer.concat(chunks),
1095
+ truncated
1096
+ }));
1097
+ req.on("error", reject);
1098
+ });
1099
+ }
1100
+ /** Delete the oldest files beyond `max` in a directory (mtime order). */
1101
+ async function pruneUploads(dir, max) {
1102
+ if (max <= 0) return;
1103
+ const names = await readdir(dir);
1104
+ if (names.length <= max) return;
1105
+ const entries = await Promise.all(names.map(async (name) => {
1106
+ let mtime = 0;
1107
+ try {
1108
+ mtime = (await stat(join(dir, name))).mtimeMs;
1109
+ } catch {
1110
+ mtime = 0;
1111
+ }
1112
+ return {
1113
+ name,
1114
+ mtime
1115
+ };
1116
+ }));
1117
+ entries.sort((a, b) => b.mtime - a.mtime);
1118
+ for (const entry of entries.slice(max)) await unlink(join(dir, entry.name)).catch(() => {});
1119
+ }
1120
+
1121
+ //#endregion
1122
+ //#region src/server/hub.ts
1123
+ /**
1124
+
1125
+ * The viewfinder hub: MULTIPLE camera uplinks (one per phone, keyed by
1126
+
1127
+ * deviceId), N loopback view downlinks. The "active" device is auto-selected
1128
+
1129
+ * as the last one to send a frame; the view side can switch it via
1130
+
1131
+ * `select_device`. Only the active device's frames are fanned out — a second
1132
+
1133
+ * phone connecting no longer kicks the first, so several paired phones coexist
1134
+
1135
+ * and the user picks which one to watch / shoot from.
1136
+
1137
+ */
1138
+ var ViewHub = class {
1139
+ cameras = new Map();
1140
+ activeDeviceId = null;
1141
+ views = new Set();
1142
+ /** captureId → { note, requestedAt } until the matching upload lands or timeout. */
1143
+ pendingCaptures = new Map();
1144
+ captureTimeoutMs = 6e4;
1145
+ constructor(config, log) {
1146
+ this.config = config;
1147
+ this.log = log;
1148
+ }
1149
+ attachCamera(deviceId, ws, name) {
1150
+ const prev = this.cameras.get(deviceId);
1151
+ if (prev) {
1152
+ try {
1153
+ prev.ws.close(1e3, "new-instance");
1154
+ } catch {}
1155
+ this.cameras.delete(deviceId);
1156
+ }
1157
+ const cam = {
1158
+ ws,
1159
+ name,
1160
+ meta: {},
1161
+ lastFrame: null,
1162
+ lastFrameAt: 0,
1163
+ frameCount: 0,
1164
+ windowStart: Date.now(),
1165
+ measuredFps: 0
1166
+ };
1167
+ this.cameras.set(deviceId, cam);
1168
+ if (this.activeDeviceId === null) this.activeDeviceId = deviceId;
1169
+ if (this.activeDeviceId === deviceId) this.sendControl(deviceId, { type: "resume_preview" });
1170
+ else this.sendControl(deviceId, { type: "pause_preview" });
1171
+ this.log("info", `camera uplink: ${name} (${deviceId.slice(0, 8)})`);
1172
+ ws.on("close", () => {
1173
+ if (this.cameras.get(deviceId)?.ws === ws) this.detachCamera(deviceId);
1174
+ });
1175
+ ws.on("message", (data, isBinary) => {
1176
+ if (isBinary) {
1177
+ this.ingestFrame(deviceId, data);
1178
+ return;
1179
+ }
1180
+ this.onCameraControl(deviceId, safeJson(data.toString()));
1181
+ });
1182
+ this.broadcastDevices();
1183
+ }
1184
+ detachCamera(deviceId) {
1185
+ const cam = this.cameras.get(deviceId);
1186
+ if (cam) this.cameras.delete(deviceId);
1187
+ if (this.activeDeviceId === deviceId) {
1188
+ const next = [...this.cameras.keys()].at(-1) ?? null;
1189
+ this.activeDeviceId = next;
1190
+ if (next) this.sendControl(next, { type: "resume_preview" });
1191
+ this.pushActiveFrameToViews();
1192
+ }
1193
+ this.broadcastDevices();
1194
+ }
1195
+ detachAll() {
1196
+ for (const cam of this.cameras.values()) try {
1197
+ cam.ws.close(1e3, "server-dispose");
1198
+ } catch {}
1199
+ this.cameras.clear();
1200
+ this.activeDeviceId = null;
1201
+ this.broadcastDevices();
1202
+ }
1203
+ pingAll() {
1204
+ for (const cam of this.cameras.values()) if (cam.ws.readyState === cam.ws.OPEN) cam.ws.ping();
1205
+ }
1206
+ onCameraControl(deviceId, msg) {
1207
+ if (!msg) return;
1208
+ const cam = this.cameras.get(deviceId);
1209
+ if (!cam) return;
1210
+ switch (msg.type) {
1211
+ case "hello":
1212
+ cam.meta = {
1213
+ width: msg.width,
1214
+ height: msg.height,
1215
+ fps: msg.fps,
1216
+ ...msg.rotation !== void 0 ? { rotation: msg.rotation } : {}
1217
+ };
1218
+ if (this.activeDeviceId === deviceId) this.broadcastToViews({
1219
+ type: "frame_meta",
1220
+ width: msg.width,
1221
+ height: msg.height,
1222
+ ...msg.rotation !== void 0 ? { rotation: msg.rotation } : {}
1223
+ });
1224
+ break;
1225
+ case "bye":
1226
+ this.detachCamera(deviceId);
1227
+ break;
1228
+ case "claim_active":
1229
+ this.selectDevice(deviceId);
1230
+ break;
1231
+ case "capture_result":
1232
+ if (msg.status !== "taken") {
1233
+ this.pendingCaptures.delete(msg.captureId);
1234
+ this.broadcastToViews({
1235
+ type: "error",
1236
+ code: "CAPTURE_DECLINED",
1237
+ message: `phone reported ${msg.status}${msg.detail ? `: ${msg.detail}` : ""}`
1238
+ });
1239
+ }
1240
+ break;
1241
+ default: break;
1242
+ }
1243
+ }
1244
+ ingestFrame(deviceId, frame) {
1245
+ const cam = this.cameras.get(deviceId);
1246
+ if (!cam || frame.byteLength === 0) return;
1247
+ if (frame.byteLength > this.config.limits.previewFrameMaxBytes) {
1248
+ this.log("warn", `dropping oversized preview frame from ${deviceId.slice(0, 8)} (${frame.byteLength}B > ${this.config.limits.previewFrameMaxBytes}B)`);
1249
+ return;
1250
+ }
1251
+ const now = Date.now();
1252
+ cam.lastFrame = frame;
1253
+ cam.lastFrameAt = now;
1254
+ cam.frameCount++;
1255
+ if (now - cam.windowStart >= 2e3) {
1256
+ cam.measuredFps = cam.frameCount * 1e3 / (now - cam.windowStart);
1257
+ cam.windowStart = now;
1258
+ cam.frameCount = 0;
1259
+ }
1260
+ if (this.activeDeviceId === deviceId) {
1261
+ for (const view of this.views) if (view.readyState === view.OPEN) view.send(frame, { binary: true });
1262
+ }
1263
+ }
1264
+ attachView(ws, hooks = {}) {
1265
+ this.views.add(ws);
1266
+ ws.on("close", () => this.views.delete(ws));
1267
+ ws.on("message", (data, isBinary) => {
1268
+ if (isBinary) return;
1269
+ const msg = parseViewClient(data.toString());
1270
+ if (!msg) return;
1271
+ if (msg.type === "capture") {
1272
+ const captureId = randomUUID();
1273
+ if (!this.requestCapture(captureId, msg.note)) this.broadcastToViews({
1274
+ type: "error",
1275
+ code: "NO_CAMERA",
1276
+ message: "no camera uplink connected"
1277
+ });
1278
+ } else if (msg.type === "select_device") this.selectDevice(msg.deviceId);
1279
+ else if (msg.type === "rename_device") hooks.onRenameDevice?.(msg.deviceId, msg.name);
1280
+ else if (msg.type === "refresh_pairing") hooks.onRefreshPairing?.();
1281
+ });
1282
+ const active = this.activeCam();
1283
+ ws.send(JSON.stringify({
1284
+ type: "meta",
1285
+ camera: active ? {
1286
+ connected: true,
1287
+ name: active.name,
1288
+ ...active.meta
1289
+ } : { connected: false },
1290
+ preview: this.config.preview,
1291
+ paired: true
1292
+ }));
1293
+ this.broadcastDevicesTo(ws);
1294
+ if (active?.lastFrame && ws.readyState === ws.OPEN) ws.send(active.lastFrame, { binary: true });
1295
+ }
1296
+ viewCount() {
1297
+ return this.views.size;
1298
+ }
1299
+ /** Update one device's display name and re-broadcast the device list. */
1300
+ renameDevice(deviceId, name) {
1301
+ const cam = this.cameras.get(deviceId);
1302
+ if (cam) cam.name = name;
1303
+ this.broadcastDevices();
1304
+ }
1305
+ /** Switch which phone's frames / shutter the view follows. */
1306
+ selectDevice(deviceId) {
1307
+ if (!this.cameras.has(deviceId)) return;
1308
+ const prevActive = this.activeDeviceId;
1309
+ if (prevActive === deviceId) return;
1310
+ this.activeDeviceId = deviceId;
1311
+ if (prevActive) this.sendControl(prevActive, { type: "pause_preview" });
1312
+ this.sendControl(deviceId, { type: "resume_preview" });
1313
+ this.broadcastDevices();
1314
+ this.pushActiveFrameToViews();
1315
+ }
1316
+ /** Send one control message to a specific phone uplink. */
1317
+ sendControl(deviceId, msg) {
1318
+ const cam = this.cameras.get(deviceId);
1319
+ if (cam && cam.ws.readyState === cam.ws.OPEN) cam.ws.send(JSON.stringify(msg));
1320
+ }
1321
+ pushActiveFrameToViews() {
1322
+ const active = this.activeCam();
1323
+ if (active?.lastFrame) {
1324
+ for (const view of this.views) if (view.readyState === view.OPEN) view.send(active.lastFrame, { binary: true });
1325
+ }
1326
+ if (active) this.broadcastToViews({
1327
+ type: "frame_meta",
1328
+ width: active.meta.width ?? 0,
1329
+ height: active.meta.height ?? 0,
1330
+ ...active.meta.rotation !== void 0 ? { rotation: active.meta.rotation } : {}
1331
+ });
1332
+ }
1333
+ activeCam() {
1334
+ return this.activeDeviceId ? this.cameras.get(this.activeDeviceId) : void 0;
1335
+ }
1336
+ broadcastDevices() {
1337
+ for (const view of this.views) this.broadcastDevicesTo(view);
1338
+ }
1339
+ broadcastDevicesTo(view) {
1340
+ if (view.readyState !== view.OPEN) return;
1341
+ view.send(JSON.stringify({
1342
+ type: "devices",
1343
+ devices: [...this.cameras.values()].map((c, i) => {
1344
+ const id = [...this.cameras.keys()][i];
1345
+ return {
1346
+ id,
1347
+ name: c.name,
1348
+ active: id === this.activeDeviceId
1349
+ };
1350
+ })
1351
+ }));
1352
+ }
1353
+ /** Ask the ACTIVE phone to shoot. Returns the captureId, or null when none. */
1354
+ requestCapture(captureId, note) {
1355
+ const active = this.activeCam();
1356
+ if (!active || active.ws.readyState !== active.ws.OPEN) return null;
1357
+ this.pendingCaptures.set(captureId, {
1358
+ note,
1359
+ requestedAt: Date.now()
1360
+ });
1361
+ active.ws.send(JSON.stringify({
1362
+ type: "capture",
1363
+ captureId,
1364
+ ...note ? { note } : {}
1365
+ }));
1366
+ this.broadcastToViews({
1367
+ type: "capture_pending",
1368
+ captureId,
1369
+ ...note ? { note } : {}
1370
+ });
1371
+ this.gcCaptures();
1372
+ return captureId;
1373
+ }
1374
+ consumeCapture(captureId) {
1375
+ const pending = this.pendingCaptures.get(captureId);
1376
+ if (!pending) return null;
1377
+ this.pendingCaptures.delete(captureId);
1378
+ return { note: pending.note };
1379
+ }
1380
+ noteFor(captureId) {
1381
+ return this.pendingCaptures.get(captureId)?.note;
1382
+ }
1383
+ gcCaptures() {
1384
+ const cutoff = Date.now() - this.captureTimeoutMs;
1385
+ for (const [id, p] of this.pendingCaptures) if (p.requestedAt < cutoff) this.pendingCaptures.delete(id);
1386
+ }
1387
+ broadcastToViews(msg) {
1388
+ const text = JSON.stringify(msg);
1389
+ for (const view of this.views) if (view.readyState === view.OPEN) view.send(text);
1390
+ }
1391
+ stats() {
1392
+ const active = this.activeCam();
1393
+ return {
1394
+ connected: this.cameras.size > 0,
1395
+ fps: active ? Math.round(active.measuredFps * 10) / 10 : 0,
1396
+ lastFrameAt: active?.lastFrameAt ?? 0,
1397
+ views: this.views.size,
1398
+ devices: this.cameras.size
1399
+ };
1400
+ }
1401
+ };
1402
+ function safeJson(text) {
1403
+ try {
1404
+ return JSON.parse(text);
1405
+ } catch {
1406
+ return null;
1407
+ }
1408
+ }
1409
+ function parseViewClient(text) {
1410
+ try {
1411
+ return JSON.parse(text);
1412
+ } catch {
1413
+ return null;
1414
+ }
1415
+ }
1416
+
1417
+ //#endregion
1418
+ //#region src/paths.ts
1419
+ /** Where pairing records + fallback uploads live (mirrors dsh-home conventions). */
1420
+ function lensDataDir() {
1421
+ const home = env.DSH_HOME ?? join(homedir(), ".dsh");
1422
+ return join(home, "phone-lens");
1423
+ }
1424
+
1425
+ //#endregion
1426
+ //#region src/index.ts
1427
+ /**
1428
+
1429
+ * phone-lens host plugin.
1430
+
1431
+ *
1432
+
1433
+ * Boots the receiver inside the dsh process so uploads can flow straight
1434
+
1435
+ * into `ctx.attachments` (and, from Phase 2 on, into agent inboxes) with no
1436
+
1437
+ * extra IPC. Everything registered here unwinds with the fiber.
1438
+
1439
+ */
1440
+ var PhoneLens = class extends Service {
1441
+ static inject = [];
1442
+ static Config = z.any();
1443
+ constructor(ctx, rawConfig) {
1444
+ super(ctx, "phoneLens");
1445
+ const config = normalizeConfig(rawConfig);
1446
+ const dataDir = lensDataDir();
1447
+ const log = (level, msg) => {
1448
+ const target = ctx.logger ?? console;
1449
+ target[level]?.(`[phone-lens] ${msg}`);
1450
+ };
1451
+ const pairing = new PairingStore(config.pairing.codeTtlMs);
1452
+ const devices = new DeviceStore(dataDir);
1453
+ const hub = new ViewHub(config, (level, msg) => log(level, msg));
1454
+ const targets = new TargetTracker(config);
1455
+ const sink = new HostDeliverySink(config, (level, msg) => log(level, msg));
1456
+ const attachments = () => ctx.get?.("attachments");
1457
+ const onAgent = (agent) => sink.track(agent);
1458
+ const offAgent = (agent) => sink.untrack(agent);
1459
+ ctx.on?.("agent/session-start", (payload) => onAgent(payload.agent));
1460
+ ctx.on?.("agent/inbox/inserted", (payload) => onAgent(payload.agent));
1461
+ ctx.on?.("agent/status", (payload) => {
1462
+ if (payload.status === "running") onAgent(payload.agent);
1463
+ });
1464
+ ctx.on?.("agent/disposed", (payload) => offAgent(payload.agent));
1465
+ let handle$1 = null;
1466
+ startLensServer({
1467
+ config,
1468
+ pairing,
1469
+ devices,
1470
+ hub,
1471
+ targets,
1472
+ sink,
1473
+ attachments,
1474
+ fallbackDir: join(dataDir, "uploads"),
1475
+ pendingDir: join(dataDir, "pending"),
1476
+ log
1477
+ }).then(async (h) => {
1478
+ handle$1 = h;
1479
+ const { code, expiresAt } = pairing.current();
1480
+ const qr = await buildPairingQr(code, expiresAt, config);
1481
+ process.stdout.write(`\n[phone-lens] 手机扫码配对(或浏览器打开 http://127.0.0.1:${h.port}/view.html):\n${qr.ascii}\n[phone-lens] 备用地址: ${qr.urls.join(" ")}\n\n`);
1482
+ }).catch((error) => {
1483
+ log("error", `receiver failed to start: ${String(error)} (check port ${config.server.port})`);
1484
+ });
1485
+ ctx.effect(() => () => {
1486
+ handle$1?.dispose();
1487
+ handle$1 = null;
1488
+ }, "phone-lens.server()");
1489
+ }
1490
+ };
1491
+
1492
+ //#endregion
1493
+ export { PhoneLens as default };
1494
+ //# sourceMappingURL=index.js.map