@aretaxia/sandbox-remote 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +31 -4
- package/sandbox-remote.mjs +45 -0
- package/scripts/sandbox-native-preview.mjs +253 -0
- package/scripts/sandbox-pairing-pilot.mjs +1126 -0
- package/scripts/sandbox-pilot-device.mjs +38 -0
- package/scripts/sandbox-pilot-preview.mjs +179 -0
- package/scripts/sandbox-pilot-t3-chat.mjs +364 -0
- package/scripts/sandbox-remote-t3-cli.mjs +33 -0
- package/scripts/sandbox-remote-windows.mjs +55 -0
- package/scripts/setup-sandbox-remote.mjs +391 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aretaxia/sandbox-remote",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Connect your local T3 Code workspace to Aretaxia Sandbox Remote Access",
|
|
5
|
+
"bin": {
|
|
6
|
+
"sandbox-remote": "./sandbox-remote.mjs"
|
|
7
|
+
},
|
|
8
|
+
"publishConfig": {
|
|
9
|
+
"access": "public"
|
|
10
|
+
},
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=22.1"
|
|
13
|
+
},
|
|
14
|
+
"os": [
|
|
15
|
+
"darwin",
|
|
16
|
+
"win32"
|
|
17
|
+
],
|
|
18
|
+
"files": [
|
|
19
|
+
"sandbox-remote.mjs",
|
|
20
|
+
"scripts/setup-sandbox-remote.mjs",
|
|
21
|
+
"scripts/sandbox-pairing-pilot.mjs",
|
|
22
|
+
"scripts/sandbox-pilot-device.mjs",
|
|
23
|
+
"scripts/sandbox-pilot-preview.mjs",
|
|
24
|
+
"scripts/sandbox-native-preview.mjs",
|
|
25
|
+
"scripts/sandbox-pilot-t3-chat.mjs",
|
|
26
|
+
"scripts/sandbox-remote-windows.mjs",
|
|
27
|
+
"scripts/sandbox-remote-t3-cli.mjs"
|
|
28
|
+
],
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"qrcode": "1.5.4",
|
|
31
|
+
"ws": "8.23.0"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const args = process.argv.slice(2);
|
|
9
|
+
const action = args[0]?.startsWith('--') ? 'setup' : (args[0] ?? 'setup');
|
|
10
|
+
const sourceRoot = fileURLToPath(new URL('.', import.meta.url));
|
|
11
|
+
const windows = process.platform === 'win32';
|
|
12
|
+
const platformData = windows ? (process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'))
|
|
13
|
+
: join(homedir(), 'Library', 'Application Support');
|
|
14
|
+
const runtimeRoot = join(platformData, 'Aretaxia', 'Sandbox Remote Runtime');
|
|
15
|
+
const installedRoot = join(runtimeRoot, 'node_modules', '@aretaxia', 'sandbox-remote');
|
|
16
|
+
|
|
17
|
+
function run(command, argv) {
|
|
18
|
+
const result = spawnSync(command, argv, { stdio: 'inherit' });
|
|
19
|
+
if (result.error) throw result.error;
|
|
20
|
+
return result.status ?? 1;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function main() {
|
|
24
|
+
const writesServicePath = action === 'setup' || action === 'address' || action === 'restart';
|
|
25
|
+
if ((process.platform === 'darwin' || windows) && writesServicePath &&
|
|
26
|
+
(!existsSync(installedRoot) || realpathSync(sourceRoot) !== realpathSync(installedRoot))) {
|
|
27
|
+
// Keep the service entry point outside npm's disposable npx cache.
|
|
28
|
+
const installArgs = ['install', '--prefix', runtimeRoot, '--install-links',
|
|
29
|
+
'--ignore-scripts', '--no-audit', '--no-fund', '--no-save', sourceRoot];
|
|
30
|
+
const npmCli = process.env.npm_execpath;
|
|
31
|
+
const bundledNpm = join(process.execPath, '..', 'node_modules', 'npm', 'bin', 'npm-cli.js');
|
|
32
|
+
const installed = windows ? run(process.execPath, [npmCli || bundledNpm, ...installArgs]) : run('npm', installArgs);
|
|
33
|
+
if (installed !== 0) return installed;
|
|
34
|
+
return run(process.execPath, [join(installedRoot, 'scripts', 'setup-sandbox-remote.mjs'), ...args]);
|
|
35
|
+
}
|
|
36
|
+
const runtime = existsSync(installedRoot) ? installedRoot : sourceRoot;
|
|
37
|
+
return run(process.execPath, [join(runtime, 'scripts', 'setup-sandbox-remote.mjs'), ...args]);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
try {
|
|
41
|
+
process.exitCode = main();
|
|
42
|
+
} catch (error) {
|
|
43
|
+
console.error(error.message);
|
|
44
|
+
process.exitCode = 1;
|
|
45
|
+
}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { request as httpRequest } from 'node:http';
|
|
4
|
+
import { pipeline } from 'node:stream';
|
|
5
|
+
|
|
6
|
+
const SESSION_COOKIE = '__Host-sandbox_native_preview';
|
|
7
|
+
const TICKET_TTL = 30_000;
|
|
8
|
+
const SESSION_TTL = 7 * 24 * 60 * 60_000;
|
|
9
|
+
const HOP_BY_HOP = new Set([
|
|
10
|
+
'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te',
|
|
11
|
+
'trailer', 'transfer-encoding', 'upgrade',
|
|
12
|
+
]);
|
|
13
|
+
|
|
14
|
+
function cookieValue(header, name) {
|
|
15
|
+
for (const item of String(header ?? '').split(';')) {
|
|
16
|
+
const [key, ...parts] = item.trim().split('=');
|
|
17
|
+
if (key === name) return parts.join('=');
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function connectionHeaders(headers) {
|
|
22
|
+
return new Set(String(headers.connection ?? '').toLowerCase().split(',').map((name) => name.trim()));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function isCrossOrigin(request, previewOrigin) {
|
|
26
|
+
return (request.headers.origin !== undefined && request.headers.origin !== previewOrigin) ||
|
|
27
|
+
['same-site', 'cross-site'].includes(request.headers['sec-fetch-site']);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function safeHeaders(headers, target, previewOrigin) {
|
|
31
|
+
const connection = connectionHeaders(headers);
|
|
32
|
+
const output = {};
|
|
33
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
34
|
+
const lower = name.toLowerCase();
|
|
35
|
+
if (value === undefined || HOP_BY_HOP.has(lower) || connection.has(lower) ||
|
|
36
|
+
['host', 'cookie', 'origin', 'referer', 'forwarded'].includes(lower) || lower.startsWith('x-forwarded-')) continue;
|
|
37
|
+
output[name] = value;
|
|
38
|
+
}
|
|
39
|
+
output.host = target.host;
|
|
40
|
+
if (headers.origin === previewOrigin) output.origin = target.origin;
|
|
41
|
+
if (typeof headers.referer === 'string' && headers.referer.startsWith(previewOrigin + '/')) {
|
|
42
|
+
output.referer = target.origin + headers.referer.slice(previewOrigin.length);
|
|
43
|
+
}
|
|
44
|
+
const cookies = String(headers.cookie ?? '').split(';').map((value) => value.trim())
|
|
45
|
+
.filter((value) => value && !value.startsWith(SESSION_COOKIE + '='));
|
|
46
|
+
if (cookies.length) output.cookie = cookies.join('; ');
|
|
47
|
+
return output;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function rewriteLocation(value, target, previewOrigin) {
|
|
51
|
+
if (!value) return value;
|
|
52
|
+
try {
|
|
53
|
+
const location = new URL(value, target);
|
|
54
|
+
return location.origin === target.origin
|
|
55
|
+
? previewOrigin + location.pathname + location.search + location.hash
|
|
56
|
+
: value;
|
|
57
|
+
} catch {
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function responseHeaders(headers, target, previewOrigin) {
|
|
63
|
+
const connection = connectionHeaders(headers);
|
|
64
|
+
const output = {};
|
|
65
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
66
|
+
const lower = name.toLowerCase();
|
|
67
|
+
if (value === undefined || HOP_BY_HOP.has(lower) || connection.has(lower) || ['set-cookie', 'clear-site-data'].includes(lower)) continue;
|
|
68
|
+
output[name] = value;
|
|
69
|
+
}
|
|
70
|
+
if (headers.location) output.location = rewriteLocation(headers.location, target, previewOrigin);
|
|
71
|
+
const setCookies = headers['set-cookie'];
|
|
72
|
+
if (setCookies) {
|
|
73
|
+
output['set-cookie'] = (Array.isArray(setCookies) ? setCookies : [setCookies])
|
|
74
|
+
.filter((cookie) => !/;\s*domain=/i.test(cookie) &&
|
|
75
|
+
!cookie.trimStart().startsWith(SESSION_COOKIE + '='));
|
|
76
|
+
}
|
|
77
|
+
output['cache-control'] = 'no-store';
|
|
78
|
+
output['cross-origin-resource-policy'] = 'same-origin';
|
|
79
|
+
output['referrer-policy'] = 'same-origin';
|
|
80
|
+
output['x-content-type-options'] = 'nosniff';
|
|
81
|
+
return output;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function nativePreviewOriginFor(connectorOrigin) {
|
|
85
|
+
const url = new URL(connectorOrigin);
|
|
86
|
+
assert(url.protocol === 'https:' && /^[a-z0-9-]+\.aretaxia\.com$/.test(url.hostname) &&
|
|
87
|
+
!url.hostname.startsWith('preview-'), 'Native preview requires a Sandbox address');
|
|
88
|
+
return 'https://preview-' + url.hostname;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function createNativePreview({ targetUrl, previewOrigin, isActive }) {
|
|
92
|
+
const target = new URL(targetUrl);
|
|
93
|
+
assert(target.protocol === 'http:' && target.hostname === '127.0.0.1' && target.port &&
|
|
94
|
+
!target.username && !target.password && !target.hash, 'Use an approved loopback HTTP dev server URL');
|
|
95
|
+
const expectedHost = new URL(previewOrigin).host;
|
|
96
|
+
const tickets = new Map();
|
|
97
|
+
const sessions = new Map();
|
|
98
|
+
const sockets = new Set();
|
|
99
|
+
|
|
100
|
+
function activeSession(request) {
|
|
101
|
+
if (!isActive()) return false;
|
|
102
|
+
const token = cookieValue(request.headers.cookie, SESSION_COOKIE);
|
|
103
|
+
const expires = token && sessions.get(token);
|
|
104
|
+
if (!expires || expires <= Date.now()) {
|
|
105
|
+
if (token) sessions.delete(token);
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function pruneExpired(entries) {
|
|
112
|
+
const now = Date.now();
|
|
113
|
+
for (const [token, expires] of entries) {
|
|
114
|
+
if (expires <= now) entries.delete(token);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function issueTicket() {
|
|
119
|
+
assert(isActive(), 'Pairing revoked');
|
|
120
|
+
pruneExpired(tickets);
|
|
121
|
+
const token = randomBytes(32).toString('base64url');
|
|
122
|
+
tickets.set(token, Date.now() + TICKET_TTL);
|
|
123
|
+
return previewOrigin + '/_sandbox/native-preview#' + token;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function handleRequest(request, response, url) {
|
|
127
|
+
if (request.headers.host?.toLowerCase() !== expectedHost) return false;
|
|
128
|
+
if (request.method === 'GET' && url.pathname === '/_sandbox/native-preview') {
|
|
129
|
+
response.writeHead(200, {
|
|
130
|
+
'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store',
|
|
131
|
+
'Content-Security-Policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
|
|
132
|
+
'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff',
|
|
133
|
+
});
|
|
134
|
+
const startUrl = JSON.stringify(previewOrigin + target.pathname + target.search)
|
|
135
|
+
.replaceAll('<', '\\u003c');
|
|
136
|
+
response.end(`<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><title>Opening preview</title><style>body{background:#111216;color:#f4f4f5;font:16px system-ui;display:grid;min-height:100vh;place-items:center;margin:0}p{max-width:25rem;padding:2rem}</style><p id="s">Opening the live site from your computer…</p><script>const t=location.hash.slice(1);history.replaceState(null,'',location.pathname);fetch(location.pathname,{method:'POST',headers:{'content-type':'text/plain'},body:t}).then(r=>{if(!r.ok)throw 0;location.replace(${startUrl})}).catch(()=>document.querySelector('#s').textContent='This preview link expired. Return to Sandbox and open it again.')</script>`);
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
if (request.method === 'POST' && url.pathname === '/_sandbox/native-preview') {
|
|
140
|
+
if (request.headers.origin !== previewOrigin || isCrossOrigin(request, previewOrigin)) {
|
|
141
|
+
response.writeHead(403).end('Origin rejected');
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
let ticket = '';
|
|
145
|
+
for await (const chunk of request) {
|
|
146
|
+
ticket += chunk;
|
|
147
|
+
if (ticket.length > 64) break;
|
|
148
|
+
}
|
|
149
|
+
const expires = tickets.get(ticket);
|
|
150
|
+
tickets.delete(ticket);
|
|
151
|
+
if (!isActive() || !expires || expires <= Date.now()) {
|
|
152
|
+
response.writeHead(409, { 'Cache-Control': 'no-store' }).end('Preview link expired');
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
pruneExpired(sessions);
|
|
156
|
+
const session = randomBytes(32).toString('base64url');
|
|
157
|
+
sessions.set(session, Date.now() + SESSION_TTL);
|
|
158
|
+
response.writeHead(204, {
|
|
159
|
+
'Cache-Control': 'no-store',
|
|
160
|
+
'Set-Cookie': `${SESSION_COOKIE}=${session}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${SESSION_TTL / 1000}`,
|
|
161
|
+
}).end();
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
if (!activeSession(request)) {
|
|
165
|
+
response.writeHead(401, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' })
|
|
166
|
+
.end('Open this preview from your paired Sandbox app.');
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
if (!['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'].includes(request.method ?? '')) {
|
|
170
|
+
response.writeHead(405).end();
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
if (isCrossOrigin(request, previewOrigin) ||
|
|
174
|
+
(!['GET', 'HEAD', 'OPTIONS'].includes(request.method) && request.headers.origin !== previewOrigin)) {
|
|
175
|
+
response.writeHead(403).end('Origin rejected');
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
if (!request.url?.startsWith('/')) {
|
|
179
|
+
response.writeHead(400).end();
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
const upstream = httpRequest({
|
|
183
|
+
protocol: 'http:', hostname: '127.0.0.1', port: target.port,
|
|
184
|
+
method: request.method, path: request.url,
|
|
185
|
+
headers: safeHeaders(request.headers, target, previewOrigin),
|
|
186
|
+
}, (upstreamResponse) => {
|
|
187
|
+
if (!isActive()) {
|
|
188
|
+
upstreamResponse.destroy();
|
|
189
|
+
response.writeHead(403).end('Pairing revoked');
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
response.writeHead(upstreamResponse.statusCode ?? 502,
|
|
193
|
+
responseHeaders(upstreamResponse.headers, target, previewOrigin));
|
|
194
|
+
pipeline(upstreamResponse, response, () => {});
|
|
195
|
+
});
|
|
196
|
+
upstream.setTimeout(30_000, () => upstream.destroy(new Error('Preview timed out')));
|
|
197
|
+
upstream.on('error', () => { if (!response.headersSent) response.writeHead(502); response.end('Local preview unavailable'); });
|
|
198
|
+
response.once('close', () => { if (!response.writableFinished) upstream.destroy(); });
|
|
199
|
+
request.pipe(upstream);
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function handleUpgrade(request, socket, head) {
|
|
204
|
+
if (request.headers.host?.toLowerCase() !== expectedHost) return false;
|
|
205
|
+
if (request.method !== 'GET' || !request.url?.startsWith('/') ||
|
|
206
|
+
request.headers.upgrade?.toLowerCase() !== 'websocket' ||
|
|
207
|
+
request.headers.origin !== previewOrigin || isCrossOrigin(request, previewOrigin) ||
|
|
208
|
+
!activeSession(request)) {
|
|
209
|
+
socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
const upstream = httpRequest({
|
|
213
|
+
protocol: 'http:', hostname: '127.0.0.1', port: target.port,
|
|
214
|
+
method: 'GET', path: request.url,
|
|
215
|
+
headers: { ...safeHeaders(request.headers, target, previewOrigin), connection: 'Upgrade', upgrade: 'websocket' },
|
|
216
|
+
});
|
|
217
|
+
upstream.on('upgrade', (upstreamResponse, upstreamSocket, upstreamHead) => {
|
|
218
|
+
if (socket.destroyed || !activeSession(request)) { upstreamSocket.destroy(); socket.destroy(); return; }
|
|
219
|
+
const lines = [`HTTP/1.1 ${upstreamResponse.statusCode ?? 101} ${upstreamResponse.statusMessage ?? 'Switching Protocols'}`];
|
|
220
|
+
for (const name of ['connection', 'upgrade', 'sec-websocket-accept', 'sec-websocket-protocol', 'sec-websocket-extensions']) {
|
|
221
|
+
const value = upstreamResponse.headers[name];
|
|
222
|
+
if (value !== undefined) lines.push(`${name}: ${value}`);
|
|
223
|
+
}
|
|
224
|
+
socket.write(lines.join('\r\n') + '\r\n\r\n');
|
|
225
|
+
if (upstreamHead.length) socket.write(upstreamHead);
|
|
226
|
+
if (head.length) upstreamSocket.write(head);
|
|
227
|
+
sockets.add(socket); sockets.add(upstreamSocket);
|
|
228
|
+
socket.once('close', () => { sockets.delete(socket); upstreamSocket.destroy(); });
|
|
229
|
+
upstreamSocket.once('close', () => { sockets.delete(upstreamSocket); socket.destroy(); });
|
|
230
|
+
upstreamSocket.on('error', () => socket.destroy());
|
|
231
|
+
socket.pipe(upstreamSocket).pipe(socket);
|
|
232
|
+
});
|
|
233
|
+
socket.on('error', () => upstream.destroy());
|
|
234
|
+
socket.once('close', () => upstream.destroy());
|
|
235
|
+
upstream.setTimeout(30_000, () => upstream.destroy());
|
|
236
|
+
upstream.on('response', (reply) => {
|
|
237
|
+
reply.resume();
|
|
238
|
+
socket.end(`HTTP/1.1 ${reply.statusCode ?? 502} ${reply.statusMessage ?? 'Bad Gateway'}\r\nConnection: close\r\n\r\n`);
|
|
239
|
+
});
|
|
240
|
+
upstream.on('error', () => socket.destroy());
|
|
241
|
+
upstream.end();
|
|
242
|
+
return true;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function revoke() {
|
|
246
|
+
tickets.clear();
|
|
247
|
+
sessions.clear();
|
|
248
|
+
for (const socket of sockets) socket.destroy();
|
|
249
|
+
sockets.clear();
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return { origin: previewOrigin, issueTicket, handleRequest, handleUpgrade, revoke };
|
|
253
|
+
}
|