Skip to content
Source
Sign inSign up
TanStack/container
Open History to see the last commit

dev-lan.mjs

202 lines6.5 KB

1import { spawn, spawnSync } from 'node:child_process'
2import { createServer } from 'node:http'
3import { mkdtemp, readFile } from 'node:fs/promises'
4import { networkInterfaces, tmpdir } from 'node:os'
5import { join } from 'node:path'
6import { randomBytes } from 'node:crypto'
7​
8const host = process.argv[2]
9const addresses = Object.values(networkInterfaces()).flat().filter(Boolean)
10if (
11 !addresses.some(
12 (address) =>
13 address.family === 'IPv4' &&
14 !address.internal &&
15 address.address === host,
16 )
18 throw new Error(
19 "Pass this Mac's active LAN IPv4 address: npm run dev:lan -- 192.168.x.x",
20 )
21if (!/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(host))
22 throw new Error('Expected a private LAN address')
23​
24// Keys live outside Vite's workspace and public directories, with owner-only permissions.
25// Nothing is installed in the Mac's keychain. The phone's trust step is manual.
26process.umask(0o077)
27const directory = await mkdtemp(join(tmpdir(), 'browser-sandbox-lan-'))
28const rootCert = join(directory, 'root-ca.pem')
29const rootKey = join(directory, 'root-ca-key.pem')
30const cert = join(directory, 'server.pem')
31const key = join(directory, 'server-key.pem')
32const csr = join(directory, 'server.csr')
33const publicCert = join(directory, 'sandbox-test-ca.cer')
34const name = `Browser Sandbox Wi-Fi Test ${randomBytes(3).toString('hex')}`
35const openssl = (...args) => {
36 const result = spawnSync('openssl', args, { encoding: 'utf8' })
37 if (result.error || result.status !== 0)
38 throw new Error(result.error?.message ?? result.stderr)
39 return result.stdout.trim()
41openssl(
42 'req',
43 '-x509',
44 '-newkey',
45 'rsa:2048',
46 '-noenc',
47 '-sha256',
48 '-days',
49 '7',
50 '-subj',
51 `/CN=${name}`,
52 '-keyout',
53 rootKey,
54 '-out',
55 rootCert,
56 '-addext',
57 'basicConstraints=critical,CA:TRUE,pathlen:0',
58 '-addext',
59 'keyUsage=critical,keyCertSign,cRLSign',
61openssl(
62 'req',
63 '-new',
64 '-newkey',
65 'rsa:2048',
66 '-noenc',
67 '-sha256',
68 '-subj',
69 `/CN=${host}`,
70 '-keyout',
71 key,
72 '-out',
73 csr,
74 '-addext',
75 `subjectAltName=IP:${host}`,
76 '-addext',
77 'basicConstraints=critical,CA:FALSE',
78 '-addext',
79 'keyUsage=critical,digitalSignature,keyEncipherment',
80 '-addext',
81 'extendedKeyUsage=serverAuth',
83openssl(
84 'x509',
85 '-req',
86 '-in',
87 csr,
88 '-CA',
89 rootCert,
90 '-CAkey',
91 rootKey,
92 '-set_serial',
93 '0x' + randomBytes(16).toString('hex'),
94 '-days',
95 '7',
96 '-sha256',
97 '-copy_extensions',
98 'copy',
99 '-out',
100 cert,
102openssl('verify', '-CAfile', rootCert, '-verify_ip', host, cert)
103openssl('x509', '-in', rootCert, '-outform', 'DER', '-out', publicCert)
104const fingerprint = openssl(
105 'x509',
106 '-in',
107 rootCert,
108 '-noout',
109 '-fingerprint',
110 '-sha256',
112const certificate = await readFile(publicCert)
113const lab = `https://${host}:4443/sandbox.html`
114const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sandbox Wi-Fi setup</title><style>body{font:17px/1.5 system-ui;max-width:38rem;margin:2rem auto;padding:0 1rem}li{margin:1rem 0}code{overflow-wrap:anywhere}a{color:#165cbd}</style></head><body>
115<h1>Sandbox Wi-Fi setup</h1>
116<p>Stay on the same Wi-Fi as the Mac. Safari needs a trusted HTTPS connection for the preview's service worker.</p>
117<ol>
118<li><a href="/sandbox-test-ca.cer">Download the test certificate</a>, then allow the download.</li>
119<li>In Settings, open <strong>Profile Downloaded</strong> and install <strong>${name}</strong>. If needed, look under General → VPN &amp; Device Management.</li>
120<li>Open Settings → General → About → Certificate Trust Settings and enable full trust for <strong>${name}</strong>.</li>
121<li>Return to Safari and <a href="${lab}">open the lab</a>. Try <strong>Run workflow in QuickJS</strong>, then <strong>Run Start app</strong>.</li>
122</ol>
123<p>This test CA expires in 7 days. Trusting it allows certificates signed by its private key, which stays on this Mac. Do not use sensitive projects. After testing, remove this profile in General → VPN &amp; Device Management. No VPN or device management enrollment is installed.</p>
124<p><a href="https://support.apple.com/en-us/102390">Apple's certificate trust instructions</a></p>
125<details><summary>Certificate fingerprint</summary><code>${fingerprint}</code><p>Compare this with the fingerprint in the Mac's terminal before trusting the certificate.</p></details>
126</body></html>`
127const setup = createServer((request, response) => {
128 response.setHeader('Cache-Control', 'no-store')
129 response.setHeader('X-Content-Type-Options', 'nosniff')
130 if (request.method !== 'GET') {
131 response.writeHead(405)
132 response.end()
133 return
134 }
135 if (request.url === '/sandbox-test-ca.cer') {
136 response.writeHead(200, {
137 'Content-Type': 'application/x-x509-ca-cert',
138 'Content-Disposition': 'attachment; filename="sandbox-test-ca.cer"',
139 })
140 response.end(certificate)
141 } else if (request.url === '/') {
142 response.writeHead(200, {
143 'Content-Type': 'text/html; charset=utf-8',
144 'Content-Security-Policy':
145 "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'",
146 })
147 response.end(html)
148 } else {
149 response.writeHead(404)
150 response.end('Not found')
151 }
152})
153await new Promise((resolve, reject) => {
154 setup.once('error', reject)
155 setup.listen(4442, host, resolve)
156})
157const env = {
158 ...process.env,
159 SANDBOX_TLS_CERT: cert,
160 SANDBOX_TLS_KEY: key,
161 SANDBOX_PREVIEW_HOST: host,
162 SANDBOX_PREVIEW_PORT: '4444',
163 VITE_SANDBOX_PREVIEW_ORIGIN: `https://${host}:4444`,
165const children = [
166 spawn(process.execPath, ['scripts/serve-preview-host.mjs'], {
167 env,
168 stdio: 'inherit',
169 }),
170 spawn(
171 'npm',
172 ['run', 'dev', '--', '--host', host, '--port', '4443', '--strictPort'],
173 { env, stdio: 'inherit', detached: true },
174 ),
176let stopping = false
177const stop = (code = 0) => {
178 if (stopping) return
179 stopping = true
180 setup.close()
181 children[0].kill('SIGTERM')
182 if (children[1].pid) {
183 try {
184 process.kill(-children[1].pid, 'SIGTERM')
185 } catch {}
186 }
187 process.exitCode = code
189for (const child of children) {
190 child.on('error', (error) => {
191 console.error(error.message)
192 stop(1)
193 })
194 child.on('exit', (code) => {
195 if (!stopping) stop(code ?? 1)
196 })
198process.on('SIGINT', () => stop())
199process.on('SIGTERM', () => stop())
200console.log(
201 `Phone setup: http://${host}:4442/\nLab: ${lab}\nCertificate: ${name}\n${fingerprint}\nPrivate certificate directory: ${directory}\nA new launch creates a new test CA. Remove the old phone profile when finished.`,