gestalt-mobile 0.78.3 → 0.79.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.
- package/README.md +22 -13
- package/dist/client/assets/index-PmiNsocJ.css +1 -0
- package/dist/client/assets/{index-jLy1t3Qp.js → index-t6olwrqi.js} +58 -53
- package/dist/client/index.html +2 -2
- package/dist/server/server/app.js +3 -0
- package/dist/server/server/cli.js +3 -0
- package/dist/server/server/composition.contracts.js +99 -1
- package/dist/server/server/composition.js +66 -0
- package/dist/server/server/config.js +39 -7
- package/dist/server/server/features/catalog/get-bootstrap/use-case.js +2 -0
- package/dist/server/server/features/previews/application/service.js +80 -0
- package/dist/server/server/features/previews/open-preview/endpoint.js +39 -0
- package/dist/server/server/features/previews/register-routes.js +11 -0
- package/dist/server/server/features/previews/stop-preview/endpoint.js +16 -0
- package/dist/server/server/features/sessions/get-impeccable/endpoint.js +10 -0
- package/dist/server/server/features/sessions/register-routes.js +3 -0
- package/dist/server/server/platform/previews/gateway.js +185 -0
- package/dist/server/server/platform/previews/impeccable.js +269 -0
- package/dist/server/server/platform/previews/proxy.js +178 -0
- package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +7 -6
- package/dist/server/server/platform/scratch/filesystem-session-scratch.js +63 -19
- package/dist/server/server/platform/scratch/managed-scratch-owner.js +1 -1
- package/dist/server/server/platform/scratch/runtime-root.js +22 -6
- package/dist/server/shared/contracts/impeccable.js +104 -0
- package/dist/server/shared/contracts/preview.js +6 -0
- package/package.json +1 -1
- package/dist/client/assets/index-DRiZTklh.css +0 -1
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
import { randomBytes } from 'node:crypto';
|
|
7
|
+
import { once } from 'node:events';
|
|
8
|
+
import { createServer } from 'node:http';
|
|
9
|
+
import { previewHandoffPath } from '../../../shared/contracts/preview.js';
|
|
10
|
+
import { previewSessionLifetime, } from '../../features/previews/application/service.js';
|
|
11
|
+
import { cookieName, previewCookie, proxyHttp, proxyWebSocket, rejectUpgrade } from './proxy.js';
|
|
12
|
+
import { impeccablePath, serveImpeccable } from './impeccable.js';
|
|
13
|
+
export function createPreviewGateway(options, service) {
|
|
14
|
+
const origin = new URL(options.origin);
|
|
15
|
+
const target = { port: options.targetPort, origin };
|
|
16
|
+
const connections = new Set();
|
|
17
|
+
let expiryCheck;
|
|
18
|
+
function track(viewer) {
|
|
19
|
+
return (disconnect) => {
|
|
20
|
+
const connection = { viewer, disconnect };
|
|
21
|
+
connections.add(connection);
|
|
22
|
+
return () => connections.delete(connection);
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function validRequest(request) {
|
|
26
|
+
return (request.headers.host === origin.host &&
|
|
27
|
+
typeof request.url === 'string' &&
|
|
28
|
+
request.url.startsWith('/') &&
|
|
29
|
+
!request.url.startsWith('//'));
|
|
30
|
+
}
|
|
31
|
+
const server = createServer((request, response) => {
|
|
32
|
+
if (!validRequest(request))
|
|
33
|
+
return text(response, 421, 'Unknown preview host.');
|
|
34
|
+
if (request.url === previewHandoffPath) {
|
|
35
|
+
if (request.method === 'GET')
|
|
36
|
+
return handoff(response);
|
|
37
|
+
if (request.method === 'POST' && request.headers.origin === origin.origin) {
|
|
38
|
+
return exchange(request, response, (code) => service.exchange(code)).catch(() => {
|
|
39
|
+
if (!response.destroyed)
|
|
40
|
+
text(response, 400, 'Invalid preview authorization.');
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return text(response, 403, 'Preview authorization must come from the preview site.');
|
|
44
|
+
}
|
|
45
|
+
if (!allowedHttpOrigin(request, origin.origin) ||
|
|
46
|
+
request.headers['service-worker'] ||
|
|
47
|
+
request.headers['sec-fetch-dest'] === 'serviceworker')
|
|
48
|
+
return text(response, 403, 'This preview request is forbidden.');
|
|
49
|
+
const viewer = readViewer(request);
|
|
50
|
+
const access = viewer && service.access(viewer);
|
|
51
|
+
if (!viewer || !access)
|
|
52
|
+
return text(response, 401, 'Open the preview from your Gestalt session.');
|
|
53
|
+
const editor = access.mode === 'impeccable' && options.impeccableHelper;
|
|
54
|
+
if (request.url?.startsWith(`${impeccablePath}/`)) {
|
|
55
|
+
if (!editor)
|
|
56
|
+
return text(response, 403, 'Open Impeccable Live from your Gestalt session.');
|
|
57
|
+
return void serveImpeccable(request, response, new URL(request.url, origin), () => editor(access.sessionId), track(viewer));
|
|
58
|
+
}
|
|
59
|
+
proxyHttp(request, response, target, track(viewer), Boolean(editor));
|
|
60
|
+
});
|
|
61
|
+
server.on('upgrade', (request, socket, head) => {
|
|
62
|
+
const viewer = readViewer(request);
|
|
63
|
+
if (!validRequest(request) ||
|
|
64
|
+
request.url === previewHandoffPath ||
|
|
65
|
+
request.url?.startsWith(`${impeccablePath}/`) ||
|
|
66
|
+
request.headers.upgrade?.toLowerCase() !== 'websocket' ||
|
|
67
|
+
request.headers.origin !== origin.origin ||
|
|
68
|
+
!viewer ||
|
|
69
|
+
!service.authorized(viewer)) {
|
|
70
|
+
socket.once('error', () => socket.destroy());
|
|
71
|
+
rejectUpgrade(socket, '401 Unauthorized');
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
proxyWebSocket(request, socket, head, target, track(viewer));
|
|
75
|
+
});
|
|
76
|
+
return {
|
|
77
|
+
async start() {
|
|
78
|
+
const listening = once(server, 'listening');
|
|
79
|
+
server.listen(options.port, '127.0.0.1');
|
|
80
|
+
await listening;
|
|
81
|
+
expiryCheck = setInterval(() => {
|
|
82
|
+
for (const connection of connections) {
|
|
83
|
+
if (!service.authorized(connection.viewer))
|
|
84
|
+
connection.disconnect();
|
|
85
|
+
}
|
|
86
|
+
}, 1000).unref();
|
|
87
|
+
const address = server.address();
|
|
88
|
+
if (!address || typeof address === 'string')
|
|
89
|
+
throw new Error('Preview listener has no port');
|
|
90
|
+
return address.port;
|
|
91
|
+
},
|
|
92
|
+
async close() {
|
|
93
|
+
clearInterval(expiryCheck);
|
|
94
|
+
for (const connection of connections)
|
|
95
|
+
connection.disconnect();
|
|
96
|
+
if (server.listening) {
|
|
97
|
+
const closed = once(server, 'close');
|
|
98
|
+
server.close();
|
|
99
|
+
server.closeAllConnections();
|
|
100
|
+
await closed;
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function readViewer(request) {
|
|
106
|
+
const pair = request.headers.cookie
|
|
107
|
+
?.split(';')
|
|
108
|
+
.filter((part) => cookieName(part) === previewCookie);
|
|
109
|
+
if (pair?.length !== 1)
|
|
110
|
+
return;
|
|
111
|
+
const token = pair[0].trim().slice(previewCookie.length + 1);
|
|
112
|
+
return validToken(token) ? token : undefined;
|
|
113
|
+
}
|
|
114
|
+
function validToken(token) {
|
|
115
|
+
return /^[\w-]{43}$/.test(token);
|
|
116
|
+
}
|
|
117
|
+
function allowedHttpOrigin(request, origin) {
|
|
118
|
+
if (request.headers.origin && request.headers.origin !== origin)
|
|
119
|
+
return false;
|
|
120
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
121
|
+
return request.headers.origin === origin;
|
|
122
|
+
const site = request.headers['sec-fetch-site'];
|
|
123
|
+
return (!site ||
|
|
124
|
+
site === 'none' ||
|
|
125
|
+
site === 'same-origin' ||
|
|
126
|
+
(request.headers['sec-fetch-mode'] === 'navigate' &&
|
|
127
|
+
request.headers['sec-fetch-dest'] === 'document'));
|
|
128
|
+
}
|
|
129
|
+
async function exchange(request, response, consume) {
|
|
130
|
+
let body = '';
|
|
131
|
+
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
132
|
+
body += String(chunk);
|
|
133
|
+
if (body.length > 43) {
|
|
134
|
+
text(response, 400, 'Invalid preview authorization.');
|
|
135
|
+
request.resume();
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const viewer = validToken(body) ? consume(body) : undefined;
|
|
140
|
+
if (!viewer) {
|
|
141
|
+
text(response, 401, 'Preview authorization expired. Open the preview again from Gestalt.');
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
response
|
|
145
|
+
.writeHead(204, {
|
|
146
|
+
'cache-control': 'no-store',
|
|
147
|
+
'set-cookie': `${previewCookie}=${viewer}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${previewSessionLifetime}`,
|
|
148
|
+
})
|
|
149
|
+
.end();
|
|
150
|
+
}
|
|
151
|
+
function text(response, status, message) {
|
|
152
|
+
response
|
|
153
|
+
.writeHead(status, {
|
|
154
|
+
'cache-control': 'no-store',
|
|
155
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
156
|
+
'x-content-type-options': 'nosniff',
|
|
157
|
+
})
|
|
158
|
+
.end(message);
|
|
159
|
+
}
|
|
160
|
+
function handoff(response) {
|
|
161
|
+
const nonce = randomBytes(16).toString('base64');
|
|
162
|
+
response.writeHead(200, {
|
|
163
|
+
'cache-control': 'no-store',
|
|
164
|
+
'content-type': 'text/html; charset=utf-8',
|
|
165
|
+
'content-security-policy': `default-src 'none'; script-src 'nonce-${nonce}'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'`,
|
|
166
|
+
'referrer-policy': 'no-referrer',
|
|
167
|
+
'x-content-type-options': 'nosniff',
|
|
168
|
+
}).end(`<!doctype html>
|
|
169
|
+
<html lang="en"><meta charset="utf-8"><title>Gestalt Preview</title>
|
|
170
|
+
<p id="status">Open the preview from your Gestalt session.</p>
|
|
171
|
+
<script nonce="${nonce}">
|
|
172
|
+
const code = location.hash.slice(1);
|
|
173
|
+
history.replaceState(null, '', location.pathname);
|
|
174
|
+
if (code) {
|
|
175
|
+
const status = document.getElementById('status');
|
|
176
|
+
status.textContent = 'Opening preview…';
|
|
177
|
+
fetch(location.pathname, { method: 'POST', body: code }).then((result) => {
|
|
178
|
+
if (result.ok) location.replace('/');
|
|
179
|
+
else status.textContent = 'Authorization expired. Open the preview again from Gestalt.';
|
|
180
|
+
}).catch(() => {
|
|
181
|
+
status.textContent = 'Could not connect. Open the preview again from Gestalt.';
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
</script></html>`);
|
|
185
|
+
}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { constants } from 'node:fs';
|
|
8
|
+
import { open, realpath } from 'node:fs/promises';
|
|
9
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
10
|
+
import { Readable, Transform, pipeline } from 'node:stream';
|
|
11
|
+
export const impeccablePath = '/.impeccable-live';
|
|
12
|
+
const bootstrapPath = `${impeccablePath}/bootstrap.js`;
|
|
13
|
+
const liveAssets = new Set(['/live.js', '/detect.js', '/modern-screenshot.js']);
|
|
14
|
+
const reads = new Set([
|
|
15
|
+
...liveAssets,
|
|
16
|
+
'/events',
|
|
17
|
+
'/status',
|
|
18
|
+
'/source',
|
|
19
|
+
'/design-system.json',
|
|
20
|
+
'/design-system/raw',
|
|
21
|
+
'/manual-edit-stash',
|
|
22
|
+
]);
|
|
23
|
+
const writes = new Set([
|
|
24
|
+
'/events',
|
|
25
|
+
'/annotation',
|
|
26
|
+
'/manual-edit-stash',
|
|
27
|
+
'/manual-edit-commit',
|
|
28
|
+
'/manual-edit-discard',
|
|
29
|
+
'/manual-edit-repair-decision',
|
|
30
|
+
]);
|
|
31
|
+
const maxJsonBytes = 2 * 1024 * 1024;
|
|
32
|
+
const maxAnnotationBytes = 8 * 1024 * 1024;
|
|
33
|
+
function within(root, path) {
|
|
34
|
+
const tail = relative(root, path);
|
|
35
|
+
return !isAbsolute(tail) && tail !== '..' && !tail.startsWith(`..${sep}`);
|
|
36
|
+
}
|
|
37
|
+
async function boundedBody(stream, limit) {
|
|
38
|
+
const chunks = [];
|
|
39
|
+
let size = 0;
|
|
40
|
+
for await (const chunk of stream) {
|
|
41
|
+
size += chunk.byteLength;
|
|
42
|
+
if (size > limit)
|
|
43
|
+
throw new Error('Impeccable request exceeded its size limit');
|
|
44
|
+
chunks.push(chunk);
|
|
45
|
+
}
|
|
46
|
+
return Buffer.concat(chunks, size);
|
|
47
|
+
}
|
|
48
|
+
function helperStream(response) {
|
|
49
|
+
return response.body
|
|
50
|
+
? Readable.fromWeb(response.body)
|
|
51
|
+
: Readable.from([]);
|
|
52
|
+
}
|
|
53
|
+
function helperUrl(helper, path, search = '') {
|
|
54
|
+
const url = new URL(path, `http://127.0.0.1:${helper.port}`);
|
|
55
|
+
url.search = search;
|
|
56
|
+
url.searchParams.set('token', helper.token);
|
|
57
|
+
return url;
|
|
58
|
+
}
|
|
59
|
+
export async function findImpeccableHelper(workspace) {
|
|
60
|
+
try {
|
|
61
|
+
const root = await realpath(workspace);
|
|
62
|
+
const path = await realpath(join(root, '.impeccable', 'live', 'server.json'));
|
|
63
|
+
if (!within(root, path))
|
|
64
|
+
return;
|
|
65
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
66
|
+
let marker;
|
|
67
|
+
try {
|
|
68
|
+
if (!(await file.stat()).isFile())
|
|
69
|
+
return;
|
|
70
|
+
const buffer = Buffer.alloc(4097);
|
|
71
|
+
const { bytesRead } = await file.read(buffer);
|
|
72
|
+
if (bytesRead > 4096)
|
|
73
|
+
return;
|
|
74
|
+
marker = JSON.parse(buffer.subarray(0, bytesRead).toString());
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
await file.close();
|
|
78
|
+
}
|
|
79
|
+
if (typeof marker.port !== 'number' ||
|
|
80
|
+
!Number.isSafeInteger(marker.port) ||
|
|
81
|
+
marker.port < 1024 ||
|
|
82
|
+
marker.port > 65535 ||
|
|
83
|
+
typeof marker.pid !== 'number' ||
|
|
84
|
+
!Number.isSafeInteger(marker.pid) ||
|
|
85
|
+
marker.pid <= 0 ||
|
|
86
|
+
typeof marker.token !== 'string' ||
|
|
87
|
+
!/^[a-zA-Z0-9_-]{24,128}$/.test(marker.token))
|
|
88
|
+
return;
|
|
89
|
+
process.kill(marker.pid, 0);
|
|
90
|
+
const helper = { root, marker: path, port: marker.port, token: marker.token };
|
|
91
|
+
const response = await fetch(helperUrl(helper, '/status'), {
|
|
92
|
+
redirect: 'error',
|
|
93
|
+
signal: AbortSignal.timeout(1000),
|
|
94
|
+
});
|
|
95
|
+
if (!response.ok) {
|
|
96
|
+
await response.body?.cancel();
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const status = JSON.parse((await boundedBody(helperStream(response), maxJsonBytes)).toString());
|
|
100
|
+
if (status?.port === helper.port && typeof status.agentPolling === 'boolean')
|
|
101
|
+
return helper;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
// The helper may still be starting or its previous process may have exited.
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
export function injectImpeccableBootstrap() {
|
|
108
|
+
let head = Buffer.alloc(0);
|
|
109
|
+
let injected = false;
|
|
110
|
+
const script = Buffer.from(`<script src="${bootstrapPath}" defer></script>`);
|
|
111
|
+
return new Transform({
|
|
112
|
+
transform(chunk, _encoding, callback) {
|
|
113
|
+
if (!head)
|
|
114
|
+
return callback(null, chunk);
|
|
115
|
+
head = Buffer.concat([head, chunk]);
|
|
116
|
+
const index = head.toString('latin1').toLowerCase().indexOf('</head>');
|
|
117
|
+
if (index >= 0 || head.length >= 64 * 1024) {
|
|
118
|
+
injected = index >= 0;
|
|
119
|
+
const body = injected
|
|
120
|
+
? Buffer.concat([head.subarray(0, index), script, head.subarray(index)])
|
|
121
|
+
: head;
|
|
122
|
+
head = undefined;
|
|
123
|
+
callback(null, body);
|
|
124
|
+
}
|
|
125
|
+
else
|
|
126
|
+
callback();
|
|
127
|
+
},
|
|
128
|
+
flush(callback) {
|
|
129
|
+
callback(null, injected ? undefined : head ? Buffer.concat([head, script]) : script);
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
function send(response, status, type, body) {
|
|
134
|
+
response
|
|
135
|
+
.writeHead(status, {
|
|
136
|
+
'content-type': type,
|
|
137
|
+
'cache-control': 'no-store',
|
|
138
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
139
|
+
'x-content-type-options': 'nosniff',
|
|
140
|
+
})
|
|
141
|
+
.end(body);
|
|
142
|
+
}
|
|
143
|
+
const bootstrap = `(() => {
|
|
144
|
+
async function connect() {
|
|
145
|
+
try {
|
|
146
|
+
const result = await fetch('${impeccablePath}/ready', { cache: 'no-store' });
|
|
147
|
+
if (result.status === 401 || result.status === 403) return;
|
|
148
|
+
if (result.status === 204) {
|
|
149
|
+
const script = document.createElement('script');
|
|
150
|
+
script.src = '${impeccablePath}/live.js';
|
|
151
|
+
script.onerror = () => { script.remove(); setTimeout(connect, 1500); };
|
|
152
|
+
document.head.appendChild(script);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
} catch {}
|
|
156
|
+
setTimeout(connect, 1500);
|
|
157
|
+
}
|
|
158
|
+
connect();
|
|
159
|
+
})();`;
|
|
160
|
+
export function browserScript(script, token) {
|
|
161
|
+
return script
|
|
162
|
+
.replaceAll(token, createHash('sha256').update(token).digest('base64url'))
|
|
163
|
+
.replace(/(['"])http:\/\/localhost:\1\s*\+\s*PORT\s*\+\s*(['"])(?=\/)/g, (_match, _first, quote) => `${quote}${impeccablePath}`)
|
|
164
|
+
.replaceAll('http://localhost:${PORT}', impeccablePath);
|
|
165
|
+
}
|
|
166
|
+
export async function serveImpeccable(request, response, url, findHelper, track) {
|
|
167
|
+
const path = url.pathname.slice(impeccablePath.length);
|
|
168
|
+
if (path === '/bootstrap.js' && request.method === 'GET') {
|
|
169
|
+
send(response, 200, 'text/javascript; charset=utf-8', bootstrap);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const reading = request.method === 'GET' && (reads.has(path) || path === '/ready');
|
|
173
|
+
const writing = request.method === 'POST' && writes.has(path);
|
|
174
|
+
if (!reading && !writing) {
|
|
175
|
+
send(response, 404, 'text/plain', 'Unknown Impeccable route.');
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const controller = new AbortController();
|
|
179
|
+
const untrack = track(() => {
|
|
180
|
+
controller.abort();
|
|
181
|
+
response.destroy();
|
|
182
|
+
});
|
|
183
|
+
response.once('close', () => {
|
|
184
|
+
untrack();
|
|
185
|
+
controller.abort();
|
|
186
|
+
});
|
|
187
|
+
try {
|
|
188
|
+
const helper = await findHelper();
|
|
189
|
+
if (controller.signal.aborted)
|
|
190
|
+
return;
|
|
191
|
+
if (path === '/ready') {
|
|
192
|
+
send(response, helper ? 204 : 200, 'text/plain', '');
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (!helper) {
|
|
196
|
+
send(response, 503, 'text/plain', 'Waiting for the Impeccable Live helper.');
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (path === '/source') {
|
|
200
|
+
const name = url.searchParams.get('path');
|
|
201
|
+
const source = name && (await realpath(resolve(helper.root, name)).catch(() => undefined));
|
|
202
|
+
if (!source || source === helper.marker || !within(helper.root, source)) {
|
|
203
|
+
send(response, 404, 'text/plain', 'Impeccable source is unavailable.');
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
url.searchParams.set('path', source);
|
|
207
|
+
}
|
|
208
|
+
let body;
|
|
209
|
+
let contentType = 'application/json';
|
|
210
|
+
if (writing) {
|
|
211
|
+
const annotation = path === '/annotation';
|
|
212
|
+
const stream = request.iterator({ destroyOnReturn: false });
|
|
213
|
+
let bytes;
|
|
214
|
+
try {
|
|
215
|
+
bytes = await boundedBody(stream, annotation ? maxAnnotationBytes : maxJsonBytes);
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
request.resume();
|
|
219
|
+
send(response, 413, 'text/plain', 'Impeccable request body is too large.');
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (annotation) {
|
|
223
|
+
body = new Uint8Array(bytes);
|
|
224
|
+
contentType = 'image/png';
|
|
225
|
+
}
|
|
226
|
+
else if (bytes.length ||
|
|
227
|
+
(path !== '/manual-edit-commit' && path !== '/manual-edit-discard')) {
|
|
228
|
+
let payload;
|
|
229
|
+
try {
|
|
230
|
+
payload = JSON.parse(bytes.toString());
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
// The Live browser endpoints send a JSON object.
|
|
234
|
+
}
|
|
235
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
236
|
+
send(response, 400, 'text/plain', 'Impeccable request body is invalid.');
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
body = JSON.stringify({ ...payload, token: helper.token });
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const timeout = setTimeout(() => controller.abort(), 10_000);
|
|
243
|
+
const upstream = await fetch(helperUrl(helper, path, url.search), {
|
|
244
|
+
method: request.method,
|
|
245
|
+
...(body === undefined ? {} : { body, headers: { 'content-type': contentType } }),
|
|
246
|
+
signal: controller.signal,
|
|
247
|
+
redirect: 'error',
|
|
248
|
+
}).finally(() => clearTimeout(timeout));
|
|
249
|
+
if (path === '/live.js' && upstream.ok) {
|
|
250
|
+
const script = (await boundedBody(helperStream(upstream), maxJsonBytes)).toString();
|
|
251
|
+
send(response, 200, 'text/javascript; charset=utf-8', browserScript(script, helper.token));
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
response.writeHead(upstream.status, {
|
|
255
|
+
'content-type': upstream.headers.get('content-type') ?? 'application/octet-stream',
|
|
256
|
+
'cache-control': 'no-store',
|
|
257
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
258
|
+
'x-content-type-options': 'nosniff',
|
|
259
|
+
});
|
|
260
|
+
response.flushHeaders();
|
|
261
|
+
pipeline(helperStream(upstream), response, () => { });
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
if (!response.headersSent && !response.destroyed)
|
|
265
|
+
send(response, 502, 'text/plain', 'The Impeccable Live helper is unavailable.');
|
|
266
|
+
else
|
|
267
|
+
response.destroy();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
import { request, } from 'node:http';
|
|
7
|
+
import { pipeline } from 'node:stream';
|
|
8
|
+
import { injectImpeccableBootstrap } from './impeccable.js';
|
|
9
|
+
export const previewCookie = '__Host-gestalt-preview';
|
|
10
|
+
const hopHeaders = [
|
|
11
|
+
'connection',
|
|
12
|
+
'keep-alive',
|
|
13
|
+
'proxy-authenticate',
|
|
14
|
+
'proxy-authorization',
|
|
15
|
+
'proxy-connection',
|
|
16
|
+
'te',
|
|
17
|
+
'trailer',
|
|
18
|
+
'transfer-encoding',
|
|
19
|
+
'upgrade',
|
|
20
|
+
];
|
|
21
|
+
function endToEndHeaders(original) {
|
|
22
|
+
const headers = { ...original };
|
|
23
|
+
const nominated = original.connection?.split(',').map((name) => name.trim().toLowerCase()) ?? [];
|
|
24
|
+
for (const name of [...hopHeaders, ...nominated])
|
|
25
|
+
delete headers[name];
|
|
26
|
+
return headers;
|
|
27
|
+
}
|
|
28
|
+
export function cookieName(part) {
|
|
29
|
+
return part.split('=', 1)[0].trim();
|
|
30
|
+
}
|
|
31
|
+
function requestHeaders(browser, origin) {
|
|
32
|
+
const headers = endToEndHeaders(browser.headers);
|
|
33
|
+
for (const name of Object.keys(headers)) {
|
|
34
|
+
if (name === 'forwarded' || name.startsWith('x-forwarded-'))
|
|
35
|
+
delete headers[name];
|
|
36
|
+
}
|
|
37
|
+
const appCookies = headers.cookie
|
|
38
|
+
?.split(';')
|
|
39
|
+
.filter((part) => ![previewCookie, 'gestalt_mobile_session'].includes(cookieName(part)));
|
|
40
|
+
if (appCookies?.length)
|
|
41
|
+
headers.cookie = appCookies.join(';').trim();
|
|
42
|
+
else
|
|
43
|
+
delete headers.cookie;
|
|
44
|
+
headers.host = origin.host;
|
|
45
|
+
headers['x-forwarded-host'] = origin.host;
|
|
46
|
+
headers['x-forwarded-proto'] = 'https';
|
|
47
|
+
return headers;
|
|
48
|
+
}
|
|
49
|
+
function responseHeaders(upstream) {
|
|
50
|
+
const headers = endToEndHeaders(upstream);
|
|
51
|
+
const cookies = headers['set-cookie']?.filter((cookie) => {
|
|
52
|
+
const [value, ...attributes] = cookie.split(';');
|
|
53
|
+
return (![previewCookie, 'gestalt_mobile_session'].includes(cookieName(value)) &&
|
|
54
|
+
!attributes.some((attribute) => cookieName(attribute).toLowerCase() === 'domain'));
|
|
55
|
+
});
|
|
56
|
+
if (cookies?.length)
|
|
57
|
+
headers['set-cookie'] = cookies;
|
|
58
|
+
else
|
|
59
|
+
delete headers['set-cookie'];
|
|
60
|
+
headers['cache-control'] = 'no-store';
|
|
61
|
+
headers['referrer-policy'] = 'no-referrer';
|
|
62
|
+
headers['x-frame-options'] = 'DENY';
|
|
63
|
+
const policy = headers['content-security-policy'];
|
|
64
|
+
headers['content-security-policy'] = [
|
|
65
|
+
...(typeof policy === 'string' ? [policy] : (policy ?? [])),
|
|
66
|
+
"frame-ancestors 'none'",
|
|
67
|
+
];
|
|
68
|
+
return headers;
|
|
69
|
+
}
|
|
70
|
+
export function unavailable(response) {
|
|
71
|
+
response
|
|
72
|
+
.writeHead(502, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' })
|
|
73
|
+
.end('The preview server is unavailable. Start the configured dev server and retry.');
|
|
74
|
+
}
|
|
75
|
+
export function rejectUpgrade(socket, status) {
|
|
76
|
+
socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
77
|
+
}
|
|
78
|
+
function upstreamRequest(browser, headers, port) {
|
|
79
|
+
const upstream = request({
|
|
80
|
+
hostname: '127.0.0.1',
|
|
81
|
+
port,
|
|
82
|
+
method: browser.method,
|
|
83
|
+
path: browser.url,
|
|
84
|
+
headers,
|
|
85
|
+
});
|
|
86
|
+
upstream.setTimeout(10_000, () => upstream.destroy(new Error('Preview upstream timed out')));
|
|
87
|
+
return upstream;
|
|
88
|
+
}
|
|
89
|
+
export function proxyHttp(browser, response, target, track, impeccable = false) {
|
|
90
|
+
const headers = requestHeaders(browser, target.origin);
|
|
91
|
+
const document = impeccable && browser.method === 'GET' && headers.accept?.includes('text/html');
|
|
92
|
+
if (document)
|
|
93
|
+
headers['accept-encoding'] = 'identity';
|
|
94
|
+
const upstream = upstreamRequest(browser, headers, target.port);
|
|
95
|
+
const untrack = track(() => {
|
|
96
|
+
upstream.destroy();
|
|
97
|
+
response.destroy();
|
|
98
|
+
});
|
|
99
|
+
response.once('close', () => {
|
|
100
|
+
untrack();
|
|
101
|
+
if (!response.writableFinished)
|
|
102
|
+
upstream.destroy();
|
|
103
|
+
});
|
|
104
|
+
upstream.once('error', () => {
|
|
105
|
+
browser.unpipe(upstream);
|
|
106
|
+
browser.resume();
|
|
107
|
+
if (!response.headersSent && !response.destroyed)
|
|
108
|
+
unavailable(response);
|
|
109
|
+
else
|
|
110
|
+
response.destroy();
|
|
111
|
+
});
|
|
112
|
+
upstream.once('response', (incoming) => {
|
|
113
|
+
upstream.setTimeout(0);
|
|
114
|
+
const headers = responseHeaders(incoming.headers);
|
|
115
|
+
const decorate = document &&
|
|
116
|
+
incoming.statusCode === 200 &&
|
|
117
|
+
headers['content-type']?.startsWith('text/html') &&
|
|
118
|
+
(!headers['content-encoding'] || headers['content-encoding'] === 'identity');
|
|
119
|
+
if (decorate) {
|
|
120
|
+
delete headers['content-length'];
|
|
121
|
+
delete headers.etag;
|
|
122
|
+
}
|
|
123
|
+
response.writeHead(incoming.statusCode ?? 502, headers);
|
|
124
|
+
if (decorate)
|
|
125
|
+
pipeline(incoming, injectImpeccableBootstrap(), response, () => { });
|
|
126
|
+
else
|
|
127
|
+
pipeline(incoming, response, () => { });
|
|
128
|
+
});
|
|
129
|
+
browser.pipe(upstream);
|
|
130
|
+
}
|
|
131
|
+
export function proxyWebSocket(browser, socket, head, target, track) {
|
|
132
|
+
const headers = requestHeaders(browser, target.origin);
|
|
133
|
+
headers.connection = 'Upgrade';
|
|
134
|
+
headers.upgrade = 'websocket';
|
|
135
|
+
const upstream = upstreamRequest(browser, headers, target.port);
|
|
136
|
+
let peer;
|
|
137
|
+
const untrack = track(() => socket.destroy());
|
|
138
|
+
socket.once('error', () => socket.destroy());
|
|
139
|
+
socket.once('close', () => {
|
|
140
|
+
untrack();
|
|
141
|
+
upstream.destroy();
|
|
142
|
+
peer?.destroy();
|
|
143
|
+
});
|
|
144
|
+
upstream.once('error', () => {
|
|
145
|
+
if (!peer && !socket.destroyed)
|
|
146
|
+
rejectUpgrade(socket, '502 Bad Gateway');
|
|
147
|
+
});
|
|
148
|
+
upstream.once('response', (response) => {
|
|
149
|
+
response.destroy();
|
|
150
|
+
if (!socket.destroyed)
|
|
151
|
+
rejectUpgrade(socket, '502 Bad Gateway');
|
|
152
|
+
});
|
|
153
|
+
upstream.once('upgrade', (response, connected, initial) => {
|
|
154
|
+
if (socket.destroyed) {
|
|
155
|
+
connected.destroy();
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
connected.setTimeout(0);
|
|
159
|
+
peer = connected;
|
|
160
|
+
connected.once('error', () => socket.destroy());
|
|
161
|
+
connected.once('close', () => socket.destroy());
|
|
162
|
+
const handshake = responseHeaders(response.headers);
|
|
163
|
+
handshake.connection = 'Upgrade';
|
|
164
|
+
handshake.upgrade = 'websocket';
|
|
165
|
+
let reply = 'HTTP/1.1 101 Switching Protocols\r\n';
|
|
166
|
+
for (const [name, values] of Object.entries(handshake)) {
|
|
167
|
+
for (const value of typeof values === 'string' ? [values] : (values ?? []))
|
|
168
|
+
reply += `${name}: ${value}\r\n`;
|
|
169
|
+
}
|
|
170
|
+
socket.write(`${reply}\r\n`);
|
|
171
|
+
if (initial.length)
|
|
172
|
+
socket.write(initial);
|
|
173
|
+
if (head.length)
|
|
174
|
+
connected.write(head);
|
|
175
|
+
socket.pipe(connected).pipe(socket);
|
|
176
|
+
});
|
|
177
|
+
upstream.end();
|
|
178
|
+
}
|
|
@@ -149,7 +149,7 @@ export class FilesystemScratchCleanup {
|
|
|
149
149
|
if (leases.some((lease) => lease.state !== 'released' || lease.consumers.length !== 0)) {
|
|
150
150
|
if (authorized && marker.ownerKind === 'mobile-session') {
|
|
151
151
|
if (marker.runtime)
|
|
152
|
-
await validateRuntime(marker, marker.runtime, true);
|
|
152
|
+
await validateRuntime(marker, marker.runtime, { allowRetiring: true });
|
|
153
153
|
counts.leasedMobileSessions.push({
|
|
154
154
|
sessionId: marker.sessionId,
|
|
155
155
|
runtimeDirectory: marker.runtime?.directory,
|
|
@@ -159,7 +159,8 @@ export class FilesystemScratchCleanup {
|
|
|
159
159
|
}
|
|
160
160
|
if (authorized) {
|
|
161
161
|
await this.retireNestedNamespaces(directory, protectedSessions, authorized, authorizedSessionId, containment);
|
|
162
|
-
if (marker.runtime &&
|
|
162
|
+
if (marker.runtime &&
|
|
163
|
+
(await validateRuntime(marker, marker.runtime, { allowRetiring: true })))
|
|
163
164
|
await this.retireNestedNamespaces(marker.runtime.directory, protectedSessions, authorized, authorizedSessionId, containment);
|
|
164
165
|
}
|
|
165
166
|
// Manual Clean Tmp bounds opportunistic inspection. Explicit Forget
|
|
@@ -168,7 +169,7 @@ export class FilesystemScratchCleanup {
|
|
|
168
169
|
const readOnlyDirectories = await this.validatePayload(directory, inspectionBudget());
|
|
169
170
|
let readOnlyRuntimeDirectories = [];
|
|
170
171
|
if (marker.runtime) {
|
|
171
|
-
const present = await validateRuntime(marker, marker.runtime, true);
|
|
172
|
+
const present = await validateRuntime(marker, marker.runtime, { allowRetiring: true });
|
|
172
173
|
if (present) {
|
|
173
174
|
await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
|
|
174
175
|
(authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
|
|
@@ -334,7 +335,7 @@ export class FilesystemScratchCleanup {
|
|
|
334
335
|
if (!marker.runtime)
|
|
335
336
|
return;
|
|
336
337
|
const runtime = marker.runtime;
|
|
337
|
-
if (!(await validateRuntime(marker, runtime, true)))
|
|
338
|
+
if (!(await validateRuntime(marker, runtime, { allowRetiring: true })))
|
|
338
339
|
return;
|
|
339
340
|
// Persist retirement intent before either authority record is removed.
|
|
340
341
|
// After a crash an absent runtime is acceptable only with this exact record;
|
|
@@ -357,13 +358,13 @@ export class FilesystemScratchCleanup {
|
|
|
357
358
|
if (!attributed && children.length)
|
|
358
359
|
reject('unrecognized');
|
|
359
360
|
if (attributed) {
|
|
360
|
-
await validateRuntime(marker, marker.runtime, true);
|
|
361
|
+
await validateRuntime(marker, marker.runtime, { allowRetiring: true });
|
|
361
362
|
await prepareReadOnlyDirectories(runtime.directory, readOnlyDirectories);
|
|
362
363
|
for (const child of children) {
|
|
363
364
|
if (child.toString() !== runtimeMarkerName)
|
|
364
365
|
await rm(payloadPath(runtime.directory, child), { recursive: true });
|
|
365
366
|
}
|
|
366
|
-
await validateRuntime(marker, marker.runtime, true);
|
|
367
|
+
await validateRuntime(marker, marker.runtime, { allowRetiring: true });
|
|
367
368
|
await rm(join(runtime.directory, runtimeMarkerName));
|
|
368
369
|
}
|
|
369
370
|
if ((await runtimeIdentity(runtime.directory)) !== runtime.identity)
|