Elffuss BraidHub

utopia-ia/elffuss-code public

c8095cfbfb2b · 11.8 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 if (/sha256sum/.test(cmd)) {
67 if (!fs.existsSync(dir)) process.exit(1);
68 const globs = /find \./.test(cmd) ? null : ((/sha256sum ([^"|;&]+)/.exec(cmd) || [])[1] || '').trim().split(/\s+/);
69 const match = (g, f) => new RegExp('^' + g.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$').test(f);
70 for (const f of fs.readdirSync(dir).sort().filter(f => !globs || globs.some(g => match(g, f)))) {
71 const p = path.join(dir, f);
72 if (fs.statSync(p).isDirectory()) { console.error('sha256sum: ' + f + ': Is a directory'); continue; }
73 console.log(crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex') + ' ' + f);
74 }
75 }
76 process.exit(0);
77}
78// rsync [-a] [--ignore-existing] [--delete] [--files-from=F] [-e …] SRC/ HOST:DEST/
79function fakeRsync(LOG, SERVER) {
80 const fs = require('fs'), path = require('path');
81 const a = process.argv.slice(2);
82 const list = a.find(x => x.startsWith('--files-from='));
83 const names = list ? fs.readFileSync(list.slice(13), 'utf8').split('\n').filter(Boolean) : null;
84 fs.appendFileSync(LOG, 'rsync ' + a.filter(x => !x.startsWith('--files-from=')).join(' ') + (names ? ' files:' + names.join(',') : '') + '\n');
85 const src = a.at(-2), dst = a.at(-1).replace(/^[^:]*:/, '').replaceAll('/var/www/', SERVER);
86 fs.mkdirSync(dst, { recursive: true });
87 const files = names || fs.readdirSync(src).filter(f => fs.statSync(path.join(src, f)).isFile());
88 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); }
89 if (a.includes('--delete') && !names) for (const f of fs.readdirSync(dst)) if (!files.includes(f)) fs.rmSync(path.join(dst, f), { recursive: true });
90}
91for (const [name, fn] of [['ssh', fakeSsh], ['rsync', fakeRsync]]) exe(name, `#!/usr/bin/env node\n(${fn.toString()})(${JSON.stringify(log)}, ${JSON.stringify(server + '/')});\n`);
92
93const run = (script, env = {}) => {
94 fs.writeFileSync(log, '');
95 const r = spawnSync('bash', [path.join(repo, script)], {
96 env: { ...process.env, PATH: bin + ':' + process.env.PATH, ELFFUSS_HOST: 'nobody@deploy.invalid', ELFFUSS_KEY: '/nonexistent', ...env },
97 encoding: 'utf8', timeout: 120000,
98 });
99 return { code: r.status, out: (r.stdout || '') + (r.stderr || ''), calls: fs.readFileSync(log, 'utf8').split('\n').filter(Boolean) };
100};
101const vendorDir = path.join(server, 'elffuss-code.utopiaia.com/vendor/x2', manifest.buildId);
102const localBuild = path.join(repo, 'web/vendor/x2', manifest.buildId);
103const want = [...manifest.files.map(f => f.name + '.gz'), manifest.licenses.name].sort();
104
105// D1
106let r = run('deploy-vendor.sh', { FAKE_FILTER: 'HEAD' });
107ok('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)
108 && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 200));
109
110// D2
111fs.writeFileSync(path.join(localBuild, 'notes.txt'), 'scratch notes\n');
112r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
113ok('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));
114fs.rmSync(path.join(localBuild, 'notes.txt'));
115const gz = path.join(localBuild, manifest.files[2].name + '.gz');
116const goodGz = fs.readFileSync(gz);
117fs.writeFileSync(gz, goodGz.subarray(0, goodGz.length >> 1));
118const co = spawnSync('node', [path.join(repo, 'vendor/vscode-ext2/check-output.mjs'), path.join(repo, 'web')], { encoding: 'utf8' });
119ok('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));
120fs.writeFileSync(gz, goodGz);
121
122// D3
123r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
124const up = r.calls.find(c => c.startsWith('rsync ')) || '';
125ok('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)
126 && up.split('files:')[1].split(',').sort().join() === want.join() && JSON.stringify(fs.readdirSync(vendorDir).sort()) === JSON.stringify(want), r.out.slice(-200));
127
128// D4
129fs.writeFileSync(path.join(vendorDir, 'stray.txt'), 'left from before\n');
130r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
131ok('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));
132
133// D5
134r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.elffuss.com' });
135ok('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));
136r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.sandbox-elsewhere.example' });
137ok('D5 …and a sandbox on another site that headers.json and config.js do not name, before uploading', r.code === 1
138 && /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)
139 && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 300));
140
141// D6
142fs.writeFileSync(path.join(repo, 'sandbox/x2/v1/notes.txt'), 'not for the server\n');
143const sbx = path.join(server, 'x2-sandbox/x2/v1');
144fs.mkdirSync(sbx, { recursive: true });
145fs.writeFileSync(path.join(sbx, 'old.html'), 'an old document\n');
146r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.utopiaia.com' });
147ok('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
148 && JSON.stringify(fs.readdirSync(sbx).sort()) === JSON.stringify(['exthost-iframe.html', 'sandbox.html']), r.out.slice(-300));
149r = run('deploy-sandbox.sh');
150const sbxProd = path.join(server, 'x2.utopiaia.com/x2/v1');
151ok('D6 with no origin or folder set, it deploys x2.utopiaia.com (headers.json) to /var/www/x2.utopiaia.com', r.code === 0
152 && r.calls.some(c => c.startsWith('rsync ') && c.endsWith(':/var/www/x2.utopiaia.com/x2/v1/'))
153 && fs.existsSync(sbxProd) && JSON.stringify(fs.readdirSync(sbxProd).sort()) === JSON.stringify(['exthost-iframe.html', 'sandbox.html'])
154 && /X2_SANDBOX=https:\/\/x2\.utopiaia\.com node tests\/x2_headers\.mjs/.test(r.out), r.out.slice(-300));
155
156// D7
157const 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;
158const today = live();
159const cfg = path.join(repo, 'web/js/ext2/config.js');
160const cfg0 = fs.readFileSync(cfg, 'utf8');
161const PROD = "'code.elffuss.com': 'https://x2.utopiaia.com',";
162const cfgNone = cfg0.replace(PROD, "'code.elffuss.com': null,");
163fs.writeFileSync(cfg, cfgNone);
164const noSandbox = live();
165fs.writeFileSync(cfg, cfg0);
166const man = path.join(repo, 'web/js/ext2/vendor-manifest.json');
167fs.writeFileSync(man, JSON.stringify({ ...manifest, enabled: false }));
168const switchedOff = live();
169ok('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
170 && today === 0 && noSandbox === 3 && switchedOff === 3, JSON.stringify({ today, noSandbox, switchedOff }));
171
172fs.rmSync(T, { recursive: true, force: true });
173console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
174process.exit(fails ? 1 : 0);