@dreamtree-org/harness-device 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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.
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.6.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)));
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