@peakflo/agent-harness 0.2.20-rc.1 → 0.2.20

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 (34) hide show
  1. package/README.md +78 -0
  2. package/dist/browser-broker/agent-actions.mjs +799 -0
  3. package/dist/browser-broker/browsers.mjs +1699 -0
  4. package/dist/browser-broker/credentials.mjs +211 -0
  5. package/dist/browser-broker/disk-guard.mjs +84 -0
  6. package/dist/browser-broker/egress.mjs +183 -0
  7. package/dist/browser-broker/input.mjs +270 -0
  8. package/dist/browser-broker/lease.mjs +547 -0
  9. package/dist/browser-broker/local-network.mjs +173 -0
  10. package/dist/browser-broker/local.mjs +158 -0
  11. package/dist/browser-broker/log.mjs +28 -0
  12. package/dist/browser-broker/network-policy.mjs +144 -0
  13. package/dist/browser-broker/os-users.mjs +493 -0
  14. package/dist/browser-broker/package.json +1 -0
  15. package/dist/browser-broker/protocol.mjs +321 -0
  16. package/dist/browser-broker/queue.mjs +37 -0
  17. package/dist/browser-broker/recorder-scripts.mjs +221 -0
  18. package/dist/browser-broker/recorder.mjs +438 -0
  19. package/dist/browser-broker/recording-store.mjs +493 -0
  20. package/dist/browser-broker/relay.mjs +399 -0
  21. package/dist/browser-broker/screencast.mjs +198 -0
  22. package/dist/browser-broker/state-store.mjs +112 -0
  23. package/dist/browser-broker/transfers.mjs +460 -0
  24. package/dist/control-plane.d.ts +6 -0
  25. package/dist/control-plane.js +10 -0
  26. package/dist/github-workspace.d.ts +2 -0
  27. package/dist/github-workspace.js +4 -0
  28. package/dist/harness.d.ts +1 -0
  29. package/dist/harness.js +24 -0
  30. package/dist/runtime/knowledge-tools.d.ts +1 -0
  31. package/dist/runtime/knowledge-tools.js +3 -0
  32. package/dist/runtime/local-browser.d.ts +33 -0
  33. package/dist/runtime/local-browser.js +135 -0
  34. package/package.json +5 -3
