Elffuss BraidHub

utopia-ia/elffuss-code public

2df00d521f0c · 12.7 KiBRawPermalink
1// The level 2 deploy scripts, without a server: deploy-vendor.sh and
2// deploy-sandbox.sh run on a copy of the files they need, with fake `git`,
3// `ssh` and `rsync` first in PATH. The fake ssh runs the remote commands
4// against a folder that plays the server; nothing leaves this machine.
5//
6// node tests/x2_deploy.mjs (needs the local vendor build, or NOT RUN)
7//
8// D1 deploy-vendor.sh refuses while main's deploy.sh lacks the vendor/x2/
9// filter (a deploy from main would delete the bundle), before any upload
10// D2 a stray file next to the bundle (notes, .DS_Store) stops it before any
11// upload; check-output.mjs names it, and a corrupt .gz is a problem, not
12// a crash
13// D3 a clean bundle: only the manifest's four files are uploaded, and the
14// server's whole folder is compared with the manifest
15// D4 a stray file already on the server makes it fail (full listing, not
16// a glob)
17// D5 deploy-sandbox.sh refuses a sandbox on Code's own site, and one that
18// headers.json and config.js do not name, before any upload
19// D6 deploy-sandbox.sh uploads the two documents only, even with a stray
20// file next to them, and removes anything else on the server; with
21// nothing set, it deploys x2.utopiaia.com (headers.json) to its folder
22// D7 check-output.mjs --live: browsers ask for the bundle only when the
23// manifest is on and config.js gives Code a sandbox (it does now)
24import fs from 'node:fs';
25import os from 'node:os';
26import path from 'node:path';
27import { spawnSync } from 'node:child_process';
28import { fileURLToPath } from 'node:url';
29
30const HERE = path.dirname(fileURLToPath(import.meta.url));
31const REPO = path.resolve(HERE, '..');
32let fails = 0;
33// (lo que dicen los scripts va en una línea y sin sus «✗», que run-modes.sh contaría como fallos)
34const ok = (name, c, extra = '') => { const x = String(extra).replace(/✗/g, '(x)').replace(/\s*\n\s*/g, ' ⏎ '); console.log((c ? '✅' : '❌') + ' ' + name + (x ? ' — ' + x : '')); if (!c) fails++; };
35
36const manifest = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'), 'utf8'));
37const build = path.join(REPO, 'web/vendor/x2', manifest.buildId);
38if (!fs.existsSync(build)) { console.log(`⏭️ NOT RUN x2_deploy — web/vendor/x2/${manifest.buildId} is not built here (vendor/vscode-ext2/build.mjs)`); process.exit(0); }
39
40const T = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'x2-deploy-'));
41const bin = path.join(T, 'bin'), server = path.join(T, 'server'), repo = path.join(T, 'repo');
42fs.mkdirSync(bin); fs.mkdirSync(server);
43const copy = (rel, { dir = false } = {}) => fs.cpSync(path.join(REPO, rel), path.join(repo, rel), { recursive: dir });
44for (const f of ['deploy-vendor.sh', 'deploy-sandbox.sh', 'vendor/vscode-ext2/check-output.mjs', 'vendor/vscode-ext2/sweep.mjs', 'vendor/vscode-ext2/sweep-allowlist.json',
45 'web/js/ext2/vendor-manifest.json', 'web/js/ext2/config.js', 'sandbox/x2/headers.mjs', 'sandbox/x2/headers.json']) copy(f);
46copy('sandbox/x2/v1', { dir: true });
47copy(`web/vendor/x2/${manifest.buildId}`, { dir: true });
48
49// ── las falsificaciones ──
50const log = path.join(T, 'calls.log');
51const exe = (name, body) => { fs.writeFileSync(path.join(bin, name), body); fs.chmodSync(path.join(bin, name), 0o755); };
52// git show <ref>:deploy.sh → un deploy.sh con o sin el filtro, según FAKE_FILTER
53exe('git', `#!/bin/sh
54echo "git $*" >> "${log}"
55ref=\${2%%:*}
56case ",$FAKE_FILTER," in *",$ref,"*) echo "VENDOR=(--filter='P vendor/x2/***' --exclude='vendor/x2/')";; *) echo "rsync -az --delete web/ host:dest/";; esac
57`);
58// ssh -i KEY HOST "orden": /var/www/ es la carpeta del falso servidor; con
59// find, la carpeta entera; con «sha256sum *.gz X», solo lo que nombra
60function fakeSsh(LOG, SERVER) {
61 const fs = require('fs'), path = require('path'), crypto = require('crypto');
62 fs.appendFileSync(LOG, 'ssh ' + process.argv.slice(2).join(' ') + '\n');
63 const cmd = process.argv.at(-1).replaceAll('/var/www/', SERVER);
64 const dir = (/cd '([^']+)'/.exec(cmd) || /mkdir -p '([^']+)'/.exec(cmd) || [])[1];
65 if (/^mkdir -p/.test(cmd)) { fs.mkdirSync(dir, { recursive: true }); process.exit(0); }
66 // stat -c '%a %n' NAMES: the octal mode of each, as GNU stat prints it
67 if (/stat -c '%a %n'/.test(cmd)) {
68 for (const n of cmd.split("stat -c '%a %n' ")[1].trim().split(/\s+/)) console.log((fs.statSync(path.join(dir, n)).mode & 0o777).toString(8) + ' ' + n);
69 process.exit(0);
70 }
71 if (/sha256sum/.test(cmd)) {
72 if (!fs.existsSync(dir)) process.exit(1);
73 const globs = /find \./.test(cmd) ? null : ((/sha256sum ([^"|;&]+)/.exec(cmd) || [])[1] || '').trim().split(/\s+/);
74 const match = (g, f) => new RegExp('^' + g.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$').test(f);
75 for (const f of fs.readdirSync(dir).sort().filter(f => !globs || globs.some(g => match(g, f)))) {
76 const p = path.join(dir, f);
77 if (fs.statSync(p).isDirectory()) { console.error('sha256sum: ' + f + ': Is a directory'); continue; }
78 console.log(crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex') + ' ' + f);
79 }
80 }
81 process.exit(0);
82}
83// rsync [-a] [--ignore-existing] [--delete] [--files-from=F] [-e …] SRC/ HOST:DEST/
84function fakeRsync(LOG, SERVER) {
85 const fs = require('fs'), path = require('path');
86 const a = process.argv.slice(2);
87 const list = a.find(x => x.startsWith('--files-from='));
88 const names = list ? fs.readFileSync(list.slice(13), 'utf8').split('\n').filter(Boolean) : null;
89 fs.appendFileSync(LOG, 'rsync ' + a.filter(x => !x.startsWith('--files-from=')).join(' ') + (names ? ' files:' + names.join(',') : '') + '\n');
90 const src = a.at(-2), dst = a.at(-1).replace(/^[^:]*:/, '').replaceAll('/var/www/', SERVER);
91 fs.mkdirSync(dst, { recursive: true });
92 const files = names || fs.readdirSync(src).filter(f => fs.statSync(path.join(src, f)).isFile());
93 for (const f of files) { const to = path.join(dst, f); if (a.includes('--ignore-existing') && fs.existsSync(to)) continue; fs.copyFileSync(path.join(src, f), to); fs.chmodSync(to, fs.statSync(path.join(src, f)).mode & 0o777); }
94 // rsync -a SRC/ DEST/ gives DEST the mode of SRC (a mktemp -d folder is 700)
95 if (a.includes('-a') && !names) fs.chmodSync(dst, fs.statSync(src).mode & 0o777);
96 if (a.includes('--delete') && !names) for (const f of fs.readdirSync(dst)) if (!files.includes(f)) fs.rmSync(path.join(dst, f), { recursive: true });
97}
98for (const [name, fn] of [['ssh', fakeSsh], ['rsync', fakeRsync]]) exe(name, `#!/usr/bin/env node\n(${fn.toString()})(${JSON.stringify(log)}, ${JSON.stringify(server + '/')});\n`);
99
100const run = (script, env = {}) => {
101 fs.writeFileSync(log, '');
102 const r = spawnSync('bash', [path.join(repo, script)], {
103 env: { ...process.env, PATH: bin + ':' + process.env.PATH, ELFFUSS_HOST: 'nobody@deploy.invalid', ELFFUSS_KEY: '/nonexistent', ...env },
104 encoding: 'utf8', timeout: 120000,
105 });
106 return { code: r.status, out: (r.stdout || '') + (r.stderr || ''), calls: fs.readFileSync(log, 'utf8').split('\n').filter(Boolean) };
107};
108const vendorDir = path.join(server, 'elffuss-code.utopiaia.com/vendor/x2', manifest.buildId);
109const localBuild = path.join(repo, 'web/vendor/x2', manifest.buildId);
110const want = [...manifest.files.map(f => f.name + '.gz'), manifest.licenses.name].sort();
111
112// D1
113let r = run('deploy-vendor.sh', { FAKE_FILTER: 'HEAD' });
114ok('D1 deploy-vendor.sh refuses while main’s deploy.sh lacks the vendor/x2/ filter, before uploading anything', r.code === 1 && /deploy\.sh de main no protege vendor\/x2\//.test(r.out)
115 && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 200));
116
117// D2
118fs.writeFileSync(path.join(localBuild, 'notes.txt'), 'scratch notes\n');
119r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
120ok('D2 a stray file next to the bundle stops it before any upload, and is named', r.code === 1 && /notes\.txt is not in the manifest/.test(r.out) && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 300));
121fs.rmSync(path.join(localBuild, 'notes.txt'));
122const gz = path.join(localBuild, manifest.files[2].name + '.gz');
123const goodGz = fs.readFileSync(gz);
124fs.writeFileSync(gz, goodGz.subarray(0, goodGz.length >> 1));
125const co = spawnSync('node', [path.join(repo, 'vendor/vscode-ext2/check-output.mjs'), path.join(repo, 'web')], { encoding: 'utf8' });
126ok('D2 a corrupt .gz is reported as a problem (it does not inflate), not a crash', co.status === 1 && /does not inflate/.test(co.stderr) && !/at .*check-output\.mjs/.test(co.stderr), co.stderr.slice(0, 300));
127fs.writeFileSync(gz, goodGz);
128
129// D3
130r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
131const up = r.calls.find(c => c.startsWith('rsync ')) || '';
132ok('D3 a clean bundle: only the manifest’s four files are uploaded, and the server’s folder then matches the manifest', r.code === 0 && /files:/.test(up)
133 && up.split('files:')[1].split(',').sort().join() === want.join() && JSON.stringify(fs.readdirSync(vendorDir).sort()) === JSON.stringify(want), r.out.slice(-200));
134
135// D4
136fs.writeFileSync(path.join(vendorDir, 'stray.txt'), 'left from before\n');
137r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
138ok('D4 a stray file already on the server makes it fail: the whole folder is compared, not a glob', r.code === 1 && /stray\.txt/.test(r.out), r.out.slice(0, 300));
139
140// D5
141r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.elffuss.com' });
142ok('D5 deploy-sandbox.sh refuses a sandbox on Code’s own site (x2.elffuss.com), before uploading', r.code === 1 && /same site as https:\/\/code\.elffuss\.com/.test(r.out) && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 300));
143r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.sandbox-elsewhere.example' });
144ok('D5 …and a sandbox on another site that headers.json and config.js do not name, before uploading', r.code === 1
145 && /headers\.json names https:\/\/x2\.utopiaia\.com for production/.test(r.out) && /config\.js names https:\/\/x2\.utopiaia\.com for code\.elffuss\.com/.test(r.out)
146 && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 300));
147
148// D6
149fs.writeFileSync(path.join(repo, 'sandbox/x2/v1/notes.txt'), 'not for the server\n');
150const sbx = path.join(server, 'x2-sandbox/x2/v1');
151fs.mkdirSync(sbx, { recursive: true });
152fs.writeFileSync(path.join(sbx, 'old.html'), 'an old document\n');
153r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.utopiaia.com' });
154ok('D6 deploy-sandbox.sh uploads only its two documents (not a stray file next to them) and leaves nothing else on the server', r.code === 0
155 && JSON.stringify(fs.readdirSync(sbx).sort()) === JSON.stringify(['exthost-iframe.html', 'sandbox.html']), r.out.slice(-300));
156r = run('deploy-sandbox.sh');
157const sbxProd = path.join(server, 'x2.utopiaia.com/x2/v1');
158ok('D6 with no origin or folder set, it deploys x2.utopiaia.com (headers.json) to /var/www/x2.utopiaia.com', r.code === 0
159 && r.calls.some(c => c.startsWith('rsync ') && c.endsWith(':/var/www/x2.utopiaia.com/x2/v1/'))
160 && fs.existsSync(sbxProd) && JSON.stringify(fs.readdirSync(sbxProd).sort()) === JSON.stringify(['exthost-iframe.html', 'sandbox.html'])
161 && /X2_SANDBOX=https:\/\/x2\.utopiaia\.com node tests\/x2_headers\.mjs/.test(r.out), r.out.slice(-300));
162const modes = fs.existsSync(sbxProd) ? [sbxProd, ...['sandbox.html', 'exthost-iframe.html'].map(f => path.join(sbxProd, f))].map(p => (fs.statSync(p).mode & 0o777).toString(8)).join(' ') : 'missing';
163ok('D6 the web server can read what it uploaded: folder 755, documents 644 (rsync -a of a mktemp folder left 700 and both 404)', modes === '755 644 644', modes);
164
165// D7
166const live = (env = {}) => spawnSync('node', [path.join(repo, 'vendor/vscode-ext2/check-output.mjs'), '--live', path.join(repo, 'web')], { encoding: 'utf8', env: { ...process.env, ...env } }).status;
167const today = live();
168const cfg = path.join(repo, 'web/js/ext2/config.js');
169const cfg0 = fs.readFileSync(cfg, 'utf8');
170const PROD = "'code.elffuss.com': 'https://x2.utopiaia.com',";
171const cfgNone = cfg0.replace(PROD, "'code.elffuss.com': null,");
172fs.writeFileSync(cfg, cfgNone);
173const noSandbox = live();
174fs.writeFileSync(cfg, cfg0);
175const man = path.join(repo, 'web/js/ext2/vendor-manifest.json');
176fs.writeFileSync(man, JSON.stringify({ ...manifest, enabled: false }));
177const switchedOff = live();
178ok('D7 check-output --live: yes today (config.js gives Code x2.utopiaia.com), no without a sandbox for Code, no with the kill switch', cfg0.includes(PROD) && cfgNone !== cfg0
179 && today === 0 && noSandbox === 3 && switchedOff === 3, JSON.stringify({ today, noSandbox, switchedOff }));
180
181fs.rmSync(T, { recursive: true, force: true });
182console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
183process.exit(fails ? 1 : 0);