@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,391 @@
1
+ import assert from 'node:assert/strict';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, isAbsolute, join } from 'node:path';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { installWindowsTask, openWindowsUrl, readWindowsTaskOptions, removeWindowsTask,
9
+ startWindowsTask, windowsTaskRunning } from './sandbox-remote-windows.mjs';
10
+ import { findWindowsT3, runT3Cli } from './sandbox-remote-t3-cli.mjs';
11
+
12
+ const home = homedir();
13
+ const windows = process.platform === 'win32';
14
+ const root = fileURLToPath(new URL('..', import.meta.url));
15
+ const label = 'com.aretaxia.sandbox.remote-pilot';
16
+ const domain = 'gui/' + process.getuid?.();
17
+ const service = domain + '/' + label;
18
+ const stateDir = windows
19
+ ? join(process.env.LOCALAPPDATA ?? join(home, 'AppData', 'Local'), 'Aretaxia', 'Sandbox Remote Pilot')
20
+ : join(home, 'Library', 'Application Support', 'Aretaxia', 'Sandbox Remote Pilot');
21
+ const servicePath = windows ? join(stateDir, 'task.json') : join(home, 'Library', 'LaunchAgents', label + '.plist');
22
+ const logPath = join(stateDir, 'connector.log');
23
+ const ownerPath = join(home, '.sandbox-pairing-pilot-owner.json');
24
+ const args = process.argv.slice(2);
25
+ const action = args[0]?.startsWith('--') ? 'setup' : (args.shift() ?? 'setup');
26
+
27
+ function normalizeSandboxOrigin(raw) {
28
+ if (!raw) return null;
29
+ const parsed = URL.parse(raw);
30
+ const localHttp = parsed?.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(parsed.hostname);
31
+ assert(parsed && (parsed.protocol === 'https:' || localHttp) &&
32
+ parsed.origin === raw.replace(/\/+$/, '') && !parsed.username && !parsed.password,
33
+ 'Provide --sandbox-url=https://your-sandbox-host');
34
+ return parsed.origin;
35
+ }
36
+
37
+ const rawOptions = args.filter((arg) => arg !== '--no-open').map((arg) => {
38
+ if (arg.startsWith('--sandbox-url=')) {
39
+ return '--sandbox-url=' + normalizeSandboxOrigin(arg.slice('--sandbox-url='.length));
40
+ }
41
+ return arg;
42
+ });
43
+ const envSandboxUrl = normalizeSandboxOrigin(process.env.SANDBOX_REMOTE_URL);
44
+ const tunnelFlags = ['--ngrok', '--cloudflare'];
45
+ const addressArgs = (options) => options.filter((arg) =>
46
+ /^--(public-origin|listen-port)=/.test(arg) || tunnelFlags.includes(arg));
47
+
48
+ const explicitSandboxUrl = rawOptions.find((arg) => arg.startsWith('--sandbox-url='))?.slice('--sandbox-url='.length)
49
+ ?? envSandboxUrl;
50
+ const localRequested = rawOptions.includes('--local') ||
51
+ (Boolean(explicitSandboxUrl) && ['http://localhost:3013', 'http://127.0.0.1:3013'].includes(explicitSandboxUrl));
52
+ const hostedRequested = rawOptions.includes('--hosted') || !localRequested;
53
+ const effectiveSandboxUrl = explicitSandboxUrl ?? (hostedRequested ? 'https://sandbox.aretaxia.com' : 'http://localhost:3013');
54
+
55
+ function buildSetupOptions() {
56
+ const options = rawOptions.filter((arg) => arg !== '--local');
57
+ if (hostedRequested && !options.some((arg) => arg.startsWith('--sandbox-url='))) {
58
+ options.push('--sandbox-url=' + effectiveSandboxUrl);
59
+ }
60
+ if (hostedRequested && !options.includes('--hosted')) {
61
+ options.push('--hosted');
62
+ }
63
+ if (hostedRequested && !addressArgs(options).length && !options.includes('--auto-address')) {
64
+ options.push('--auto-address');
65
+ }
66
+ return options;
67
+ }
68
+
69
+ const setupOptions = buildSetupOptions();
70
+ const setupPage = effectiveSandboxUrl + '/sandbox/pairing-pilot';
71
+ const run = (exe, argv) => execFileSync(exe, argv, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 15_000 });
72
+ const launch = (...argv) => run('/bin/launchctl', argv);
73
+
74
+ function loaded() {
75
+ if (windows) return windowsTaskRunning();
76
+ try { launch('print', service); return true; } catch { return false; }
77
+ }
78
+
79
+ async function ownerRequest(path, method, body) {
80
+ if (!loaded()) return null;
81
+ try {
82
+ const config = JSON.parse(readFileSync(ownerPath, 'utf8'));
83
+ if (config.service !== true || !Number.isInteger(config.port) || config.port < 1024 || config.port > 65535 ||
84
+ typeof config.secret !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(config.secret)) return null;
85
+ const response = await fetch('http://127.0.0.1:' + config.port + path, {
86
+ method,
87
+ headers: { Authorization: 'Bearer ' + config.secret },
88
+ body,
89
+ signal: AbortSignal.timeout(8000),
90
+ });
91
+ const text = await response.text();
92
+ let json = null;
93
+ try { json = JSON.parse(text); } catch { /* text response */ }
94
+ return { ok: response.ok, status: response.status, text, json, contentType: response.headers.get('content-type') };
95
+ } catch { return null; }
96
+ }
97
+
98
+ async function status() {
99
+ const res = await ownerRequest('/status', 'GET');
100
+ return res?.ok ? res.json : null;
101
+ }
102
+
103
+ function readLogTail() {
104
+ if (!existsSync(logPath)) return '';
105
+ try {
106
+ const lines = readFileSync(logPath, 'utf8').trim().split(/\r?\n/).slice(-8);
107
+ return lines.length ? '\nRecent connector log:\n' + lines.join('\n') : '';
108
+ } catch {
109
+ return '';
110
+ }
111
+ }
112
+
113
+ async function waitForReady() {
114
+ for (let attempt = 0; attempt < 45; attempt += 1) {
115
+ const state = await status();
116
+ if (state?.ready) return state;
117
+ if (attempt >= 3 && !loaded()) {
118
+ throw new Error('The connector stopped before becoming ready. Check ' + logPath + readLogTail());
119
+ }
120
+ await delay(1000);
121
+ }
122
+ throw new Error('The connector did not become ready. Check ' + logPath + readLogTail());
123
+ }
124
+
125
+ async function waitForHostedApproval(initialState) {
126
+ let state = initialState;
127
+ if (state.enrollment?.expired) {
128
+ const refreshed = await ownerRequest('/enrollment/refresh', 'POST');
129
+ if (refreshed?.ok && refreshed.json) {
130
+ state = { ...state, enrollment: refreshed.json };
131
+ }
132
+ }
133
+ if (!state.enrollment) return state;
134
+ console.log('Open this Sandbox page to sign in and approve this computer:');
135
+ console.log(' ' + state.enrollment.consentUrl);
136
+ console.log('Confirm verification code ' + state.enrollment.verificationCode + ' matches before approving.');
137
+ if (!args.includes('--no-open')) {
138
+ if (windows) openWindowsUrl(state.enrollment.consentUrl);
139
+ else run('/usr/bin/open', [state.enrollment.consentUrl]);
140
+ }
141
+ const deadline = Math.max(Date.now() + 60_000, Date.parse(state.enrollment.expiresAt) || Date.now() + 300_000);
142
+ while (Date.now() < deadline) {
143
+ await delay(1500);
144
+ if (!loaded()) {
145
+ throw new Error('The connector stopped while waiting for approval. Check ' + logPath + readLogTail());
146
+ }
147
+ const next = await status();
148
+ if (!next) continue;
149
+ if (next.verified && next.origin) return next;
150
+ if (next.enrollment?.expired) {
151
+ throw new Error(next.enrollment.error || 'Hosted enrollment expired or was denied. Run setup again.');
152
+ }
153
+ }
154
+ throw new Error('Timed out waiting for Sandbox approval. Re-run setup to try again.');
155
+ }
156
+
157
+ async function unload() {
158
+ if (!loaded()) return;
159
+ if (windows) await ownerRequest('/shutdown', 'POST');
160
+ else launch('bootout', service);
161
+ for (let attempt = 0; attempt < 60; attempt += 1) {
162
+ if (!loaded()) return;
163
+ await delay(250);
164
+ }
165
+ throw new Error('The connector is still shutting down.');
166
+ }
167
+
168
+ function findCloudflared() {
169
+ const explicit = process.env.SANDBOX_CLOUDFLARED;
170
+ if (explicit) {
171
+ assert(isAbsolute(explicit) && existsSync(explicit), 'SANDBOX_CLOUDFLARED must identify an installed binary');
172
+ return explicit;
173
+ }
174
+ const tools = join(home, '.t3', 'tools', 'cloudflared');
175
+ const versions = existsSync(tools) ? readdirSync(tools).sort((left, right) => right.localeCompare(left, undefined, { numeric: true })) : [];
176
+ const bundled = versions.map((version) => join(tools, version, process.platform + '-' + process.arch,
177
+ windows ? 'cloudflared.exe' : 'cloudflared')).find(existsSync);
178
+ if (bundled) return bundled;
179
+ try { return findExecutable('cloudflared'); }
180
+ catch { throw new Error('Install cloudflared or let official T3 Code download its connector first.'); }
181
+ }
182
+
183
+ function findExecutable(name) {
184
+ return windows ? run('where.exe', [name + '.exe']).split(/\r?\n/)[0].trim()
185
+ : run('/usr/bin/which', [name]).trim();
186
+ }
187
+
188
+ function plistString(value) {
189
+ return '<string>' + value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;') + '</string>';
190
+ }
191
+
192
+ function install(options) {
193
+ const t3 = windows ? findWindowsT3() : findExecutable('t3');
194
+ const address = validateAddress(addressArgs(options));
195
+ assert(!options.includes('--auto-address') || !address.length,
196
+ 'Automatic address setup cannot be combined with a manual address.');
197
+ const cloudflared = !address.length || address.includes('--cloudflare') ? findCloudflared() : '';
198
+ if (address.includes('--ngrok')) {
199
+ assert(!windows, 'The existing ngrok pilot is macOS-only.');
200
+ assert(existsSync(join(stateDir, 'ngrok')) && existsSync(join(stateDir, 'ngrok.yml')),
201
+ 'The smac2 ngrok executable and private configuration are required.');
202
+ }
203
+ if (address.includes('--cloudflare')) {
204
+ assert(existsSync(join(stateDir, 'cloudflare-tunnel-token')),
205
+ 'The private Cloudflare tunnel token file is required.');
206
+ }
207
+ const paths = [...new Set([dirname(t3), dirname(process.execPath), '/usr/bin', '/bin', '/usr/sbin', '/sbin'])].join(':');
208
+ assert(options.every((arg) =>
209
+ /^--(chat-thread|allow-thread|thread-id|preview-url|native-preview-origin|public-origin|listen-port|sandbox-url)=.+$/.test(arg) ||
210
+ arg === '--preview' || arg === '--auto-address' || arg === '--hosted' || tunnelFlags.includes(arg)),
211
+ 'Unknown setup option');
212
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
213
+ if (windows) {
214
+ writeFileSync(servicePath, JSON.stringify({
215
+ node: process.execPath, log: logPath,
216
+ arguments: [join(root, 'scripts/sandbox-pairing-pilot.mjs'), '--service', ...options],
217
+ environment: {
218
+ SANDBOX_T3_EXECUTABLE: t3,
219
+ SANDBOX_CLOUDFLARED: cloudflared,
220
+ SANDBOX_PILOT_QR: join(stateDir, 'pairing.png'),
221
+ SANDBOX_PILOT_DEVICE_FILE: join(stateDir, 'approved-device.json'),
222
+ },
223
+ }), { mode: 0o600 });
224
+ installWindowsTask(servicePath, root);
225
+ return;
226
+ }
227
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
228
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
229
+ <plist version="1.0"><dict>
230
+ <key>Label</key>${plistString(label)}
231
+ <key>ProgramArguments</key><array>${[process.execPath, join(root, 'scripts/sandbox-pairing-pilot.mjs'), '--service', ...options].map(plistString).join('')}</array>
232
+ <key>WorkingDirectory</key>${plistString(root)}
233
+ <key>RunAtLoad</key><true/>
234
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
235
+ <key>ThrottleInterval</key><integer>15</integer>
236
+ <key>Umask</key><integer>63</integer>
237
+ <key>StandardOutPath</key>${plistString(logPath)}
238
+ <key>StandardErrorPath</key>${plistString(logPath)}
239
+ <key>EnvironmentVariables</key><dict>
240
+ <key>PATH</key>${plistString(paths)}
241
+ <key>SANDBOX_CLOUDFLARED</key>${plistString(cloudflared)}
242
+ <key>SANDBOX_PILOT_QR</key>${plistString(join(stateDir, 'pairing.png'))}
243
+ <key>SANDBOX_PILOT_DEVICE_FILE</key>${plistString(join(stateDir, 'approved-device.json'))}
244
+ </dict></dict></plist>
245
+ `;
246
+ chmodSync(stateDir, 0o700);
247
+ mkdirSync(dirname(servicePath), { recursive: true });
248
+ const stage = servicePath + '.' + process.pid + '.tmp';
249
+ try {
250
+ writeFileSync(stage, xml, { mode: 0o600, flag: 'wx' });
251
+ run('/usr/bin/plutil', ['-lint', stage]);
252
+ renameSync(stage, servicePath);
253
+ } finally { rmSync(stage, { force: true }); }
254
+ }
255
+
256
+ function validateAddress(options) {
257
+ if (!options.length) return options;
258
+ const origin = options.find((arg) => arg.startsWith('--public-origin='))?.slice('--public-origin='.length);
259
+ const port = Number(options.find((arg) => arg.startsWith('--listen-port='))?.slice('--listen-port='.length));
260
+ const url = origin && URL.parse(origin);
261
+ const providers = options.filter((arg) => tunnelFlags.includes(arg));
262
+ assert(providers.length <= 1 && options.length === 2 + providers.length &&
263
+ addressArgs(options).length === options.length &&
264
+ url?.protocol === 'https:' && url.origin === origin && !url.port &&
265
+ Number.isInteger(port) && port >= 1024 && port <= 65535,
266
+ 'Provide --public-origin=https://your-hostname and --listen-port=port');
267
+ return options;
268
+ }
269
+
270
+ function storedOptions() {
271
+ if (windows) return readWindowsTaskOptions(servicePath);
272
+ return JSON.parse(run('/usr/bin/plutil', ['-extract', 'ProgramArguments', 'json', '-o', '-', servicePath])).slice(3);
273
+ }
274
+
275
+ async function runLocalOwnerAction(ownerAction) {
276
+ const current = await status();
277
+ assert(current?.ready, 'Connector is not running.');
278
+ assert(current.verified && current.ownerId, 'Complete Sandbox sign-in and approval first.');
279
+ const res = await ownerRequest('/owner/' + ownerAction, 'POST', current.ownerId);
280
+ assert(res, 'Could not reach the local connector.');
281
+ if (!res.ok) {
282
+ throw new Error(res.text || 'Owner action failed (' + res.status + ').');
283
+ }
284
+ if (ownerAction === 'qr') {
285
+ const updated = await status();
286
+ console.log('Pairing QR ready at ' + (updated?.qrPath ?? join(stateDir, 'pairing.png')));
287
+ } else {
288
+ console.log(res.text);
289
+ }
290
+ }
291
+
292
+ async function main() {
293
+ assert(process.platform === 'darwin' || windows, 'This pilot installer supports macOS and Windows.');
294
+ if (action === 'status') {
295
+ const state = await status();
296
+ console.log(state ? JSON.stringify(state) : loaded() ? 'Connector is starting.' : 'Connector is stopped.');
297
+ return;
298
+ }
299
+ if (action === 'qr' || action === 'approve' || action === 'revoke') {
300
+ await runLocalOwnerAction(action);
301
+ return;
302
+ }
303
+ if (action === 'uninstall' || action === 'restart' || action === 'reauthorize') {
304
+ let restartOptions;
305
+ if (action === 'restart' && rawOptions.length) {
306
+ assert(existsSync(servicePath), 'Run setup first.');
307
+ const updates = new Map();
308
+ for (const option of rawOptions) {
309
+ const [, name, value] = option.match(/^--(preview-url|native-preview-origin)=(.+)$/) ?? [];
310
+ assert(name && !updates.has(name), 'Restart accepts one --preview-url and one --native-preview-origin.');
311
+ const url = URL.parse(value);
312
+ if (name === 'preview-url') {
313
+ assert(url?.protocol === 'http:' && url.hostname === '127.0.0.1' && url.port &&
314
+ !url.username && !url.password && !url.hash, 'Use an approved loopback HTTP dev server URL');
315
+ } else {
316
+ assert(url?.protocol === 'https:' && url.origin === value, 'Invalid --native-preview-origin');
317
+ }
318
+ updates.set(name, option);
319
+ }
320
+ restartOptions = storedOptions().filter((option) => !updates.has(option.split('=')[0].slice(2)));
321
+ restartOptions.push(...updates.values());
322
+ }
323
+ await unload();
324
+ if (restartOptions) install(restartOptions);
325
+ if (action !== 'restart') {
326
+ const sessionPath = join(stateDir, 't3-session.json');
327
+ if (existsSync(sessionPath)) {
328
+ const { sessionId } = JSON.parse(readFileSync(sessionPath, 'utf8'));
329
+ const executable = windows ? findWindowsT3() : findExecutable('t3');
330
+ const sessions = JSON.parse(runT3Cli(executable, ['auth', 'session', 'list', '--json']));
331
+ if (sessions.some((session) => session.sessionId === sessionId &&
332
+ session.client?.label === 'Aretaxia Sandbox · Remote Access')) {
333
+ runT3Cli(executable, ['auth', 'session', 'revoke', sessionId]);
334
+ }
335
+ rmSync(sessionPath);
336
+ }
337
+ }
338
+ if (action === 'uninstall') {
339
+ if (windows) removeWindowsTask();
340
+ rmSync(servicePath, { force: true });
341
+ rmSync(stateDir, { recursive: true, force: true });
342
+ console.log('Sandbox Remote Pilot removed.');
343
+ return;
344
+ }
345
+ assert(existsSync(servicePath), 'Run setup first.');
346
+ } else if (action === 'address') {
347
+ assert(existsSync(servicePath), 'Run setup first.');
348
+ const address = validateAddress(setupOptions);
349
+ assert(address.length, 'Specify a stable address and the tunnel’s loopback port.');
350
+ const current = storedOptions().filter((arg) => !addressArgs([arg]).length && arg !== '--auto-address');
351
+ if (windows) await unload();
352
+ install([...current, ...address]);
353
+ if (!windows) await unload();
354
+ } else {
355
+ assert(action === 'setup', 'Use setup, address, status, qr, approve, revoke, restart, reauthorize, or uninstall.');
356
+ if (!existsSync(servicePath)) install(setupOptions);
357
+ else if (rawOptions.length) {
358
+ assert(JSON.stringify(storedOptions()) === JSON.stringify(setupOptions),
359
+ 'Setup already uses different test options. Rerun without options to keep the existing configuration.');
360
+ }
361
+ }
362
+ if (!loaded()) {
363
+ if (windows) startWindowsTask();
364
+ else launch('bootstrap', domain, servicePath);
365
+ }
366
+ let state = await waitForReady();
367
+ if (action === 'setup' && state.enrollment) {
368
+ state = await waitForHostedApproval(state);
369
+ console.log('Sandbox Remote Pilot is running. Tunnel: ' + state.origin + '. Phone pairing: ' + state.pairing + '.');
370
+ if (state.qrPath) console.log('Pairing QR saved at: ' + state.qrPath);
371
+ return;
372
+ }
373
+ console.log('Sandbox Remote Pilot is running. Phone pairing: ' + state.pairing + '.');
374
+ if (state.origin) console.log('Tunnel address: ' + state.origin);
375
+ if (state.qrPath) console.log('Pairing QR saved at: ' + state.qrPath);
376
+ if (action === 'setup' || action === 'address') {
377
+ const managePage = hostedRequested && state.environmentId
378
+ ? setupPage + '?environmentId=' + encodeURIComponent(state.environmentId)
379
+ : setupPage;
380
+ console.log('Verify your Sandbox account and scan the QR at ' + managePage);
381
+ if (!args.includes('--no-open')) {
382
+ if (windows) openWindowsUrl(managePage);
383
+ else run('/usr/bin/open', [managePage]);
384
+ }
385
+ }
386
+ }
387
+
388
+ main().catch((error) => {
389
+ console.error(error.message);
390
+ process.exitCode = 1;
391
+ });
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.