turno-browser 0.3.0 → 0.4.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.
Files changed (94) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +32 -3
  3. package/dist/act-model.d.ts +85 -0
  4. package/dist/act-model.js +116 -0
  5. package/dist/act.d.ts +37 -0
  6. package/dist/act.js +599 -0
  7. package/dist/api.d.ts +29 -2
  8. package/dist/api.js +29 -2
  9. package/dist/argv.d.ts +16 -2
  10. package/dist/argv.js +100 -3
  11. package/dist/batch.d.ts +5 -0
  12. package/dist/batch.js +3 -3
  13. package/dist/bin/mcp.js +58 -1
  14. package/dist/captcha.d.ts +77 -0
  15. package/dist/captcha.js +333 -0
  16. package/dist/cdp-relay.d.ts +20 -0
  17. package/dist/cdp-relay.js +101 -0
  18. package/dist/chrome-features.d.ts +23 -0
  19. package/dist/chrome-features.js +44 -0
  20. package/dist/diagnose.d.ts +7 -0
  21. package/dist/diagnose.js +61 -6
  22. package/dist/doctor.d.ts +37 -3
  23. package/dist/doctor.js +230 -5
  24. package/dist/engine-attach.d.ts +27 -0
  25. package/dist/engine-attach.js +165 -0
  26. package/dist/engine-camoufox.d.ts +32 -0
  27. package/dist/engine-camoufox.js +270 -0
  28. package/dist/engine-lightpanda.d.ts +72 -0
  29. package/dist/engine-lightpanda.js +292 -0
  30. package/dist/engine.d.ts +63 -11
  31. package/dist/engine.js +104 -28
  32. package/dist/flows.d.ts +127 -0
  33. package/dist/flows.js +294 -0
  34. package/dist/governor.d.ts +42 -7
  35. package/dist/governor.js +82 -32
  36. package/dist/host.d.ts +17 -2
  37. package/dist/host.js +618 -41
  38. package/dist/human-input.d.ts +84 -0
  39. package/dist/human-input.js +443 -0
  40. package/dist/humanize.d.ts +123 -0
  41. package/dist/humanize.js +241 -0
  42. package/dist/identities.js +2 -0
  43. package/dist/idle-timer.d.ts +12 -0
  44. package/dist/idle-timer.js +25 -0
  45. package/dist/index.d.ts +8 -3
  46. package/dist/index.js +5 -1
  47. package/dist/lifecycle.d.ts +9 -1
  48. package/dist/lifecycle.js +9 -1
  49. package/dist/live-client.d.ts +22 -0
  50. package/dist/live-client.js +93 -0
  51. package/dist/live-page.d.ts +11 -0
  52. package/dist/live-page.js +143 -0
  53. package/dist/live-server.d.ts +173 -0
  54. package/dist/live-server.js +640 -0
  55. package/dist/live.d.ts +120 -0
  56. package/dist/live.js +203 -0
  57. package/dist/login-tool.d.ts +13 -0
  58. package/dist/login-tool.js +5 -1
  59. package/dist/login.d.ts +4 -1
  60. package/dist/login.js +11 -2
  61. package/dist/network-chrome.d.ts +74 -0
  62. package/dist/network-chrome.js +178 -0
  63. package/dist/network.d.ts +125 -0
  64. package/dist/network.js +263 -0
  65. package/dist/opt-in-settings.d.ts +69 -0
  66. package/dist/opt-in-settings.js +151 -0
  67. package/dist/recorder.d.ts +88 -0
  68. package/dist/recorder.js +538 -0
  69. package/dist/recordings.d.ts +116 -0
  70. package/dist/recordings.js +474 -0
  71. package/dist/redact.d.ts +7 -0
  72. package/dist/redact.js +18 -0
  73. package/dist/replay.d.ts +20 -0
  74. package/dist/replay.js +382 -0
  75. package/dist/reputation.d.ts +24 -2
  76. package/dist/reputation.js +63 -17
  77. package/dist/session-export.js +1 -1
  78. package/dist/session.d.ts +10 -2
  79. package/dist/session.js +10 -2
  80. package/dist/settings.d.ts +104 -2
  81. package/dist/settings.js +204 -6
  82. package/dist/sharing.d.ts +96 -0
  83. package/dist/sharing.js +269 -0
  84. package/dist/snippet.d.ts +8 -2
  85. package/dist/snippet.js +10 -4
  86. package/dist/tab-locks.d.ts +63 -0
  87. package/dist/tab-locks.js +179 -0
  88. package/dist/tools.d.ts +38 -0
  89. package/dist/tools.js +20 -1
  90. package/dist/tuning.d.ts +14 -0
  91. package/dist/tuning.js +9 -0
  92. package/dist/upstream.d.ts +11 -0
  93. package/npm-shrinkwrap.json +2 -2
  94. package/package.json +1 -1
