@dreamtree-org/harness-device 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -208,6 +208,7 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
208
208
  | `env_manage` | The app's `.env`. `list` shows names only. `set` takes a value or `from_secret` (copies a device secret without exposing it), and asks first |
209
209
  | `exec` | One program with an argv and no shell. The program must be on `EXEC_ALLOW` (a default list of dev tools); shells and wrappers such as `bash`, `env`, `sudo` or `xargs` are always refused. Runs in the app folder or a confined sub-folder. `env_refs` injects device secrets by name and redacts them from output. Timeout and output cap (head and tail kept). A durable job: `job_status` with `offset` streams new output, `job_cancel` kills the whole process tree. Never restarted. Linux holds the per-process caps in a systemd scope; on macOS the watchdog covers running jobs. Each run is recorded in `events` (program, folder, outcome, exit code, duration; never env or output) |
210
210
  | `workspace_create` / `workspace_list` / `workspace_status` / `workspace_archive` | Per-ticket workspaces of a cloned app. Each is a git worktree under `APPS_DIR/.worktrees/<app>/<ticket>` on branch `ticket/<TICKET>`, created from a pinned revision (`base`, default `origin/<branch>`; the SHA is recorded). It gets its own port (4100–4999, kept across retries) and is registered as the app `<app>--<ticket>`, so every app tool works on it. Creating it again returns the same workspace. Git operations on one repository are serialized by a lock. Archiving stops its process, removes the folder, frees the port and keeps the branch; uncommitted changes make it refuse unless the user agrees to discard them. `REPO_ALLOW` (owner/repo, owner/*) limits which repositories `git_clone` and workspaces accept. Per-workspace databases (`database: true`) answer BLOCKED until the shared development DB provisioner exists; no local database container is started instead |
211
+ | `preview_start` / `preview_list` / `preview_stop` / `preview_screenshot` | Protected previews of an app or workspace. Starts its dev server on its own port if nothing answers there and health-checks it; on failure it returns the app's last output and stops it. A per-preview proxy listens on 127.0.0.1 only and forwards to that one app port. Every request needs a token bound to the preview and its expiry, signed with a device key (`state/preview.key`). The link sets an HttpOnly cookie. The record is checked on each request, so a stopped preview is refused at once, and WebSocket upgrades are checked too. Reach it with the SSH tunnel command it returns. A public ngrok URL is opt-in (`public: true`, user-approved) and still needs the token. `preview_stop` revokes the link, stops the proxy, closes the tunnel and stops the app if the preview started it. Expired previews, and previews whose app or proxy is gone, are ended by `preview_list` and by every watchdog pass (`limits --enforce`). `preview_screenshot` (browser capability) loads it in the device browser and returns a PNG |
211
212
  | `shell_exec` (`app exec <app> -- <cmd>`) | One command in the app folder: up to 120s inline, otherwise as a job. Through the pool it needs `device:admin` |
212
213
  | `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
213
214
 
@@ -222,6 +223,11 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
222
223
  - A folder removed by hand: run `git worktree prune` in the app, then `workspace_create` again, which reuses the kept branch.
223
224
  - A stale `state/locks/git-<app>.lock` from a dead process is cleared automatically.
224
225
 
226
+ **Recovering a preview:**
227
+ - `harness-device preview` lists previews after reconciling them; `harness-device preview stop <id>` ends one.
228
+ - Records are in `state/previews/`, and the proxy logs are under the target `proc-preview-<id>`.
229
+ - Rotating `state/preview.key` (delete it) invalidates every outstanding link.
230
+
225
231
  ### Join a pool (HarnessPro)
226
232
 
227
233
  `harness-device join <hub> --enroll <secret>` adds this device to a HarnessPro pool. You don't type it yourself: the dashboard's **Connect a device** gives a one-time `curl … | bash` command that installs harness-device and runs it.
@@ -373,3 +379,17 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
373
379
  ---
374
380
 
375
381
  **Made with ❤️ by [Partha Preetham Krishna](https://www.linkedin.com/in/partha-preetham-krishna-68ba00197/)** under [Dreamtree-Org](https://www.dreamtreeglobal.com) · [www.dreamtreeglobal.com](https://www.dreamtreeglobal.com)
382
+
383
+ **Link health, readiness and leases:**
384
+ - **Heartbeats:** each link to the hub is a session, and every heartbeat carries a sequence number, so the hub drops beats that are replayed or out of order.
385
+ - Each beat also reports readiness separately from being connected: not stopped or restarting on purpose, not critical, and `POOL_SCOPES` allowing work. Placement uses only devices that are both online and ready.
386
+ - Each beat also reports the running jobs and processes, and the boot time; a reboot shows in the hub's audit.
387
+ - A device silent for 45s is offline, and no work goes to it.
388
+ - **Reconnects:** 1s, doubling to 60s while it fails, with jitter.
389
+ - **Leases:** every pool call with side effects carries a lease (id, a fence that only grows, expiry), and runs at most once:
390
+ - The device journals each lease in `state/leases/`. A lease delivered again is answered from the journal.
391
+ - An expired lease, or one older than the last finished, is refused.
392
+ - A dropped link does not stop a running call. After reconnecting, the hub asks for the leases it still waits on and the device answers from the journal.
393
+ - A call cut off by a restart or reboot is reported as uncertain and never re-run, so check the state before retrying.
394
+ - The hub refuses results for expired leases or with the wrong fence, and records them in the device's audit.
395
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamtree-org/harness-device",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Turn a Linux server into a reboot-proof Claude Code harness: Remote Control per project in tmux, a persistent Chromium + Playwright MCP on a virtual display, live viewers (noVNC, ttyd, Playwright UI), self-healing systemd services, plus Docker, Dokploy, ngrok and AI-provider tooling.",
5
5
  "author": {
6
6
  "name": "Partha Preetham Krishna",
@@ -113,6 +113,7 @@ Apps are repositories this device runs, in \`${cfg.APPS_DIR || '~/apps'}\`; unli
113
113
  - Files: \`file_read\` / \`file_write\` inside the app folder only; .git and .env are off limits. Environment: \`env_manage\` (names only; \`from_secret\` copies a device secret without you seeing it). Never put secrets in files or commands.
114
114
  - One-off programs: \`exec\` with an argv (no shell), e.g. \`{"app":"web","argv":["npm","test"]}\`. The program must be on the allowlist; secrets go in by name with \`env_refs\` and are redacted from output. Long runs come back as a job id: stream with \`job_status\` (offset), stop with \`job_cancel\`. Prefer it to \`proc_add\` for anything that should end, and to \`shell_exec\` whenever shell syntax isn't needed.
115
115
  - Per-ticket work: \`workspace_create {"app":"web","ticket":"HARNESS-5"}\` gives a git worktree on branch ticket/HARNESS-5 from a pinned base, with its own port, as the app \`web--harness-5\` (use it with exec, file_*, project_start…). \`workspace_status\` shows uncommitted files and commits ahead; \`workspace_archive\` keeps the branch and refuses to lose uncommitted work unless the user agrees.
116
+ - Previews: \`preview_start {"app":"web--harness-5"}\` starts the dev server if needed, health-checks it and returns an expiring link through an authenticating proxy (127.0.0.1; give the user the url and the ssh_tunnel command). Only with \`public: true\` (asks the user) does it get a public ngrok URL. \`preview_screenshot\` is evidence; \`preview_stop\` revokes the link.
116
117
  - \`shell_exec\` runs one shell command in an app folder; through the pool it needs device:admin.
117
118
  - Private GitHub repos use the device secret GITHUB_TOKEN; if it is missing, ask the user to set it (on the machine, or as a pool secret), never for the token itself.
118
119
 
package/src/cli.js CHANGED
@@ -276,6 +276,7 @@ export async function main(argv) {
276
276
  const ctx = loadContext(env);
277
277
  if (f.enforce) {
278
278
  const r = await limits.enforce(ctx);
279
+ try { for (const p of await (await import('./preview.js')).reconcile(ctx)) log.info(`preview ${p.id} ended: ${p.reason}`); } catch (e) { log.warn(`previews: ${e.message}`); }
279
280
  if (f.json) return console.log(JSON.stringify(r, null, 2));
280
281
  for (const a of r.actions) log.warn(`stopped ${a.name}: ${a.reason}`);
281
282
  if (!f.quiet && !r.actions.length) log.ok('all within limits');
@@ -337,6 +338,19 @@ export async function main(argv) {
337
338
  throw new Error('usage: harness-device app list|clone|pull|setup|start|stop|deploy|exec');
338
339
  }
339
340
 
341
+ case 'preview': {
342
+ const ctx = loadContext(env);
343
+ const preview = await import('./preview.js');
344
+ if (sub === 'proxy') {
345
+ await preview.serveProxy(ctx, rest[0]);
346
+ log.ok(`preview proxy ${rest[0]} listening`);
347
+ return new Promise(() => {}); // runs until its process is stopped
348
+ }
349
+ if (sub === 'stop') return console.log(JSON.stringify(await preview.stopPreview(ctx, { id: rest[0] }), null, 2));
350
+ await preview.reconcile(ctx);
351
+ return console.log(JSON.stringify(preview.listPreviews(ctx), null, 2));
352
+ }
353
+
340
354
  case 'job':
341
355
  case 'jobs': {
342
356
  const ctx = loadContext(env);
package/src/mcp/server.js CHANGED
@@ -20,6 +20,7 @@ import * as project from '../project.js';
20
20
  import * as jobs from '../jobs.js';
21
21
  import * as execMod from '../exec.js';
22
22
  import * as ws from '../workspace.js';
23
+ import * as preview from '../preview.js';
23
24
  import { Cancelled, NeedsUser, interaction } from './interact.js';
24
25
 
25
26
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
@@ -217,6 +218,39 @@ export function buildServer(env = process.env, opts = {}) {
217
218
  return text(await ws.archiveWorkspace(c, { name: a.workspace, force: !!a.discard_changes }));
218
219
  });
219
220
 
221
+ tool('preview_start', 'Preview an app or workspace (e.g. web--harness-5): starts its dev server on its own port if nothing answers there (command, else its start command), health-checks it (failures return the app\'s last output), and returns an expiring link through an authenticating proxy on this device (127.0.0.1 only: reach it with the ssh_tunnel command). public=true also opens a public ngrok URL, still behind the link\'s token; it asks the user first. Stop with preview_stop.',
222
+ { app: APP, command: z.string().max(500).optional(), ttl_minutes: z.number().int().min(1).max(10080).optional(), health_seconds: z.number().int().min(1).max(300).optional(),
223
+ health_path: z.string().regex(/^\/[^\s]{0,200}$/).optional(), public: z.boolean().optional(), ...CONFIRM, ...FORCE },
224
+ async (c, a, u) => {
225
+ await guard(c, a, `previewing ${a.app}`);
226
+ if (a.public) await u.confirm(`Open a public internet URL (ngrok) for the preview of ${a.app}? Anyone with the link can open it until it expires or is stopped.`);
227
+ await preview.reconcile(c);
228
+ try {
229
+ return text(await preview.startPreview(c, { app: a.app, command: a.command, ttlMinutes: a.ttl_minutes, healthSeconds: a.health_seconds, healthPath: a.health_path, public: !!a.public }));
230
+ } catch (e) {
231
+ if (e.logs !== undefined) return { isError: true, content: [{ type: 'text', text: e.message }] };
232
+ throw e;
233
+ }
234
+ });
235
+
236
+ tool('preview_list', 'Previews on this device: app, ports, expiry, public or not, status (stopped ones show why). Ends previews that expired or whose app went away. With id: a fresh link for an active preview.',
237
+ { id: z.string().regex(/^pv-[0-9a-f]{8}$/).optional() },
238
+ async (c, a) => {
239
+ await preview.reconcile(c);
240
+ if (a.id) { const p = preview.getPreview(c, a.id); if (!p) throw new Error(`No preview ${a.id}`); return text(p.status === 'active' ? preview.link(c, p) : p); }
241
+ return text(preview.listPreviews(c).slice(0, 30));
242
+ });
243
+
244
+ tool('preview_stop', 'Stop a preview: its link stops working at once, its proxy and public URL (if any) close, and the app stops too if the preview started it (keep_app=true leaves it running).',
245
+ { id: z.string().regex(/^pv-[0-9a-f]{8}$/), keep_app: z.boolean().optional() },
246
+ async (c, a) => text(await preview.stopPreview(c, { id: a.id, stopApp: !a.keep_app })));
247
+
248
+ if (has(base, 'browser')) {
249
+ tool('preview_screenshot', 'Evidence: open an active preview in the device browser and return a PNG of the page.',
250
+ { id: z.string().regex(/^pv-[0-9a-f]{8}$/), width: z.number().int().min(320).max(2560).optional(), height: z.number().int().min(240).max(2560).optional() },
251
+ async (c, a) => ({ content: [{ type: 'image', data: await preview.screenshot(c, a.id, { width: a.width, height: a.height }), mimeType: 'image/png' }] }));
252
+ }
253
+
220
254
  tool('job_cancel', 'Stop a running job (exec, clone, setup, deploy…): its whole process tree is terminated (TERM, then KILL after 5s); the job ends as cancelled.',
221
255
  { id: z.string().regex(/^[a-z0-9-]{6,40}$/) },
222
256
  async (c, a) => text(jobs.cancelJob(c, a.id)));
@@ -0,0 +1,126 @@
1
+ // Fenced execution leases (HARNESS-1), device side.
2
+ //
3
+ // The hub attaches a lease to every pool call with side effects:
4
+ // { id, fence, exp } id = the call id, fence = a number the hub only ever
5
+ // increases per device, exp = when the hub stops waiting.
6
+ //
7
+ // The device keeps a durable journal of leases (state/leases/<id>.json):
8
+ // started → done with the result. So:
9
+ // - A lease seen again (the hub re-sent it after a reconnect) is never run
10
+ // twice: a finished one is answered from the journal, one still running is
11
+ // answered when it finishes, and one that was interrupted (the device
12
+ // restarted mid-call) is reported as uncertain, not re-run.
13
+ // - An expired lease (delivered late, after the hub gave up) is refused, and
14
+ // so is a fence lower than the highest this device has finished (a delayed
15
+ // message from before a newer lease on the same work).
16
+ // - Results are sent on whatever link is current when the call ends; a result
17
+ // that finds no link waits in the journal for the hub's `reconcile`.
18
+
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+
22
+ const ID = /^[\w-]{6,64}$/;
23
+ const KEEP = 500;
24
+ const SKEW_MS = 30_000; // clock tolerance between hub and device
25
+ const inflight = new Map(); // lease id -> Promise<result> (this process only)
26
+
27
+ const dir = (ctx) => path.join(ctx.paths.state, 'leases');
28
+ const file = (ctx, id) => path.join(dir(ctx), `${id}.json`);
29
+
30
+ export function readLease(ctx, id) {
31
+ if (!ID.test(String(id || ''))) return null;
32
+ try { return JSON.parse(fs.readFileSync(file(ctx, id), 'utf8')); } catch { return null; }
33
+ }
34
+ function writeLease(ctx, rec) {
35
+ fs.mkdirSync(dir(ctx), { recursive: true });
36
+ const tmp = `${file(ctx, rec.id)}.${process.pid}.tmp`;
37
+ fs.writeFileSync(tmp, JSON.stringify(rec), { mode: 0o600 });
38
+ fs.renameSync(tmp, file(ctx, rec.id)); // atomic: a crash leaves the old or the new record
39
+ }
40
+
41
+ /** The highest fence of a finished lease (the device's high-water mark). */
42
+ export function highFence(ctx) {
43
+ try { return Number(fs.readFileSync(path.join(dir(ctx), 'HIGH'), 'utf8')) || 0; } catch { return 0; }
44
+ }
45
+ function raiseFence(ctx, fence) {
46
+ if (fence > highFence(ctx)) fs.writeFileSync(path.join(dir(ctx), 'HIGH'), String(fence));
47
+ }
48
+
49
+ function prune(ctx) {
50
+ const all = fs.readdirSync(dir(ctx)).filter((f) => f.endsWith('.json'));
51
+ if (all.length <= KEEP) return;
52
+ all.map((f) => ({ f, t: fs.statSync(path.join(dir(ctx), f)).mtimeMs })).sort((a, b) => a.t - b.t)
53
+ .slice(0, all.length - KEEP).forEach(({ f }) => fs.rmSync(path.join(dir(ctx), f), { force: true }));
54
+ }
55
+
56
+ const refused = (text, extra = {}) => ({ isError: true, content: [{ type: 'text', text }], ...extra });
57
+ export const UNCERTAIN = 'This call was interrupted before it finished (the device restarted or the call was cut off). It was not run again, so its effect is uncertain: check the state (job_status, app_list, logs) before retrying.';
58
+
59
+ /**
60
+ * Run `exec()` under a lease, at most once. Returns the result to send, or
61
+ * null when nothing should be sent now (a duplicate of a call still running:
62
+ * its result is sent when it ends).
63
+ */
64
+ export async function runLeased(ctx, lease, { tool, now = Date.now() }, exec) {
65
+ const id = String(lease.id || '');
66
+ const fence = Number(lease.fence);
67
+ if (!ID.test(id) || !Number.isSafeInteger(fence) || fence < 1) return refused('Malformed lease; not run.');
68
+ const prev = readLease(ctx, id);
69
+ if (prev) {
70
+ if (prev.status === 'done') return { ...prev.result, replayed: true };
71
+ if (inflight.has(id)) return null;
72
+ return refused(UNCERTAIN, { uncertain: true });
73
+ }
74
+ if (lease.exp && Number(lease.exp) + SKEW_MS < now) return refused(`Stale lease ${id}: it expired before it reached this device, so it was not run.`, { stale: true });
75
+ if (fence <= highFence(ctx)) return refused(`Stale lease ${id}: fence ${fence} is not newer than this device's last finished lease (${highFence(ctx)}); not run.`, { stale: true });
76
+
77
+ writeLease(ctx, { id, fence, tool, status: 'started', startedAt: new Date(now).toISOString(), pid: process.pid });
78
+ const p = (async () => {
79
+ let result;
80
+ try { result = await exec(); } catch (e) { result = refused(String(e?.message || e)); }
81
+ writeLease(ctx, { ...readLease(ctx, id), status: 'done', result, finishedAt: new Date().toISOString() });
82
+ raiseFence(ctx, fence);
83
+ try { prune(ctx); } catch { /* best effort */ }
84
+ return result;
85
+ })();
86
+ inflight.set(id, p);
87
+ try { return await p; } finally { inflight.delete(id); }
88
+ }
89
+
90
+ /** Is this lease still running in this process? (Its result will be sent when it ends.) */
91
+ export const running = (id) => inflight.has(String(id));
92
+ export const whenDone = (id) => inflight.get(String(id));
93
+
94
+ /**
95
+ * The hub's view after a reconnect: for each lease it still waits on, what to
96
+ * send back. done → the stored result; running here → nothing yet; unknown or
97
+ * interrupted → uncertain (never re-run).
98
+ */
99
+ export function reconcile(ctx, leases = []) {
100
+ const out = [];
101
+ for (const l of leases.slice(0, 200)) {
102
+ const id = String(l?.id || '');
103
+ if (!ID.test(id)) continue;
104
+ const rec = readLease(ctx, id);
105
+ if (rec?.status === 'done') out.push({ id, state: 'done', result: { ...rec.result, replayed: true } });
106
+ else if (inflight.has(id)) out.push({ id, state: 'running' });
107
+ else if (rec) out.push({ id, state: 'interrupted', result: refused(UNCERTAIN, { uncertain: true }) });
108
+ else out.push({ id, state: 'unknown', result: refused(`This device has no record of lease ${id}: it never arrived, so it was not run.`, { notRun: true }) });
109
+ }
110
+ return out;
111
+ }
112
+
113
+ /** Leases interrupted by a restart (started, not done, not running here): marked so on startup. */
114
+ export function markInterrupted(ctx) {
115
+ if (!fs.existsSync(dir(ctx))) return [];
116
+ const hit = [];
117
+ for (const f of fs.readdirSync(dir(ctx)).filter((x) => x.endsWith('.json'))) {
118
+ const rec = readLease(ctx, f.slice(0, -5));
119
+ if (rec?.status === 'started' && !inflight.has(rec.id)) {
120
+ writeLease(ctx, { ...rec, status: 'done', interrupted: true, result: refused(UNCERTAIN, { uncertain: true }), finishedAt: new Date().toISOString() });
121
+ raiseFence(ctx, rec.fence);
122
+ hit.push(rec.id);
123
+ }
124
+ }
125
+ return hit;
126
+ }
package/src/pool/link.js CHANGED
@@ -1,13 +1,19 @@
1
1
  // The `harness-pool` service: one outbound WebSocket to the pool hub.
2
2
  //
3
- // device → hub hello { version, device, caps, tools: [{name, description, inputSchema}] }
4
- // beat { resources, limits, max, counts, secretsVer, configVer } every 15s
5
- // result { id, result } per call
3
+ // device → hub hello { version, device, caps, tools, session, boot, highFence }
4
+ // beat { session, seq, boot, ready, resources, limits, max, counts, running, secretsVer, configVer } every 15s
5
+ // result { id, result, fence? } per call
6
6
  // synced { kind, report } after secrets/config
7
- // hub → device call { id, tool, args }
7
+ // hub → device call { id, tool, args, lease?: { id, fence, exp } }
8
+ // reconcile { leases: [{ id, fence }] } after a reconnect: what the hub still waits on
8
9
  // secrets { ver, values } config { ver, values }
9
10
  // disconnect
10
11
  //
12
+ // HARNESS-1: `seq` grows with every beat of a link `session`, so the hub can
13
+ // drop replayed or out-of-order beats; `ready` says whether this device can
14
+ // take work now (connected is not the same as ready). Calls with side effects
15
+ // carry a lease and run at most once (./leases.js).
16
+ //
11
17
  // Calls run through this device's own MCP server (buildServer) over an
12
18
  // in-memory transport, so every local rule applies unchanged: POOL_SCOPES
13
19
  // (set on the machine, never by the hub), confirmations, the resource gate,
@@ -23,7 +29,12 @@ import * as resources from '../resources.js';
23
29
  import * as limits from '../limits.js';
24
30
  import * as state from '../state.js';
25
31
  import path from 'node:path';
32
+ import os from 'node:os';
33
+ import crypto from 'node:crypto';
34
+ import fs from 'node:fs';
26
35
  import { PKG } from '../util.js';
36
+ import { isStopped } from '../lifecycle.js';
37
+ import * as leases from './leases.js';
27
38
  import { readPool, writePool } from './join.js';
28
39
  import { applySecrets, applyConfig, versions } from './sync.js';
29
40
 
@@ -40,17 +51,45 @@ export async function localTools(env) {
40
51
  await server.connect(a);
41
52
  const client = new Client({ name: 'harness-pool', version: PKG.version });
42
53
  await client.connect(b);
43
- return { client, close: () => client.close() };
54
+ // A dropped link must not cut off calls still running: close once the last one ends.
55
+ const t = { client, busy: 0, closing: false };
56
+ t.close = async () => { t.closing = true; if (t.busy === 0) await client.close(); };
57
+ t.done = () => { t.busy--; if (t.closing && t.busy === 0) client.close().catch(() => {}); };
58
+ return t;
44
59
  }
45
60
 
46
- async function beat(env) {
61
+ /** When this machine booted (ms, rounded): changes after a reboot. */
62
+ export const bootTime = () => Math.round((Date.now() - os.uptime() * 1000) / 10000) * 10000;
63
+
64
+ /**
65
+ * Can this device take new work now? Connected is not enough: it must not be
66
+ * stopped or restarting on purpose, critical on CPU/RAM/disk, or without the
67
+ * scope to run anything.
68
+ */
69
+ export function readiness(ctx, sample, { tools = 1 } = {}) {
70
+ const reasons = [];
71
+ const stopped = isStopped(ctx);
72
+ if (stopped) reasons.push(`stopped on purpose (${stopped.why || 'stop'})`);
73
+ if (fs.existsSync(path.join(ctx.paths.state, 'restarting'))) reasons.push('restarting');
74
+ if (sample?.level === 'critical') reasons.push(`critical: ${(sample.reasons || []).join('; ') || 'CPU, RAM or disk'}`);
75
+ if (!poolScopes(ctx.cfg).some((s) => s === 'device:operate' || s === 'device:admin')) reasons.push('POOL_SCOPES is read-only: it can be watched, not given work');
76
+ if (!tools) reasons.push('its tools did not start');
77
+ return { ok: reasons.length === 0, reasons };
78
+ }
79
+
80
+ async function beat(env, link = {}) {
47
81
  const ctx = loadContext(env);
48
82
  const s = await resources.sample(ctx, { quick: true });
49
83
  let gs = [];
50
84
  try { gs = limits.groups(ctx); } catch { /* no tmux yet */ }
51
85
  const l = limits.limits(ctx.cfg);
86
+ let runningJobs = [];
87
+ try { runningJobs = (await import('../jobs.js')).listJobs(ctx).filter((j) => j.status === 'running').map((j) => j.id).slice(0, 50); } catch { /* none */ }
52
88
  return {
53
89
  t: 'beat',
90
+ session: link.session, seq: link.seq ? ++link.seq.n : undefined, boot: bootTime(),
91
+ ready: readiness(ctx, s, { tools: link.tools ?? 1 }),
92
+ running: { jobs: runningJobs, procs: state.listProcs(ctx).filter((p) => p.running).map((p) => p.name).slice(0, 50) },
54
93
  resources: { level: s.level, reasons: s.reasons, cpu: s.cpu, memory: s.memory, disk: s.disk },
55
94
  limits: limits.report(ctx, gs),
56
95
  max: { reserveMem: l.reserveMem, harnessMem: l.harnessMem, procMem: l.procMem, procCpu: l.procCpu, maxSessions: l.maxSessions, maxProcs: l.maxProcs, cores: l.cores, totalMem: l.totalMem },
@@ -68,13 +107,28 @@ export async function handle(env, tools, msg, send) {
68
107
  const ctx = loadContext(env);
69
108
  switch (msg.t) {
70
109
  case 'call': {
71
- let result;
72
- try {
73
- result = await tools.client.callTool({ name: String(msg.tool), arguments: msg.args || {} }, undefined, { timeout: Math.min(Number(msg.timeoutMs) || 120000, 2 * 3600 * 1000) });
74
- } catch (e) {
75
- result = { isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] };
110
+ const run = async () => {
111
+ tools.busy = (tools.busy || 0) + 1;
112
+ try {
113
+ return await tools.client.callTool({ name: String(msg.tool), arguments: msg.args || {} }, undefined, { timeout: Math.min(Number(msg.timeoutMs) || 120000, 2 * 3600 * 1000) });
114
+ } catch (e) {
115
+ return { isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] };
116
+ } finally { if (tools.done) tools.done(); else tools.busy--; }
117
+ };
118
+ if (!msg.lease) { send({ t: 'result', id: msg.id, result: await run() }); return; }
119
+ const result = await leases.runLeased(ctx, msg.lease, { tool: String(msg.tool) }, run);
120
+ if (result?.stale) state.event(ctx, `pool: refused stale lease ${msg.lease.id} for ${msg.tool}`);
121
+ if (result) send({ t: 'result', id: msg.id, result, fence: Number(msg.lease.fence) });
122
+ return;
123
+ }
124
+ case 'reconcile': {
125
+ const out = leases.reconcile(ctx, Array.isArray(msg.leases) ? msg.leases : []);
126
+ const fenceOf = Object.fromEntries((msg.leases || []).map((l) => [String(l?.id), Number(l?.fence)]));
127
+ for (const r of out) {
128
+ if (r.state === 'running') leases.whenDone(r.id).then((res) => send({ t: 'result', id: r.id, result: res, fence: fenceOf[r.id] })).catch(() => {});
129
+ else send({ t: 'result', id: r.id, result: r.result, fence: fenceOf[r.id] });
76
130
  }
77
- send({ t: 'result', id: msg.id, result });
131
+ if (out.length) state.event(ctx, `pool: reconnect reconciled ${out.length} lease(s): ${out.map((r) => `${r.id} ${r.state}`).join(', ')}`);
78
132
  return;
79
133
  }
80
134
  case 'secrets': {
@@ -109,6 +163,12 @@ export async function handle(env, tools, msg, send) {
109
163
 
110
164
  /** Run the link until stopped: reconnects with backoff, stops for good when revoked or disconnected. */
111
165
  export async function runLink(env = process.env, { log = (m) => console.error(`[pool] ${m}`) } = {}) {
166
+ // Leased calls run inside this process: any left "started" were cut off by a restart or reboot.
167
+ try {
168
+ const ctx = loadContext(env);
169
+ const hit = leases.markInterrupted(ctx);
170
+ if (hit.length) { state.event(ctx, `pool: ${hit.length} lease(s) interrupted by a restart, marked uncertain (not re-run): ${hit.join(', ')}`); log(`${hit.length} interrupted lease(s) marked uncertain`); }
171
+ } catch (e) { log(`lease journal: ${e.message}`); }
112
172
  let delay = 1000;
113
173
  for (;;) {
114
174
  const p = readPool(loadContext(env).paths.pool);
@@ -120,14 +180,19 @@ export async function runLink(env = process.env, { log = (m) => console.error(`[
120
180
  const outcome = await connectOnce(env, p, log);
121
181
  if (outcome === 'stop') { log('disconnected by the hub; waiting to be joined again'); delay = 1000; continue; }
122
182
  if (outcome === 'revoked') { log('the hub revoked this device; join again to reconnect'); await new Promise((r) => setTimeout(r, 600000)); continue; }
123
- if (outcome === 'ok') delay = 1000;
124
- const wait = Math.round(delay * (0.5 + Math.random()));
125
- log(`reconnecting in ${Math.round(wait / 1000)}s`);
126
- await new Promise((r) => setTimeout(r, wait));
127
- delay = Math.min(delay * 2, 60000);
183
+ const b = backoff(delay, outcome);
184
+ log(`reconnecting in ${Math.round(b.wait / 1000)}s`);
185
+ await new Promise((r) => setTimeout(r, b.wait));
186
+ delay = b.next;
128
187
  }
129
188
  }
130
189
 
190
+ /** Reconnect backoff: 1s after a link that worked, doubling to 60s while it fails; ±50% jitter so a fleet doesn't reconnect at once. */
191
+ export function backoff(delay, outcome, rand = Math.random) {
192
+ const base = outcome === 'ok' ? 1000 : delay;
193
+ return { wait: Math.round(base * (0.5 + rand())), next: Math.min(base * 2, 60000) };
194
+ }
195
+
131
196
  /** One connection. Resolves 'ok' (was connected, then dropped), 'failed', 'revoked' or 'stop'. */
132
197
  export function connectOnce(env, p, log = () => {}) {
133
198
  return new Promise((resolve) => {
@@ -136,6 +201,7 @@ export function connectOnce(env, p, log = () => {}) {
136
201
  let tools;
137
202
  let timer;
138
203
  let connected = false;
204
+ const link = { session: crypto.randomBytes(8).toString('hex'), seq: { n: 0 }, tools: 0 };
139
205
  let stopped = false;
140
206
  const send = (m) => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(m)); };
141
207
  const finish = (how) => { clearInterval(timer); if (tools) tools.close().catch(() => {}); resolve(how); };
@@ -148,9 +214,10 @@ export function connectOnce(env, p, log = () => {}) {
148
214
  tools = await localTools(env);
149
215
  const list = (await tools.client.listTools()).tools.map((x) => ({ name: x.name, description: x.description, inputSchema: x.inputSchema }));
150
216
  const ctx = loadContext(env);
151
- send({ t: 'hello', version: PKG.version, device: ctx.cfg.DEVICE, caps: ctx.caps.map((c) => c.id), scopes: poolScopes(ctx.cfg), tools: list });
152
- send(await beat(env));
153
- timer = setInterval(() => { beat(env).then(send).catch((e) => log(`heartbeat failed: ${e.message}`)); }, BEAT_MS);
217
+ link.tools = list.length;
218
+ send({ t: 'hello', version: PKG.version, device: ctx.cfg.DEVICE, caps: ctx.caps.map((c) => c.id), scopes: poolScopes(ctx.cfg), tools: list, session: link.session, boot: bootTime(), highFence: leases.highFence(ctx) });
219
+ send(await beat(env, link));
220
+ timer = setInterval(() => { beat(env, link).then(send).catch((e) => log(`heartbeat failed: ${e.message}`)); }, Number(env.HD_POOL_BEAT_MS) || BEAT_MS);
154
221
  } catch (e) {
155
222
  log(`could not start the device tools: ${e.message}`);
156
223
  ws.close();
package/src/preview.js ADDED
@@ -0,0 +1,351 @@
1
+ // Protected application previews (HARNESS-9).
2
+ //
3
+ // preview_start runs an app (or workspace) on its own port, health-checks it,
4
+ // and puts a small authenticating proxy in front of it on another port:
5
+ //
6
+ // - The proxy only listens on 127.0.0.1 and only forwards to that one app
7
+ // port on 127.0.0.1. Reaching it from elsewhere means the SSH tunnel, or a
8
+ // public ngrok URL, which is opt-in (the user approves it).
9
+ // - Every request needs a token bound to this preview and an expiry, signed
10
+ // with a device key (state/preview.key). The link carries it once
11
+ // (?hd_preview=…); the proxy then sets an HttpOnly cookie and redirects to
12
+ // the clean URL. The preview record is re-read on each request, so a
13
+ // stopped preview is refused at once, even with an unexpired token.
14
+ // - preview_stop revokes it, stops the proxy, closes its tunnel and, if the
15
+ // preview started the app, the app. reconcile() (each watchdog pass and
16
+ // every preview_list) ends previews that expired or whose app went away.
17
+ // - preview_screenshot loads the preview in the device browser (CDP) and
18
+ // returns a PNG, as evidence.
19
+
20
+ import crypto from 'node:crypto';
21
+ import fs from 'node:fs';
22
+ import http from 'node:http';
23
+ import net from 'node:net';
24
+ import path from 'node:path';
25
+ import { spawn } from 'node:child_process';
26
+ import { getApp, saveApp, procName } from './apps.js';
27
+ import { allocatePort, releasePort } from './workspace.js';
28
+ import * as project from './project.js';
29
+ import * as state from './state.js';
30
+ import { PKG_ROOT } from './util.js';
31
+
32
+ const ID = /^pv-[0-9a-f]{8}$/;
33
+ const COOKIE = (id) => `hd_preview_${id.slice(3)}`;
34
+ const PARAM = 'hd_preview';
35
+ const dir = (ctx) => path.join(ctx.paths.state, 'previews');
36
+ const recFile = (ctx, id) => path.join(dir(ctx), `${id}.json`);
37
+ const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
38
+ const inline = (ctx) => ctx.env.HD_PREVIEW_INLINE === '1';
39
+ const servers = new Map(); // inline mode: id -> proxy server
40
+
41
+ function deviceKey(ctx) {
42
+ const f = path.join(ctx.paths.state, 'preview.key');
43
+ if (!fs.existsSync(f)) {
44
+ fs.mkdirSync(path.dirname(f), { recursive: true });
45
+ try { fs.writeFileSync(f, crypto.randomBytes(32).toString('hex'), { mode: 0o600, flag: 'wx' }); } catch (e) { if (e.code !== 'EEXIST') throw e; }
46
+ }
47
+ return Buffer.from(fs.readFileSync(f, 'utf8').trim(), 'hex');
48
+ }
49
+
50
+ const sign = (ctx, body) => crypto.createHmac('sha256', deviceKey(ctx)).update(body).digest('base64url');
51
+ export const makeToken = (ctx, id, exp) => `${id}.${exp}.${sign(ctx, `${id}.${exp}`)}`;
52
+
53
+ /** { ok, reason } for a token presented to preview `id`. */
54
+ export function checkToken(ctx, id, token, now = Date.now()) {
55
+ const [tid, exp, sig] = String(token || '').split('.');
56
+ if (!tid || !exp || !sig) return { ok: false, reason: 'no preview token' };
57
+ const want = Buffer.from(sign(ctx, `${tid}.${exp}`));
58
+ const got = Buffer.from(sig);
59
+ if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { ok: false, reason: 'invalid preview token' };
60
+ if (tid !== id) return { ok: false, reason: 'this token is for another preview' };
61
+ if (Number(exp) <= now) return { ok: false, reason: 'preview link expired' };
62
+ const rec = getPreview(ctx, id);
63
+ if (!rec || rec.status !== 'active') return { ok: false, reason: 'preview stopped' };
64
+ if (Date.parse(rec.expiresAt) <= now) return { ok: false, reason: 'preview link expired' };
65
+ return { ok: true, rec };
66
+ }
67
+
68
+ export function getPreview(ctx, id) {
69
+ if (!ID.test(String(id || ''))) return null;
70
+ try { return JSON.parse(fs.readFileSync(recFile(ctx, id), 'utf8')); } catch { return null; }
71
+ }
72
+ function savePreview(ctx, rec) {
73
+ fs.mkdirSync(dir(ctx), { recursive: true });
74
+ const tmp = `${recFile(ctx, rec.id)}.${process.pid}.tmp`;
75
+ fs.writeFileSync(tmp, JSON.stringify(rec, null, 2), { mode: 0o600 });
76
+ fs.renameSync(tmp, recFile(ctx, rec.id));
77
+ return rec;
78
+ }
79
+ export function listPreviews(ctx) {
80
+ if (!fs.existsSync(dir(ctx))) return [];
81
+ return fs.readdirSync(dir(ctx)).filter((f) => f.endsWith('.json')).map((f) => getPreview(ctx, f.slice(0, -5))).filter(Boolean)
82
+ .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
83
+ }
84
+
85
+ /** Any HTTP answer below 500 on 127.0.0.1:port within `seconds`. */
86
+ export async function waitHealthy(port, seconds = 60, pathName = '/') {
87
+ const deadline = Date.now() + seconds * 1000;
88
+ for (;;) {
89
+ const code = await new Promise((resolve) => {
90
+ const r = http.get({ host: '127.0.0.1', port, path: pathName, timeout: 2000 }, (res) => { res.resume(); resolve(res.statusCode); });
91
+ r.on('error', () => resolve(0)); r.on('timeout', () => { r.destroy(); resolve(0); });
92
+ });
93
+ if (code && code < 500) return code;
94
+ if (Date.now() >= deadline) return 0;
95
+ await new Promise((r) => setTimeout(r, 500));
96
+ }
97
+ }
98
+
99
+ const procLog = (ctx, name) => path.join(ctx.paths.logs, `proc-${name}.log`);
100
+ function tailOf(file, lines = 40) {
101
+ if (!fs.existsSync(file)) return '(no output yet)';
102
+ return fs.readFileSync(file, 'utf8').split('\n').slice(-lines).join('\n').trim() || '(no output)';
103
+ }
104
+
105
+ /** Register a process; inline (tests) it is spawned here with the same log file the tmux window would use. */
106
+ function runProc(ctx, name, cwd, command) {
107
+ if (!inline(ctx)) return state.addProc(ctx, name, cwd, command);
108
+ fs.mkdirSync(ctx.paths.logs, { recursive: true });
109
+ const fd = fs.openSync(procLog(ctx, name), 'a');
110
+ const child = spawn('sh', ['-c', command], { cwd, env: ctx.env, detached: true, stdio: ['ignore', fd, fd] });
111
+ child.unref();
112
+ fs.closeSync(fd);
113
+ fs.mkdirSync(path.join(ctx.paths.state, 'inline-procs'), { recursive: true });
114
+ fs.writeFileSync(path.join(ctx.paths.state, 'inline-procs', name), String(child.pid));
115
+ }
116
+ function stopProc(ctx, name) {
117
+ if (!inline(ctx)) { try { state.removeProc(ctx, name); } catch { /* already gone */ } return; }
118
+ const f = path.join(ctx.paths.state, 'inline-procs', name);
119
+ if (!fs.existsSync(f)) return;
120
+ try { process.kill(-Number(fs.readFileSync(f, 'utf8')), 'SIGTERM'); } catch { /* gone */ }
121
+ fs.rmSync(f, { force: true });
122
+ }
123
+ const procKnown = (ctx, name) => (inline(ctx) ? fs.existsSync(path.join(ctx.paths.state, 'inline-procs', name)) : state.listProcs(ctx).some((p) => p.name === name));
124
+
125
+ export async function startPreview(ctx, { app: name, ttlMinutes = 60, healthSeconds = 60, command, healthPath = '/', public: pub = false, publish = null }) {
126
+ let app = getApp(ctx, name);
127
+ const ttl = Math.max(1, Math.min(Number(ttlMinutes) || 60, 7 * 24 * 60));
128
+ const port = app.port || await allocatePort(ctx, app.name);
129
+ if (!app.project && app.port !== port) app = saveApp(ctx, { ...app, port });
130
+
131
+ // Start the app unless something already answers on its port.
132
+ let startedApp = false;
133
+ if (!(await waitHealthy(port, 0, healthPath))) {
134
+ const cmd = command || app.startOverride || app.start;
135
+ if (!cmd) throw new Error(`No start command known for ${app.name}: give command (e.g. "npm run dev")`);
136
+ if (inline(ctx)) runProc(ctx, procName(app), app.dir, project.startLine(cmd, port));
137
+ else project.start(ctx, { app: app.name, command, port });
138
+ startedApp = true;
139
+ if (!(await waitHealthy(port, healthSeconds, healthPath))) {
140
+ const logs = tailOf(procLog(ctx, procName(app)));
141
+ stopProc(ctx, procName(app));
142
+ state.event(ctx, `preview of ${app.name}: health check failed on port ${port}; app stopped`);
143
+ const err = new Error(`${app.name} did not answer on http://127.0.0.1:${port}${healthPath} within ${healthSeconds}s, so it was stopped. Last output:\n${logs}`);
144
+ err.logs = logs;
145
+ throw err;
146
+ }
147
+ }
148
+
149
+ const id = `pv-${crypto.randomBytes(4).toString('hex')}`;
150
+ const proxyPort = await allocatePort(ctx, `preview-${id}`);
151
+ const expiresAt = new Date(Date.now() + ttl * 60000).toISOString();
152
+ const rec = savePreview(ctx, {
153
+ id, app: app.name, ticket: app.workspace?.ticket || null, appPort: port, proxyPort, startedApp,
154
+ status: 'active', public: false, publicUrl: null, createdAt: new Date().toISOString(), expiresAt,
155
+ });
156
+ if (inline(ctx)) servers.set(id, await serveProxy(ctx, id));
157
+ else {
158
+ state.addProc(ctx, `preview-${id}`, app.dir, `HARNESS_DEVICE_HOME=${q(ctx.paths.home)} exec ${q(process.execPath)} ${q(path.join(PKG_ROOT, 'bin', 'harness-device.js'))} preview proxy ${id}`);
159
+ if (!(await waitPort(proxyPort, 15))) { await stopPreview(ctx, { id, reason: 'proxy did not start', stopApp: startedApp }); throw new Error(`The preview proxy did not start (logs: proc-preview-${id})`); }
160
+ }
161
+ if (pub) {
162
+ const r = await (publish || defaultPublish)(ctx, proxyPort);
163
+ savePreview(ctx, { ...getPreview(ctx, id), public: true, publicUrl: r.url || null });
164
+ }
165
+ state.event(ctx, `preview ${id} of ${app.name}: app port ${port}, proxy ${proxyPort}, expires ${expiresAt}${pub ? ', public URL opened' : ''}`);
166
+ return link(ctx, getPreview(ctx, id));
167
+ }
168
+
169
+ /** The links for a preview (a fresh token valid until the preview expires). */
170
+ export function link(ctx, rec) {
171
+ const token = makeToken(ctx, rec.id, Date.parse(rec.expiresAt));
172
+ return {
173
+ id: rec.id, app: rec.app, ticket: rec.ticket, app_port: rec.appPort, proxy_port: rec.proxyPort, expires_at: rec.expiresAt,
174
+ url: `http://127.0.0.1:${rec.proxyPort}/?${PARAM}=${token}`,
175
+ ssh_tunnel: `ssh -N -L ${rec.proxyPort}:127.0.0.1:${rec.proxyPort} <user>@<this-machine> (then open the url on your computer)`,
176
+ ...(rec.publicUrl ? { public_url: `${rec.publicUrl}/?${PARAM}=${token}` } : {}),
177
+ };
178
+ }
179
+
180
+ async function defaultPublish(ctx, port) {
181
+ const device = await import('./device.js');
182
+ const r = await device.ngrokUp(ctx, { ports: [port] });
183
+ const t = r.tunnels.find((x) => String(x.addr || '').endsWith(`:${port}`) || x.name === `app${port}`);
184
+ return { url: t ? t.url : null };
185
+ }
186
+
187
+ async function defaultUnpublish(ctx, stillPublic) {
188
+ const device = await import('./device.js');
189
+ if (stillPublic.length) await device.ngrokUp(ctx, { tunnels: stillPublic.map((p) => `app${p.proxyPort}`) });
190
+ else ctx.platform.ngrokDown(ctx);
191
+ }
192
+
193
+ export async function stopPreview(ctx, { id, reason = 'stopped', stopApp = true, unpublish = null }) {
194
+ const rec = getPreview(ctx, id);
195
+ if (!rec) throw new Error(`No preview ${id}`);
196
+ const closeInline = async () => {
197
+ const srv = servers.get(id);
198
+ if (!srv) return;
199
+ servers.delete(id);
200
+ await new Promise((r) => { srv.close(r); srv.closeAllConnections(); });
201
+ };
202
+ if (rec.status !== 'active') { await closeInline(); return { id, status: rec.status, note: 'already stopped' }; }
203
+ savePreview(ctx, { ...rec, status: 'stopped', stoppedAt: new Date().toISOString(), stopReason: reason });
204
+ await closeInline();
205
+ stopProc(ctx, `preview-${id}`);
206
+ releasePort(ctx, `preview-${id}`);
207
+ let tunnel = 'none';
208
+ if (rec.public) {
209
+ const still = listPreviews(ctx).filter((p) => p.status === 'active' && p.public);
210
+ await (unpublish || defaultUnpublish)(ctx, still);
211
+ tunnel = still.length ? 'closed (other public previews kept)' : 'closed';
212
+ }
213
+ let app = 'left running';
214
+ const others = listPreviews(ctx).some((p) => p.status === 'active' && p.app === rec.app);
215
+ if (stopApp && rec.startedApp && !others) {
216
+ try { const a = getApp(ctx, rec.app); stopProc(ctx, procName(a)); app = 'stopped'; } catch { app = 'gone'; }
217
+ }
218
+ state.event(ctx, `preview ${id} of ${rec.app} ${reason}: link revoked, tunnel ${tunnel}, app ${app}`);
219
+ return { id, status: 'stopped', reason, tunnel, app };
220
+ }
221
+
222
+ /** End previews that expired or whose app or proxy went away. */
223
+ export async function reconcile(ctx, opts = {}) {
224
+ const changed = [];
225
+ for (const p of listPreviews(ctx).filter((x) => x.status === 'active')) {
226
+ let reason = null;
227
+ if (Date.parse(p.expiresAt) <= Date.now()) reason = 'expired';
228
+ else if (!procKnown(ctx, `preview-${p.id}`) && !servers.has(p.id)) reason = 'proxy gone';
229
+ else {
230
+ let appProc = false;
231
+ try { appProc = procKnown(ctx, procName(getApp(ctx, p.app))); } catch { /* app removed */ }
232
+ if (!appProc && !(await waitHealthy(p.appPort, 0))) reason = 'app gone';
233
+ }
234
+ if (reason) changed.push(await stopPreview(ctx, { id: p.id, reason, ...opts }));
235
+ }
236
+ return changed;
237
+ }
238
+
239
+ async function waitPort(port, seconds) {
240
+ const deadline = Date.now() + seconds * 1000;
241
+ while (Date.now() < deadline) {
242
+ const up = await new Promise((r) => { const s = net.connect(port, '127.0.0.1', () => { s.end(); r(true); }); s.on('error', () => r(false)); });
243
+ if (up) return true;
244
+ await new Promise((r) => setTimeout(r, 250));
245
+ }
246
+ return false;
247
+ }
248
+
249
+ function cookieOf(req, name) {
250
+ for (const part of String(req.headers.cookie || '').split(';')) {
251
+ const [k, ...v] = part.trim().split('=');
252
+ if (k === name) return v.join('=');
253
+ }
254
+ return '';
255
+ }
256
+ function stripCookie(header, name) {
257
+ const kept = String(header || '').split(';').map((s) => s.trim()).filter((s) => s && !s.startsWith(`${name}=`));
258
+ return kept.length ? kept.join('; ') : undefined;
259
+ }
260
+
261
+ /** The proxy for one preview: 127.0.0.1:proxyPort → 127.0.0.1:appPort, token required. */
262
+ export function serveProxy(ctx, id) {
263
+ const rec = getPreview(ctx, id);
264
+ if (!rec) throw new Error(`No preview ${id}`);
265
+ const name = COOKIE(id);
266
+ const auth = (req) => {
267
+ const u = new URL(req.url, 'http://x');
268
+ const fromQuery = u.searchParams.get(PARAM);
269
+ const c = checkToken(ctx, id, fromQuery || cookieOf(req, name));
270
+ return { ...c, fromQuery, u };
271
+ };
272
+ const server = http.createServer((req, res) => {
273
+ const a = auth(req);
274
+ if (!a.ok) { res.writeHead(401, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }); return res.end(`Preview access denied: ${a.reason}.\n`); }
275
+ if (a.fromQuery) {
276
+ a.u.searchParams.delete(PARAM);
277
+ const maxAge = Math.max(1, Math.floor((Date.parse(a.rec.expiresAt) - Date.now()) / 1000));
278
+ res.writeHead(302, { location: `${a.u.pathname}${a.u.search}`, 'set-cookie': `${name}=${a.fromQuery}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${maxAge}`, 'cache-control': 'no-store' });
279
+ return res.end();
280
+ }
281
+ const headers = { ...req.headers, host: `127.0.0.1:${a.rec.appPort}` };
282
+ const ck = stripCookie(req.headers.cookie, name);
283
+ if (ck) headers.cookie = ck; else delete headers.cookie;
284
+ const up = http.request({ host: '127.0.0.1', port: a.rec.appPort, method: req.method, path: req.url, headers }, (r) => {
285
+ res.writeHead(r.statusCode, r.headers);
286
+ r.pipe(res);
287
+ });
288
+ up.on('error', (e) => { if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain' }); res.end(`The app is not answering: ${e.code || e.message}\n`); });
289
+ req.pipe(up);
290
+ });
291
+ // WebSockets (dev-server reload): same check, then a raw pipe to the app.
292
+ server.on('upgrade', (req, socket, head) => {
293
+ const a = auth(req);
294
+ if (!a.ok || a.fromQuery) { socket.end('HTTP/1.1 401 Unauthorized\r\n\r\n'); return; }
295
+ const upstream = net.connect(a.rec.appPort, '127.0.0.1', () => {
296
+ const ck = stripCookie(req.headers.cookie, name);
297
+ const lines = [`${req.method} ${req.url} HTTP/1.1`];
298
+ for (const [k, v] of Object.entries({ ...req.headers, host: `127.0.0.1:${a.rec.appPort}` })) {
299
+ if (k === 'cookie') { if (ck) lines.push(`cookie: ${ck}`); continue; }
300
+ for (const one of [].concat(v)) lines.push(`${k}: ${one}`);
301
+ }
302
+ upstream.write(`${lines.join('\r\n')}\r\n\r\n`);
303
+ if (head && head.length) upstream.write(head);
304
+ upstream.pipe(socket); socket.pipe(upstream);
305
+ });
306
+ upstream.on('error', () => socket.destroy());
307
+ socket.on('error', () => upstream.destroy());
308
+ });
309
+ return new Promise((resolve, reject) => {
310
+ server.once('error', reject);
311
+ server.listen(rec.proxyPort, '127.0.0.1', () => resolve(server));
312
+ });
313
+ }
314
+
315
+ /** Load the preview in the device browser over CDP and return a PNG (base64). */
316
+ export async function screenshot(ctx, id, { width = 1280, height = 800, waitMs = 1500 } = {}) {
317
+ const rec = getPreview(ctx, id);
318
+ if (!rec || rec.status !== 'active') throw new Error(`No active preview ${id}`);
319
+ const { default: WebSocket } = await import('ws');
320
+ const base = `http://127.0.0.1:${ctx.cfg.CDP_PORT}`;
321
+ const target = await fetch(`${base}/json/new?about:blank`, { method: 'PUT' }).then((r) => r.json()).catch(() => null);
322
+ if (!target?.webSocketDebuggerUrl) throw new Error(`The device browser is not reachable on ${base} (browser capability off, or browser_restart it)`);
323
+ const ws = new WebSocket(target.webSocketDebuggerUrl);
324
+ let n = 0;
325
+ const pending = new Map();
326
+ const events = [];
327
+ ws.on('message', (m) => {
328
+ const msg = JSON.parse(m);
329
+ if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } else if (msg.method) events.push(msg.method);
330
+ });
331
+ const send = (method, params = {}) => new Promise((resolve, reject) => {
332
+ const i = ++n;
333
+ pending.set(i, (msg) => (msg.error ? reject(new Error(`${method}: ${msg.error.message}`)) : resolve(msg.result)));
334
+ ws.send(JSON.stringify({ id: i, method, params }));
335
+ });
336
+ try {
337
+ await new Promise((r, j) => { ws.once('open', r); ws.once('error', j); });
338
+ await send('Page.enable');
339
+ await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
340
+ await send('Page.navigate', { url: link(ctx, rec).url });
341
+ const until = Date.now() + 15000;
342
+ while (!events.includes('Page.loadEventFired') && Date.now() < until) await new Promise((r) => setTimeout(r, 100));
343
+ await new Promise((r) => setTimeout(r, waitMs));
344
+ const shot = await send('Page.captureScreenshot', { format: 'png' });
345
+ state.event(ctx, `preview ${id}: screenshot taken`);
346
+ return shot.data;
347
+ } finally {
348
+ ws.close();
349
+ await fetch(`${base}/json/close/${target.id}`).catch(() => {});
350
+ }
351
+ }
@@ -12,10 +12,10 @@ const ORDER = ['device:read', 'device:operate', 'device:admin'];
12
12
 
13
13
  const TOOLS = {
14
14
  'device:read': ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs', 'resources', 'screenshot', 'docker_summary', 'ngrok_status', 'config_get',
15
- 'app_list', 'file_read', 'job_status', 'workspace_list', 'workspace_status'],
15
+ 'app_list', 'file_read', 'job_status', 'workspace_list', 'workspace_status', 'preview_list', 'preview_screenshot'],
16
16
  'device:operate': ['proc_add', 'proc_remove', 'session_new', 'restart_service', 'browser_restart', 'run_tests_live', 'playwright_ui', 'ngrok_up', 'ngrok_down', 'disk_cleanup', 'docker_limit',
17
17
  'git_clone', 'git_pull', 'project_setup', 'project_start', 'project_stop', 'project_deploy', 'file_write', 'env_manage',
18
- 'exec', 'job_cancel', 'workspace_create', 'workspace_archive'],
18
+ 'exec', 'job_cancel', 'workspace_create', 'workspace_archive', 'preview_start', 'preview_stop'],
19
19
  // shell_exec is not listed: it needs device:admin (unknown tools do).
20
20
  };
21
21