@aretaxia/sandbox-remote 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1100 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawn } from 'node:child_process';
3
+ import { createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, verify } from 'node:crypto';
4
+ import { createServer } from 'node:http';
5
+ import { createInterface } from 'node:readline';
6
+ import { dirname, join } from 'node:path';
7
+ import { homedir, hostname, tmpdir } from 'node:os';
8
+ import { existsSync, readdirSync, readFileSync, renameSync, writeFileSync, unlinkSync, rmSync } from 'node:fs';
9
+ import QRCode from 'qrcode';
10
+ import WebSocket, { WebSocketServer } from 'ws';
11
+ import { openPilotChat } from './sandbox-pilot-t3-chat.mjs';
12
+ import { startPilotPreview } from './sandbox-pilot-preview.mjs';
13
+ import { createNativePreview, nativePreviewOriginFor } from './sandbox-native-preview.mjs';
14
+ import { deviceDigest, loadDevice, matchesDeviceCookie, saveDevice } from './sandbox-pilot-device.mjs';
15
+
16
+ const selfTest = process.argv.includes('--self-test');
17
+ const serviceMode = process.argv.includes('--service');
18
+ const claimLifetime = 5 * 60_000;
19
+ const pilotLifetime = 20 * 60_000;
20
+ const stableLifetime = 7 * 24 * 60 * 60_000;
21
+ const option = (name) => process.argv.find((argument) => argument.startsWith(name + '='))?.slice(name.length + 1);
22
+ const autoAddress = process.argv.includes('--auto-address');
23
+ const rawSandboxUrl = option('--sandbox-url') ?? process.env.SANDBOX_REMOTE_URL;
24
+ const resolveAppOrigin = (value) => {
25
+ if (!value) return 'http://localhost:3013';
26
+ const parsed = new URL(value);
27
+ const localHttp = parsed.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(parsed.hostname);
28
+ assert((parsed.protocol === 'https:' || localHttp) && parsed.origin === value.replace(/\/+$/, '') &&
29
+ !parsed.username && !parsed.password, 'Invalid --sandbox-url');
30
+ return parsed.origin;
31
+ };
32
+ const appOrigin = resolveAppOrigin(rawSandboxUrl);
33
+ const codeAssetOrigin = process.env.SANDBOX_PILOT_CODE_ASSET_ORIGIN;
34
+ if (codeAssetOrigin) {
35
+ assert(/^http:\/\/127\.0\.0\.1:[0-9]{1,5}$/.test(codeAssetOrigin) &&
36
+ URL.parse(codeAssetOrigin)?.port, 'Code assets require an explicit loopback HTTP origin');
37
+ }
38
+ const hostedMode = process.argv.includes('--hosted') ||
39
+ (Boolean(rawSandboxUrl) && !['http://localhost:3013', 'http://127.0.0.1:3013'].includes(appOrigin));
40
+ let stableOrigin = option('--public-origin');
41
+ const useNgrok = process.argv.includes('--ngrok');
42
+ const useCloudflare = process.argv.includes('--cloudflare');
43
+ const listenPort = Number(option('--listen-port') ?? (autoAddress ? 3768 : 0));
44
+ const devicePath = process.env.SANDBOX_PILOT_DEVICE_FILE;
45
+ const validAutomaticOrigin = (value) => /^https:\/\/sbx-[a-f0-9]{24}\.aretaxia\.com$/.test(value);
46
+ const validOwnerId = (value) => typeof value === 'string' && /^[0-9a-f-]{36}$/i.test(value);
47
+ const addressPath = autoAddress && devicePath ? join(dirname(devicePath), 'auto-address') : undefined;
48
+ const automaticTokenPath = addressPath ? addressPath + '-token' : undefined;
49
+ let automaticOwnerId;
50
+ let ownerVerifierPublicKey;
51
+ if (autoAddress) {
52
+ assert(serviceMode && !stableOrigin && !useNgrok && !useCloudflare && addressPath &&
53
+ Number.isInteger(listenPort) && listenPort >= 1024 && listenPort <= 65535, 'Invalid automatic address configuration');
54
+ try {
55
+ const saved = JSON.parse(readFileSync(addressPath, 'utf8'));
56
+ assert(typeof saved.origin === 'string' && validAutomaticOrigin(saved.origin) &&
57
+ validOwnerId(saved.ownerId), 'The saved automatic address is invalid');
58
+ stableOrigin = saved.origin;
59
+ automaticOwnerId = saved.ownerId.toLowerCase();
60
+ if (typeof saved.ownerVerifierPublicKey === 'string' && saved.ownerVerifierPublicKey) {
61
+ ownerVerifierPublicKey = saved.ownerVerifierPublicKey;
62
+ }
63
+ }
64
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
65
+ }
66
+ if (stableOrigin) {
67
+ const publicUrl = new URL(stableOrigin);
68
+ assert(serviceMode && publicUrl.protocol === 'https:' && publicUrl.origin === stableOrigin &&
69
+ !publicUrl.port && devicePath && Number.isInteger(listenPort) && listenPort >= 1024 && listenPort <= 65535,
70
+ 'Stable addresses require a service, an HTTPS origin and a fixed loopback port');
71
+ assert(!(useNgrok && useCloudflare), 'Choose only one tunnel provider');
72
+ } else if (!autoAddress) {
73
+ assert(listenPort === 0 && !useNgrok && !useCloudflare, 'Use a fixed loopback port and tunnel with a stable public address');
74
+ }
75
+ const secret = () => randomBytes(32).toString('base64url');
76
+ const sockets = new WebSocketServer({ noServer: true, maxPayload: 4096 });
77
+ const seenOwnerJtis = new Map();
78
+ let claim;
79
+ let device;
80
+ let deviceExpiry;
81
+ let origin;
82
+ let tunnel;
83
+ let stopping = false;
84
+ let owner;
85
+ let environment;
86
+ let admin;
87
+ let ownerFile;
88
+ let chat;
89
+ let preview;
90
+ let nativePreview;
91
+ let nativePreviewHost;
92
+ let waitingForAddress = autoAddress && !stableOrigin;
93
+ let pendingEnrollment = null;
94
+ let enrollmentTimer = null;
95
+ let enrollmentActive = false;
96
+ const qrPath = process.env.SANDBOX_PILOT_QR ?? join(tmpdir(), 'sandbox-pairing-pilot.png');
97
+ const machineName = selfTest ? 'Test computer' : hostname();
98
+ const connectedMessage = 'Connected to ' + machineName + '.';
99
+
100
+ const page = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
101
+ <title>Sandbox pairing pilot</title><style>body{margin:48px auto;padding:0 20px;max-width:420px;background:#17181d;color:#f2f3f5;font:16px/1.55 system-ui}button{padding:12px;font:inherit;border-radius:8px}main{min-height:230px}</style>
102
+ <main><h1>Connect to your computer</h1><p>Approve your phone on the desktop to use Sandbox Code remotely.</p>
103
+ <button id="claim">Request pairing</button><p id="status" role="status"></p><a id="code" hidden href="/sandbox/app/code?connector=pilot">Open Sandbox Code</a>
104
+ <section id="chat" hidden><h2 id="thread"></h2><ol id="messages" style="padding-left:20px;max-height:340px;overflow:auto;white-space:pre-wrap"></ol>
105
+ <form id="composer"><label for="message">Message the test thread</label><br><textarea id="message" required maxlength="1000" rows="3" style="width:100%;box-sizing:border-box;font:inherit"></textarea><button id="send">Send</button></form></section></main><script src="/pilot.js"></script></html>`;
106
+
107
+ const browserScript = `
108
+ const claim = location.hash.slice(1);
109
+ history.replaceState(null, '', location.pathname);
110
+ const button = document.getElementById('claim');
111
+ const status = document.getElementById('status');
112
+ const chat = document.getElementById('chat');
113
+ const textarea = document.getElementById('message');
114
+ const sendButton = document.getElementById('send');
115
+ let ws;
116
+ let reconnect;
117
+ let pending;
118
+ function connect() {
119
+ clearTimeout(reconnect);
120
+ ws = new WebSocket(location.origin.replace(/^http/, 'ws') + '/connection');
121
+ ws.onmessage = ({data}) => {
122
+ if (!data.startsWith('{')) {
123
+ status.textContent = data;
124
+ if (data.startsWith('Connected to ')) document.getElementById('code').hidden = false;
125
+ return;
126
+ }
127
+ const event = JSON.parse(data);
128
+ if (event.type === 'chat') {
129
+ chat.hidden = false;
130
+ sendButton.disabled = !!pending;
131
+ document.getElementById('thread').textContent = event.title;
132
+ const messages = document.getElementById('messages');
133
+ const nearEnd = messages.scrollHeight - messages.scrollTop - messages.clientHeight < 60;
134
+ messages.replaceChildren(...event.messages.map(({role,text}) => {
135
+ const entry = document.createElement('li');
136
+ entry.textContent = (role === 'user' ? 'You: ' : 'T3: ') + text;
137
+ return entry;
138
+ }));
139
+ if (nearEnd) messages.scrollTop = messages.scrollHeight;
140
+ } else if (event.type === 'sent' || event.type === 'send-error') {
141
+ if (event.id !== pending) return;
142
+ pending = null;
143
+ sendButton.disabled = false;
144
+ if (event.type === 'sent') textarea.value = '';
145
+ status.textContent = event.type === 'sent' ? 'Sent to T3 Code.' : event.message;
146
+ } else if (event.type === 'status') status.textContent = event.message;
147
+ };
148
+ ws.onclose = ({code}) => {
149
+ sendButton.disabled = true;
150
+ if (pending) {
151
+ pending = null;
152
+ status.textContent = 'Delivery uncertain. Check the conversation before sending again.';
153
+ } else status.textContent = 'The test connection closed.';
154
+ if (code !== 1008 && !chat.hidden) reconnect = setTimeout(connect, 1500);
155
+ };
156
+ }
157
+ if (!claim) {
158
+ button.hidden = true;
159
+ connect();
160
+ }
161
+ button.onclick = async () => {
162
+ button.disabled = true;
163
+ try {
164
+ const reply = await fetch('/claim', { method: 'POST', headers: {'Content-Type':'text/plain'}, body: claim });
165
+ if (!reply.ok) throw new Error('This QR has expired or was already used. Ask for a fresh QR.');
166
+ button.hidden = true;
167
+ status.textContent = 'Waiting for approval on your computer…';
168
+ connect();
169
+ } catch (error) {
170
+ status.textContent = error.message;
171
+ }
172
+ };
173
+ document.getElementById('composer').onsubmit = (event) => {
174
+ event.preventDefault();
175
+ if (!textarea.value.trim() || pending || ws?.readyState !== WebSocket.OPEN) return;
176
+ pending = crypto.randomUUID();
177
+ sendButton.disabled = true;
178
+ status.textContent = 'Sending to T3 Code…';
179
+ ws.send(JSON.stringify({ type: 'send', id: pending, text: textarea.value.trim() }));
180
+ };`;
181
+
182
+ function send(response, status, body, contentType = 'text/plain; charset=utf-8', headers = {}) {
183
+ response.writeHead(status, {
184
+ 'Content-Type': contentType,
185
+ 'Cache-Control': 'no-store',
186
+ 'Referrer-Policy': 'no-referrer',
187
+ 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'",
188
+ 'X-Content-Type-Options': 'nosniff',
189
+ ...headers,
190
+ });
191
+ response.end(body);
192
+ }
193
+
194
+ function hasDevice(request) {
195
+ return device && device.ownerId?.toLowerCase() === owner?.id?.toLowerCase() &&
196
+ device.expiresAt > Date.now() && device.environmentId === environment?.environmentId &&
197
+ matchesDeviceCookie(request.headers.cookie, device.digest);
198
+ }
199
+
200
+ function verifyOwnerBearer(request, expectedAction) {
201
+ if (!ownerVerifierPublicKey || !owner?.id || !environment?.environmentId || !origin) return false;
202
+ const authHeader = request.headers.authorization;
203
+ const token = authHeader?.match(/^Bearer\s+([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/) ;
204
+ if (!token) return false;
205
+ try {
206
+ const keyObject = createPublicKey({
207
+ key: Buffer.from(ownerVerifierPublicKey, 'base64url'),
208
+ format: 'der',
209
+ type: 'spki',
210
+ });
211
+ if (keyObject.asymmetricKeyType !== 'ed25519') return false;
212
+ const ok = verify(null, Buffer.from(token[1], 'utf8'), keyObject, Buffer.from(token[2], 'base64url'));
213
+ if (!ok) return false;
214
+ const payload = JSON.parse(Buffer.from(token[1], 'base64url').toString('utf8'));
215
+ const now = Date.now();
216
+ if (payload?.v !== 1 ||
217
+ typeof payload.sub !== 'string' || payload.sub.toLowerCase() !== owner.id.toLowerCase() ||
218
+ payload.env !== environment.environmentId ||
219
+ payload.origin !== origin ||
220
+ payload.action !== expectedAction ||
221
+ !Number.isSafeInteger(payload.exp) || payload.exp <= now || payload.exp > now + 120_000 ||
222
+ typeof payload.jti !== 'string' || !/^[0-9a-f-]{36}$/i.test(payload.jti)) {
223
+ return false;
224
+ }
225
+ for (const [jti, exp] of seenOwnerJtis) {
226
+ if (exp <= now) seenOwnerJtis.delete(jti);
227
+ }
228
+ if (seenOwnerJtis.has(payload.jti)) return false;
229
+ seenOwnerJtis.set(payload.jti, payload.exp);
230
+ return true;
231
+ } catch {
232
+ return false;
233
+ }
234
+ }
235
+
236
+ const ownerConnectPage = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
237
+ <title>Connecting to Sandbox</title><style>body{margin:48px auto;padding:0 20px;max-width:420px;background:#17181d;color:#f2f3f5;font:16px/1.55 system-ui}a{color:#f2f3f5}</style>
238
+ <main><h1>Connecting to your computer</h1><p id="status" role="status">Verifying your Sandbox pass…</p><p id="fallback" hidden><a href="/">Open pairing page</a></p></main><script src="/pilot-connect.js"></script></html>`;
239
+
240
+ const ownerConnectScript = `
241
+ const token = location.hash.slice(1);
242
+ history.replaceState(null, '', location.pathname);
243
+ const status = document.getElementById('status');
244
+ const fallback = document.getElementById('fallback');
245
+ if (!token) {
246
+ status.textContent = 'Missing connection pass. Open your computer from Sandbox again.';
247
+ fallback.hidden = false;
248
+ } else {
249
+ fetch('/pilot/owner/connect', {
250
+ method: 'POST',
251
+ headers: { Authorization: 'Bearer ' + token },
252
+ credentials: 'same-origin',
253
+ }).then(async (res) => {
254
+ if (!res.ok) throw new Error(await res.text() || 'Connection pass expired.');
255
+ location.replace('/sandbox/app/code?connector=pilot');
256
+ }).catch((err) => {
257
+ status.textContent = err && err.message ? err.message : 'Could not connect.';
258
+ fallback.hidden = false;
259
+ });
260
+ }
261
+ `;
262
+
263
+ async function handleOwnerControl(request, response, action) {
264
+ const browserOrigin = request.headers.origin;
265
+ const expectedOrigin = action === 'connect' ? origin : appOrigin;
266
+ const browserHeaders = action !== 'connect' && browserOrigin === appOrigin ? {
267
+ 'Access-Control-Allow-Origin': appOrigin,
268
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
269
+ 'Access-Control-Allow-Headers': 'Authorization',
270
+ Vary: 'Origin',
271
+ } : {};
272
+ if (browserOrigin && browserOrigin !== expectedOrigin) return send(response, 403, 'Origin rejected');
273
+ if (request.method === 'OPTIONS' && action !== 'connect' && browserOrigin === appOrigin) {
274
+ return send(response, 204, '', 'text/plain', browserHeaders);
275
+ }
276
+ const reply = (status, body, contentType, extra) => send(response, status, body, contentType, { ...browserHeaders, ...extra });
277
+ if (request.method !== 'POST' || !verifyOwnerBearer(request, action)) {
278
+ return reply(403, 'Forbidden');
279
+ }
280
+ if (action === 'connect') {
281
+ claim = null;
282
+ disconnectDevice();
283
+ const token = secret();
284
+ const lifetime = stableOrigin ? stableLifetime : pilotLifetime;
285
+ device = {
286
+ digest: deviceDigest(token), approved: true, ownerId: owner.id, environmentId: environment.environmentId,
287
+ expiresAt: Date.now() + lifetime,
288
+ };
289
+ if (stableOrigin) {
290
+ saveDevice(devicePath, stableOrigin, device);
291
+ scheduleExpiry(lifetime);
292
+ } else if (serviceMode) {
293
+ scheduleExpiry(lifetime);
294
+ }
295
+ if (!selfTest) console.log('Owner handoff approved on ' + machineName + '.');
296
+ return reply(200, 'Connected.', 'text/plain; charset=utf-8', {
297
+ 'Set-Cookie': 'sandbox_pilot=' + token + '; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=' + lifetime / 1000,
298
+ });
299
+ }
300
+ if (action === 'status') {
301
+ return reply(200, JSON.stringify({
302
+ ready: Boolean(origin) && !waitingForAddress,
303
+ verified: Boolean(owner),
304
+ origin: origin ?? null,
305
+ pairing: device?.approved ? 'approved' : device ? 'pending' : 'unpaired',
306
+ }), 'application/json; charset=utf-8');
307
+ }
308
+ if (action === 'approve') {
309
+ return approve() ? reply(200, 'Phone approved. Open Sandbox Code on your phone.')
310
+ : reply(409, 'Scan the QR and request pairing first.');
311
+ }
312
+ if (action === 'revoke') {
313
+ claim = null;
314
+ revoke();
315
+ return reply(200, 'Phone access removed.');
316
+ }
317
+ if (!origin) return reply(503, 'The remote address is still starting.');
318
+ if (device) {
319
+ return reply(409, device.approved ? 'This phone is already approved.' : 'A phone is waiting for approval.');
320
+ }
321
+ if (!claim || Date.now() >= claim.expires) await createClaim();
322
+ const current = claim;
323
+ const image = await current?.image;
324
+ if (!image || claim !== current) return reply(409, 'The QR was already used.');
325
+ return reply(200, image, 'image/png');
326
+ }
327
+
328
+ async function handleCodeRequest(request, response, url) {
329
+ const ownerAction = url.pathname.match(/^\/pilot\/owner\/(status|qr|approve|revoke|connect)$/)?.[1];
330
+ if (ownerAction) {
331
+ if (ownerAction === 'connect' && request.method === 'GET') {
332
+ return send(response, 200, ownerConnectPage, 'text/html; charset=utf-8');
333
+ }
334
+ return handleOwnerControl(request, response, ownerAction);
335
+ }
336
+ if (!chat || !device?.approved || !hasDevice(request)) return send(response, 403, 'Pair this phone first');
337
+ const paired = device;
338
+ const active = () => device === paired && paired.approved;
339
+ const respond = (body) => active()
340
+ ? send(response, 200, JSON.stringify(body), 'application/json; charset=utf-8')
341
+ : send(response, 403, 'Pairing revoked');
342
+ try {
343
+ const segment = url.pathname.match(/^\/pilot\/thread\/([^/]+)$/)?.[1];
344
+ const threadId = segment ? decodeURIComponent(segment) : undefined;
345
+ if (request.method === 'GET' && url.pathname === '/pilot/machine') {
346
+ return respond({ id: 'sandbox-pilot:' + environment.environmentId, label: machineName + ' · Sandbox connection',
347
+ previewUrl: preview?.url, nativePreviewUrl: nativePreview ? '/pilot/native-preview/open' : undefined });
348
+ }
349
+ if (request.method === 'GET' && url.pathname === '/pilot/native-preview/open') {
350
+ if (!nativePreview) return send(response, 404, 'Native preview is unavailable');
351
+ if ((request.headers.origin && request.headers.origin !== origin) ||
352
+ ['same-site', 'cross-site'].includes(request.headers['sec-fetch-site'])) {
353
+ return send(response, 403, 'Origin rejected');
354
+ }
355
+ return send(response, 302, '', 'text/plain; charset=utf-8', { Location: nativePreview.issueTicket() });
356
+ }
357
+ if (request.method === 'GET' && url.pathname === '/pilot/shell') return respond(await chat.getShell());
358
+ if (request.method === 'GET' && threadId && chat.threadIds.includes(threadId)) {
359
+ return respond(await chat.getThread(threadId));
360
+ }
361
+ const previewAction = url.pathname.match(/^\/pilot\/preview\/(open|close|adjust)$/)?.[1];
362
+ if (request.method === 'POST' && (previewAction || ['/pilot/send', '/pilot/stop'].includes(url.pathname))) {
363
+ if (request.headers.origin !== origin) return send(response, 403, 'Origin rejected');
364
+ let body = '';
365
+ for await (const chunk of request) {
366
+ body += chunk;
367
+ if (body.length > 2048) return send(response, 413, 'Message too large');
368
+ }
369
+ const data = JSON.parse(body);
370
+ if (!active() || !data || !chat.threadIds.includes(data.threadId)) return send(response, 400, 'Invalid test thread');
371
+ if (previewAction) {
372
+ if (!preview) return send(response, 404, 'Preview is unavailable');
373
+ return respond(await preview.command(previewAction, data, paired, active));
374
+ }
375
+ if (url.pathname === '/pilot/stop') {
376
+ await chat.stopThread(data.threadId, active);
377
+ console.log('Code tab stop acknowledged by local stock T3.');
378
+ return respond({ accepted: true });
379
+ }
380
+ if (
381
+ !/^[0-9a-f-]{36}$/i.test(data.id) || typeof data.text !== 'string' ||
382
+ !data.text.trim() || data.text.length > 1000) return send(response, 400, 'Invalid test message');
383
+ await chat.sendMessage(data.id, data.text.trim(), active, data.threadId, data.mode);
384
+ console.log('Code tab message acknowledged by local stock T3.');
385
+ return respond({ accepted: true });
386
+ }
387
+ if (request.method === 'GET' && (url.pathname === '/sandbox/app/code' ||
388
+ url.pathname === '/manifest.webmanifest' || url.pathname === '/apple-touch-icon.png' ||
389
+ /^\/_next\/static\/[a-zA-Z0-9_.%-][a-zA-Z0-9_.%/\-]*$/.test(url.pathname) ||
390
+ /^\/(?:images|fonts|icons)\/[a-zA-Z0-9_.%/\-]+$/.test(url.pathname))) {
391
+ // Only the paired device can fetch the Code screen and its static resources.
392
+ // Do not forward cookies, arbitrary Next API paths, or framework control headers.
393
+ if (codeAssetOrigin && (/%(?!40|5b|5d)/i.test(url.pathname) || url.pathname.endsWith('.map'))) {
394
+ return send(response, 404, 'Not found');
395
+ }
396
+ const upstream = await fetch((codeAssetOrigin ?? appOrigin) + url.pathname +
397
+ (codeAssetOrigin ? '' : url.search), {
398
+ redirect: 'error', signal: AbortSignal.timeout(30_000),
399
+ });
400
+ const contentType = upstream.headers.get('content-type') ?? 'application/octet-stream';
401
+ const body = Buffer.from(await upstream.arrayBuffer());
402
+ if (!active()) return send(response, 403, 'Pairing revoked');
403
+ response.writeHead(upstream.status, {
404
+ 'Content-Type': contentType, 'Cache-Control': 'private, no-store',
405
+ 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff',
406
+ });
407
+ response.end(body);
408
+ return;
409
+ }
410
+ return send(response, 404, 'Not found');
411
+ } catch {
412
+ return send(response, request.method === 'POST' ? 502 : 503, 'Local T3 operation did not complete');
413
+ }
414
+ }
415
+
416
+ const server = createServer(async (request, response) => {
417
+ const requestUrl = URL.parse(request.url, local);
418
+ if (nativePreviewHost && request.headers.host?.toLowerCase() === nativePreviewHost) {
419
+ try {
420
+ if (requestUrl && nativePreview && await nativePreview.handleRequest(request, response, requestUrl)) return;
421
+ send(response, 404, 'Native preview is unavailable');
422
+ } catch {
423
+ if (!response.headersSent && !response.destroyed) send(response, 502, 'Native preview unavailable');
424
+ else response.destroy();
425
+ }
426
+ return;
427
+ }
428
+ if (stableOrigin && request.headers.host?.toLowerCase() !== new URL(stableOrigin).host &&
429
+ request.headers.host !== new URL(local).host) return send(response, 404, 'Not found');
430
+ if (request.method === 'GET' && request.url === '/') return send(response, 200, page, 'text/html; charset=utf-8');
431
+ if (request.method === 'GET' && request.url === '/pilot.js') return send(response, 200, browserScript, 'text/javascript; charset=utf-8');
432
+ if (request.method === 'GET' && request.url === '/pilot-connect.js') return send(response, 200, ownerConnectScript, 'text/javascript; charset=utf-8');
433
+ if (request.method !== 'POST' || request.url !== '/claim') {
434
+ const url = URL.parse(request.url, local);
435
+ if (url?.origin !== local) return send(response, 404, 'Not found');
436
+ return handleCodeRequest(request, response, url);
437
+ }
438
+ if (request.headers.origin !== origin) return send(response, 403, 'Origin rejected');
439
+ let candidate = '';
440
+ try {
441
+ for await (const chunk of request) {
442
+ candidate += chunk;
443
+ if (candidate.length > 64) return send(response, 413, 'Invalid claim');
444
+ }
445
+ } catch {
446
+ return send(response, 400, 'Invalid claim');
447
+ }
448
+ // Consume synchronously so two requests cannot both claim the computer.
449
+ if (!claim || Date.now() >= claim.expires || candidate !== claim.secret) return send(response, 409, 'Claim unavailable');
450
+ claim = null;
451
+ const token = secret();
452
+ const lifetime = stableOrigin ? stableLifetime : pilotLifetime;
453
+ device = {
454
+ digest: deviceDigest(token), approved: false, ownerId: owner.id, environmentId: environment.environmentId,
455
+ expiresAt: Date.now() + lifetime,
456
+ };
457
+ if (serviceMode) scheduleExpiry(stableOrigin ? claimLifetime : lifetime);
458
+ if (!selfTest) console.log('Phone requested pairing. Type approve to connect or revoke to reject.');
459
+ return send(response, 202, 'Waiting for approval', 'text/plain', {
460
+ 'Set-Cookie': 'sandbox_pilot=' + token + '; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=' + lifetime / 1000,
461
+ });
462
+ });
463
+
464
+ server.on('upgrade', (request, socket, head) => {
465
+ if (nativePreviewHost && request.headers.host?.toLowerCase() === nativePreviewHost) {
466
+ if (!nativePreview?.handleUpgrade(request, socket, head)) socket.destroy();
467
+ return;
468
+ }
469
+ if (stableOrigin && request.headers.host?.toLowerCase() !== new URL(stableOrigin).host &&
470
+ request.headers.host !== new URL(local).host) {
471
+ socket.destroy();
472
+ return;
473
+ }
474
+ const watchingCode = request.url === '/pilot/events';
475
+ const url = URL.parse(request.url, local);
476
+ const watchingPreview = url?.origin === local && url.pathname === '/pilot/preview-stream';
477
+ const threadId = url?.searchParams.get('threadId');
478
+ const tabId = url?.searchParams.get('tabId');
479
+ if ((!watchingCode && !watchingPreview && request.url !== '/connection') || request.headers.origin !== origin ||
480
+ !hasDevice(request) || ((watchingCode || watchingPreview) && (!chat || !device?.approved)) ||
481
+ (watchingPreview && !preview?.authorize(threadId, tabId, device))) {
482
+ socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');
483
+ return;
484
+ }
485
+ sockets.handleUpgrade(request, socket, head, (ws) => {
486
+ const paired = device;
487
+ if (watchingPreview) {
488
+ void preview.bridge(ws, threadId, tabId, url.searchParams.get('interactive') === 'true',
489
+ () => device === paired && paired.approved && preview.authorize(threadId, tabId, paired));
490
+ return;
491
+ }
492
+ if (watchingCode) {
493
+ const active = () => device === paired && ws.readyState === WebSocket.OPEN;
494
+ let cancelWatch;
495
+ ws.once('close', () => cancelWatch?.());
496
+ void chat.watchShell(() => { if (active() && ws.bufferedAmount < 4096) ws.send('changed'); },
497
+ () => { if (active()) ws.close(1011, 'T3 subscription closed'); })
498
+ .then((cancel) => { if (active()) cancelWatch = cancel; else cancel(); })
499
+ .catch(() => { if (active()) ws.close(1011, 'T3 subscription unavailable'); });
500
+ return;
501
+ }
502
+ ws.send(paired.approved ? connectedMessage : 'Waiting for approval on ' + machineName + '…');
503
+ if (chat && paired.approved) attachChat(ws, paired);
504
+ });
505
+ });
506
+
507
+ const chatSockets = new WeakSet();
508
+ function attachChat(ws, paired) {
509
+ if (chatSockets.has(ws)) return;
510
+ chatSockets.add(ws);
511
+ const active = () => device === paired && paired.approved && ws.readyState === WebSocket.OPEN;
512
+ const reply = (data) => { if (active()) ws.send(JSON.stringify(data)); };
513
+ let disconnect;
514
+ ws.once('close', () => disconnect?.());
515
+ void chat.watch(reply, () => reply({ type: 'status', message: 'Lost the local T3 subscription. Reload to reconnect.' }))
516
+ .then((cleanup) => { if (active()) disconnect = cleanup; else cleanup(); })
517
+ .catch(() => reply({ type: 'status', message: 'Could not open the local T3 conversation.' }));
518
+ ws.on('message', async (raw) => {
519
+ if (!active()) return;
520
+ let message;
521
+ try { message = JSON.parse(raw.toString()); } catch { return; }
522
+ if (message?.type !== 'send' || !/^[0-9a-f-]{36}$/i.test(message.id) ||
523
+ typeof message.text !== 'string' || !message.text.trim() || message.text.length > 1000) return;
524
+ try {
525
+ await chat.sendMessage(message.id, message.text.trim(), active);
526
+ reply({ type: 'sent', id: message.id });
527
+ console.log('Phone message acknowledged by local stock T3.');
528
+ } catch {
529
+ reply({ type: 'send-error', id: message.id, message: 'Delivery could not be confirmed. Check the conversation before sending again.' });
530
+ }
531
+ });
532
+ }
533
+
534
+ function scheduleExpiry(delay) {
535
+ clearTimeout(deviceExpiry);
536
+ deviceExpiry = setTimeout(() => {
537
+ try { revoke(); }
538
+ catch {
539
+ console.error('Could not remove the expired phone record.');
540
+ disconnectDevice();
541
+ }
542
+ }, delay);
543
+ }
544
+
545
+ function disconnectDevice() {
546
+ clearTimeout(deviceExpiry);
547
+ device = null;
548
+ for (const ws of sockets.clients) ws.close(1008, 'Pairing revoked');
549
+ preview?.revoke();
550
+ nativePreview?.revoke();
551
+ }
552
+
553
+ function activateNativePreview() {
554
+ if (nativePreviewHost || !origin) return;
555
+ const configuredOrigin = option('--native-preview-origin');
556
+ let previewOrigin;
557
+ try {
558
+ previewOrigin = configuredOrigin ?? nativePreviewOriginFor(origin);
559
+ } catch {
560
+ return;
561
+ }
562
+ if (configuredOrigin) {
563
+ const parsed = URL.parse(configuredOrigin);
564
+ if (parsed?.protocol !== 'https:' || parsed.origin !== configuredOrigin ||
565
+ parsed.hostname === new URL(origin).hostname) {
566
+ console.error('Invalid --native-preview-origin. Streamed preview is still available.');
567
+ return;
568
+ }
569
+ }
570
+ nativePreviewHost = new URL(previewOrigin).host;
571
+ if (!preview || !option('--preview-url')) return;
572
+ nativePreview = createNativePreview({
573
+ targetUrl: preview.url,
574
+ previewOrigin,
575
+ isActive: () => Boolean(device?.approved),
576
+ });
577
+ console.log('Native localhost preview ready at ' + previewOrigin);
578
+ }
579
+
580
+ function revoke() {
581
+ if (stableOrigin) rmSync(devicePath, { force: true });
582
+ disconnectDevice();
583
+ }
584
+
585
+ function approve() {
586
+ if (!device || device.expiresAt <= Date.now() || device.ownerId?.toLowerCase() !== owner?.id?.toLowerCase() ||
587
+ device.environmentId !== environment?.environmentId) return false;
588
+ if (device.approved) return true;
589
+ if (stableOrigin) {
590
+ saveDevice(devicePath, stableOrigin, device);
591
+ scheduleExpiry(device.expiresAt - Date.now());
592
+ }
593
+ device.approved = true;
594
+ for (const ws of sockets.clients) {
595
+ if (ws.readyState !== WebSocket.OPEN) continue;
596
+ ws.send(connectedMessage);
597
+ if (chat) attachChat(ws, device);
598
+ }
599
+ if (!selfTest) console.log('Approved pairing on ' + machineName + '.');
600
+ return true;
601
+ }
602
+
603
+ async function createClaim() {
604
+ assert(owner?.id && environment?.environmentId, 'Verify the account and T3 environment before issuing a claim');
605
+ revoke();
606
+ const next = { secret: secret(), expires: Date.now() + claimLifetime };
607
+ claim = next;
608
+ if (!selfTest) {
609
+ next.image = QRCode.toBuffer(origin + '/#' + next.secret, { width: 360, margin: 4 });
610
+ const image = await next.image;
611
+ if (claim !== next) return;
612
+ writeFileSync(qrPath, image, { mode: 0o600 });
613
+ console.log('Pairing QR ready for five minutes at ' + qrPath);
614
+ }
615
+ }
616
+
617
+ function stopEnrollment() {
618
+ enrollmentActive = false;
619
+ clearTimeout(enrollmentTimer);
620
+ enrollmentTimer = null;
621
+ }
622
+
623
+ function stop() {
624
+ if (stopping) return;
625
+ stopping = true;
626
+ stopEnrollment();
627
+ disconnectDevice();
628
+ for (const ws of sockets.clients) ws.terminate();
629
+ server.close();
630
+ admin?.close();
631
+ if (ownerFile) try { unlinkSync(ownerFile); } catch { /* Already removed. */ }
632
+ if (serviceMode) try { unlinkSync(qrPath); } catch { /* Already removed. */ }
633
+ tunnel?.kill();
634
+ void (async () => {
635
+ await preview?.close();
636
+ await chat?.close();
637
+ })().catch(() => {
638
+ console.error('Could not revoke the temporary chat session. Check T3 Sharing & access.');
639
+ process.exitCode = 1;
640
+ });
641
+ }
642
+
643
+ async function startHostedEnrollment() {
644
+ assert(autoAddress && hostedMode && waitingForAddress, 'Hosted enrollment is not active');
645
+ stopEnrollment();
646
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');
647
+ const publicKeyB64 = publicKey.export({ format: 'der', type: 'spki' }).toString('base64url');
648
+ const enrollResponse = await fetch(appOrigin + '/api/sandbox/pairing-pilot/enroll', {
649
+ method: 'POST',
650
+ headers: { 'Content-Type': 'application/json' },
651
+ body: JSON.stringify({
652
+ environmentId: environment.environmentId,
653
+ machineName,
654
+ platform: process.platform,
655
+ listenPort,
656
+ publicKey: publicKeyB64,
657
+ }),
658
+ signal: AbortSignal.timeout(10_000),
659
+ });
660
+ const enrollData = await enrollResponse.json().catch(() => ({}));
661
+ if (!enrollResponse.ok || typeof enrollData.enrollmentId !== 'string' || typeof enrollData.consentPath !== 'string') {
662
+ throw new Error(enrollData.error || 'Hosted enrollment failed with HTTP ' + enrollResponse.status);
663
+ }
664
+ const consentUrl = new URL(enrollData.consentPath, appOrigin).href;
665
+ pendingEnrollment = {
666
+ enrollmentId: enrollData.enrollmentId,
667
+ verificationCode: enrollData.verificationCode,
668
+ keyFingerprint: enrollData.keyFingerprint,
669
+ consentUrl,
670
+ expiresAt: enrollData.expiresAt,
671
+ expired: false,
672
+ error: null,
673
+ };
674
+ enrollmentActive = true;
675
+ console.log('Hosted Sandbox consent page: ' + consentUrl);
676
+ console.log('Confirm machine "' + machineName + '" and code ' + enrollData.verificationCode + ' before approving.');
677
+
678
+ async function pollClaim() {
679
+ if (!enrollmentActive || stopping || !waitingForAddress) return;
680
+ try {
681
+ const timestampMs = Date.now();
682
+ const nonce = secret();
683
+ const message = Buffer.from(
684
+ `sandbox-pilot-claim-v1\n${enrollData.enrollmentId}\n${environment.environmentId}\n${timestampMs}\n${nonce}`,
685
+ 'utf8',
686
+ );
687
+ const signature = sign(null, message, privateKey).toString('base64url');
688
+ const claimRes = await fetch(appOrigin + '/api/sandbox/pairing-pilot/enroll/claim', {
689
+ method: 'POST',
690
+ headers: { 'Content-Type': 'application/json' },
691
+ body: JSON.stringify({
692
+ enrollmentId: enrollData.enrollmentId,
693
+ environmentId: environment.environmentId,
694
+ timestampMs,
695
+ nonce,
696
+ signature,
697
+ }),
698
+ signal: AbortSignal.timeout(12_000),
699
+ });
700
+ const claimData = await claimRes.json().catch(() => ({}));
701
+ if (!enrollmentActive || stopping) return;
702
+ if (claimRes.status === 202) {
703
+ enrollmentTimer = setTimeout(() => void pollClaim(), 2000);
704
+ return;
705
+ }
706
+ if (!claimRes.ok) {
707
+ pendingEnrollment = {
708
+ ...pendingEnrollment,
709
+ expired: true,
710
+ error: typeof claimData.error === 'string' ? claimData.error : 'Enrollment ended (' + claimRes.status + ').',
711
+ };
712
+ stopEnrollment();
713
+ console.error(pendingEnrollment.error);
714
+ return;
715
+ }
716
+ const { origin: provisioned, token, ownerId, ownerVerifierPublicKey: verifierKey } = claimData;
717
+ assert(typeof provisioned === 'string' && validAutomaticOrigin(provisioned) &&
718
+ validOwnerId(ownerId) && typeof token === 'string' && /^[A-Za-z0-9_=-]{20,3000}$/.test(token) &&
719
+ typeof verifierKey === 'string' && verifierKey.length >= 32,
720
+ 'Hosted provisioning returned an invalid connector payload');
721
+ const normalizedOwner = ownerId.toLowerCase();
722
+ writePrivateFile(automaticTokenPath, token);
723
+ writePrivateFile(addressPath, JSON.stringify({
724
+ origin: provisioned,
725
+ ownerId: normalizedOwner,
726
+ ownerVerifierPublicKey: verifierKey,
727
+ }));
728
+ stableOrigin = provisioned;
729
+ origin = provisioned;
730
+ owner = { id: normalizedOwner };
731
+ ownerVerifierPublicKey = verifierKey;
732
+ waitingForAddress = false;
733
+ activateNativePreview();
734
+ pendingEnrollment = null;
735
+ stopEnrollment();
736
+ startNamedTunnel(automaticTokenPath);
737
+ await createClaim();
738
+ console.log('Sandbox account approved. Tunnel active at ' + origin);
739
+ } catch {
740
+ if (enrollmentActive && !stopping && waitingForAddress) {
741
+ enrollmentTimer = setTimeout(() => void pollClaim(), 3000);
742
+ }
743
+ }
744
+ }
745
+
746
+ enrollmentTimer = setTimeout(() => void pollClaim(), 1500);
747
+ return pendingEnrollment;
748
+ }
749
+
750
+ await new Promise((resolve, reject) => {
751
+ server.once('error', reject);
752
+ server.listen(listenPort, '127.0.0.1', resolve);
753
+ });
754
+ const local = 'http://127.0.0.1:' + server.address().port;
755
+
756
+ if (selfTest) {
757
+ origin = local;
758
+ owner = { id: '11111111-1111-4111-8111-111111111111' };
759
+ environment = { environmentId: 'test-environment' };
760
+ const ownerPair = generateKeyPairSync('ed25519');
761
+ ownerVerifierPublicKey = ownerPair.publicKey.export({ format: 'der', type: 'spki' }).toString('base64url');
762
+ const signOwner = (action, overrides = {}) => {
763
+ const payload = Buffer.from(JSON.stringify({
764
+ v: 1,
765
+ sub: owner.id,
766
+ env: environment.environmentId,
767
+ origin,
768
+ action,
769
+ iat: Date.now(),
770
+ exp: Date.now() + 30_000,
771
+ jti: randomUUID(),
772
+ ...overrides,
773
+ }), 'utf8').toString('base64url');
774
+ const sig = sign(null, Buffer.from(payload, 'utf8'), ownerPair.privateKey).toString('base64url');
775
+ return `${payload}.${sig}`;
776
+ };
777
+ const claimRequest = (value, requestOrigin = origin) => fetch(local + '/claim', {
778
+ method: 'POST', headers: { Origin: requestOrigin }, body: value,
779
+ });
780
+ try {
781
+ await createClaim();
782
+ claim.expires = Date.now();
783
+ assert.equal((await claimRequest(claim.secret)).status, 409);
784
+ await createClaim();
785
+ assert.equal((await claimRequest(claim.secret, 'https://example.invalid')).status, 403);
786
+ const pair = await Promise.all([claimRequest(claim.secret), claimRequest(claim.secret)]);
787
+ assert.deepEqual(pair.map((r) => r.status).sort(), [202, 409]);
788
+ const cookie = pair.find((r) => r.status === 202).headers.get('set-cookie').split(';')[0];
789
+ const wsUrl = local.replace(/^http/, 'ws') + '/connection';
790
+ const outsider = new WebSocket(wsUrl, { origin });
791
+ await new Promise((resolve, reject) => {
792
+ outsider.once('error', (error) => error.message.includes('403') ? resolve() : reject(error));
793
+ outsider.once('open', () => reject(new Error('Unpaired client connected')));
794
+ });
795
+ const originalOwner = owner;
796
+ owner = { id: '22222222-2222-4222-8222-222222222222' };
797
+ assert.equal(hasDevice({ headers: { cookie } }), false);
798
+ owner = originalOwner;
799
+ const originalEnvironment = environment;
800
+ environment = { environmentId: 'different-environment' };
801
+ assert.equal(hasDevice({ headers: { cookie } }), false);
802
+ environment = originalEnvironment;
803
+
804
+ // Verify signed owner-control endpoints, wrong-action denial, expiry, and jti replay rejection.
805
+ const statusToken = signOwner('status');
806
+ const preflight = await fetch(local + '/pilot/owner/status', {
807
+ method: 'OPTIONS', headers: { Origin: appOrigin, 'Access-Control-Request-Headers': 'authorization' },
808
+ });
809
+ assert.equal(preflight.status, 204);
810
+ assert.equal(preflight.headers.get('access-control-allow-origin'), appOrigin);
811
+ assert.equal((await fetch(local + '/pilot/owner/status', {
812
+ method: 'POST', headers: { Origin: 'https://example.invalid', Authorization: 'Bearer ' + statusToken },
813
+ })).status, 403);
814
+ const browserStatus = await fetch(local + '/pilot/owner/status', {
815
+ method: 'POST', headers: { Origin: appOrigin, Authorization: 'Bearer ' + signOwner('status') },
816
+ });
817
+ assert.equal(browserStatus.status, 200);
818
+ assert.equal(browserStatus.headers.get('access-control-allow-origin'), appOrigin);
819
+ assert.equal((await fetch(local + '/pilot/owner/status', {
820
+ method: 'POST', headers: { Authorization: 'Bearer ' + statusToken },
821
+ })).status, 200);
822
+ assert.equal((await fetch(local + '/pilot/owner/status', {
823
+ method: 'POST', headers: { Authorization: 'Bearer ' + statusToken },
824
+ })).status, 403);
825
+ assert.equal((await fetch(local + '/pilot/owner/approve', {
826
+ method: 'POST', headers: { Authorization: 'Bearer ' + signOwner('status') },
827
+ })).status, 403);
828
+ assert.equal((await fetch(local + '/pilot/owner/status', {
829
+ method: 'POST', headers: { Authorization: 'Bearer ' + signOwner('status', { exp: Date.now() - 1000 }) },
830
+ })).status, 403);
831
+
832
+ const phone = new WebSocket(wsUrl, { origin, headers: { Cookie: cookie } });
833
+ await new Promise((resolve, reject) => {
834
+ phone.on('error', reject);
835
+ phone.on('message', (message) => {
836
+ if (message.toString().startsWith('Waiting')) approve();
837
+ else if (message.toString() === connectedMessage) revoke();
838
+ });
839
+ phone.once('close', (code) => code === 1008 ? resolve() : reject(new Error('Expected revocation')));
840
+ });
841
+ console.log('PASS: QR expiry, origin check, concurrent claims, wrong account and environment, unpaired socket, signed owner controls, replay rejection, approval and revocation');
842
+ } finally {
843
+ stop();
844
+ }
845
+ } else {
846
+ const t3 = await fetch('http://127.0.0.1:3773/.well-known/t3/environment', { signal: AbortSignal.timeout(5000) });
847
+ assert(t3.ok, 'Stock T3 is not answering on this computer');
848
+ environment = await t3.json();
849
+ assert(environment.environmentId && environment.serverVersion, 'Stock T3 did not identify its environment');
850
+ if (stableOrigin) {
851
+ origin = stableOrigin;
852
+ if (automaticOwnerId) owner = { id: automaticOwnerId };
853
+ device = loadDevice(devicePath, origin, environment.environmentId);
854
+ if (device) {
855
+ owner = { id: device.ownerId };
856
+ scheduleExpiry(device.expiresAt - Date.now());
857
+ console.log('Restored the approved phone pairing.');
858
+ }
859
+ }
860
+ console.log('Verified the local stock T3 environment, version ' + environment.serverVersion);
861
+ const chatTitle = option('--chat-thread');
862
+ const threadIdOpt = option('--thread-id');
863
+ if (chatTitle || threadIdOpt || hostedMode || serviceMode) {
864
+ try {
865
+ const additionalTitles = process.argv.filter((argument) => argument.startsWith('--allow-thread='))
866
+ .map((argument) => argument.slice('--allow-thread='.length));
867
+ const previewUrl = option('--preview-url');
868
+ const usePreview = process.argv.includes('--preview') || Boolean(previewUrl);
869
+ const sessionPath = serviceMode ? join(dirname(qrPath), 't3-session.json') : undefined;
870
+ chat = await openPilotChat(chatTitle, environment.environmentId, additionalTitles, {
871
+ preview: usePreview,
872
+ sessionPath,
873
+ threadId: threadIdOpt,
874
+ });
875
+ await chat.snapshot();
876
+ if (usePreview) {
877
+ preview = await startPilotPreview(chat, previewUrl);
878
+ console.log('Ready to stream the approved localhost page over the paired connection.');
879
+ }
880
+ console.log('Ready to serve T3 threads over the paired connection.');
881
+ } catch (error) {
882
+ stop();
883
+ throw error;
884
+ }
885
+ }
886
+
887
+ activateNativePreview();
888
+
889
+ // The dev app checks its own Sandbox session and signs this local handoff.
890
+ const ownerSecret = secret();
891
+ admin = createServer(async (request, response) => {
892
+ if (request.headers.authorization !== 'Bearer ' + ownerSecret) return send(response, 403, 'Forbidden');
893
+ if (request.method === 'GET' && request.url === '/status') {
894
+ return send(response, 200, JSON.stringify({
895
+ ready: Boolean(origin) || waitingForAddress,
896
+ verified: Boolean(owner),
897
+ pairing: device?.approved ? 'approved' : device ? 'pending' : 'unpaired',
898
+ origin: origin ?? null,
899
+ environmentId: environment.environmentId,
900
+ ownerId: owner?.id ?? null,
901
+ qrPath: claim ? qrPath : null,
902
+ enrollment: pendingEnrollment,
903
+ }), 'application/json');
904
+ }
905
+ if (request.method === 'POST' && request.url === '/native-preview') {
906
+ if (!nativePreview || !device?.approved) return send(response, 409, 'Native preview is unavailable');
907
+ return send(response, 200, JSON.stringify({ url: nativePreview.issueTicket() }), 'application/json');
908
+ }
909
+ if (serviceMode && request.method === 'POST' && request.url === '/shutdown') {
910
+ response.once('finish', stop);
911
+ return send(response, 200, '{}', 'application/json');
912
+ }
913
+ if (autoAddress && hostedMode && request.method === 'POST' && request.url === '/enrollment/refresh') {
914
+ if (!waitingForAddress) return send(response, 409, JSON.stringify({ error: 'Already provisioned.' }), 'application/json');
915
+ try {
916
+ const refreshed = await startHostedEnrollment();
917
+ return send(response, 200, JSON.stringify(refreshed), 'application/json');
918
+ } catch (error) {
919
+ return send(response, 503, JSON.stringify({ error: error.message }), 'application/json');
920
+ }
921
+ }
922
+ if (autoAddress && request.method === 'POST' && request.url === '/owner/address') {
923
+ try {
924
+ let body = '';
925
+ for await (const chunk of request) {
926
+ body += chunk;
927
+ if (body.length > 4096) return send(response, 413, 'Invalid address');
928
+ }
929
+ const { origin: provisioned, token, ownerId } = JSON.parse(body);
930
+ if (typeof provisioned !== 'string' || !validAutomaticOrigin(provisioned) ||
931
+ !validOwnerId(ownerId) ||
932
+ typeof token !== 'string' || !/^[A-Za-z0-9_=-]{20,3000}$/.test(token)) {
933
+ return send(response, 400, 'Invalid address');
934
+ }
935
+ if (!waitingForAddress) return send(response, origin === provisioned && owner?.id === ownerId ? 200 : 409,
936
+ 'Address already configured');
937
+ writePrivateFile(automaticTokenPath, token);
938
+ writePrivateFile(addressPath, JSON.stringify({ origin: provisioned, ownerId }));
939
+ stableOrigin = provisioned;
940
+ origin = provisioned;
941
+ owner = { id: ownerId };
942
+ waitingForAddress = false;
943
+ activateNativePreview();
944
+ writePrivateFile(configPath, JSON.stringify({
945
+ port: admin.address().port, secret: ownerSecret, pid: process.pid, service: serviceMode,
946
+ }));
947
+ startNamedTunnel(automaticTokenPath);
948
+ return send(response, 200, 'Address saved');
949
+ } catch {
950
+ return send(response, 503, 'Could not save the automatic address');
951
+ }
952
+ }
953
+ if (request.method !== 'POST' || !['/owner', '/owner/qr', '/owner/approve', '/owner/revoke'].includes(request.url)) {
954
+ return send(response, 404, 'Not found');
955
+ }
956
+ let accountId = '';
957
+ try {
958
+ for await (const chunk of request) {
959
+ accountId += chunk;
960
+ if (accountId.length > 64) return send(response, 400, 'Invalid account');
961
+ }
962
+ if (!/^[0-9a-f-]{36}$/i.test(accountId)) return send(response, 400, 'Invalid account');
963
+ if (request.url !== '/owner') {
964
+ if (owner?.id?.toLowerCase() !== accountId.toLowerCase()) return send(response, 403, 'Verify the pilot owner first');
965
+ if (request.url === '/owner/approve') {
966
+ return approve() ? send(response, 200, 'Phone approved. Open Sandbox Code on your phone.')
967
+ : send(response, 409, 'Scan the QR and request pairing first.');
968
+ }
969
+ if (request.url === '/owner/revoke') {
970
+ claim = null;
971
+ revoke();
972
+ return send(response, 200, 'Phone access removed.');
973
+ }
974
+ if (!origin) return send(response, 503, 'The remote address is still starting.');
975
+ if (device) return send(response, 409, device.approved
976
+ ? 'This phone is already approved.' : 'A phone is waiting for approval.');
977
+ if (!claim || Date.now() >= claim.expires) await createClaim();
978
+ const current = claim;
979
+ const image = await current?.image;
980
+ if (!image || claim !== current) return send(response, 409, 'The QR was already used.');
981
+ return send(response, 200, image, 'image/png');
982
+ }
983
+ if (owner && owner.id.toLowerCase() !== accountId.toLowerCase()) return send(response, 403, 'This pilot already has an owner');
984
+ owner = { id: accountId };
985
+ if (origin && !claim && !device) await createClaim();
986
+ console.log('Verified the signed-in Sandbox account as the pilot owner.');
987
+ return send(response, 200, 'Sandbox account verified. The pairing QR will appear on this computer.');
988
+ } catch {
989
+ return send(response, 503, 'Sandbox account verification unavailable');
990
+ }
991
+ });
992
+ await new Promise((resolve) => admin.listen(0, '127.0.0.1', resolve));
993
+ const configPath = join(homedir(), '.sandbox-pairing-pilot-owner.json');
994
+ try {
995
+ if (serviceMode) {
996
+ try {
997
+ const previous = JSON.parse(readFileSync(configPath, 'utf8'));
998
+ if (previous.service === true && Number.isSafeInteger(previous.pid) && previous.pid > 0) {
999
+ try { process.kill(previous.pid, 0); }
1000
+ catch (error) { if (error.code === 'ESRCH') unlinkSync(configPath); }
1001
+ }
1002
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
1003
+ }
1004
+ writeFileSync(configPath, JSON.stringify({ port: admin.address().port, secret: ownerSecret,
1005
+ pid: process.pid, service: serviceMode,
1006
+ address: waitingForAddress && !hostedMode ? { environmentId: environment.environmentId, port: listenPort } : undefined,
1007
+ }), { mode: 0o600, flag: 'wx' });
1008
+ ownerFile = configPath;
1009
+ } catch {
1010
+ stop();
1011
+ throw new Error('A pairing pilot configuration already exists or cannot be written.');
1012
+ }
1013
+ console.log('Owner setup: ' + appOrigin + '/sandbox/pairing-pilot');
1014
+ if (useNgrok) {
1015
+ const directory = dirname(devicePath);
1016
+ startTunnel(join(directory, 'ngrok'),
1017
+ ['http', local, '--url', stableOrigin, '--config', join(directory, 'ngrok.yml'), '--inspect=false',
1018
+ '--log', 'stderr', '--log-level', 'warn'], 'Stable tunnel').stderr.resume();
1019
+ } else if (autoAddress) {
1020
+ if (stableOrigin) {
1021
+ startNamedTunnel(automaticTokenPath);
1022
+ if (owner && !device) void createClaim().catch((error) => console.error(error.message));
1023
+ } else if (hostedMode) {
1024
+ await startHostedEnrollment();
1025
+ }
1026
+ } else if (useCloudflare) {
1027
+ const tokenFile = join(dirname(devicePath), 'cloudflare-tunnel-token');
1028
+ startTunnel(cloudflaredBinary(), ['tunnel', '--no-autoupdate', '--loglevel', 'warn', 'run',
1029
+ '--token-file', tokenFile], 'Named Cloudflare tunnel').stderr.resume();
1030
+ } else if (!stableOrigin) startQuickTunnel();
1031
+ const input = serviceMode ? null : createInterface({ input: process.stdin });
1032
+ input?.on('line', (line) => {
1033
+ if (line === 'approve') approve();
1034
+ if (line === 'revoke') revoke();
1035
+ if (line === 'new' && origin && owner) void createClaim().catch((error) => console.error(error.message));
1036
+ if (line === 'stop') stop();
1037
+ });
1038
+ const expiry = serviceMode ? undefined : setTimeout(stop, pilotLifetime);
1039
+ server.once('close', () => { input?.close(); clearTimeout(expiry); });
1040
+ process.on('SIGINT', stop);
1041
+ process.on('SIGTERM', stop);
1042
+ }
1043
+
1044
+ function startTunnel(binary, args, label) {
1045
+ tunnel = spawn(binary, args, {
1046
+ stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true,
1047
+ env: process.platform === 'win32' ? process.env : { HOME: homedir(), PATH: process.env.PATH },
1048
+ });
1049
+ tunnel.on('error', () => { console.error(label + ' could not start.'); stop(); process.exitCode = 1; });
1050
+ tunnel.on('exit', (code) => {
1051
+ const unexpected = !stopping;
1052
+ if (unexpected) console.error(label + ' exited with code ' + code);
1053
+ stop();
1054
+ if (unexpected) process.exitCode = 1;
1055
+ });
1056
+ return tunnel;
1057
+ }
1058
+
1059
+ function writePrivateFile(path, value) {
1060
+ const stage = path + '.' + process.pid + '.new';
1061
+ try {
1062
+ writeFileSync(stage, value, { mode: 0o600, flag: 'wx' });
1063
+ renameSync(stage, path);
1064
+ } finally { rmSync(stage, { force: true }); }
1065
+ }
1066
+
1067
+ function startNamedTunnel(tokenFile) {
1068
+ startTunnel(cloudflaredBinary(), ['tunnel', '--no-autoupdate', '--loglevel', 'warn', 'run',
1069
+ '--token-file', tokenFile], 'Named Cloudflare tunnel').stderr.resume();
1070
+ }
1071
+
1072
+ function cloudflaredBinary() {
1073
+ if (process.env.SANDBOX_CLOUDFLARED) return process.env.SANDBOX_CLOUDFLARED;
1074
+ const tools = join(homeDir(), '.t3', 'tools', 'cloudflared');
1075
+ if (existsSync(tools)) {
1076
+ const versions = readdirSync(tools).sort((left, right) => right.localeCompare(left, undefined, { numeric: true }));
1077
+ const exeName = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';
1078
+ const bundled = versions.map((version) => join(tools, version, process.platform + '-' + process.arch, exeName)).find(existsSync);
1079
+ if (bundled) return bundled;
1080
+ }
1081
+ return 'cloudflared';
1082
+ }
1083
+
1084
+ function homeDir() {
1085
+ return homedir();
1086
+ }
1087
+
1088
+ function startQuickTunnel() {
1089
+ const child = startTunnel(cloudflaredBinary(), ['tunnel', '--no-autoupdate', '--url', local], 'Quick Tunnel');
1090
+ let output = '';
1091
+ child.stderr.on('data', (chunk) => {
1092
+ if (origin) return;
1093
+ output = (output + chunk).slice(-8000);
1094
+ const url = output.match(/https:\/\/[\w-]+\.trycloudflare\.com/)?.[0];
1095
+ if (url) {
1096
+ origin = url;
1097
+ if (owner) void createClaim().catch((error) => { console.error(error.message); stop(); });
1098
+ }
1099
+ });
1100
+ }