phase 1 rework

This commit is contained in:
admin_rb committed 2026-10-23 16:38:55 +02:00
1 parent 211bfd174d
commit 20054198f3
38 files changed
+5001 -1019

No files matched your search

+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env node
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const REPOSITORY_ROOT = path.resolve(__dirname, '..');
const MANIFEST_PATH = path.join(REPOSITORY_ROOT, 'tests/fixtures/protected-lib-manifest.json');
function readManifest() {
return JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf8'));
}
/** Read the entire tree without following symbolic links or writing bytecode. */
function inspectTree(directory) {
const entries = new Map();
function visit(absolutePath, relativePath) {
const stat = fs.lstatSync(absolutePath);
if (stat.isSymbolicLink()) {
entries.set(relativePath, { type: 'symlink' });
return;
}
if (stat.isDirectory()) {
entries.set(relativePath, { type: 'directory' });
for (const name of fs.readdirSync(absolutePath).sort()) {
visit(path.join(absolutePath, name), relativePath === '.' ? name : `${relativePath}/${name}`);
}
return;
}
if (stat.isFile()) {
entries.set(relativePath, {
type: 'file',
// Git's regular-file mode records the owner executable bit.
executable: Boolean(stat.mode & 0o100),
sha256: crypto.createHash('sha256').update(fs.readFileSync(absolutePath)).digest('hex'),
});
return;
}
entries.set(relativePath, { type: 'other' });
}
visit(directory, '.');
return entries;
}
/**
* Verify the fixed scripts/lib boundary against the reviewed baseline.
* No git dependency, imports of Python code, or filesystem writes are used.
*/
function verifyProtectedTree(repositoryRoot = REPOSITORY_ROOT, manifest = readManifest()) {
const errors = [];
if (manifest.version !== 1 || manifest.protectedRoot !== 'scripts/lib' || !Array.isArray(manifest.entries)) {
return { ok: false, errors: ['Invalid protected-library manifest.'], fileCount: 0 };
}
const expected = new Map();
for (const entry of manifest.entries) {
if (!entry || typeof entry.path !== 'string' || expected.has(entry.path) ||
(entry.path !== '.' && (path.posix.isAbsolute(entry.path) || entry.path.split('/').some(part => !part || part === '.' || part === '..'))) ||
!['file', 'directory'].includes(entry.type) ||
(entry.type === 'file' && (!/^[a-f0-9]{64}$/.test(entry.sha256) || typeof entry.executable !== 'boolean'))) {
return { ok: false, errors: ['Invalid protected-library manifest entry.'], fileCount: 0 };
}
expected.set(entry.path, entry);
}
if (expected.get('.')?.type !== 'directory') {
return { ok: false, errors: ['Protected-library manifest is missing its root directory.'], fileCount: 0 };
}
let actual;
try {
const scriptsDirectory = path.join(path.resolve(repositoryRoot), 'scripts');
const scriptsStat = fs.lstatSync(scriptsDirectory);
if (!scriptsStat.isDirectory() || scriptsStat.isSymbolicLink()) {
return { ok: false, errors: ['scripts must be a real directory, not a symbolic link.'], fileCount: 0 };
}
actual = inspectTree(path.join(scriptsDirectory, 'lib'));
} catch (error) {
return { ok: false, errors: [`Cannot inspect scripts/lib (${error.code || 'filesystem error'}).`], fileCount: 0 };
}
for (const [name, wanted] of expected) {
const found = actual.get(name);
const label = name === '.' ? 'scripts/lib' : `scripts/lib/${name}`;
if (!found) {
errors.push(`Missing protected entry: ${label}`);
} else if (found.type !== wanted.type) {
errors.push(`Protected entry type changed: ${label}`);
} else if (wanted.type === 'file') {
if (found.sha256 !== wanted.sha256) errors.push(`Protected file content changed: ${label}`);
if (found.executable !== wanted.executable) errors.push(`Protected file executable bit changed: ${label}`);
}
}
for (const name of actual.keys()) {
if (!expected.has(name)) errors.push(`Unexpected protected entry: scripts/lib/${name}`);
}
return {
ok: errors.length === 0,
errors,
fileCount: [...actual.values()].filter(entry => entry.type === 'file').length,
};
}
if (require.main === module) {
try {
const result = verifyProtectedTree();
if (result.ok) {
console.log(`Protected library verified: ${result.fileCount} files match the reviewed baseline; no added or missing entries.`);
} else {
for (const error of result.errors) console.error(error);
process.exitCode = 1;
}
} catch (error) {
console.error(`Protected-library verification failed (${error.code || 'invalid manifest'}).`);
process.exitCode = 1;
}
}
module.exports = { verifyProtectedTree, readManifest };
+63
View File
@@ -0,0 +1,63 @@
const fs = require('node:fs');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { verifyProtectedTree } = require('./check-protected-lib');
const root = path.resolve(__dirname, '..');
const temporaryRoot = fs.mkdtempSync(path.join(root, '.test-tmp-'));
Object.assign(process.env, { TMPDIR: temporaryRoot, TMP: temporaryRoot,
TEMP: temporaryRoot, PYTHONDONTWRITEBYTECODE: '1' });
function protect() {
const result = verifyProtectedTree(root);
if (!result.ok) throw new Error(`Protected library check failed:\n${result.errors.join('\n')}`);
console.log(`Protected library: ${result.fileCount} files match the original baseline.`);
}
async function runPython() {
const result = await new Promise((resolve) => {
const child = spawn(process.env.TEST_PYTHON || 'python3',
['-B', '-m', 'unittest', 'discover', '-s', 'tests/python', '-v'],
{ cwd: root, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
let output = '', settled = false;
function finish(status, error) {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve({ output, status, error });
}
const timer = setTimeout(() => {
child.kill('SIGKILL');
finish(null, new Error('Python suite exceeded its 60-second timeout.'));
}, 60000);
child.stdout.on('data', data => { output += data.toString(); });
child.stderr.on('data', data => { output += data.toString(); });
child.on('error', error => finish(null, error));
child.on('close', code => finish(code));
});
const count = Number(result.output.match(/Ran (\d+) tests?/)?.[1] || 0);
if (result.error || result.status !== 0 || count === 0 || /skipped=([1-9]\d*)/.test(result.output)) {
console.error(`Python downloader: FAILED${result.error ? ` (${result.error.message})` : ''}`);
console.error(result.output);
process.exitCode = 1;
} else {
console.log(`Python downloader: ${count} tests passed.`);
}
}
// Direct registration executes the actual tests on supported Node versions and
// also works in restricted runtimes that cannot fork Node's test runner.
async function main() {
protect();
await runPython();
const suites = fs.readdirSync(path.join(root, 'tests')).filter(name => name.endsWith('.test.js')).sort();
if (!suites.length) throw new Error('No Node test suites were found.');
for (const suite of suites) require(path.join(root, 'tests', suite));
}
process.once('exit', () => {
try { protect(); } catch (error) { console.error(error.message); process.exitCode = 1; }
fs.rmSync(temporaryRoot, { recursive: true, force: true });
});
main().catch(error => { console.error(error.message); process.exitCode = 1; });