Elffuss BraidHub

utopia-ia/elffuss-code public

9a38018bfc74 · 10.5 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
18// D6 deploy-sandbox.sh uploads the two documents only, even with a stray
19// file next to them, and removes anything else on the server
20// D7 check-output.mjs --live: browsers ask for the bundle only when the
21// manifest is on and config.js gives Code a sandbox
22import fs from 'node:fs';
23import os from 'node:os';
24import path from 'node:path';
25import { spawnSync } from 'node:child_process';
26import { fileURLToPath } from 'node:url';
27
28const HERE = path.dirname(fileURLToPath(import.meta.url));
29const REPO = path.resolve(HERE, '..');
30let fails = 0;
31// (lo que dicen los scripts va en una línea y sin sus «✗», que run-modes.sh contaría como fallos)
32const 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++; };
33
34const manifest = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'), 'utf8'));
35const build = path.join(REPO, 'web/vendor/x2', manifest.buildId);
36if (!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); }
37
38const T = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'x2-deploy-'));
39const bin = path.join(T, 'bin'), server = path.join(T, 'server'), repo = path.join(T, 'repo');
40fs.mkdirSync(bin); fs.mkdirSync(server);
41const copy = (rel, { dir = false } = {}) => fs.cpSync(path.join(REPO, rel), path.join(repo, rel), { recursive: dir });
42for (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',
43 'web/js/ext2/vendor-manifest.json', 'web/js/ext2/config.js', 'sandbox/x2/headers.mjs', 'sandbox/x2/headers.json']) copy(f);
44copy('sandbox/x2/v1', { dir: true });
45copy(`web/vendor/x2/${manifest.buildId}`, { dir: true });
46
47// ── las falsificaciones ──
48const log = path.join(T, 'calls.log');
49const exe = (name, body) => { fs.writeFileSync(path.join(bin, name), body); fs.chmodSync(path.join(bin, name), 0o755); };
50// git show <ref>:deploy.sh → un deploy.sh con o sin el filtro, según FAKE_FILTER
51exe('git', `#!/bin/sh
52echo "git $*" >> "${log}"
53ref=\${2%%:*}
54case ",$FAKE_FILTER," in *",$ref,"*) echo "VENDOR=(--filter='P vendor/x2/***' --exclude='vendor/x2/')";; *) echo "rsync -az --delete web/ host:dest/";; esac
55`);
56// ssh -i KEY HOST "orden": /var/www/ es la carpeta del falso servidor; con
57// find, la carpeta entera; con «sha256sum *.gz X», solo lo que nombra
58function fakeSsh(LOG, SERVER) {
59 const fs = require('fs'), path = require('path'), crypto = require('crypto');
60 fs.appendFileSync(LOG, 'ssh ' + process.argv.slice(2).join(' ') + '\n');
61 const cmd = process.argv.at(-1).replaceAll('/var/www/', SERVER);
62 const dir = (/cd '([^']+)'/.exec(cmd) || /mkdir -p '([^']+)'/.exec(cmd) || [])[1];
63 if (/^mkdir -p/.test(cmd)) { fs.mkdirSync(dir, { recursive: true }); process.exit(0); }
64 if (/sha256sum/.test(cmd)) {
65 if (!fs.existsSync(dir)) process.exit(1);
66 const globs = /find \./.test(cmd) ? null : ((/sha256sum ([^"|;&]+)/.exec(cmd) || [])[1] || '').trim().split(/\s+/);
67 const match = (g, f) => new RegExp('^' + g.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$').test(f);
68 for (const f of fs.readdirSync(dir).sort().filter(f => !globs || globs.some(g => match(g, f)))) {
69 const p = path.join(dir, f);
70 if (fs.statSync(p).isDirectory()) { console.error('sha256sum: ' + f + ': Is a directory'); continue; }
71 console.log(crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex') + ' ' + f);
72 }
73 }
74 process.exit(0);
75}
76// rsync [-a] [--ignore-existing] [--delete] [--files-from=F] [-e …] SRC/ HOST:DEST/
77function fakeRsync(LOG, SERVER) {
78 const fs = require('fs'), path = require('path');
79 const a = process.argv.slice(2);
80 const list = a.find(x => x.startsWith('--files-from='));
81 const names = list ? fs.readFileSync(list.slice(13), 'utf8').split('\n').filter(Boolean) : null;
82 fs.appendFileSync(LOG, 'rsync ' + a.filter(x => !x.startsWith('--files-from=')).join(' ') + (names ? ' files:' + names.join(',') : '') + '\n');
83 const src = a.at(-2), dst = a.at(-1).replace(/^[^:]*:/, '').replaceAll('/var/www/', SERVER);
84 fs.mkdirSync(dst, { recursive: true });
85 const files = names || fs.readdirSync(src).filter(f => fs.statSync(path.join(src, f)).isFile());
86 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); }
87 if (a.includes('--delete') && !names) for (const f of fs.readdirSync(dst)) if (!files.includes(f)) fs.rmSync(path.join(dst, f), { recursive: true });
88}
89for (const [name, fn] of [['ssh', fakeSsh], ['rsync', fakeRsync]]) exe(name, `#!/usr/bin/env node\n(${fn.toString()})(${JSON.stringify(log)}, ${JSON.stringify(server + '/')});\n`);
90
91const run = (script, env = {}) => {
92 fs.writeFileSync(log, '');
93 const r = spawnSync('bash', [path.join(repo, script)], {
94 env: { ...process.env, PATH: bin + ':' + process.env.PATH, ELFFUSS_HOST: 'nobody@deploy.invalid', ELFFUSS_KEY: '/nonexistent', ...env },
95 encoding: 'utf8', timeout: 120000,
96 });
97 return { code: r.status, out: (r.stdout || '') + (r.stderr || ''), calls: fs.readFileSync(log, 'utf8').split('\n').filter(Boolean) };
98};
99const vendorDir = path.join(server, 'elffuss-code.utopiaia.com/vendor/x2', manifest.buildId);
100const localBuild = path.join(repo, 'web/vendor/x2', manifest.buildId);
101const want = [...manifest.files.map(f => f.name + '.gz'), manifest.licenses.name].sort();
102
103// D1
104let r = run('deploy-vendor.sh', { FAKE_FILTER: 'HEAD' });
105ok('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)
106 && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 200));
107
108// D2
109fs.writeFileSync(path.join(localBuild, 'notes.txt'), 'scratch notes\n');
110r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
111ok('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));
112fs.rmSync(path.join(localBuild, 'notes.txt'));
113const gz = path.join(localBuild, manifest.files[2].name + '.gz');
114const goodGz = fs.readFileSync(gz);
115fs.writeFileSync(gz, goodGz.subarray(0, goodGz.length >> 1));
116const co = spawnSync('node', [path.join(repo, 'vendor/vscode-ext2/check-output.mjs'), path.join(repo, 'web')], { encoding: 'utf8' });
117ok('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));
118fs.writeFileSync(gz, goodGz);
119
120// D3
121r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
122const up = r.calls.find(c => c.startsWith('rsync ')) || '';
123ok('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)
124 && up.split('files:')[1].split(',').sort().join() === want.join() && JSON.stringify(fs.readdirSync(vendorDir).sort()) === JSON.stringify(want), r.out.slice(-200));
125
126// D4
127fs.writeFileSync(path.join(vendorDir, 'stray.txt'), 'left from before\n');
128r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
129ok('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));
130
131// D5
132r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.elffuss.com' });
133ok('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));
134
135// D6
136fs.writeFileSync(path.join(repo, 'sandbox/x2/v1/notes.txt'), 'not for the server\n');
137const sbx = path.join(server, 'x2-sandbox/x2/v1');
138fs.mkdirSync(sbx, { recursive: true });
139fs.writeFileSync(path.join(sbx, 'old.html'), 'an old document\n');
140r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.sandbox-elsewhere.example' });
141ok('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
142 && JSON.stringify(fs.readdirSync(sbx).sort()) === JSON.stringify(['exthost-iframe.html', 'sandbox.html']), r.out.slice(-300));
143
144// D7
145const 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;
146const today = live();
147const cfg = path.join(repo, 'web/js/ext2/config.js');
148const cfg0 = fs.readFileSync(cfg, 'utf8');
149fs.writeFileSync(cfg, cfg0.replace("'code.elffuss.com': null,", "'code.elffuss.com': 'https://x2.sandbox-elsewhere.example',"));
150const withSandbox = live();
151const man = path.join(repo, 'web/js/ext2/vendor-manifest.json');
152fs.writeFileSync(man, JSON.stringify({ ...manifest, enabled: false }));
153const switchedOff = live();
154ok('D7 check-output --live: not today (config.js gives Code no sandbox), yes once it does, no with the kill switch', today === 3 && withSandbox === 0 && switchedOff === 3, JSON.stringify({ today, withSandbox, switchedOff }));
155
156fs.rmSync(T, { recursive: true, force: true });
157console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
158process.exit(fails ? 1 : 0);