@@ -0,0 +1,640 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { createServer } from "node:http";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { PauseGate, liveFilePath } from "./live.js";
7
+ import { deniedPage, livePage } from "./live-page.js";
8
+ /** How long a link's code works. */
9
+ const CODE_MS = 2 * 60_000;
10
+ /** Largest request body accepted. */
11
+ const MAX_BODY = 16 * 1024;
12
+ /** Keys the view may press besides plain characters. */
13
+ const KEYS = new Set([
14
+ "Enter",
15
+ "Backspace",
16
+ "Tab",
17
+ "Escape",
18
+ "Delete",
19
+ "ArrowUp",
20
+ "ArrowDown",
21
+ "ArrowLeft",
22
+ "ArrowRight",
23
+ "Home",
24
+ "End",
25
+ "PageUp",
26
+ "PageDown",
27
+ ]);
28
+ class HttpError extends Error {
29
+ status;
30
+ constructor(status, message) {
31
+ super(message);
32
+ this.status = status;
33
+ }
34
+ }
35
+ function plainUrl(url) {
36
+ try {
37
+ const u = new URL(url);
38
+ return u.protocol === "http:" || u.protocol === "https:" ? `${u.origin}${u.pathname}` : u.protocol;
39
+ }
40
+ catch {
41
+ return "";
42
+ }
43
+ }
44
+ async function titleOf(page) {
45
+ let timer;
46
+ const late = new Promise((r) => {
47
+ timer = setTimeout(() => r(""), 1_000);
48
+ });
49
+ try {
50
+ return await Promise.race([page.title().catch(() => ""), late]);
51
+ }
52
+ finally {
53
+ clearTimeout(timer);
54
+ }
55
+ }
56
+ function sameSecret(a, b) {
57
+ const x = Buffer.from(a);
58
+ const y = Buffer.from(b);
59
+ return x.length === y.length && timingSafeEqual(x, y);
60
+ }
61
+ async function readJson(req) {
62
+ const chunks = [];
63
+ let size = 0;
64
+ for await (const chunk of req) {
65
+ size += chunk.length;
66
+ if (size > MAX_BODY)
67
+ throw new HttpError(413, "request body too large");
68
+ chunks.push(chunk);
69
+ }
70
+ if (!size)
71
+ return {};
72
+ try {
73
+ const v = JSON.parse(Buffer.concat(chunks).toString("utf8"));
74
+ if (typeof v === "object" && v !== null && !Array.isArray(v))
75
+ return v;
76
+ }
77
+ catch {
78
+ /* below */
79
+ }
80
+ throw new HttpError(400, "the body must be a JSON object");
81
+ }
82
+ function listen(server, ...args) {
83
+ return new Promise((resolve, reject) => {
84
+ server.once("error", reject);
85
+ server.listen(...args, () => {
86
+ server.off("error", reject);
87
+ resolve();
88
+ });
89
+ });
90
+ }
91
+ const num = (v, min, max) => {
92
+ if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max)
93
+ throw new HttpError(400, `expected a number from ${min} to ${max}`);
94
+ return v;
95
+ };
96
+ export class LiveServer {
97
+ o;
98
+ gate = new PauseGate();
99
+ browser;
100
+ /** The browser `onPause` was called for, so `onResume` goes to the same one. */
101
+ heldBrowser;
102
+ lastBySession = new Map();
103
+ last;
104
+ pinned;
105
+ busy = 0;
106
+ ids = new WeakMap();
107
+ nextId = 1;
108
+ viewers = new Set();
109
+ cast;
110
+ casting = Promise.resolve();
111
+ hidden = false;
112
+ token = randomBytes(32).toString("base64url");
113
+ codes = new Map();
114
+ tcp;
115
+ unix;
116
+ port = 0;
117
+ socketDir;
118
+ started = "";
119
+ queued = false;
120
+ heartbeat;
121
+ closed = false;
122
+ onExit = () => this.cleanupFiles();
123
+ constructor(o) {
124
+ this.o = o;
125
+ }
126
+ get paused() {
127
+ return this.gate.paused !== undefined;
128
+ }
129
+ get waitMs() {
130
+ return this.o.policy.waitMs;
131
+ }
132
+ /** The control socket path (tests). */
133
+ get socket() {
134
+ return this.socketDir && join(this.socketDir, "control.sock");
135
+ }
136
+ get cookieName() {
137
+ return `turno-live-${this.port}`;
138
+ }
139
+ starting;
140
+ /** Listens on the socket and on 127.0.0.1, and writes live.json (once). */
141
+ start() {
142
+ this.starting ??= this.listenAll();
143
+ return this.starting;
144
+ }
145
+ async listenAll() {
146
+ this.socketDir = mkdtempSync(join(tmpdir(), "turno-live-"));
147
+ chmodSync(this.socketDir, 0o700);
148
+ const socket = this.socket;
149
+ this.unix = createServer((req, res) => void this.handle(req, res, true));
150
+ await listen(this.unix, socket);
151
+ chmodSync(socket, 0o600);
152
+ this.tcp = createServer((req, res) => void this.handle(req, res, false));
153
+ await listen(this.tcp, 0, "127.0.0.1");
154
+ this.port = this.tcp.address().port;
155
+ // The live view never keeps the server process alive on its own.
156
+ this.unix.unref();
157
+ this.tcp.unref();
158
+ this.started = new Date().toISOString();
159
+ const file = liveFilePath(this.o.identity.id, this.o.identity.env);
160
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
161
+ const data = { version: 1, pid: process.pid, socket, port: this.port, started: this.started };
162
+ const tmp = `${file}.${process.pid}.tmp`;
163
+ writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
164
+ renameSync(tmp, file);
165
+ process.once("exit", this.onExit);
166
+ this.heartbeat = setInterval(() => {
167
+ for (const v of this.viewers)
168
+ v.write(": ping\n\n");
169
+ }, 15_000);
170
+ this.heartbeat.unref();
171
+ this.o.log?.(`live view on http://127.0.0.1:${this.port} for "${this.o.identity.id}"; open it with: turno browser live ${this.o.identity.id}`);
172
+ }
173
+ cleanupFiles() {
174
+ const file = liveFilePath(this.o.identity.id, this.o.identity.env);
175
+ try {
176
+ const data = JSON.parse(readFileSync(file, "utf8"));
177
+ if (data.pid === process.pid && data.socket === this.socket)
178
+ rmSync(file, { force: true });
179
+ }
180
+ catch {
181
+ /* gone or not ours */
182
+ }
183
+ if (this.socketDir)
184
+ rmSync(this.socketDir, { recursive: true, force: true });
185
+ }
186
+ async close() {
187
+ if (this.closed)
188
+ return;
189
+ this.closed = true;
190
+ this.gate.resume();
191
+ clearInterval(this.heartbeat);
192
+ for (const v of this.viewers)
193
+ v.end();
194
+ this.viewers.clear();
195
+ await this.retarget();
196
+ await Promise.all([this.tcp, this.unix].map((s) => new Promise((r) => {
197
+ if (!s)
198
+ return r();
199
+ s.closeAllConnections?.();
200
+ s.close(() => r());
201
+ })));
202
+ process.off("exit", this.onExit);
203
+ this.cleanupFiles();
204
+ }
205
+ // The host's side.
206
+ /** A browser launched; returns what to call when it goes away. */
207
+ bind(browser) {
208
+ this.browser = browser;
209
+ this.last = undefined;
210
+ this.pinned = undefined;
211
+ this.lastBySession.clear();
212
+ if (this.paused && this.heldBrowser !== browser) {
213
+ this.heldBrowser = browser;
214
+ void browser.onPause?.().catch(() => { });
215
+ }
216
+ void this.retarget();
217
+ this.pushState();
218
+ return () => {
219
+ if (this.browser !== browser)
220
+ return;
221
+ this.browser = undefined;
222
+ if (this.heldBrowser === browser)
223
+ this.heldBrowser = undefined;
224
+ void this.retarget();
225
+ this.pushState();
226
+ };
227
+ }
228
+ /** The page a call of `session` worked on; the view follows the latest one. */
229
+ follow(session, page) {
230
+ if (!page || page.isClosed())
231
+ return;
232
+ this.lastBySession.set(session, page);
233
+ if (this.last === page)
234
+ return;
235
+ this.last = page;
236
+ void this.retarget();
237
+ this.pushState();
238
+ }
239
+ /** The page the last call of `session` worked on (it may have closed since). */
240
+ lastPage(session) {
241
+ return this.lastBySession.get(session);
242
+ }
243
+ /** An agent call starts; returns what to call when it ends. */
244
+ begin() {
245
+ this.busy++;
246
+ this.pushState();
247
+ let done = false;
248
+ return () => {
249
+ if (done)
250
+ return;
251
+ done = true;
252
+ this.busy--;
253
+ this.pushState();
254
+ };
255
+ }
256
+ /** A vault or sensitive value is about to go into `page`: the view stops showing it now. */
257
+ hide(page) {
258
+ if (page && page === this.cast?.page) {
259
+ this.hidden = true;
260
+ this.pushState();
261
+ }
262
+ }
263
+ /** The id the view and the note give a tab. */
264
+ idOf(page) {
265
+ let id = this.ids.get(page);
266
+ if (id === undefined) {
267
+ id = this.nextId++;
268
+ this.ids.set(page, id);
269
+ }
270
+ return id;
271
+ }
272
+ /** The agent's pages: every page, or in attach mode only those the agent worked on. */
273
+ pages() {
274
+ const b = this.browser;
275
+ if (!b)
276
+ return [];
277
+ if (b.userBrowser)
278
+ return [...new Set(this.lastBySession.values())].filter((p) => !p.isClosed());
279
+ try {
280
+ return b.context.pages().filter((p) => !p.isClosed());
281
+ }
282
+ catch {
283
+ return [];
284
+ }
285
+ }
286
+ urlOf(page) {
287
+ return this.browser?.urlOf?.(page) ?? page.url();
288
+ }
289
+ /** The tabs now, as the note compares them. */
290
+ async tabStates() {
291
+ return await Promise.all(this.pages().map(async (p) => ({ id: this.idOf(p), url: this.urlOf(p), title: await titleOf(p) })));
292
+ }
293
+ /** Pauses the agent. `front`: bring the shown tab to the front of a headed window. */
294
+ async pause(by, front = false) {
295
+ if (!this.gate.start(by, this.tabStates()))
296
+ return false;
297
+ this.o.log?.(`"${this.o.identity.id}" paused (${by}); the agent's next call waits up to ${this.o.policy.waitMs / 1000}s`);
298
+ const b = this.browser;
299
+ if (b) {
300
+ this.heldBrowser = b;
301
+ await b.onPause?.().catch(() => { });
302
+ const target = this.target();
303
+ if (front && !this.o.headless && !b.userBrowser && target)
304
+ await target.bringToFront().catch(() => { });
305
+ }
306
+ this.pushState();
307
+ return true;
308
+ }
309
+ resume() {
310
+ if (!this.gate.resume())
311
+ return false;
312
+ this.o.log?.(`"${this.o.identity.id}" resumed`);
313
+ const b = this.heldBrowser;
314
+ this.heldBrowser = undefined;
315
+ b?.onResume?.();
316
+ this.pushState();
317
+ return true;
318
+ }
319
+ /** The tab the view shows: the one picked, else the agent's latest, else the first. */
320
+ target() {
321
+ if (this.pinned && !this.pinned.isClosed())
322
+ return this.pinned;
323
+ this.pinned = undefined;
324
+ if (this.last && !this.last.isClosed())
325
+ return this.last;
326
+ return this.browser?.userBrowser ? undefined : this.pages()[0];
327
+ }
328
+ refusal() {
329
+ return this.o.viewRefusal(this.browser?.engine);
330
+ }
331
+ status() {
332
+ const reason = this.refusal();
333
+ const paused = this.gate.paused;
334
+ const target = this.browser ? this.target() : undefined;
335
+ const tabs = this.pages().map((p) => {
336
+ const session = this.browser?.owner?.(p);
337
+ return {
338
+ id: this.idOf(p),
339
+ url: this.o.redactor.text(plainUrl(this.urlOf(p))),
340
+ title: "",
341
+ ...(session ? { session: session.slice(0, 8) } : {}),
342
+ };
343
+ });
344
+ return {
345
+ identity: this.o.identity.id,
346
+ pid: process.pid,
347
+ port: this.port,
348
+ started: this.started,
349
+ paused: paused ? { since: new Date(paused.since).toISOString(), by: paused.by } : null,
350
+ waiting: this.gate.held,
351
+ busy: this.busy,
352
+ wait: this.o.policy.waitMs,
353
+ browser: this.browser !== undefined,
354
+ engine: this.browser?.engine ?? null,
355
+ view: { available: reason === undefined, ...(reason ? { reason } : {}), headless: this.o.headless },
356
+ showing: target && reason === undefined ? this.idOf(target) : null,
357
+ pinned: this.pinned !== undefined,
358
+ hidden: target ? this.o.guard.holds(target) || (this.hidden && this.cast?.page === target) : false,
359
+ viewers: this.viewers.size,
360
+ tabs,
361
+ };
362
+ }
363
+ /** The status with tab titles (they need a round trip to each page). */
364
+ async fullStatus() {
365
+ const s = this.status();
366
+ const titles = new Map((await this.tabStates()).map((t) => [t.id, t.title]));
367
+ for (const t of s.tabs)
368
+ t.title = this.o.redactor.text(titles.get(t.id) ?? "");
369
+ return s;
370
+ }
371
+ pushState() {
372
+ if (this.queued || !this.viewers.size)
373
+ return;
374
+ this.queued = true;
375
+ queueMicrotask(() => {
376
+ this.queued = false;
377
+ void this.fullStatus()
378
+ .then((s) => this.broadcast("state", JSON.stringify(s)))
379
+ .catch(() => { });
380
+ });
381
+ }
382
+ broadcast(event, data) {
383
+ for (const v of this.viewers)
384
+ v.write(`event: ${event}\ndata: ${data}\n\n`);
385
+ }
386
+ /** Starts or moves the screencast to the tab the view should show, or stops it. */
387
+ retarget() {
388
+ this.casting = this.casting.then(() => this.doRetarget()).catch(() => { });
389
+ return this.casting;
390
+ }
391
+ async doRetarget() {
392
+ const b = this.browser;
393
+ const want = this.viewers.size && b && !this.closed && !this.refusal() ? this.target() : undefined;
394
+ if (this.cast?.page === want && (!want || !want.isClosed()))
395
+ return;
396
+ const old = this.cast;
397
+ this.cast = undefined;
398
+ this.hidden = false;
399
+ if (old) {
400
+ await old.cdp.send("Page.stopScreencast").catch(() => { });
401
+ await old.cdp.detach().catch(() => { });
402
+ }
403
+ if (!want || !b)
404
+ return;
405
+ const cdp = await b.context.newCDPSession(want);
406
+ const cast = { page: want, cdp };
407
+ this.cast = cast;
408
+ cdp.on("Page.screencastFrame", (f) => {
409
+ void cdp.send("Page.screencastFrameAck", { sessionId: f.sessionId }).catch(() => { });
410
+ if (this.cast !== cast)
411
+ return;
412
+ // Checked as each frame arrives: once the guard holds the page, no frame of it leaves.
413
+ if (this.o.guard.holds(want)) {
414
+ if (!this.hidden) {
415
+ this.hidden = true;
416
+ this.pushState();
417
+ }
418
+ return;
419
+ }
420
+ if (this.hidden) {
421
+ this.hidden = false;
422
+ this.pushState();
423
+ }
424
+ this.broadcast("frame", JSON.stringify({
425
+ tab: this.idOf(want),
426
+ w: f.metadata.deviceWidth ?? 0,
427
+ h: f.metadata.deviceHeight ?? 0,
428
+ data: f.data,
429
+ }));
430
+ });
431
+ want.once("close", () => {
432
+ void this.retarget();
433
+ this.pushState();
434
+ });
435
+ await cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1280, maxHeight: 1280 });
436
+ }
437
+ // HTTP.
438
+ hostOk(req) {
439
+ const host = (req.headers.host ?? "").toLowerCase();
440
+ return host === `127.0.0.1:${this.port}` || host === `localhost:${this.port}`;
441
+ }
442
+ originOk(req) {
443
+ const origin = req.headers.origin;
444
+ return (req.headers["x-turno-live"] === "1" &&
445
+ (origin === `http://127.0.0.1:${this.port}` || origin === `http://localhost:${this.port}`));
446
+ }
447
+ cookieOk(req) {
448
+ for (const part of (req.headers.cookie ?? "").split(";")) {
449
+ const eq = part.indexOf("=");
450
+ if (eq < 0)
451
+ continue;
452
+ if (part.slice(0, eq).trim() === this.cookieName && sameSecret(part.slice(eq + 1).trim(), this.token))
453
+ return true;
454
+ }
455
+ return false;
456
+ }
457
+ /** A one-time code for a link (socket only). */
458
+ issueCode() {
459
+ const now = Date.now();
460
+ for (const [c, until] of this.codes)
461
+ if (until < now)
462
+ this.codes.delete(c);
463
+ const code = randomBytes(24).toString("base64url");
464
+ this.codes.set(code, now + CODE_MS);
465
+ return code;
466
+ }
467
+ takeCode(code) {
468
+ for (const [c, until] of this.codes) {
469
+ if (sameSecret(c, code)) {
470
+ this.codes.delete(c);
471
+ return until >= Date.now();
472
+ }
473
+ }
474
+ return false;
475
+ }
476
+ send(res, status, type, body, headers = {}) {
477
+ res.writeHead(status, {
478
+ "Content-Type": type,
479
+ "Cache-Control": "no-store",
480
+ "X-Content-Type-Options": "nosniff",
481
+ "Referrer-Policy": "no-referrer",
482
+ "X-Frame-Options": "DENY",
483
+ ...headers,
484
+ });
485
+ res.end(body);
486
+ }
487
+ json(res, status, value) {
488
+ this.send(res, status, "application/json; charset=utf-8", JSON.stringify(value));
489
+ }
490
+ async handle(req, res, trusted) {
491
+ try {
492
+ if (!trusted && !this.hostOk(req))
493
+ return this.send(res, 403, "text/plain", "forbidden");
494
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
495
+ const method = req.method ?? "GET";
496
+ if (!trusted && method === "GET" && url.pathname === "/" && url.searchParams.has("code")) {
497
+ if (!this.takeCode(url.searchParams.get("code") ?? ""))
498
+ return this.send(res, 403, "text/html; charset=utf-8", deniedPage(this.o.identity.id));
499
+ return this.send(res, 303, "text/plain", "", {
500
+ Location: "/",
501
+ "Set-Cookie": `${this.cookieName}=${this.token}; HttpOnly; SameSite=Strict; Path=/`,
502
+ });
503
+ }
504
+ if (!trusted && !this.cookieOk(req)) {
505
+ if (method === "GET" && url.pathname === "/")
506
+ return this.send(res, 401, "text/html; charset=utf-8", deniedPage(this.o.identity.id));
507
+ return this.json(res, 401, { error: "not signed in to this live view" });
508
+ }
509
+ if (method === "POST" && !trusted && !this.originOk(req))
510
+ return this.json(res, 403, { error: "a request from another origin" });
511
+ const route = `${method} ${url.pathname}`;
512
+ if (route === "GET /" && !trusted) {
513
+ const nonce = randomBytes(16).toString("base64");
514
+ return this.send(res, 200, "text/html; charset=utf-8", livePage(nonce), {
515
+ "Content-Security-Policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; img-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
516
+ });
517
+ }
518
+ if (route === "GET /state")
519
+ return this.json(res, 200, await this.fullStatus());
520
+ if (route === "GET /events" && !trusted)
521
+ return this.events(req, res);
522
+ if (route === "POST /pause") {
523
+ await readJson(req);
524
+ await this.pause(trusted ? "turno browser pause" : "the live view", trusted);
525
+ return this.json(res, 200, await this.fullStatus());
526
+ }
527
+ if (route === "POST /resume") {
528
+ await readJson(req);
529
+ this.resume();
530
+ return this.json(res, 200, await this.fullStatus());
531
+ }
532
+ if (route === "POST /follow") {
533
+ const body = await readJson(req);
534
+ if (body.tab === null || body.tab === undefined)
535
+ this.pinned = undefined;
536
+ else {
537
+ const page = this.pages().find((p) => this.idOf(p) === body.tab);
538
+ if (!page)
539
+ throw new HttpError(404, "no such tab (it may have closed)");
540
+ this.pinned = page;
541
+ }
542
+ await this.retarget();
543
+ this.pushState();
544
+ return this.json(res, 200, await this.fullStatus());
545
+ }
546
+ if (route === "POST /input" && !trusted) {
547
+ await this.input(await readJson(req));
548
+ return this.json(res, 200, { ok: true });
549
+ }
550
+ if (route === "POST /link" && trusted) {
551
+ await readJson(req);
552
+ const reason = this.refusal();
553
+ if (reason)
554
+ throw new HttpError(409, reason);
555
+ return this.json(res, 200, { url: `http://127.0.0.1:${this.port}/?code=${this.issueCode()}` });
556
+ }
557
+ return this.json(res, 404, { error: "not found" });
558
+ }
559
+ catch (error) {
560
+ const status = error instanceof HttpError ? error.status : 500;
561
+ if (!res.headersSent)
562
+ this.json(res, status, { error: this.o.redactor.text(String(error.message)) });
563
+ else
564
+ res.end();
565
+ }
566
+ }
567
+ events(req, res) {
568
+ res.writeHead(200, {
569
+ "Content-Type": "text/event-stream",
570
+ "Cache-Control": "no-store",
571
+ Connection: "keep-alive",
572
+ "X-Content-Type-Options": "nosniff",
573
+ });
574
+ res.write("retry: 3000\n\n");
575
+ this.viewers.add(res);
576
+ req.on("close", () => {
577
+ this.viewers.delete(res);
578
+ void this.retarget();
579
+ });
580
+ void this.retarget();
581
+ this.pushState();
582
+ }
583
+ /** Why input from the view cannot go to the page now. */
584
+ inputRefusal(page) {
585
+ const reason = this.refusal();
586
+ if (reason)
587
+ return reason;
588
+ if (!this.paused)
589
+ return "Pause first: input from the view goes to the page only while the agent waits.";
590
+ if (this.busy)
591
+ return "A call that started before the pause is still running; try again when it ends.";
592
+ if (!page)
593
+ return "There is no tab to send it to.";
594
+ if (this.o.guard.holds(page))
595
+ return "This page holds a vault or sensitive value, so the view hides it; use the browser window for it.";
596
+ return undefined;
597
+ }
598
+ async input(body) {
599
+ const page = this.browser ? this.target() : undefined;
600
+ const why = this.inputRefusal(page);
601
+ if (why)
602
+ throw new HttpError(409, why);
603
+ const p = page;
604
+ const xy = () => [num(body.x, 0, 20_000), num(body.y, 0, 20_000)];
605
+ switch (body.type) {
606
+ case "click": {
607
+ const [x, y] = xy();
608
+ await p.mouse.click(x, y);
609
+ break;
610
+ }
611
+ case "dblclick": {
612
+ const [x, y] = xy();
613
+ await p.mouse.dblclick(x, y);
614
+ break;
615
+ }
616
+ case "wheel": {
617
+ const [x, y] = xy();
618
+ await p.mouse.move(x, y);
619
+ await p.mouse.wheel(num(body.dx, -20_000, 20_000), num(body.dy, -20_000, 20_000));
620
+ break;
621
+ }
622
+ case "text": {
623
+ if (typeof body.text !== "string" || !body.text || body.text.length > 1_000)
624
+ throw new HttpError(400, "text must be 1 to 1000 characters");
625
+ await p.keyboard.insertText(body.text);
626
+ break;
627
+ }
628
+ case "key": {
629
+ if (typeof body.key !== "string" || !KEYS.has(body.key))
630
+ throw new HttpError(400, "unknown key");
631
+ await p.keyboard.press(body.key);
632
+ break;
633
+ }
634
+ default:
635
+ throw new HttpError(400, "type must be click, dblclick, wheel, text or key");
636
+ }
637
+ this.gate.noteInput();
638
+ }
639
+ }
640
+ //# sourceMappingURL=live-server.js.map