heyquilt 0.3.187 → 0.3.188
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/RELEASES.md +12 -0
- package/bin/quilt.js +5 -0
- package/package.json +1 -1
- package/src/account.js +8 -0
- package/src/api/fly-machines.js +46 -4
- package/src/api/memory-store.js +21 -2
- package/src/api/routes/preview.js +240 -0
- package/src/api/server.js +7 -3
- package/src/api/supabase-store.js +16 -0
- package/src/passes.js +3 -1
- package/src/preview/address.js +40 -0
- package/src/preview/proxy.js +183 -0
- package/src/preview/runner.js +172 -0
- package/src/preview/ticket.js +85 -0
- package/src/preview-vm.js +296 -0
- package/src/previews.js +156 -0
- package/src/server.js +28 -3
- package/src/session.js +106 -11
- package/src/ui/app.css +53 -1
- package/src/ui/app.js +2 -0
- package/src/ui/common.js +1 -0
- package/src/ui/preview-page.js +221 -0
- package/src/ui/projects.js +13 -3
- package/src/ui/session.js +26 -3
- package/src/ui-server.js +36 -4
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// The way in to a preview machine (plans/previews.md): one small server on the machine's public
|
|
2
|
+
// port. A request names its machine and its branch's slot in the address (address.js). The proxy
|
|
3
|
+
// sends one for another machine on to it (Fly replays the request there), lets in only the
|
|
4
|
+
// codebase's members (ticket.js: a ticket from the accounts API, then a cookie of its own), and
|
|
5
|
+
// passes the rest, WebSockets included (hot reload), to that slot's dev server on localhost.
|
|
6
|
+
//
|
|
7
|
+
// The dev server is told it is being asked at `localhost:<port>`: Vite, Next and others refuse a
|
|
8
|
+
// host they do not know. What comes back is made to work inside a frame on the app's page: the
|
|
9
|
+
// headers that forbid framing go, redirects to localhost point back at the preview's address,
|
|
10
|
+
// and the app's own cookies are kept to the frame the way ours is.
|
|
11
|
+
import http from 'node:http'
|
|
12
|
+
import net from 'node:net'
|
|
13
|
+
import crypto from 'node:crypto'
|
|
14
|
+
import { parsePreviewHost, previewDomain, previewHost } from './address.js'
|
|
15
|
+
import { verifyPreviewTicket, mintCookie, readCookie, cookieFrom, withoutCookie, setCookieHeader, TICKET_PARAM } from './ticket.js'
|
|
16
|
+
|
|
17
|
+
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c])
|
|
18
|
+
const page = (title, body, extra = '') => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${extra}<title>${esc(title)}</title><style>body{font:15px/1.5 system-ui,sans-serif;margin:0;min-height:100vh;display:grid;place-items:center;background:#f3f3f6;color:#1d1b2e}main{max-width:34em;padding:24px}h1{font-size:19px;margin:0 0 6px}p{margin:0 0 10px;color:#55536a}pre{font:12px/1.5 ui-monospace,Menlo,monospace;background:#fff;border:1px solid #dfdfe6;border-radius:6px;padding:12px;overflow:auto;max-height:50vh;white-space:pre-wrap}</style></head><body><main><h1>${esc(title)}</h1>${body}</main></body></html>`
|
|
19
|
+
|
|
20
|
+
export const NOT_ALLOWED = page('Open this preview from Quilt', '<p>A preview is for the people in its codebase. Open it from the codebase in Quilt, or ask someone in it for an invite.</p>')
|
|
21
|
+
|
|
22
|
+
/** What a slot with no running app answers: it is starting, it failed (with the last of what it printed), or nothing is there. */
|
|
23
|
+
export function waitingPage (app) {
|
|
24
|
+
if (app && app.state === 'starting') return page('Starting…', `<p>${esc(app.name || 'The app')} is starting${app.branch ? ` from ${esc(app.branch)}` : ''}. This page loads it when it is up.</p>`, '<meta http-equiv="refresh" content="2">')
|
|
25
|
+
if (app && app.state === 'failed') return page('It did not start', `<p>${esc(app.name || 'The app')} stopped before it was up${app.branch ? ` (${esc(app.branch)})` : ''}. The last of what it printed:</p><pre>${esc(app.output || 'Nothing was printed.')}</pre>`)
|
|
26
|
+
return page('Nothing is running here', '<p>Nobody has this branch of the preview open. Open it from the codebase in Quilt to start it.</p>')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The address without the ticket: what the app being previewed is asked for, and where a ticket's redirect goes. */
|
|
30
|
+
export function withoutTicket (url) {
|
|
31
|
+
const u = new URL(url, 'http://x')
|
|
32
|
+
u.searchParams.delete(TICKET_PARAM)
|
|
33
|
+
return u.pathname + u.search
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A cookie the previewed app sets, kept to this address and readable inside a frame on another site. */
|
|
37
|
+
export function frameCookie (value) {
|
|
38
|
+
const parts = String(value).split(';').map((p) => p.trim()).filter(Boolean)
|
|
39
|
+
const keep = parts.filter((p, i) => i === 0 || !/^(domain|samesite|secure|partitioned)(=|$)/i.test(p))
|
|
40
|
+
return [...keep, 'Secure', 'SameSite=None', 'Partitioned'].join('; ')
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A security policy without the part that says who may frame the page. */
|
|
44
|
+
const frameable = (csp) => String(csp).split(';').map((d) => d.trim()).filter((d) => d && !/^frame-ancestors(\s|$)/i.test(d)).join('; ')
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The headers the dev server answered with, as the browser gets them: nothing that forbids the
|
|
48
|
+
* frame, redirects to `local` (the dev server's own origin) sent to `outside` (the preview's).
|
|
49
|
+
*/
|
|
50
|
+
export function outHeaders (headers, { local, outside }) {
|
|
51
|
+
const out = {}
|
|
52
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
53
|
+
if (k === 'x-frame-options') continue
|
|
54
|
+
if (k === 'content-security-policy' || k === 'content-security-policy-report-only') {
|
|
55
|
+
const kept = [].concat(v).map(frameable).filter(Boolean)
|
|
56
|
+
if (kept.length) out[k] = kept.length === 1 ? kept[0] : kept
|
|
57
|
+
} else if (k === 'location') {
|
|
58
|
+
const to = String(v)
|
|
59
|
+
const hit = local.find((o) => to === o || to.startsWith(o + '/') || to.startsWith(o + '?'))
|
|
60
|
+
out[k] = hit ? outside + to.slice(hit.length) : to
|
|
61
|
+
} else if (k === 'set-cookie') {
|
|
62
|
+
out[k] = [].concat(v).map(frameCookie)
|
|
63
|
+
} else out[k] = v
|
|
64
|
+
}
|
|
65
|
+
return out
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The request's headers as the dev server gets them: asked at localhost, without our cookie. */
|
|
69
|
+
export function inHeaders (headers, { port, outside }) {
|
|
70
|
+
const local = `http://localhost:${port}`
|
|
71
|
+
const out = { ...headers, host: `localhost:${port}`, 'x-forwarded-host': headers.host || '', 'x-forwarded-proto': 'https' }
|
|
72
|
+
if (out.origin === outside) out.origin = local
|
|
73
|
+
if (typeof out.referer === 'string' && out.referer.startsWith(outside)) out.referer = local + out.referer.slice(outside.length)
|
|
74
|
+
const cookie = withoutCookie(out.cookie)
|
|
75
|
+
if (cookie) out.cookie = cookie; else delete out.cookie
|
|
76
|
+
return out
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Starts the proxy. `machine`: this machine's id; `room`: the codebase it previews; `slots`: a Map
|
|
81
|
+
* of slot -> { port, state: 'starting' | 'running' | 'failed', name, branch, output } that whoever
|
|
82
|
+
* runs the apps keeps up to date. Resolves to { port, lastRequestAt(), close }.
|
|
83
|
+
*/
|
|
84
|
+
export async function startPreviewProxy ({ port = 8080, host = '0.0.0.0', machine, room, domain, passPublicKey, slots = new Map(), now = Date.now, log = () => {}, secret = crypto.randomBytes(32), upstreamHost = 'localhost' }) {
|
|
85
|
+
const dom = previewDomain(domain)
|
|
86
|
+
const me = String(machine || '').toLowerCase()
|
|
87
|
+
previewHost(me, 0, dom) // a bad machine id stops it at start
|
|
88
|
+
if (!passPublicKey) throw new Error('The preview proxy needs the accounts API\'s public key to check tickets.')
|
|
89
|
+
|
|
90
|
+
// When a member last asked for anything: a tab left open in a browser counts as someone looking.
|
|
91
|
+
let lastRequestAt = 0
|
|
92
|
+
// Where a request belongs: { machine, slot } on this machine, { replay } for another, or null (not a preview's address).
|
|
93
|
+
const where = (req) => {
|
|
94
|
+
const at = parsePreviewHost(req.headers.host, dom)
|
|
95
|
+
if (!at) return null
|
|
96
|
+
return at.machine === me ? at : { replay: at.machine }
|
|
97
|
+
}
|
|
98
|
+
// Who is asking: { sub } from our cookie, { sub, fresh: true } from a ticket in the address, or null.
|
|
99
|
+
const who = (req) => {
|
|
100
|
+
const c = readCookie(cookieFrom(req.headers.cookie), secret, { now: now() })
|
|
101
|
+
if (c) return { sub: c.sub }
|
|
102
|
+
let ticket = ''
|
|
103
|
+
try { ticket = new URL(req.url, 'http://x').searchParams.get(TICKET_PARAM) || '' } catch {}
|
|
104
|
+
const p = ticket ? verifyPreviewTicket(ticket, passPublicKey, { room, now: now() }) : null
|
|
105
|
+
return p ? { sub: p.sub, fresh: true } : null
|
|
106
|
+
}
|
|
107
|
+
const send = (res, status, html, headers = {}) => {
|
|
108
|
+
res.writeHead(status, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-length': Buffer.byteLength(html), ...headers })
|
|
109
|
+
res.end(html)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const server = http.createServer((req, res) => {
|
|
113
|
+
const at = where(req)
|
|
114
|
+
if (!at) {
|
|
115
|
+
if (req.url === '/healthz') { res.writeHead(200, { 'content-type': 'text/plain', 'cache-control': 'no-store' }); return res.end('ok') }
|
|
116
|
+
return send(res, 404, page('Not a preview', '<p>This address is not a preview.</p>'))
|
|
117
|
+
}
|
|
118
|
+
if (at.replay) { res.writeHead(409, { 'fly-replay': `instance=${at.replay}`, 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }); return res.end('This preview is on another machine.') }
|
|
119
|
+
const member = who(req)
|
|
120
|
+
if (!member) return send(res, 401, NOT_ALLOWED)
|
|
121
|
+
// A ticket is taken once: the cookie replaces it, and the address is clean from then on.
|
|
122
|
+
if (member.fresh) { res.writeHead(302, { location: withoutTicket(req.url), 'set-cookie': setCookieHeader(mintCookie({ sub: member.sub, now: now() }, secret)), 'cache-control': 'no-store' }); return res.end() }
|
|
123
|
+
lastRequestAt = now()
|
|
124
|
+
const app = slots.get(at.slot)
|
|
125
|
+
if (!app || app.state !== 'running' || !app.port) return send(res, 503, waitingPage(app), { 'retry-after': '2' })
|
|
126
|
+
const outside = `https://${previewHost(me, at.slot, dom)}`
|
|
127
|
+
const headers = inHeaders(req.headers, { port: app.port, outside })
|
|
128
|
+
delete headers.connection
|
|
129
|
+
const up = http.request({ host: upstreamHost, port: app.port, method: req.method, path: withoutTicket(req.url), headers, autoSelectFamily: true }, (r) => {
|
|
130
|
+
res.writeHead(r.statusCode, r.statusMessage, outHeaders(r.headers, { local: [`http://localhost:${app.port}`, `http://127.0.0.1:${app.port}`], outside }))
|
|
131
|
+
r.pipe(res)
|
|
132
|
+
})
|
|
133
|
+
up.on('error', (err) => {
|
|
134
|
+
log(`slot ${at.slot}: ${err.message}`)
|
|
135
|
+
if (res.headersSent) return res.destroy()
|
|
136
|
+
send(res, 502, page('The app is not answering', `<p>${esc(app.name || 'The app')} is running but did not answer. Reload in a moment.</p>`))
|
|
137
|
+
})
|
|
138
|
+
req.on('aborted', () => up.destroy())
|
|
139
|
+
req.pipe(up)
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
// WebSockets (a dev server's hot reload): the same checks, then bytes both ways.
|
|
143
|
+
server.on('upgrade', (req, socket, head) => {
|
|
144
|
+
const refuse = (line, extra = '') => { socket.write(`HTTP/1.1 ${line}\r\n${extra}Connection: close\r\nContent-Length: 0\r\n\r\n`); socket.destroy() }
|
|
145
|
+
const at = where(req)
|
|
146
|
+
if (!at) return refuse('404 Not Found')
|
|
147
|
+
if (at.replay) return refuse('409 Conflict', `fly-replay: instance=${at.replay}\r\n`)
|
|
148
|
+
if (!who(req)) return refuse('401 Unauthorized')
|
|
149
|
+
lastRequestAt = now()
|
|
150
|
+
const app = slots.get(at.slot)
|
|
151
|
+
if (!app || app.state !== 'running' || !app.port) return refuse('503 Service Unavailable')
|
|
152
|
+
const outside = `https://${previewHost(me, at.slot, dom)}`
|
|
153
|
+
const local = `http://localhost:${app.port}`
|
|
154
|
+
const up = net.connect({ host: upstreamHost, port: app.port, autoSelectFamily: true }, () => {
|
|
155
|
+
const lines = [`${req.method} ${withoutTicket(req.url)} HTTP/${req.httpVersion}`]
|
|
156
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2) {
|
|
157
|
+
const name = req.rawHeaders[i]
|
|
158
|
+
let value = req.rawHeaders[i + 1]
|
|
159
|
+
const k = name.toLowerCase()
|
|
160
|
+
if (k === 'host') value = `localhost:${app.port}`
|
|
161
|
+
else if (k === 'origin' && value === outside) value = local
|
|
162
|
+
else if (k === 'cookie') { value = withoutCookie(value); if (!value) continue }
|
|
163
|
+
lines.push(`${name}: ${value}`)
|
|
164
|
+
}
|
|
165
|
+
up.write(lines.join('\r\n') + '\r\n\r\n')
|
|
166
|
+
if (head && head.length) up.write(head)
|
|
167
|
+
socket.pipe(up)
|
|
168
|
+
up.pipe(socket)
|
|
169
|
+
})
|
|
170
|
+
const end = () => { socket.destroy(); up.destroy() }
|
|
171
|
+
up.on('error', end)
|
|
172
|
+
socket.on('error', end)
|
|
173
|
+
up.on('close', end)
|
|
174
|
+
socket.on('close', end)
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve) })
|
|
178
|
+
return {
|
|
179
|
+
port: server.address().port,
|
|
180
|
+
lastRequestAt: () => lastRequestAt,
|
|
181
|
+
close: () => new Promise((resolve) => { server.closeAllConnections?.(); server.close(() => resolve()) })
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Running a codebase's app for a preview (plans/previews.md): the install its lockfile asks for,
|
|
2
|
+
// then its dev command, then finding the port it opened. One of these per preview and branch, in
|
|
3
|
+
// that branch's folder on the preview machine (src/preview-vm.js keeps them and fills the way
|
|
4
|
+
// in's slots from them). It runs whatever the codebase says, as the machine's own user.
|
|
5
|
+
import { spawn } from 'node:child_process'
|
|
6
|
+
import crypto from 'node:crypto'
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import net from 'node:net'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
|
|
11
|
+
export const INSTALL_TIMEOUT_MS = 15 * 60 * 1000
|
|
12
|
+
export const START_TIMEOUT_MS = 5 * 60 * 1000
|
|
13
|
+
const OUTPUT_KEPT = 8000
|
|
14
|
+
const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b[@-_]/g // eslint-disable-line no-control-regex
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* How a folder's packages are installed and its dev script run, by the lockfile it has:
|
|
18
|
+
* { name, install, dev } (install: null when there is no package.json, so nothing to install).
|
|
19
|
+
*/
|
|
20
|
+
export function packageManager (dir) {
|
|
21
|
+
const has = (f) => fs.existsSync(path.join(dir, f))
|
|
22
|
+
if (!has('package.json')) return { name: '', install: null, dev: '' }
|
|
23
|
+
if (has('pnpm-lock.yaml')) return { name: 'pnpm', install: 'pnpm install --frozen-lockfile', dev: 'pnpm run dev', lock: 'pnpm-lock.yaml' }
|
|
24
|
+
if (has('yarn.lock')) return { name: 'yarn', install: 'yarn install --frozen-lockfile', dev: 'yarn run dev', lock: 'yarn.lock' }
|
|
25
|
+
if (has('bun.lockb') || has('bun.lock')) return { name: 'bun', install: 'bun install', dev: 'bun run dev', lock: has('bun.lock') ? 'bun.lock' : 'bun.lockb' }
|
|
26
|
+
// Without its lockfile (one over 2 MB is never shared) npm resolves the versions again.
|
|
27
|
+
if (has('package-lock.json')) return { name: 'npm', install: 'npm ci', dev: 'npm run dev', lock: 'package-lock.json' }
|
|
28
|
+
return { name: 'npm', install: 'npm install', dev: 'npm run dev', lock: '' }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** What an install depends on, as one hash: package.json and the lockfile. Changed: install again. */
|
|
32
|
+
export function installStamp (dir, pm = packageManager(dir)) {
|
|
33
|
+
const h = crypto.createHash('sha256')
|
|
34
|
+
for (const f of ['package.json', pm.lock].filter(Boolean)) { try { h.update(f).update(fs.readFileSync(path.join(dir, f))) } catch {} }
|
|
35
|
+
return h.digest('hex')
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The ports a dev server's output names as its own address (http://localhost:5173), newest first. */
|
|
39
|
+
export function portsIn (text) {
|
|
40
|
+
const out = []
|
|
41
|
+
for (const m of String(text || '').matchAll(/https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::(\d{2,5}))/g)) {
|
|
42
|
+
const p = Number(m[1])
|
|
43
|
+
if (p >= 1 && p <= 65535) { const i = out.indexOf(p); if (i >= 0) out.splice(i, 1); out.unshift(p) }
|
|
44
|
+
}
|
|
45
|
+
return out
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A port nothing has open right now, for an app to be given as PORT. */
|
|
49
|
+
export function freePort (host = '127.0.0.1') {
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
const s = net.createServer()
|
|
52
|
+
s.once('error', reject)
|
|
53
|
+
s.listen(0, host, () => { const { port } = s.address(); s.close(() => resolve(port)) })
|
|
54
|
+
})
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Whether something accepts connections on `port` here. */
|
|
58
|
+
export function listening (port, { host = 'localhost', timeoutMs = 400 } = {}) {
|
|
59
|
+
return new Promise((resolve) => {
|
|
60
|
+
const s = net.connect({ host, port, autoSelectFamily: true })
|
|
61
|
+
const done = (ok) => { s.destroy(); resolve(ok) }
|
|
62
|
+
s.setTimeout(timeoutMs, () => done(false))
|
|
63
|
+
s.once('connect', () => done(true))
|
|
64
|
+
s.once('error', () => done(false))
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Installs (when what the install depends on changed since the last one) and starts the app in
|
|
70
|
+
* `dir`. `command`: the preview's own, else the folder's dev script. `port`: given to the app as
|
|
71
|
+
* PORT; `fixedPort`: the preview says which port the app opens. `taken()`: ports other apps on
|
|
72
|
+
* the machine have, never taken for this one. `onChange()` is called when its state, port or
|
|
73
|
+
* output changes. Returns { state: 'starting' | 'running' | 'failed', port, output, stop() }.
|
|
74
|
+
*/
|
|
75
|
+
export function startApp ({ dir, command = '', env = {}, port, fixedPort = 0, taken = () => [], onChange = () => {}, log = () => {}, installTimeoutMs = INSTALL_TIMEOUT_MS, startTimeoutMs = START_TIMEOUT_MS, host = 'localhost', pollMs = 400 }) {
|
|
76
|
+
const app = { state: 'starting', port: 0, output: '', stop, stamp: '', pid: 0 }
|
|
77
|
+
let child = null
|
|
78
|
+
let stopped = false
|
|
79
|
+
let timer = null
|
|
80
|
+
const say = (text) => {
|
|
81
|
+
app.output = (app.output + String(text).replace(ANSI, '').replace(/\r\n?/g, '\n')).slice(-OUTPUT_KEPT)
|
|
82
|
+
onChange()
|
|
83
|
+
}
|
|
84
|
+
const set = (state, extra = '') => {
|
|
85
|
+
if (stopped || app.state === 'failed') return
|
|
86
|
+
app.state = state
|
|
87
|
+
if (extra) say(extra.endsWith('\n') ? extra : extra + '\n')
|
|
88
|
+
else onChange()
|
|
89
|
+
}
|
|
90
|
+
// Its own keys never reach the app; PORT and what the preview sets do.
|
|
91
|
+
const childEnv = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^(QUILT_|FLY_)/.test(k)))
|
|
92
|
+
Object.assign(childEnv, { BROWSER: 'none', FORCE_COLOR: '0', ...env, PORT: String(port) })
|
|
93
|
+
|
|
94
|
+
/** Runs one shell command in the folder; resolves to its exit code (null: killed). */
|
|
95
|
+
const run = (cmd, timeoutMs) => new Promise((resolve) => {
|
|
96
|
+
say(`$ ${cmd}\n`)
|
|
97
|
+
child = spawn(cmd, { cwd: dir, env: childEnv, shell: true, detached: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
98
|
+
const mine = child
|
|
99
|
+
app.pid = mine.pid || 0
|
|
100
|
+
onChange()
|
|
101
|
+
const over = timeoutMs ? setTimeout(() => { say(`\nStopped: it took longer than ${Math.round(timeoutMs / 60000)} minutes.\n`); kill(mine) }, timeoutMs) : null
|
|
102
|
+
mine.stdout.on('data', say)
|
|
103
|
+
mine.stderr.on('data', say)
|
|
104
|
+
mine.on('error', (err) => { clearTimeout(over); say(`\n${err.message}\n`); resolve(127) })
|
|
105
|
+
mine.on('exit', (code) => { clearTimeout(over); if (child === mine) { child = null; app.pid = 0 } resolve(code) })
|
|
106
|
+
})
|
|
107
|
+
const kill = (c, signal = 'SIGTERM') => { try { process.kill(-c.pid, signal) } catch { try { c.kill(signal) } catch {} } }
|
|
108
|
+
|
|
109
|
+
;(async () => {
|
|
110
|
+
if (!fs.existsSync(dir)) return set('failed', 'This preview\'s folder is not in the codebase on this branch.')
|
|
111
|
+
const pm = packageManager(dir)
|
|
112
|
+
const cmd = String(command || '').trim() || pm.dev
|
|
113
|
+
if (!cmd) return set('failed', 'There is nothing to run here: no command for this preview, and no package.json with a dev script.')
|
|
114
|
+
if (pm.install) {
|
|
115
|
+
const stamp = installStamp(dir, pm)
|
|
116
|
+
const mark = path.join(dir, 'node_modules', '.quilt-preview-install')
|
|
117
|
+
let had = ''
|
|
118
|
+
try { had = fs.readFileSync(mark, 'utf8') } catch {}
|
|
119
|
+
if (had !== stamp) {
|
|
120
|
+
const code = await run(pm.install, installTimeoutMs)
|
|
121
|
+
if (stopped) return
|
|
122
|
+
if (code !== 0) return set('failed', `The install stopped (${code === null ? 'killed' : `exit ${code}`}).`)
|
|
123
|
+
try { fs.mkdirSync(path.dirname(mark), { recursive: true }); fs.writeFileSync(mark, stamp) } catch {}
|
|
124
|
+
}
|
|
125
|
+
app.stamp = stamp
|
|
126
|
+
}
|
|
127
|
+
const startedAt = Date.now()
|
|
128
|
+
const exited = run(cmd)
|
|
129
|
+
exited.then((code) => {
|
|
130
|
+
clearInterval(timer)
|
|
131
|
+
if (stopped) return
|
|
132
|
+
app.port = 0
|
|
133
|
+
set('failed', `The app stopped (${code === null ? 'killed' : `exit ${code}`}).`)
|
|
134
|
+
log(`${dir}: ${cmd} stopped (${code})`)
|
|
135
|
+
})
|
|
136
|
+
// Which port it opened: the one the preview names, else the one it was given, else one its output names.
|
|
137
|
+
let looking = false
|
|
138
|
+
timer = setInterval(async () => {
|
|
139
|
+
if (looking || stopped || app.state !== 'starting') return
|
|
140
|
+
looking = true
|
|
141
|
+
try {
|
|
142
|
+
const others = taken()
|
|
143
|
+
const candidates = (fixedPort ? [fixedPort] : [port, ...portsIn(app.output)]).filter((p) => !others.includes(p))
|
|
144
|
+
for (const p of candidates) {
|
|
145
|
+
if (await listening(p, { host })) {
|
|
146
|
+
if (stopped || app.state !== 'starting') return
|
|
147
|
+
app.port = p
|
|
148
|
+
clearInterval(timer)
|
|
149
|
+
log(`${dir}: ${cmd} is up on ${p}`)
|
|
150
|
+
return set('running')
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (Date.now() - startedAt > startTimeoutMs && child) { say(`\nNo port was opened in ${Math.round(startTimeoutMs / 60000)} minutes.\n`); kill(child) }
|
|
154
|
+
} finally { looking = false }
|
|
155
|
+
}, pollMs)
|
|
156
|
+
})().catch((err) => set('failed', err.message))
|
|
157
|
+
|
|
158
|
+
async function stop () {
|
|
159
|
+
if (stopped) return
|
|
160
|
+
stopped = true
|
|
161
|
+
clearInterval(timer)
|
|
162
|
+
const c = child
|
|
163
|
+
if (!c) return
|
|
164
|
+
await new Promise((resolve) => {
|
|
165
|
+
const hard = setTimeout(() => kill(c, 'SIGKILL'), 4000)
|
|
166
|
+
c.once('exit', () => { clearTimeout(hard); resolve() })
|
|
167
|
+
kill(c)
|
|
168
|
+
})
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return app
|
|
172
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Who may open a preview (plans/previews.md): the codebase's members, nobody else, since a dev
|
|
2
|
+
// server hands out source code. The accounts API signs a ticket for a member, a few minutes long,
|
|
3
|
+
// with the key it signs passes with; the first request to a preview carries it in the address.
|
|
4
|
+
// The machine checks it with the API's public key and answers with a cookie of its own, good for
|
|
5
|
+
// that address until the machine starts again.
|
|
6
|
+
//
|
|
7
|
+
// A ticket is shaped like a pass (base64url JSON, a dot, the Ed25519 signature) but is not one:
|
|
8
|
+
// it has `t: 'preview'` and no `kind`, so the relay never takes it for a pass (verifyPass), and
|
|
9
|
+
// nothing but a ticket is taken here.
|
|
10
|
+
import crypto from 'node:crypto'
|
|
11
|
+
import { signPass, readPass } from '../passes.js'
|
|
12
|
+
import { parsePublicKey } from '../identity.js'
|
|
13
|
+
|
|
14
|
+
export const TICKET_VERSION = 1
|
|
15
|
+
export const TICKET_TTL_MS = 5 * 60 * 1000
|
|
16
|
+
// The cookie outlives the ticket: a preview stays open for a working day without asking again.
|
|
17
|
+
export const COOKIE_TTL_MS = 12 * 60 * 60 * 1000
|
|
18
|
+
export const COOKIE_NAME = 'quilt_preview'
|
|
19
|
+
export const TICKET_PARAM = 'quilt_ticket'
|
|
20
|
+
const ROOM = /^[A-Za-z0-9_-]{1,64}$/
|
|
21
|
+
const SUB = /^(person|agent):[A-Za-z0-9_-]{1,64}$/
|
|
22
|
+
|
|
23
|
+
/** A ticket for member `sub` to open previews of codebase `room`. */
|
|
24
|
+
export function signPreviewTicket ({ room, sub, ttlMs = TICKET_TTL_MS, now = Date.now() }, signingKey) {
|
|
25
|
+
if (!ROOM.test(String(room || ''))) throw new Error('Which codebase?')
|
|
26
|
+
if (!SUB.test(String(sub || ''))) throw new Error('Who is it for?')
|
|
27
|
+
return signPass({ v: TICKET_VERSION, t: 'preview', room, sub, exp: now + ttlMs }, signingKey)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The ticket's payload when it is signed by the API, is for `room` and has not run out; else null. */
|
|
31
|
+
export function verifyPreviewTicket (ticket, publicKey, { room, now = Date.now() } = {}) {
|
|
32
|
+
const key = typeof publicKey === 'string' ? parsePublicKey(publicKey) : publicKey
|
|
33
|
+
const p = readPass(ticket)
|
|
34
|
+
if (!key || !p) return null
|
|
35
|
+
const [body, sig] = String(ticket).split('.')
|
|
36
|
+
let signed = false
|
|
37
|
+
try { signed = crypto.verify(null, Buffer.from(body), key, Buffer.from(sig, 'base64url')) } catch {}
|
|
38
|
+
if (!signed || p.v !== TICKET_VERSION || p.t !== 'preview') return null
|
|
39
|
+
if (typeof p.exp !== 'number' || p.exp <= now) return null
|
|
40
|
+
if (typeof p.room !== 'string' || !ROOM.test(p.room) || p.room !== room) return null
|
|
41
|
+
if (typeof p.sub !== 'string' || !SUB.test(p.sub)) return null
|
|
42
|
+
return p
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const mac = (secret, text) => crypto.createHmac('sha256', secret).update(text).digest('base64url')
|
|
46
|
+
|
|
47
|
+
/** The machine's own cookie for someone whose ticket it took: `<exp>.<who>.<mac>`, signed with a secret it made at start. */
|
|
48
|
+
export function mintCookie ({ sub, ttlMs = COOKIE_TTL_MS, now = Date.now() }, secret) {
|
|
49
|
+
const body = `${now + ttlMs}.${Buffer.from(String(sub)).toString('base64url')}`
|
|
50
|
+
return `${body}.${mac(secret, body)}`
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Who a cookie is for ({ sub, exp }) when this machine made it and it has not run out; else null. */
|
|
54
|
+
export function readCookie (value, secret, { now = Date.now() } = {}) {
|
|
55
|
+
const parts = String(value || '').split('.')
|
|
56
|
+
if (parts.length !== 3) return null
|
|
57
|
+
const [exp, who, sig] = parts
|
|
58
|
+
const want = mac(secret, `${exp}.${who}`)
|
|
59
|
+
const a = Buffer.from(sig)
|
|
60
|
+
const b = Buffer.from(want)
|
|
61
|
+
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null
|
|
62
|
+
const at = Number(exp)
|
|
63
|
+
if (!Number.isFinite(at) || at <= now) return null
|
|
64
|
+
return { sub: Buffer.from(who, 'base64url').toString('utf8'), exp: at }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** One cookie's value out of a `Cookie` header, or ''. */
|
|
68
|
+
export function cookieFrom (header, name = COOKIE_NAME) {
|
|
69
|
+
for (const part of String(header || '').split(';')) {
|
|
70
|
+
const i = part.indexOf('=')
|
|
71
|
+
if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim()
|
|
72
|
+
}
|
|
73
|
+
return ''
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A `Cookie` header without ours: the app being previewed never sees it. */
|
|
77
|
+
export function withoutCookie (header, name = COOKIE_NAME) {
|
|
78
|
+
return String(header || '').split(';').map((p) => p.trim()).filter((p) => p && p.split('=')[0].trim() !== name).join('; ')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The `Set-Cookie` for a preview's address. It is read inside a frame on the app's page, which is
|
|
83
|
+
* another site: SameSite=None with Partitioned keeps it to that frame.
|
|
84
|
+
*/
|
|
85
|
+
export const setCookieHeader = (value, { ttlMs = COOKIE_TTL_MS } = {}) => `${COOKIE_NAME}=${value}; Path=/; Max-Age=${Math.floor(ttlMs / 1000)}; HttpOnly; Secure; SameSite=None; Partitioned`
|