@@ -0,0 +1,547 @@
1
+ /**
2
+ * The input lease of one chat browser. PURE: no I/O, no timers; the clock and
3
+ * the id generator are passed in, so every race is a unit test.
4
+ *
5
+ * THE BROKER IS THE AUTHORITY (protocol v2). It decides every control change
6
+ * and fences every agent command and person input against the lease it holds:
7
+ *
8
+ * state = { epoch, leaseId, controller, pending, lastInputSeq }
9
+ * controller = { kind: 'agent' }
10
+ * | { kind: 'user', userId, connectionId|null, name|null, graceUntil: ms|null }
11
+ * pending = { userId, name, connectionId, at: ms } | null
12
+ *
13
+ * Every grant (agent -> person, person -> agent, person -> person, a person's
14
+ * lease moving to a new connection) is a NEW lease: epoch + 1, a fresh lease
15
+ * id, and the input sequence restarts. Epochs never decrease, also across a
16
+ * broker restart (`restoreLease` continues above the persisted epoch).
17
+ *
18
+ * Fences:
19
+ * command refused unless the agent holds the lease AND the command names the
20
+ * current epoch when it reaches the front of the browser's serial
21
+ * queue: `takeover_active` while a person holds it, else `stale_lease`.
22
+ * Replayed command ids are refused by the caller's IdLru
23
+ * (`stale_sequence`).
24
+ * input refused unless a person holds the lease AND connectionId, epoch and
25
+ * leaseId all match AND seq > lastInputSeq (`not_controller`,
26
+ * `stale_lease`, `stale_sequence`).
27
+ */
28
+
29
+ export const DEFAULT_GRACE_MS = 60_000;
30
+ export const COMMAND_ID_MEMORY = 2048;
31
+
32
+ function err(code, message) {
33
+ return { code, message };
34
+ }
35
+
36
+ const AGENT = Object.freeze({ kind: 'agent' });
37
+
38
+ function str(value, max = 200) {
39
+ return typeof value === 'string' && value.length > 0 && value.length <= max;
40
+ }
41
+
42
+ /** Shape check for a BrowserViewerIdentity. Returns a message or null. */
43
+ export function invalidViewer(viewer, { needConnection = true } = {}) {
44
+ if (!viewer || typeof viewer !== 'object') return 'viewer is required';
45
+ if (!str(viewer.userId)) return 'viewer.userId is required';
46
+ if (needConnection && !str(viewer.connectionId))
47
+ return 'viewer.connectionId is required';
48
+ if (
49
+ viewer.name !== undefined &&
50
+ viewer.name !== null &&
51
+ (typeof viewer.name !== 'string' || viewer.name.length > 200)
52
+ ) {
53
+ return 'viewer.name must be a string';
54
+ }
55
+ return null;
56
+ }
57
+
58
+ function userController(viewer, { connectionId, graceUntil }) {
59
+ return {
60
+ kind: 'user',
61
+ userId: viewer.userId,
62
+ connectionId: connectionId ?? null,
63
+ name: typeof viewer.name === 'string' ? viewer.name : null,
64
+ graceUntil: graceUntil ?? null
65
+ };
66
+ }
67
+
68
+ /** A new lease on top of `state` (epoch + 1, new id, input sequence restarts). */
69
+ function grant(state, controller, ctx, { keepPending = false } = {}) {
70
+ let pending = keepPending ? state.pending : null;
71
+ if (
72
+ pending &&
73
+ controller.kind === 'user' &&
74
+ pending.userId === controller.userId
75
+ )
76
+ pending = null;
77
+ return {
78
+ epoch: state.epoch + 1,
79
+ leaseId: ctx.newId(),
80
+ controller,
81
+ pending,
82
+ lastInputSeq: 0
83
+ };
84
+ }
85
+
86
+ function personName(controller) {
87
+ return controller.kind === 'user' && controller.name
88
+ ? controller.name
89
+ : 'the person in control';
90
+ }
91
+
92
+ /**
93
+ * The lease for a browser that is being OPENED. `previous` is what the broker
94
+ * remembers for this chat (a closed browser or a restored state file), so the
95
+ * epoch continues above it. A member who opened the browser gets the lease,
96
+ * held for grace until their viewer `connect`s; otherwise a person's restored
97
+ * lease that is still inside grace is kept; otherwise the agent holds it.
98
+ */
99
+ export function openLease(
100
+ previous,
101
+ { initialController, now, graceMs, newId }
102
+ ) {
103
+ const base = { epoch: previous?.epoch ?? 0, pending: null };
104
+ const ctx = { newId };
105
+ if (
106
+ initialController &&
107
+ !invalidViewer(initialController, { needConnection: false })
108
+ ) {
109
+ return grant(
110
+ base,
111
+ userController(initialController, {
112
+ connectionId: null,
113
+ graceUntil: now + graceMs
114
+ }),
115
+ ctx
116
+ );
117
+ }
118
+ const prev = previous?.controller;
119
+ if (
120
+ prev?.kind === 'user' &&
121
+ prev.graceUntil !== null &&
122
+ prev.graceUntil > now
123
+ ) {
124
+ return grant(base, { ...prev, connectionId: null }, ctx);
125
+ }
126
+ return grant(base, AGENT, ctx);
127
+ }
128
+
129
+ /**
130
+ * After a broker restart. Anything in flight is fenced (epoch + 1, new lease
131
+ * id). A person keeps the lease only if it was still theirs: connected, or
132
+ * disconnected but inside grace; they get a fresh grace to `connect` again.
133
+ */
134
+ export function restoreLease(persisted, { now, graceMs, newId }) {
135
+ const epoch =
136
+ Number.isSafeInteger(persisted?.epoch) && persisted.epoch >= 0
137
+ ? persisted.epoch
138
+ : 0;
139
+ const prev = persisted?.controller;
140
+ const userAlive =
141
+ prev?.kind === 'user' &&
142
+ str(prev.userId) &&
143
+ (prev.graceUntil === null || prev.graceUntil > now);
144
+ const controller = userAlive
145
+ ? {
146
+ kind: 'user',
147
+ userId: prev.userId,
148
+ connectionId: null,
149
+ name: prev.name ?? null,
150
+ graceUntil: now + graceMs
151
+ }
152
+ : AGENT;
153
+ return grant({ epoch, pending: null }, controller, { newId });
154
+ }
155
+
156
+ /**
157
+ * Apply one control op. Returns
158
+ * { ok: true, state, change, notice } change: null (nothing happened) |
159
+ * 'to_user' | 'to_agent' | 'user_to_user' | 'rebind' | 'grace' | 'pending' | 'cleared'
160
+ * { ok: false, error }
161
+ * `state` is the same object when nothing changed.
162
+ */
163
+ export function control(state, op, viewer, ctx) {
164
+ const needConnection =
165
+ op === 'connect' || op === 'disconnect' || op === 'take';
166
+ const bad = invalidViewer(viewer, { needConnection });
167
+ if (bad) return { ok: false, error: err('invalid_args', bad) };
168
+ const c = state.controller;
169
+ const isController = c.kind === 'user' && c.userId === viewer.userId;
170
+ const same = (s) => ({ ok: true, state: s, change: null, notice: null });
171
+
172
+ switch (op) {
173
+ case 'connect': {
174
+ // Rebind a held lease to the person's new socket, only while it waits
175
+ // for them (grace, or a lease granted at open before any socket).
176
+ if (isController && (c.graceUntil !== null || c.connectionId === null)) {
177
+ const next = grant(
178
+ state,
179
+ userController(
180
+ { ...c, name: viewer.name ?? c.name },
181
+ {
182
+ connectionId: viewer.connectionId,
183
+ graceUntil: null
184
+ }
185
+ ),
186
+ ctx,
187
+ { keepPending: true }
188
+ );
189
+ return { ok: true, state: next, change: 'rebind', notice: null };
190
+ }
191
+ return same(state);
192
+ }
193
+ case 'disconnect': {
194
+ if (isController && c.connectionId === viewer.connectionId) {
195
+ const next = {
196
+ ...state,
197
+ controller: {
198
+ ...c,
199
+ connectionId: null,
200
+ graceUntil: ctx.now + ctx.graceMs
201
+ }
202
+ };
203
+ return { ok: true, state: next, change: 'grace', notice: null };
204
+ }
205
+ if (state.pending && state.pending.connectionId === viewer.connectionId) {
206
+ return {
207
+ ok: true,
208
+ state: { ...state, pending: null },
209
+ change: 'cleared',
210
+ notice: null
211
+ };
212
+ }
213
+ return same(state);
214
+ }
215
+ case 'take': {
216
+ const asked = userController(viewer, {
217
+ connectionId: viewer.connectionId,
218
+ graceUntil: null
219
+ });
220
+ if (c.kind === 'agent') {
221
+ return {
222
+ ok: true,
223
+ state: grant(state, asked, ctx),
224
+ change: 'to_user',
225
+ notice: {
226
+ kind: 'takeover',
227
+ message: `${asked.name || 'A member'} took control of the browser.`
228
+ }
229
+ };
230
+ }
231
+ if (isController) {
232
+ if (c.connectionId === viewer.connectionId && c.graceUntil === null)
233
+ return same(state);
234
+ // Their own lease, from another (or a reconnected) socket.
235
+ const next = grant(
236
+ state,
237
+ { ...asked, name: asked.name ?? c.name },
238
+ ctx,
239
+ { keepPending: true }
240
+ );
241
+ return { ok: true, state: next, change: 'rebind', notice: null };
242
+ }
243
+ if (c.graceUntil !== null && c.graceUntil <= ctx.now) {
244
+ return {
245
+ ok: true,
246
+ state: grant(state, asked, ctx),
247
+ change: 'user_to_user',
248
+ notice: {
249
+ kind: 'takeover',
250
+ message: `${asked.name || 'A member'} took control of the browser.`
251
+ }
252
+ };
253
+ }
254
+ const pending = {
255
+ userId: viewer.userId,
256
+ name: asked.name,
257
+ connectionId: viewer.connectionId,
258
+ at: ctx.now
259
+ };
260
+ if (
261
+ state.pending &&
262
+ state.pending.userId === pending.userId &&
263
+ state.pending.connectionId === pending.connectionId
264
+ ) {
265
+ return same(state);
266
+ }
267
+ return {
268
+ ok: true,
269
+ state: { ...state, pending },
270
+ change: 'pending',
271
+ notice: {
272
+ kind: 'request',
273
+ message: `${asked.name || 'A member'} asked for control of the browser.`
274
+ }
275
+ };
276
+ }
277
+ case 'hand_back': {
278
+ if (!isController)
279
+ return {
280
+ ok: false,
281
+ error: err(
282
+ 'not_controller',
283
+ 'Only the person in control can hand it back.'
284
+ )
285
+ };
286
+ return {
287
+ ok: true,
288
+ state: grant(state, AGENT, ctx),
289
+ change: 'to_agent',
290
+ notice: {
291
+ kind: 'handback',
292
+ message: `${personName(c)} handed control back to the agent.`
293
+ }
294
+ };
295
+ }
296
+ case 'grant': {
297
+ if (!isController)
298
+ return {
299
+ ok: false,
300
+ error: err(
301
+ 'not_controller',
302
+ 'Only the person in control can grant a request.'
303
+ )
304
+ };
305
+ const p = state.pending;
306
+ if (!p)
307
+ return {
308
+ ok: false,
309
+ error: err('not_found', 'There is no pending request.')
310
+ };
311
+ const next = grant(
312
+ state,
313
+ {
314
+ kind: 'user',
315
+ userId: p.userId,
316
+ connectionId: p.connectionId,
317
+ name: p.name,
318
+ graceUntil: null
319
+ },
320
+ ctx
321
+ );
322
+ return {
323
+ ok: true,
324
+ state: next,
325
+ change: 'user_to_user',
326
+ notice: {
327
+ kind: 'takeover',
328
+ message: `${p.name || 'A member'} took control of the browser.`
329
+ }
330
+ };
331
+ }
332
+ case 'deny': {
333
+ if (!isController)
334
+ return {
335
+ ok: false,
336
+ error: err(
337
+ 'not_controller',
338
+ 'Only the person in control can deny a request.'
339
+ )
340
+ };
341
+ if (!state.pending) return same(state);
342
+ return {
343
+ ok: true,
344
+ state: { ...state, pending: null },
345
+ change: 'cleared',
346
+ notice: null
347
+ };
348
+ }
349
+ case 'revoke': {
350
+ if (isController) {
351
+ return {
352
+ ok: true,
353
+ state: grant(state, AGENT, ctx),
354
+ change: 'to_agent',
355
+ notice: {
356
+ kind: 'access_revoked',
357
+ message: `Control returned to the agent: ${personName(c)} no longer has access.`
358
+ }
359
+ };
360
+ }
361
+ if (state.pending?.userId === viewer.userId) {
362
+ return {
363
+ ok: true,
364
+ state: { ...state, pending: null },
365
+ change: 'cleared',
366
+ notice: null
367
+ };
368
+ }
369
+ return same(state);
370
+ }
371
+ default:
372
+ return { ok: false, error: err('invalid_args', 'Unknown control op') };
373
+ }
374
+ }
375
+
376
+ /** Grace timer fired: the person did not come back in time. */
377
+ export function expireGrace(state, now, ctx) {
378
+ const c = state.controller;
379
+ if (c.kind !== 'user' || c.graceUntil === null || c.graceUntil > now) {
380
+ return { ok: true, state, change: null, notice: null };
381
+ }
382
+ return {
383
+ ok: true,
384
+ state: grant(state, AGENT, ctx),
385
+ change: 'to_agent',
386
+ notice: {
387
+ kind: 'grace_expired',
388
+ message: `Control returned to the agent after ${personName(c)} disconnected.`
389
+ }
390
+ };
391
+ }
392
+
393
+ /** The ms timestamp the grace timer must fire at, or null. */
394
+ export function graceDeadline(state) {
395
+ const c = state.controller;
396
+ return c.kind === 'user' && c.graceUntil !== null ? c.graceUntil : null;
397
+ }
398
+
399
+ /** Fence an agent command at the front of the queue. Null when it may run. */
400
+ export function checkCommand(state, epoch) {
401
+ if (!Number.isSafeInteger(epoch) || epoch < 0)
402
+ return err('invalid_args', 'epoch must be a non-negative integer');
403
+ if (state.controller.kind === 'user') {
404
+ return err(
405
+ 'takeover_active',
406
+ 'A person controls the browser. Agent input is paused until they hand it back.'
407
+ );
408
+ }
409
+ if (epoch !== state.epoch) {
410
+ return err(
411
+ 'stale_lease',
412
+ `Lease epoch ${epoch} is not the current epoch ${state.epoch}.`
413
+ );
414
+ }
415
+ return null;
416
+ }
417
+
418
+ /** Fence a person's input push. On success returns the state with lastInputSeq advanced. */
419
+ export function acceptInput(state, msg) {
420
+ const c = state.controller;
421
+ if (c.kind !== 'user') {
422
+ return {
423
+ ok: false,
424
+ error: err(
425
+ 'not_controller',
426
+ 'Input is accepted only while a person holds the lease.'
427
+ )
428
+ };
429
+ }
430
+ if (
431
+ !Number.isSafeInteger(msg?.epoch) ||
432
+ typeof msg.leaseId !== 'string' ||
433
+ typeof msg.connectionId !== 'string'
434
+ ) {
435
+ return {
436
+ ok: false,
437
+ error: err('invalid_args', 'epoch, leaseId and connectionId are required')
438
+ };
439
+ }
440
+ if (msg.epoch !== state.epoch || msg.leaseId !== state.leaseId) {
441
+ return {
442
+ ok: false,
443
+ error: err(
444
+ 'stale_lease',
445
+ 'The input names a lease that is no longer current.'
446
+ )
447
+ };
448
+ }
449
+ if (c.connectionId === null || msg.connectionId !== c.connectionId) {
450
+ return {
451
+ ok: false,
452
+ error: err(
453
+ 'stale_lease',
454
+ 'Input is accepted only from the controlling connection.'
455
+ )
456
+ };
457
+ }
458
+ if (!Number.isSafeInteger(msg.seq) || msg.seq < 1) {
459
+ return {
460
+ ok: false,
461
+ error: err('invalid_args', 'seq must be a positive integer')
462
+ };
463
+ }
464
+ if (msg.seq <= state.lastInputSeq) {
465
+ return {
466
+ ok: false,
467
+ error: err(
468
+ 'stale_sequence',
469
+ `Input sequence ${msg.seq} is not after ${state.lastInputSeq}.`
470
+ )
471
+ };
472
+ }
473
+ return { ok: true, state: { ...state, lastInputSeq: msg.seq } };
474
+ }
475
+
476
+ /** Is `viewer` the person who holds the lease, at `epoch`? (uploads) */
477
+ export function checkController(state, viewer, epoch) {
478
+ const bad = invalidViewer(viewer, { needConnection: false });
479
+ if (bad) return err('invalid_args', bad);
480
+ const c = state.controller;
481
+ if (c.kind !== 'user' || c.userId !== viewer.userId) {
482
+ return err('not_controller', 'Only the person in control can do this.');
483
+ }
484
+ if (epoch !== state.epoch)
485
+ return err(
486
+ 'stale_lease',
487
+ `Lease epoch ${epoch} is not the current epoch ${state.epoch}.`
488
+ );
489
+ return null;
490
+ }
491
+
492
+ const iso = (ms) =>
493
+ ms === null || ms === undefined ? null : new Date(ms).toISOString();
494
+
495
+ /** The lease part of BrowserCoreState (wire shape: ISO times, no connection of the requester). */
496
+ export function leaseView(state) {
497
+ const c = state.controller;
498
+ return {
499
+ epoch: state.epoch,
500
+ leaseId: state.leaseId,
501
+ controller:
502
+ c.kind === 'agent'
503
+ ? { kind: 'agent' }
504
+ : {
505
+ kind: 'user',
506
+ userId: c.userId,
507
+ connectionId: c.connectionId,
508
+ name: c.name,
509
+ graceUntil: iso(c.graceUntil)
510
+ },
511
+ pendingRequest: state.pending
512
+ ? {
513
+ userId: state.pending.userId,
514
+ name: state.pending.name,
515
+ at: iso(state.pending.at)
516
+ }
517
+ : null
518
+ };
519
+ }
520
+
521
+ /** What goes in the state file: the lease without input counters or the requester. */
522
+ export function persistable(state) {
523
+ return {
524
+ epoch: state.epoch,
525
+ leaseId: state.leaseId,
526
+ controller: state.controller
527
+ };
528
+ }
529
+
530
+ /** Bounded memory of command ids already seen (replay -> stale_sequence). */
531
+ export class IdLru {
532
+ #set = new Set();
533
+ constructor(limit = COMMAND_ID_MEMORY) {
534
+ this.limit = limit;
535
+ }
536
+ /** Remember `id`; false when it was already seen. */
537
+ add(id) {
538
+ if (this.#set.has(id)) return false;
539
+ this.#set.add(id);
540
+ if (this.#set.size > this.limit)
541
+ this.#set.delete(this.#set.values().next().value);
542
+ return true;
543
+ }
544
+ get size() {
545
+ return this.#set.size;
546
+ }
547
+ }
@@ -0,0 +1,173 @@
1
+ /** Runner preview network boundary. No DNS lookup or arbitrary host. CONNECT uses the same explicit port. */
2
+ import http from 'node:http';
3
+ import net from 'node:net';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { BROWSER_DENIED_TCP_PORTS } from './network-policy.mjs';
6
+
7
+ export function previewPort(value) {
8
+ if (
9
+ !Number.isInteger(value) ||
10
+ value < 1024 ||
11
+ value > 65535 ||
12
+ BROWSER_DENIED_TCP_PORTS.includes(value)
13
+ )
14
+ throw new Error(
15
+ 'Use a dev-server port from 1024 to 65535. Harness ports are refused.'
16
+ );
17
+ return value;
18
+ }
19
+
20
+ export function previewTarget(raw, allowedPort) {
21
+ try {
22
+ const url = new URL(raw);
23
+ if (
24
+ !['http:', 'ws:'].includes(url.protocol) ||
25
+ !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) ||
26
+ url.username ||
27
+ url.password ||
28
+ Number(url.port) !== allowedPort
29
+ )
30
+ return null;
31
+ // Dial IPv4 loopback only. Never resolve a page-supplied host.
32
+ url.hostname = '127.0.0.1';
33
+ return url;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /** A separate authenticated loopback proxy per chat; only one explicit port. */
40
+ export async function localNetwork({ deniedPorts = () => [] } = {}) {
41
+ let port = null;
42
+ const sockets = new Set();
43
+ const password = randomBytes(32).toString('hex');
44
+ const auth = `Basic ${Buffer.from(`preview:${password}`).toString('base64')}`;
45
+ const allowedTarget = (raw) => {
46
+ const target = previewTarget(raw, port);
47
+ const denied = [...deniedPorts(), server.address()?.port];
48
+ return target && !denied.includes(Number(target.port)) ? target : null;
49
+ };
50
+ const targetOf = (req) =>
51
+ req.headers['proxy-authorization'] === auth ? allowedTarget(req.url) : null;
52
+ const track = (socket) => {
53
+ sockets.add(socket);
54
+ socket.on('error', () => {});
55
+ socket.once('close', () => sockets.delete(socket));
56
+ return socket;
57
+ };
58
+ const server = http.createServer((req, res) => {
59
+ const target = targetOf(req);
60
+ if (!target) {
61
+ res.writeHead(req.headers['proxy-authorization'] === auth ? 403 : 407, {
62
+ 'Proxy-Authenticate': 'Basic realm="preview"'
63
+ });
64
+ res.end('Use browser_preview_local for an allowed local server.');
65
+ return;
66
+ }
67
+ const headers = { ...req.headers, host: target.host };
68
+ delete headers['proxy-authorization'];
69
+ delete headers['proxy-connection'];
70
+ const upstream = http.request(
71
+ target,
72
+ { method: req.method, headers },
73
+ (reply) => {
74
+ res.writeHead(reply.statusCode ?? 502, reply.headers);
75
+ reply.pipe(res);
76
+ }
77
+ );
78
+ upstream.on('socket', track);
79
+ upstream.on('error', () => {
80
+ if (!res.headersSent) res.writeHead(502);
81
+ res.end(
82
+ 'Local preview could not reach the server. Bind the dev server to 127.0.0.1 and retry browser_preview_local. IPv6-only servers are not supported.'
83
+ );
84
+ });
85
+ res.on('close', () => upstream.destroy());
86
+ req.pipe(upstream);
87
+ });
88
+ server.on('connection', track);
89
+ // Chromium uses CONNECT for WebSockets, including ws://. The destination
90
+ // must still be this chat's one literal-loopback port. There is no DNS.
91
+ server.on('connect', (req, socket, head) => {
92
+ if (req.headers['proxy-authorization'] !== auth) {
93
+ socket.end(
94
+ 'HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm="preview"\r\nContent-Length: 0\r\n\r\n'
95
+ );
96
+ return;
97
+ }
98
+ const target = allowedTarget(`http://${req.url}/`);
99
+ if (!target) {
100
+ socket.end('HTTP/1.1 403 Forbidden\r\n\r\n');
101
+ return;
102
+ }
103
+ const upstream = track(
104
+ net.connect(Number(target.port), '127.0.0.1', () => {
105
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
106
+ if (head.length) upstream.write(head);
107
+ socket.pipe(upstream).pipe(socket);
108
+ })
109
+ );
110
+ upstream.on('error', () => socket.destroy());
111
+ socket.on('error', () => upstream.destroy());
112
+ socket.on('close', () => upstream.destroy());
113
+ });
114
+ server.on('upgrade', (req, socket, head) => {
115
+ const target = targetOf(req);
116
+ if (!target) {
117
+ socket.destroy();
118
+ return;
119
+ }
120
+ const upstream = track(
121
+ net.connect(Number(target.port), '127.0.0.1', () => {
122
+ const headers = { ...req.headers, host: target.host };
123
+ delete headers['proxy-authorization'];
124
+ delete headers['proxy-connection'];
125
+ upstream.write(
126
+ `${req.method} ${target.pathname}${target.search} HTTP/1.1\r\n` +
127
+ Object.entries(headers)
128
+ .map(([k, v]) => `${k}: ${v}\r\n`)
129
+ .join('') +
130
+ '\r\n'
131
+ );
132
+ if (head.length) upstream.write(head);
133
+ socket.pipe(upstream).pipe(socket);
134
+ })
135
+ );
136
+ upstream.on('error', () => socket.destroy());
137
+ socket.on('error', () => upstream.destroy());
138
+ socket.on('close', () => upstream.destroy());
139
+ });
140
+ await new Promise((resolve, reject) => {
141
+ server.once('error', reject);
142
+ server.listen(0, '127.0.0.1', resolve);
143
+ });
144
+ return {
145
+ proxy: {
146
+ server: `http://127.0.0.1:${server.address().port}`,
147
+ username: 'preview',
148
+ password
149
+ },
150
+ allow(value) {
151
+ const next = previewPort(value);
152
+ if ([...deniedPorts(), server.address()?.port].includes(next))
153
+ throw new Error(
154
+ 'This port belongs to a runner service, not a dev server.'
155
+ );
156
+ if (port !== next) for (const socket of sockets) socket.destroy();
157
+ port = next;
158
+ return `http://127.0.0.1:${port}/`;
159
+ },
160
+ revoke() {
161
+ port = null;
162
+ for (const socket of sockets) socket.destroy();
163
+ },
164
+ permits(raw) {
165
+ return !!allowedTarget(raw);
166
+ },
167
+ async close() {
168
+ port = null;
169
+ for (const socket of sockets) socket.destroy();
170
+ await new Promise((resolve) => server.close(resolve));
171
+ }
172
+ };
173
+ }