@@ -0,0 +1,76 @@
|
||||
// Native Fortify, CSRF and Inertia protocol for owned loopback QA only.
|
||||
export function createNativeInertiaClient(origin, check) {
|
||||
const base = new URL(origin);
|
||||
if (base.protocol !== "http:" || !["localhost", "127.0.0.1"].includes(base.hostname) || !base.port) throw Error("Owned loopback client required");
|
||||
const cookies = new Map();
|
||||
let version = '';
|
||||
const request = async (route, options = {}) => {
|
||||
if (!route.startsWith('/') || new URL(route, base).origin !== base.origin) throw Error('External HTTP destination refused');
|
||||
const response = await fetch(new URL(route, base), { ...options, redirect: 'manual', headers: {
|
||||
Accept: 'application/json', Cookie: [...cookies].map(([k, v]) => `${k}=${v}`).join('; '),
|
||||
...(options.headers?.['X-Inertia'] === 'true' ? { 'X-Inertia-Version': version } : {}), ...options.headers,
|
||||
} });
|
||||
for (const header of response.headers.getSetCookie()) {
|
||||
const pair = header.split(';', 1)[0];
|
||||
const index = pair.indexOf('=');
|
||||
if (index > 0) cookies.set(pair.slice(0, index), pair.slice(index + 1));
|
||||
}
|
||||
// A checker may inspect only status/headers. Drain the network body before
|
||||
// a closed PHP socket can leave Undici paused, retaining a readable clone.
|
||||
const buffered = response.clone();
|
||||
await response.arrayBuffer();
|
||||
return buffered;
|
||||
};
|
||||
const csrf = () => ({ 'X-XSRF-TOKEN': decodeURIComponent(cookies.get('XSRF-TOKEN') ?? '') });
|
||||
const login = async email => {
|
||||
const initial = await request('/login', { headers: { Accept: 'text/html' } });
|
||||
check(initial.status === 200, 'native login page');
|
||||
const initialPage = (await initial.text()).match(/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/);
|
||||
check(initialPage !== null, 'native initial page protocol');
|
||||
version = JSON.parse(initialPage[1]).version;
|
||||
check(typeof version === 'string' && version.length > 0, 'native asset version');
|
||||
const payload = JSON.stringify({ email, password: 'password', remember: false });
|
||||
const invalid = await request('/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload });
|
||||
check(invalid.status === 419, 'missing CSRF refused before login');
|
||||
const response = await request('/login', { method: 'POST', headers: { 'Content-Type': 'application/json', ...csrf() }, body: payload });
|
||||
check([200, 302].includes(response.status), 'native Fortify credentials accepted');
|
||||
const stale = await request('/dashboard', { headers: { 'X-Inertia': 'true', 'X-Inertia-Version': 'deliberately-stale-synthetic-version' } });
|
||||
check(stale.status === 409 && stale.headers.has('X-Inertia-Location'), 'stale asset protocol refused without changing access rules');
|
||||
const dashboard = await request('/dashboard', { headers: { 'X-Inertia': 'true' } });
|
||||
check(dashboard.status === 200, `authenticated dashboard status ${dashboard.status}`);
|
||||
const state = await dashboard.json();
|
||||
check(state.props.auth?.user?.email === email, 'session retains the exact native actor');
|
||||
};
|
||||
const page = async (route, component) => {
|
||||
const response = await request(route, { headers: { 'X-Inertia': 'true' } });
|
||||
let error = '';
|
||||
if (response.status !== 200) {
|
||||
try { error = String((await response.clone().json()).message ?? '').slice(0, 180); } catch { /* status remains diagnostic */ }
|
||||
}
|
||||
check(response.status === 200, `${component} native route status ${response.status} ${error}`);
|
||||
check(response.headers.get('X-Inertia') === 'true', `${component} native Inertia response`);
|
||||
const page = await response.json();
|
||||
check(page.component === component, `${component} component`);
|
||||
check(page.encryptHistory === true, `${component} encrypted history`);
|
||||
if (component.startsWith('purchase-controls/')) check(response.headers.get('Cache-Control')?.includes('private') && response.headers.get('Cache-Control')?.includes('no-store'), 'purchase controls private response');
|
||||
return page;
|
||||
};
|
||||
const logout = async () => {
|
||||
check([200, 204, 302].includes((await request('/logout', { method: 'POST', headers: csrf() })).status), 'native logout');
|
||||
check((await request('/auditoria/eventos')).status === 401, 'closed session cannot read metadata');
|
||||
};
|
||||
const post = async (route, payload, expected = 302) => {
|
||||
const response = await request(route, { method: 'POST', headers: { 'Content-Type': 'application/json', ...csrf() }, body: JSON.stringify(payload) });
|
||||
const allowed = Array.isArray(expected) ? expected : [expected];
|
||||
let detail = '';
|
||||
if (!allowed.includes(response.status)) {
|
||||
try {
|
||||
const error = await response.clone().json();
|
||||
detail = String(error.message ?? '').slice(0, 180) + ' fields=' + Object.keys(error.errors ?? {}).join(',');
|
||||
} catch { /* status is still diagnostic */ }
|
||||
}
|
||||
check(allowed.includes(response.status), `native command ${route} status ${response.status} ${detail}`);
|
||||
return response;
|
||||
};
|
||||
return { request, login, page, logout, post };
|
||||
}
|
||||
@@ -98,13 +98,35 @@ try {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/CapitalRegisterTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||
'--filter=capital|register|line destination|submitted requisitions|revoked requester|confirmed import classifications|partial native order retains|native consolidated order retains']];
|
||||
}
|
||||
if (in_array('--supply-search-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ProcurementSearchTest.php', 'tests/Feature/SavedProcurementSearchesTest.php']];
|
||||
}
|
||||
if (in_array('--audit-investigation-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/AuditMetadataBlockTest.php', 'tests/Feature/InternalRequisitionCandidateTest.php',
|
||||
'--filter=audit metadata block|auditor investigates|literal zero action|requisition audit export']];
|
||||
}
|
||||
if (in_array('--warehouse-search-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/WarehouseRequestsTest.php', 'tests/Feature/WarehouseFulfilmentTest.php',
|
||||
'tests/Feature/WarehouseExchangeTest.php', 'tests/Feature/ProcurementSearchTest.php', 'tests/Feature/SavedProcurementSearchesTest.php']];
|
||||
}
|
||||
if (in_array('--capital-approval-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/CapitalRegisterTest.php', 'tests/Feature/RequisitionCategoriesTest.php',
|
||||
'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionApprovalLevelsTest.php', 'tests/Feature/IncompleteRequisitionDraftTest.php']];
|
||||
}
|
||||
if (in_array('--capital-equipment-trace-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||
'tests/Feature/CapitalRegisterTest.php', '--filter=native frozen asset origin|equipment backlink|asset references reuse']];
|
||||
}
|
||||
if (in_array('--requisition-cycles-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php']];
|
||||
}
|
||||
if (in_array('--urgent-review-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', '--filter=posterior urgent review|urgent review keeps indeterminate']];
|
||||
}
|
||||
if (in_array('--cycle-history-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', 'tests/Feature/ImportEstimatesTest.php',
|
||||
'--filter=native expiry returns the same request|expired import cycle preserves']];
|
||||
}
|
||||
if (in_array('--requisition-cycles-artifact', $argv, true)) {
|
||||
$artifact = json_decode(file_get_contents(base_path('docs/proofs/requisition-expiry-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (! preg_match('~^storage/framework/testing/requisition-cycles-qa-[a-f0-9]{16}$~D', $artifact['path'] ?? '')
|
||||
@@ -153,6 +175,27 @@ try {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||
'--filter=native delivery analysis|native consolidated order retains']];
|
||||
}
|
||||
if (in_array('--duplicate-hints-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionDuplicateHintsTest.php']];
|
||||
}
|
||||
if (in_array('--submission-preview-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionSubmissionPreviewTest.php',
|
||||
'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionApprovalLevelsTest.php']];
|
||||
}
|
||||
if (in_array('--submission-preview-delta', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionSubmissionPreviewTest.php',
|
||||
'tests/Feature/ImportEstimatesTest.php', '--filter=submission preview|native submission approves the full estimate']];
|
||||
}
|
||||
if (in_array('--receipt-preparation-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ReceiptStockTest.php']];
|
||||
}
|
||||
if (in_array('--supplier-preparation-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/SupplierMaintenanceTest.php']];
|
||||
}
|
||||
if (in_array('--capital-approval-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionApprovalLevelsTest.php',
|
||||
'tests/Feature/CapitalRegisterTest.php', '--filter=classified machinery']];
|
||||
}
|
||||
if (in_array('--expense-allocation-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ExpenseAllocationsTest.php', 'tests/Feature/ProcurementPayableInsightsTest.php']];
|
||||
}
|
||||
@@ -179,6 +222,10 @@ try {
|
||||
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||
[PHP_BINARY, 'tests/Concurrency/requisition-cycle-recovery-worker.php', $database, 'recover-cycles']];
|
||||
}
|
||||
if (in_array('--urgent-expiry-recovery', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||
[PHP_BINARY, 'tests/Concurrency/requisition-cycle-recovery-worker.php', $database, 'recover-urgent']];
|
||||
}
|
||||
if (in_array('--capital-concurrency', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-capital']];
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
// Own disposable Compras database/role/cluster for the real common-ledger schema.
|
||||
// Never starts, configures or connects to an operational SGF/Compras database.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { createServer } from 'node:net';
|
||||
|
||||
const id = crypto.randomBytes(6).toString('hex');
|
||||
const workspace = path.resolve('C:/laragon/www/compras');
|
||||
if (path.resolve(process.cwd()) !== workspace) throw Error('Compras workspace required');
|
||||
if (process.argv.includes('--integrated-cycles-only') && !process.argv.includes('--integrated-schema')) throw Error('Integrated cycles require the complete isolated schema composition');
|
||||
if (process.argv.includes('--integrated-orders-only') && !process.argv.includes('--integrated-schema')) throw Error('Integrated orders require the complete isolated schema composition');
|
||||
if (process.argv.includes('--integrated-import-costs-only') && !process.argv.includes('--integrated-schema')) throw Error('Integrated import costs require the complete isolated schema composition');
|
||||
if (process.argv.includes('--integrated-release-journeys') && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Release journeys require the complete pinned private composition');
|
||||
if (process.argv.includes('--native-review-http-only') && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Native HTTP review requires the complete pinned private composition');
|
||||
if (process.argv.includes('--native-office-http-only') && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Native office HTTP journey requires the complete pinned private composition');
|
||||
if (process.argv.some(flag => ['--independent-procurement-only', '--privacy-controllers-only'].includes(flag)) && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Focused release regressions require the complete pinned private composition');
|
||||
const privateParent = path.join(workspace, 'storage/framework/testing');
|
||||
const frozenRuntime = process.argv.includes('--frozen-runtime');
|
||||
if (frozenRuntime && !process.argv.includes('--integrated-schema')) throw Error('Frozen runtime requires the complete isolated schema composition');
|
||||
const financeRoot = path.join(privateParent, 'requisition-ledger-runtime-qa-182e10ceec556e12');
|
||||
const financePin = '182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df';
|
||||
const budgetRoot = path.join(privateParent, 'requisition-cycles-qa-35701ec1614f871e');
|
||||
function verifyPrivateRuntime(root, pin, count) {
|
||||
const manifestFile = path.join(root, 'manifest.json');
|
||||
if (fs.lstatSync(root).isSymbolicLink() || fs.lstatSync(manifestFile).isSymbolicLink()) throw Error('Private runtime links refused');
|
||||
const bytes = fs.readFileSync(manifestFile);
|
||||
if (crypto.createHash('sha256').update(bytes).digest('hex') !== pin) throw Error('Pinned runtime manifest differs');
|
||||
const manifest = JSON.parse(bytes);
|
||||
const entries = Array.isArray(manifest.files) ? manifest.files.map(e => [e.file, e.sha256]) : Object.entries(manifest.files);
|
||||
if (entries.length !== count) throw Error('Private runtime file count differs');
|
||||
const expected = new Set(['manifest.json']);
|
||||
const boundary = fs.realpathSync(root) + path.sep;
|
||||
for (const [file, hash] of entries) {
|
||||
if (typeof file !== 'string' || !/^[A-Za-z0-9_./-]+$/.test(file) || file.split('/').includes('..') || expected.has(file)) throw Error('Private runtime path refused');
|
||||
const target = path.join(root, file);
|
||||
if (!fs.realpathSync(target).startsWith(boundary) || fs.lstatSync(target).isSymbolicLink() || !fs.lstatSync(target).isFile()
|
||||
|| crypto.createHash('sha256').update(fs.readFileSync(target)).digest('hex') !== hash) throw Error('Private runtime byte mismatch');
|
||||
expected.add(file);
|
||||
}
|
||||
const walk = directory => {
|
||||
for (const name of fs.readdirSync(directory)) {
|
||||
const target = path.join(directory, name);
|
||||
const stat = fs.lstatSync(target);
|
||||
if (stat.isSymbolicLink()) throw Error('Private runtime links refused');
|
||||
if (stat.isDirectory()) walk(target);
|
||||
else if (!stat.isFile() || !expected.delete(path.relative(root, target).replaceAll('\\', '/'))) throw Error('Unexpected private runtime file');
|
||||
}
|
||||
};
|
||||
walk(root);
|
||||
if (expected.size !== 0) throw Error('Private runtime file missing');
|
||||
}
|
||||
if (frozenRuntime) {
|
||||
verifyPrivateRuntime(financeRoot, financePin, 44);
|
||||
verifyPrivateRuntime(budgetRoot, 'fe1dec59a6d619670e887fd2f972a6de176b858a90f03cf43a017c681606816a', 24);
|
||||
console.log(JSON.stringify({ private_frozen_runtime: true, finance_manifest_sha256: financePin,
|
||||
budget_manifest_sha256: 'fe1dec59a6d619670e887fd2f972a6de176b858a90f03cf43a017c681606816a', finance_files: 44, budget_files: 24 }));
|
||||
}
|
||||
const root = path.join(privateParent, `rq01-ledger-qa-${id}`);
|
||||
const cluster = path.join(root, 'postgres');
|
||||
if (path.dirname(root) !== privateParent || !/^rq01-ledger-qa-[a-f0-9]{12}$/.test(path.basename(root))) throw Error('Private QA root refused');
|
||||
fs.mkdirSync(root);
|
||||
const database = `compras_receipts_test_${id}`;
|
||||
const role = `payable_history_native_${id}`;
|
||||
const password = crypto.randomBytes(30).toString('hex');
|
||||
const adminPassword = crypto.randomBytes(30).toString('hex');
|
||||
const passwordFile = path.join(root, 'admin-password.txt');
|
||||
fs.writeFileSync(passwordFile, adminPassword);
|
||||
const pg = 'C:/Program Files/PostgreSQL/17/bin';
|
||||
const psql = path.join(pg, 'psql.exe');
|
||||
function pgRun(binary, args) {
|
||||
const result = spawnSync(path.join(pg, binary), args, { windowsHide: true, encoding: 'utf8',
|
||||
// Detached PostgreSQL Windows children must not inherit a captured pipe.
|
||||
...(binary === 'pg_ctl.exe' ? { stdio: 'ignore' } : {}),
|
||||
});
|
||||
if (result.status !== 0) throw Error('Private QA cluster operation failed: ' + (result.stderr || ''));
|
||||
}
|
||||
function sql(input) {
|
||||
const result = spawnSync(psql, ['-h', '127.0.0.1', '-p', '55439', '-U', 'sgf_regression_owner', '-d', 'postgres', '-X', '-v', 'ON_ERROR_STOP=1', '-At'], {
|
||||
windowsHide: true, encoding: 'utf8', input,
|
||||
env: { ...process.env, PGPASSWORD: adminPassword },
|
||||
});
|
||||
if (result.status !== 0) throw Error('Isolated ledger SQL failed: ' + (result.stderr || '').replaceAll(password, '[private]').replaceAll(adminPassword, '[private]'));
|
||||
return result.stdout.trim();
|
||||
}
|
||||
let createdRole = false;
|
||||
let createdDatabase = false;
|
||||
let started = false;
|
||||
let restoreRole = null;
|
||||
let restoreDatabase = null;
|
||||
let reviewServer = null;
|
||||
try {
|
||||
// The ledger contract fixes this QA port; an occupied port is refused, never stopped.
|
||||
pgRun('initdb.exe', ['-D', cluster, '-U', 'sgf_regression_owner', '-A', 'scram-sha-256', '--pwfile='+passwordFile, '-E', 'UTF8', '--locale=C']);
|
||||
fs.appendFileSync(path.join(cluster, 'postgresql.conf'), `\nlisten_addresses='127.0.0.1'\nport=55439\ncluster_name='sgf_modular_regression_${id}'\n`);
|
||||
pgRun('pg_ctl.exe', ['-D', cluster, '-l', path.join(root, 'postgres.log'), '-w', 'start']);
|
||||
started = true;
|
||||
if (sql("SELECT current_setting('cluster_name')") !== `sgf_modular_regression_${id}`) throw Error('Unexpected cluster');
|
||||
sql(`CREATE ROLE ${role} LOGIN PASSWORD '${password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;`);
|
||||
createdRole = true;
|
||||
sql(`CREATE DATABASE ${database} OWNER ${role};`);
|
||||
createdDatabase = true;
|
||||
sql(`REVOKE ALL ON DATABASE ${database} FROM PUBLIC;`);
|
||||
const environment = { ...process.env, APP_ENV: 'testing', APP_DEBUG: 'false', APP_KEY: 'base64:'+crypto.randomBytes(32).toString('base64'), DB_CONNECTION: 'pgsql', DB_URL: '', DB_HOST: '127.0.0.1', DB_PORT: '55439',
|
||||
DB_DATABASE: database, DB_USERNAME: role, DB_PASSWORD: password, CACHE_STORE: 'array', SESSION_DRIVER: 'array',
|
||||
MAIL_MAILER: 'array', QUEUE_CONNECTION: 'sync', BROADCAST_CONNECTION: 'null',
|
||||
COMMON_BUDGET_PATH: frozenRuntime ? path.join(budgetRoot, 'budget-control') : 'C:/laragon/www/sgf-tempo/packages/budget-control',
|
||||
RQ01_LEDGER_QA_SOURCE: frozenRuntime ? path.join(financeRoot, 'general-ledger') : 'C:/laragon/www/sgf-tempo/packages/general-ledger',
|
||||
RQ01_LEDGER_INTEGRATED_SCHEMA: process.argv.includes('--integrated-schema') ? '1' : '0',
|
||||
RQ01_NATIVE_OFFICE_JOURNEY: process.argv.includes('--native-office-http-only') ? '1' : '0' };
|
||||
delete environment.COMMON_FINANCE_BUNDLE_ROOT;
|
||||
delete environment.COMMON_FINANCE_BUNDLE_SHA256;
|
||||
if (frozenRuntime) {
|
||||
environment.COMMON_FINANCE_BUNDLE_ROOT = financeRoot;
|
||||
environment.COMMON_FINANCE_BUNDLE_SHA256 = financePin;
|
||||
}
|
||||
const raceOnly = process.argv.includes('--race-only');
|
||||
const recoveryOnly = process.argv.includes('--recovery-only');
|
||||
const nativeFixtureOnly = process.argv.includes('--native-review-fixture-only');
|
||||
const nativeHttpOnly = process.argv.includes('--native-review-http-only');
|
||||
const nativeOfficeOnly = process.argv.includes('--native-office-http-only');
|
||||
const nativeReview = process.argv.includes('--native-review') || nativeFixtureOnly || nativeHttpOnly || nativeOfficeOnly;
|
||||
const setupOnly = raceOnly || recoveryOnly || nativeReview;
|
||||
const args = setupOnly ? ['artisan', 'migrate', '--force', '--no-interaction'] : process.argv.includes('--integrated-release-journeys') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/RequisitionBudgetCyclesTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/ImportLandedCostsTest.php', '--filter=RequisitionBudgetCyclesTest|ImportLandedCostsTest|native office purchase|native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-import-costs-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostsTest.php'] : process.argv.includes('--integrated-orders-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-cycles-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php'] : process.argv.includes('--office-process-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=native office purchase'] : ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||
'--filter=minimal purchasing catalogue|chart references reject|native line account assignment|classified line requires|native submission requires account|zero monetary line retains|native order preserves common ledger|native office purchase'];
|
||||
if (process.argv.includes('--runtime-guard-only')) {
|
||||
if (!frozenRuntime || !process.argv.includes('--integrated-schema') || setupOnly) throw Error('Runtime guard requires only the frozen isolated composition');
|
||||
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=pinned private runtime refuses');
|
||||
}
|
||||
if (process.argv.includes('--independent-procurement-only')) {
|
||||
if (setupOnly) throw Error('Independent procurement is a focused native Pest regression');
|
||||
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=office_with_independent_procurement');
|
||||
}
|
||||
if (process.argv.includes('--privacy-controllers-only')) {
|
||||
if (setupOnly) throw Error('Private controllers are focused native Pest regressions');
|
||||
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=budget consultations|purchase control preparations');
|
||||
}
|
||||
const result = spawnSync('php', args, {
|
||||
cwd: process.cwd(), windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment,
|
||||
});
|
||||
if (!setupOnly || result.status !== 0) process.stdout.write((result.stdout || '').replaceAll(password, '[private]'));
|
||||
process.stderr.write((result.stderr || '').replaceAll(password, '[private]'));
|
||||
process.exitCode = result.status === 0 ? 0 : 1;
|
||||
if (result.status === 0 && raceOnly) {
|
||||
const race = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'race'], {
|
||||
cwd: process.cwd(), windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment,
|
||||
});
|
||||
process.stdout.write((race.stdout || '').replaceAll(password, '[private]'));
|
||||
process.stderr.write((race.stderr || '').replaceAll(password, '[private]'));
|
||||
process.exitCode = race.status === 0 ? 0 : 1;
|
||||
}
|
||||
if (result.status === 0 && recoveryOnly) {
|
||||
const worker = (mode, env, payload = null) => {
|
||||
const args = ['tests/Concurrency/requisition-account-worker.php', env.DB_DATABASE, mode];
|
||||
if (payload !== null) args.push(JSON.stringify(payload));
|
||||
const result = spawnSync('php', args, { cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env });
|
||||
if (result.status !== 0) throw Error('Account recovery worker failed: ' + (result.stderr || result.stdout || '').replaceAll(password, '[private]'));
|
||||
return JSON.parse(result.stdout);
|
||||
};
|
||||
const fixture = worker('prepare-recovery', environment);
|
||||
const pgCommand = (binary, args, env) => {
|
||||
const result = spawnSync(path.join(pg, binary), args, { windowsHide: true, encoding: 'utf8',
|
||||
env: { ...process.env, PGHOST: '127.0.0.1', PGPORT: '55439', PGUSER: env.DB_USERNAME, PGPASSWORD: env.DB_PASSWORD } });
|
||||
if (result.status !== 0) throw Error('Private account backup/restore failed');
|
||||
};
|
||||
const dump = path.join(root, 'accounts.dump');
|
||||
pgCommand('pg_dump.exe', ['--format=custom', '--no-owner', '--no-acl', '--file='+dump, '--dbname='+database], environment);
|
||||
const restoredId = crypto.randomBytes(6).toString('hex');
|
||||
const restoredPassword = crypto.randomBytes(30).toString('hex');
|
||||
const targetRole = `payable_history_native_${restoredId}`;
|
||||
const targetDatabase = `compras_receipts_test_${restoredId}`;
|
||||
sql(`CREATE ROLE ${targetRole} LOGIN PASSWORD '${restoredPassword}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;`);
|
||||
restoreRole = targetRole;
|
||||
sql(`CREATE DATABASE ${targetDatabase} OWNER ${targetRole};`);
|
||||
restoreDatabase = targetDatabase;
|
||||
sql(`REVOKE ALL ON DATABASE ${targetDatabase} FROM PUBLIC;`);
|
||||
const restoredEnvironment = { ...environment, DB_DATABASE: targetDatabase, DB_USERNAME: targetRole, DB_PASSWORD: restoredPassword };
|
||||
pgCommand('pg_restore.exe', ['--no-owner', '--no-acl', '--exit-on-error', '--dbname='+targetDatabase, dump], restoredEnvironment);
|
||||
console.log(JSON.stringify(worker('verify-recovery', restoredEnvironment, fixture)));
|
||||
}
|
||||
if (result.status === 0 && nativeReview) {
|
||||
for (const relative of ['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private']) {
|
||||
fs.mkdirSync(path.join(root, relative), { recursive: true });
|
||||
}
|
||||
const seed = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'prepare-native-review'], {
|
||||
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024,
|
||||
env: { ...environment, SGC_REQUISITION_QA_ROOT: root },
|
||||
});
|
||||
if (seed.status !== 0) throw Error('Native review fixture failed: '+(seed.stderr || seed.stdout || '').replaceAll(password, '[private]'));
|
||||
const fixture = JSON.parse(seed.stdout);
|
||||
fs.writeFileSync(path.join(root, 'native-review.json'), JSON.stringify(fixture));
|
||||
const assets = path.join(privateParent, 'sgc-company-preparation-final-qa-20261128');
|
||||
const manifest = fs.readFileSync(path.join(assets, 'manifest.json'));
|
||||
const manifestHash = crypto.createHash('sha256').update(manifest).digest('hex');
|
||||
if (manifestHash !== 'df4e07d422af16897581371283d9730f41076ad2888d1e4911bdd7cadbb92c5f') throw Error('Unexpected private review manifest');
|
||||
for (const entry of Object.values(JSON.parse(manifest))) {
|
||||
if (!fs.existsSync(path.join(assets, entry.file))) throw Error('Private review asset missing');
|
||||
}
|
||||
fs.cpSync(assets, path.join(root, 'public/build'), { recursive: true });
|
||||
if (nativeFixtureOnly) {
|
||||
console.log(JSON.stringify({ private_native_fixture_verified: true, ...fixture, private_manifest_sha256: manifestHash }));
|
||||
} else {
|
||||
const port = await new Promise((resolve, reject) => {
|
||||
const socket = createServer(); socket.on('error', reject);
|
||||
socket.listen(0, '127.0.0.1', () => { const address = socket.address(); socket.close(() => resolve(address.port)); });
|
||||
});
|
||||
const url = `http://localhost:${port}`;
|
||||
reviewServer = spawn('php', ['-S', `127.0.0.1:${port}`, '-t', path.join(root, 'public'), 'tests/Support/requisition-qa-http-router.php'], {
|
||||
cwd: workspace, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: { ...environment, APP_URL: url, ASSET_URL: url, SESSION_DRIVER: 'file', SESSION_COOKIE: `sgc_req_qa_${id}`,
|
||||
SGC_REQUISITION_QA_ROOT: root, SGC_REQUISITION_QA_PORT: String(port),
|
||||
SGC_PRODUCT_ENTITLEMENTS: JSON.stringify({ [fixture.tenant_id]: ['procurement.internal'] }) },
|
||||
});
|
||||
let diagnostic = '';
|
||||
reviewServer.stdout.on('data', data => { diagnostic = (diagnostic + data).slice(-4000); });
|
||||
reviewServer.stderr.on('data', data => { diagnostic = (diagnostic + data).slice(-4000); });
|
||||
let ready = false;
|
||||
for (let attempt = 0; attempt < 40; attempt++) {
|
||||
try {
|
||||
ready = true;
|
||||
for (const route of ['/up', '/login']) {
|
||||
const response = await fetch(url + route);
|
||||
await response.arrayBuffer();
|
||||
ready = ready && response.status === 200;
|
||||
}
|
||||
} catch { ready = false; /* startup only */ }
|
||||
if (ready) break;
|
||||
if (reviewServer.exitCode !== null) break;
|
||||
await new Promise(resolve => setTimeout(resolve, 250));
|
||||
}
|
||||
if (!ready) throw Error('Native review server unavailable: '+diagnostic.replaceAll(password, '[private]'));
|
||||
if (nativeOfficeOnly) {
|
||||
const { verifyOfficePurchaseHttp } = await import('./requisition-office-http-check.mjs');
|
||||
const result = await verifyOfficePurchaseHttp(url, fixture, async () => {
|
||||
const state = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'read-office-purchase'], {
|
||||
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024,
|
||||
env: { ...environment, SGC_REQUISITION_QA_ROOT: root },
|
||||
});
|
||||
if (state.status !== 0) throw Error('Native office assertion worker failed: ' + (state.stderr || state.stdout || '').replaceAll(password, '[private]').replaceAll(environment.APP_KEY, '[private]'));
|
||||
return JSON.parse(state.stdout);
|
||||
}, value => console.log(JSON.stringify(value)));
|
||||
console.log(JSON.stringify({ private_native_office_http_verified: true, ...result, private_manifest_sha256: manifestHash }));
|
||||
} else if (nativeHttpOnly) {
|
||||
const { verifyNativeReviewHttp } = await import('./requisition-native-http-check.mjs');
|
||||
const pageAssets = ['resources/js/pages/supply/index.tsx', 'resources/js/pages/purchase-controls/index.tsx', 'resources/js/pages/purchase-controls/orders.tsx', 'resources/js/pages/budgets/index.tsx', 'resources/js/pages/conflicts/index.tsx', 'resources/js/pages/conflicts/show.tsx', 'resources/js/pages/payments/index.tsx', 'resources/js/pages/stock/index.tsx', 'resources/js/pages/stock/operations.tsx', 'resources/js/pages/stock/lots.tsx', 'resources/js/pages/stock/reversals.tsx', 'resources/js/pages/stock/dispositions.tsx', 'resources/js/pages/equipment/index.tsx', 'resources/js/pages/investment/index.tsx', 'resources/js/pages/company/parameters.tsx', 'resources/js/pages/company/index.tsx', 'resources/js/pages/company/setup.tsx']
|
||||
.map(key => JSON.parse(manifest)[key]);
|
||||
const result = await verifyNativeReviewHttp(url, fixture, {
|
||||
assets: pageAssets.map(entry => ({ file: entry.file, sha256: crypto.createHash('sha256').update(fs.readFileSync(path.join(assets, entry.file))).digest('hex') })),
|
||||
snapshot: async () => {
|
||||
const result = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'read-native-sources'], {
|
||||
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment,
|
||||
});
|
||||
if (result.status !== 0) throw Error('Native HTTP read snapshot failed');
|
||||
return JSON.parse(result.stdout).snapshot;
|
||||
},
|
||||
});
|
||||
console.log(JSON.stringify({ private_native_http_verified: true, ...result, private_manifest_sha256: manifestHash }));
|
||||
} else {
|
||||
const stopFile = path.join(root, 'stop-review');
|
||||
console.log(JSON.stringify({ private_native_review_running: true, url, stop_file: stopFile, ...fixture, private_manifest_sha256: manifestHash }));
|
||||
const until = Date.now() + 20 * 60 * 1000;
|
||||
while (!fs.existsSync(stopFile) && Date.now() < until) {
|
||||
if (reviewServer.exitCode !== null) throw Error('Private native review stopped unexpectedly');
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (reviewServer && reviewServer.exitCode === null) {
|
||||
const closed = new Promise(resolve => reviewServer.once('exit', resolve));
|
||||
reviewServer.kill();
|
||||
await closed;
|
||||
}
|
||||
if (restoreDatabase) {
|
||||
sql(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${restoreDatabase}' AND pid<>pg_backend_pid();`);
|
||||
sql(`DROP DATABASE ${restoreDatabase};`);
|
||||
}
|
||||
if (restoreRole) sql(`DROP ROLE ${restoreRole};`);
|
||||
if (createdDatabase) {
|
||||
sql(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${database}' AND pid<>pg_backend_pid();`);
|
||||
sql(`DROP DATABASE ${database};`);
|
||||
}
|
||||
if (createdRole) sql(`DROP ROLE ${role};`);
|
||||
if (started) pgRun('pg_ctl.exe', ['-D', cluster, '-m', 'fast', '-w', 'stop']);
|
||||
// Verified absolute task root, containing only this newly-created cluster and secrets.
|
||||
if (path.dirname(path.resolve(root)) !== privateParent || path.basename(root) !== `rq01-ledger-qa-${id}`) throw Error('Cleanup root refused');
|
||||
fs.rmSync(root, { recursive: true });
|
||||
console.log(JSON.stringify({ isolated_database_removed: createdDatabase, isolated_role_removed: createdRole,
|
||||
restored_database_removed: restoreDatabase !== null, restored_role_removed: restoreRole !== null, operational_changes: false }));
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Package the already-used common QA runtime into a private Compras artefact.
|
||||
// No database, operational package, settings or SGF source is modified.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
const workspace = 'C:/laragon/www/compras';
|
||||
if (path.resolve(process.cwd()) !== path.resolve(workspace)) throw Error('Compras workspace required');
|
||||
const canonical = 'C:/laragon/www/sgf-tempo/packages';
|
||||
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
const sources = ['finance-bundle/Bundle.php'];
|
||||
for (const name of ['payables', 'general-ledger']) {
|
||||
for (const file of ['bootstrap.php', 'README.md']) {
|
||||
if (fs.existsSync(path.join(canonical, name, file))) sources.push(`${name}/${file}`);
|
||||
}
|
||||
for (const dir of ['src', 'ui']) {
|
||||
for (const file of fs.readdirSync(path.join(canonical, name, dir)).sort()) {
|
||||
if (!/^[A-Za-z0-9_-]+\.php$/.test(file)) throw Error('Unexpected runtime source');
|
||||
sources.push(`${name}/${dir}/${file}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const content = sources.map(source => {
|
||||
const actual = path.join(canonical, source);
|
||||
if (!fs.lstatSync(actual).isFile() || fs.lstatSync(actual).isSymbolicLink()) throw Error('Regular runtime files required');
|
||||
return { file: source === 'finance-bundle/Bundle.php' ? 'Bundle.php' : source, bytes: fs.readFileSync(actual) };
|
||||
}).sort((a, b) => a.file.localeCompare(b.file));
|
||||
const files = content.map(({ file, bytes }) => ({ file, sha256: hash(bytes) }));
|
||||
const manifest = JSON.stringify({ contract: 'COMMON-FINANCE-BUNDLE-v1', synthetic_only: true, files }, null, 2) + '\n';
|
||||
const pin = hash(manifest);
|
||||
const root = path.join(workspace, 'storage/framework/testing', `requisition-ledger-runtime-qa-${pin.slice(0, 16)}`);
|
||||
if (!fs.existsSync(root)) {
|
||||
fs.mkdirSync(root);
|
||||
for (const { file, bytes } of content) {
|
||||
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, file), bytes, { flag: 'wx' });
|
||||
}
|
||||
fs.writeFileSync(path.join(root, 'manifest.json'), manifest, { flag: 'wx' });
|
||||
}
|
||||
if (hash(fs.readFileSync(path.join(root, 'manifest.json'))) !== pin) throw Error('Existing artefact differs; never overwrite');
|
||||
// The caller fixes this manifest and loader hash before loading any executable.
|
||||
for (const { file, sha256 } of files) {
|
||||
const target = path.join(root, file);
|
||||
if (!fs.lstatSync(target).isFile() || fs.lstatSync(target).isSymbolicLink() || hash(fs.readFileSync(target)) !== sha256) throw Error('Artefact byte mismatch');
|
||||
}
|
||||
const code = 'require $argv[1]."/Bundle.php"; echo json_encode(Tempo\\Finance\\Composition\\Bundle::verify($argv[1],$argv[2]),JSON_THROW_ON_ERROR);';
|
||||
const checked = spawnSync('php', ['-r', code, root, pin], { windowsHide: true, encoding: 'utf8' });
|
||||
if (checked.status !== 0) throw Error('Existing common bundle verifier refused the private artefact');
|
||||
console.log(JSON.stringify({ root, manifest_sha256: pin, files: files.length, verified: true, synthetic_only: true, installed_or_activated: false }));
|
||||
@@ -0,0 +1,102 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { createNativeInertiaClient } from './lib/native-inertia-client.mjs';
|
||||
|
||||
/** Exercise native Fortify sessions and read routes, without business commands or a browser claim. */
|
||||
export async function verifyNativeReviewHttp(origin, fixture, { assets, snapshot }) {
|
||||
const base = new URL(origin);
|
||||
if (base.protocol !== 'http:' || !['localhost', '127.0.0.1'].includes(base.hostname) || !base.port || typeof snapshot !== 'function') throw Error('Owned loopback review required');
|
||||
let checks = 0;
|
||||
const check = (condition, label) => { if (!condition) throw Error(`Native HTTP verification failed: ${label}`); checks++; };
|
||||
const client = () => createNativeInertiaClient(base.href, check);
|
||||
const guest = client();
|
||||
check((await guest.request('/auditoria/eventos')).status === 401, 'anonymous metadata access refused');
|
||||
check(Array.isArray(assets) && assets.length > 0, 'private candidate assets supplied');
|
||||
for (const asset of assets) {
|
||||
const file = await guest.request(`/build/${asset.file}`);
|
||||
check(file.status === 200, 'private candidate asset served');
|
||||
check(crypto.createHash('sha256').update(Buffer.from(await file.arrayBuffer())).digest('hex') === asset.sha256, 'HTTP asset bytes match private build');
|
||||
}
|
||||
const reviewer = client();
|
||||
const auditor = client();
|
||||
const requester = client();
|
||||
await reviewer.login(fixture.synthetic_login);
|
||||
await auditor.login(fixture.synthetic_metadata_login);
|
||||
await requester.login(fixture.synthetic_requester_login);
|
||||
// Login/logout may legitimately rotate native authentication fields. Compare the read window only.
|
||||
const before = await snapshot();
|
||||
const budgets = await reviewer.page('/orcamentos', 'budgets/index');
|
||||
check(budgets.props.budgets.length > 0, 'native synthetic budget is visible to its authorised reader');
|
||||
const budgetHeaders = await reviewer.request('/orcamentos');
|
||||
check(budgetHeaders.headers.get('Cache-Control')?.includes('no-store'), 'private budget response not cacheable');
|
||||
check((await requester.request('/orcamentos')).status === 403, 'requester cannot read operational budget preparations');
|
||||
for (const actor of [reviewer, requester]) {
|
||||
await actor.page('/conflitos', 'conflicts/index');
|
||||
const response = await actor.request('/conflitos');
|
||||
check(response.headers.get('Cache-Control')?.includes('no-store'), 'personal conflicts not cacheable');
|
||||
}
|
||||
for (const [route, component] of [['/stock', 'stock/index'], ['/stock/operacoes', 'stock/operations']]) {
|
||||
await reviewer.page(route, component);
|
||||
const response = await reviewer.request(route);
|
||||
check(response.headers.get('Cache-Control')?.includes('no-store'), 'stock workspace not cacheable');
|
||||
check((await requester.request(route)).status === 403, 'requester cannot read operational stock workspace');
|
||||
}
|
||||
for (const [route, component] of [['/equipamentos', 'equipment/index'], ['/regras-investimento', 'investment/index']]) {
|
||||
const page = await reviewer.page(route, component);
|
||||
check(page.props.canManage === true, 'native administrative preparation scope retained');
|
||||
const response = await reviewer.request(route);
|
||||
check(response.headers.get('Cache-Control')?.includes('no-store'), 'equipment and investment preparation not cacheable');
|
||||
check((await requester.request(route)).status === 403, 'requester cannot inherit equipment or investment administration');
|
||||
}
|
||||
const companyConfiguration = await reviewer.page('/administracao/parametrizacao', 'company/parameters');
|
||||
check(companyConfiguration.props.ready === true && Array.isArray(companyConfiguration.props.profiles) && companyConfiguration.props.profiles.length > 0, 'existing synthetic company configuration remains consultable');
|
||||
const companyResponse = await reviewer.request('/administracao/parametrizacao');
|
||||
check(companyResponse.headers.get('Cache-Control')?.includes('no-store'), 'company configuration not cacheable');
|
||||
check((await requester.request('/administracao/parametrizacao')).status === 403, 'requester cannot inherit configuration administration');
|
||||
const detail = await reviewer.page(`/requisicoes/${fixture.historical_decision_request}`, 'requisitions/show');
|
||||
check(detail.props.canReadAuditMetadata === true, 'native request audit navigation permission');
|
||||
const history = await reviewer.page(`/requisicoes/${fixture.historical_decision_request}/prazos`, 'requisitions/expiry');
|
||||
check(history.props.history.data[0].request.total_minor === 10000, 'original cycle amount survives native HTTP');
|
||||
const query = new URLSearchParams({ request_reference: fixture.audit_request_reference });
|
||||
const metadata = await reviewer.page(`/auditoria/eventos?${query}`, 'audit/metadata');
|
||||
check(metadata.props.requestContext?.number === fixture.audit_request_reference, 'authorised native context locator');
|
||||
const minimalEvents = page => {
|
||||
check(page.props.events.data.length > 0, 'filtered native events present');
|
||||
check(page.props.events.data.every(e => JSON.stringify(Object.keys(e).sort()) === JSON.stringify(['action', 'created_at', 'id', 'user_id'])), 'events contain only four metadata fields');
|
||||
};
|
||||
minimalEvents(metadata);
|
||||
for (const [view, component] of [['agreements', 'supply/index'], ['contracts', 'supply/index'], ['calendar', 'supply/index'], ['imports', 'supply/index'],
|
||||
['history', 'supply/history'], ['suggestions', 'supply/suggestions'], ['reservations', 'supply/coordination'], ['deliveries', 'supply/coordination'], ['alternatives', 'supply/coordination']]) {
|
||||
const page = await reviewer.page(`/compras/fornecimento?view=${view}`, component);
|
||||
if (['imports', 'reservations', 'deliveries', 'alternatives'].includes(view)) check(page.props.canPrepare === false, `${view} read does not grant preparation`);
|
||||
}
|
||||
const operationalControls = await reviewer.page('/revisao-compras', 'purchase-controls/index');
|
||||
check(operationalControls.props.policies.length === 1 && operationalControls.props.policies[0].status === 'pending' && operationalControls.props.policies[0].enabled === false, 'existing synthetic policy remains pending and disabled in operational view');
|
||||
await reviewer.page('/ordens/cancelamentos', 'purchase-controls/orders');
|
||||
const ownControls = await requester.page('/revisao-compras', 'purchase-controls/index');
|
||||
check(ownControls.props.policies.length === 0 && ownControls.props.awards.length === 0 && ownControls.props.cancellations.length === 0, 'requester does not inherit operational policy or cancellation data');
|
||||
const ownRequest = await requester.page(`/requisicoes/${fixture.historical_decision_request}`, 'requisitions/show');
|
||||
check(ownRequest.props.canReadAuditMetadata === false, 'request ownership does not grant metadata audit');
|
||||
check((await requester.request('/auditoria/eventos')).status === 403, 'requester audit route refuses absent capability');
|
||||
const limited = await auditor.page(`/auditoria/eventos?${query}`, 'audit/metadata');
|
||||
minimalEvents(limited);
|
||||
check(limited.props.requestContext === null, 'metadata-only actor receives no private process locator');
|
||||
check((await auditor.request(`/requisicoes/${fixture.historical_decision_request}`)).status === 404, 'metadata-only actor cannot read private request');
|
||||
check((await auditor.request('/compras/fornecimento?view=agreements')).status === 403, 'metadata grant does not grant supply access');
|
||||
const csv = async actor => {
|
||||
const response = await actor.request(`/auditoria/eventos.csv?${query}`);
|
||||
check(response.status === 200 && response.headers.get('Content-Type')?.includes('text/csv'), 'native metadata CSV');
|
||||
check(response.headers.get('Cache-Control')?.includes('no-store'), 'private CSV not cacheable');
|
||||
const body = await response.text();
|
||||
check(body.includes(fixture.audit_request_reference), 'CSV preserves exact criteria');
|
||||
return body;
|
||||
};
|
||||
check(await csv(reviewer) === await csv(auditor), 'both metadata grants export the same scoped metadata without private context');
|
||||
const after = await snapshot();
|
||||
check(JSON.stringify(before) === JSON.stringify(after), 'all native table rows and columns unchanged during read window');
|
||||
await reviewer.logout();
|
||||
await auditor.logout();
|
||||
await requester.logout();
|
||||
return { checks, fortify_sessions: 3, missing_csrf_refused: true, stale_inertia_version_refused: true, supply_views: 9, purchase_control_views: 2, requester_scope_verified: true, encrypted_history_verified: true,
|
||||
budget_view_verified: true, conflict_index_verified: true, stock_views_verified: 2, equipment_view_verified: true, investment_view_verified: true, company_configuration_verified: true, metadata_scope_isolation_verified: true, readonly_tables_equal: Object.keys(before).length,
|
||||
private_asset_verified: true, private_assets_verified: assets.length, business_commands_sent: 0, browser_visual_acceptance: false };
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { createNativeInertiaClient } from './lib/native-inertia-client.mjs';
|
||||
|
||||
/** Same 100 MZN illustrative office scenario as the native Pest journey, through real HTTP sessions. */
|
||||
export async function verifyOfficePurchaseHttp(origin, fixture, readState, progress) {
|
||||
const office = fixture.office_journey;
|
||||
if (!office || fixture.synthetic_only !== true || typeof readState !== 'function') throw Error('Dedicated synthetic office HTTP fixture required');
|
||||
let checks = 0;
|
||||
let commands = 0;
|
||||
let phase = 'login';
|
||||
const check = (condition, label) => { if (!condition) throw Error(`Office HTTP verification failed [${phase}]: ${label}`); checks++; };
|
||||
const stage = name => { phase = name; progress?.({ office_http_phase: name, checks }); };
|
||||
const clients = {};
|
||||
for (const [name, actor] of Object.entries(office.actors)) {
|
||||
clients[name] = createNativeInertiaClient(origin, check);
|
||||
await clients[name].login(actor.email);
|
||||
}
|
||||
const { owner, buyer, head, finance, reviewer, warehouse, procurement_reviewer: procurementReviewer } = clients;
|
||||
const state = async () => {
|
||||
const source = await readState();
|
||||
if (source.budget !== null) {
|
||||
// The common balance contract takes a lock. Use its native authorised endpoint, never a second calculator.
|
||||
const page = await finance.page('/orcamentos', 'budgets/index');
|
||||
const budget = page.props.budgets.find(row => Number(row.id) === Number(source.budget.id));
|
||||
const fields = ['approved_total_minor', 'reinforced_minor', 'reserved_minor', 'committed_minor', 'consumed_minor', 'available_minor'];
|
||||
check(budget !== undefined && fields.every(field => Object.hasOwn(budget, field)), 'native authoritative budget balance fields');
|
||||
const after = await readState();
|
||||
check(after.financial_fingerprint === source.financial_fingerprint, 'native balance consultation has no financial effects');
|
||||
after.budget.balance = Object.fromEntries(fields.map(field => [field, budget[field]]));
|
||||
return after;
|
||||
}
|
||||
return source;
|
||||
};
|
||||
const post = async (client, route, data, expected = 302) => { commands++; return client.post(route, data, expected); };
|
||||
const date = days => new Date(Date.parse(fixture.clock) + days * 86400000).toISOString().slice(0, 10);
|
||||
const roles = { department_head: head, procurement: buyer, finance: reviewer };
|
||||
const awardRoles = { ...roles, procurement: procurementReviewer };
|
||||
let selectorRefused = false;
|
||||
let current = await state();
|
||||
check(current.request === null && current.budget === null && current.stock === null, 'dedicated purchase references are initially unused');
|
||||
|
||||
stage('budget');
|
||||
check((await owner.request('/orcamentos')).status === 403, 'requester cannot read company budget data');
|
||||
await post(finance, '/orcamentos', { cost_center_id: office.cost_center_id, year: Number(date(0).slice(0, 4)),
|
||||
kind: 'operating', includes_tax: true, amount: '1000.00', reason: 'Dotação exclusivamente sintética do percurso HTTP, sem valores reais' });
|
||||
current = await state();
|
||||
check(current.budget !== null && Number(current.budget.created_by) === office.actors.finance.id, 'native budget issuer');
|
||||
await post(finance, `/orcamentos/${current.budget.id}/aprovar`, {}, 403);
|
||||
check((await state()).budget.approved_by === null, 'budget issuer cannot approve their own allocation');
|
||||
await post(reviewer, `/orcamentos/${current.budget.id}/aprovar`, {});
|
||||
current = await state();
|
||||
check(Number(current.budget.approved_by) === office.actors.reviewer.id && Number(current.budget.balance.available_minor) === 100000, 'independent native budget approval');
|
||||
|
||||
stage('request_and_accounts');
|
||||
await post(owner, '/requisicoes', { operation_key: crypto.randomUUID(), cost_center_id: office.cost_center_id,
|
||||
priority: 'normal', needed_by: date(7), justification: 'Compra HTTP exclusivamente sintética; taxa ilustrativa zero, sem regra fiscal real',
|
||||
items: [{ description: 'Material de escritório HTTP QA', category: office.category, purchase_type: 'consumable',
|
||||
production_area: null, quantity: '1.000', unit: 'un', unit_price: '100.00', tax_rate: '0.00',
|
||||
procurement_category: 'office_equipment', category_reason: 'Aquisição de escritório exclusivamente sintética para testar o percurso HTTP' }] });
|
||||
current = await state();
|
||||
const requestId = current.request.id;
|
||||
const lineId = current.request.items[0].id;
|
||||
const accountPage = await owner.page(`/requisicoes/${requestId}/contas`, 'requisitions/accounts');
|
||||
const account = accountPage.props.accounts.data[0];
|
||||
check(account !== undefined, 'actual common movement account available');
|
||||
await post(owner, `/requisicoes/${requestId}/contas`, { operation_key: crypto.randomUUID(), version: 0, item_id: lineId,
|
||||
basis_hash: accountPage.props.items[0].basis_hash, reason: 'Imputação documental explícita na base própria do percurso HTTP QA',
|
||||
allocations: [{ account_id: account.id, source_hash: account.source_hash, subtotal: '100.00', total: '100.00' }] });
|
||||
current = await state();
|
||||
const submit = { operation_key: crypto.randomUUID(), process_version: current.request.process_version };
|
||||
await post(owner, `/requisicoes/${requestId}/submeter`, submit);
|
||||
await post(owner, `/requisicoes/${requestId}/submeter`, submit);
|
||||
current = await state();
|
||||
check(current.request.status === 'pending' && Number(current.budget.balance.reserved_minor) === 10000, 'submission replay preserves one native reserve');
|
||||
await post(owner, `/requisicoes/${requestId}/decidir`, { operation_key: crypto.randomUUID(), process_version: current.request.process_version,
|
||||
decision: 'approved', comment: 'Tentativa própria exclusivamente sintética, que deve ser recusada' }, 403);
|
||||
for (let level = 0; current.request.status === 'pending' && level < 8; level++) {
|
||||
const step = current.request.steps.find(s => s.decision === 'pending');
|
||||
check(step !== undefined && roles[step.role] !== undefined, 'frozen request level has a native eligible actor');
|
||||
await post(roles[step.role], `/requisicoes/${requestId}/decidir`, { operation_key: crypto.randomUUID(),
|
||||
process_version: current.request.process_version, decision: 'approved', comment: 'Conferência independente do pedido HTTP exclusivamente sintético' });
|
||||
current = await state();
|
||||
}
|
||||
check(current.request.status === 'approved', 'native request circuit completed');
|
||||
|
||||
stage('suppliers_and_quotes');
|
||||
for (let index = 0; index < 3; index++) {
|
||||
const nuit = String(300000001 + index);
|
||||
await post(buyer, '/fornecedores', { name: `Fornecedor HTTP QA ${index + 1}`, nuit, contact: 'Contacto sintético',
|
||||
email: `office-http-${index}@example.invalid`, phone: '123456789', address: 'Morada exclusivamente sintética',
|
||||
category: office.category, beneficiaries: 'Beneficiário exclusivamente sintético', document_references: 'Referências fictícias de ensaio',
|
||||
diligence_notes: 'Preparação de dados sintéticos sem fornecedor real', blocked: false, next_review: date(365) });
|
||||
current = await state();
|
||||
const supplier = current.suppliers.find(s => s.nuit === nuit);
|
||||
check(supplier !== undefined, 'native supplier created');
|
||||
await post(finance, `/fornecedores/${supplier.id}/validar`, { version: supplier.version, status: 'active', comment: 'Conferência financeira independente de dados exclusivamente sintéticos' });
|
||||
await post(buyer, `/requisicoes/${requestId}/cotacoes`, { currency: 'MZN', supplier_id: supplier.id,
|
||||
reference: `HTTP-OFFICE-QUOTE-${index + 1}`, delivery_days: 5, valid_until: date(30),
|
||||
payment_terms: 'Condições exclusivamente sintéticas de trinta dias', no_conflict: true,
|
||||
items: [{ requisition_item_id: lineId, unit_price: `${100 + index * 10}.00`, discount_type: 'none', discount_value: '0.00' }] });
|
||||
current = await state();
|
||||
const quote = current.quotes.find(q => q.supplier_id === supplier.id);
|
||||
check(quote !== undefined, 'native quote created');
|
||||
for (const evaluator of [head, reviewer]) await post(evaluator, `/cotacoes/${quote.id}/avaliar`, {
|
||||
quality: '5', history: '5', payment: '5', comment: 'Avaliação independente exclusivamente sintética do percurso HTTP', no_conflict: true });
|
||||
}
|
||||
current = await state();
|
||||
check(current.quotes.length === 3 && Number(current.quotes[0].total_minor) === 10000, 'three independently evaluated native quotations');
|
||||
|
||||
stage('award_and_order');
|
||||
await post(buyer, `/requisicoes/${requestId}/adjudicacao`, { quotation_id: current.quotes[0].id,
|
||||
justification: 'Escolha exclusivamente sintética da proposta com maior pontuação pelo circuito nativo',
|
||||
delivery_date: date(7), delivery_location: 'Armazém exclusivamente sintético de ensaio HTTP' });
|
||||
current = await state();
|
||||
const awardId = current.award.id;
|
||||
for (let level = 0; current.award.status !== 'approved' && level < 8; level++) {
|
||||
const step = current.award.steps.find(s => s.decision === 'pending');
|
||||
check(step !== undefined && awardRoles[step.role] !== undefined, 'final-value level has a native eligible actor');
|
||||
if (step.role === 'procurement') {
|
||||
await post(buyer, `/adjudicacoes/${awardId}/decidir`, { decision: 'approved', comment: 'Tentativa do próprio selector exclusivamente sintética, que deve ser recusada' }, 403);
|
||||
current = await state();
|
||||
check(current.award.steps.find(row => row.id === step.id)?.decision === 'pending', 'selector refusal preserves the pending independent decision');
|
||||
selectorRefused = true;
|
||||
}
|
||||
await post(awardRoles[step.role], `/adjudicacoes/${awardId}/decidir`, { decision: 'approved', comment: 'Conferência independente do valor final exclusivamente sintético HTTP' });
|
||||
current = await state();
|
||||
}
|
||||
check(current.award.status === 'approved' && selectorRefused, 'native final-value approvals completed by an independent buyer');
|
||||
await post(buyer, `/adjudicacoes/${awardId}/emitir`, {});
|
||||
current = await state();
|
||||
const orderId = current.order.id;
|
||||
const orderLineId = current.order.items[0].id;
|
||||
const issued = current.financial_fingerprint;
|
||||
await post(buyer, `/adjudicacoes/${awardId}/emitir`, {});
|
||||
current = await state();
|
||||
check(current.order.id === orderId && current.financial_fingerprint === issued, 'order replay has no financial or document effect');
|
||||
check(Number(current.order.total_minor) === 10000 && current.order.account_assignments[lineId].data.allocations[0].account.id === account.id, 'order preserves exact amount and native chart attribution');
|
||||
|
||||
stage('receipt_and_invoice');
|
||||
await post(warehouse, '/stock/artigos', { code: 'HTTP-OFFICE-QA', name: 'Material de escritório HTTP QA', unit: 'un' });
|
||||
current = await state();
|
||||
const receipt = { idempotency_key: crypto.randomUUID(), delivery_note: 'HTTP-OFFICE-DELIVERY-QA', received_on: date(0),
|
||||
warehouse_id: office.warehouse_id, items: [{ purchase_order_item_id: orderLineId, received_quantity: '1.000', accepted_quantity: '1.000',
|
||||
quality_status: 'compliant', stock_item_id: current.stock.id }] };
|
||||
await post(warehouse, `/ordens/${orderId}/recepcoes`, receipt, 201);
|
||||
current = await state();
|
||||
const received = current.financial_fingerprint;
|
||||
await post(warehouse, `/ordens/${orderId}/recepcoes`, receipt, 200);
|
||||
current = await state();
|
||||
check(current.financial_fingerprint === received && current.order.receipts.length === 1 && current.stock.movements === 1 && current.stock.quantity_milli === 1000, 'receipt replay preserves one physical movement');
|
||||
await post(finance, `/ordens/${orderId}/facturas`, { number: 'HTTP-OFFICE-INVOICE-QA', issued_on: date(0), subtotal: '100.00', tax: '0.00', total: '100.00',
|
||||
items: [{ purchase_order_item_id: orderLineId, quantity: '1.000', unit: 'un', unit_price: '100.00', tax_rate: '0.00' }] });
|
||||
current = await state();
|
||||
const invoiceId = current.invoice.id;
|
||||
await post(finance, `/facturas/${invoiceId}/validar`, {}, 403);
|
||||
current = await state();
|
||||
check(current.invoice.status === 'pending', 'invoice author cannot validate their own invoice');
|
||||
await post(reviewer, `/facturas/${invoiceId}/validar`, {});
|
||||
current = await state();
|
||||
check(current.invoice.status === 'validated' && Number(current.budget.balance.consumed_minor) === 10000
|
||||
&& Number(current.budget.balance.available_minor) === 90000, 'native invoice validation consumes the exact commitment');
|
||||
const consumedBudget = JSON.stringify(current.budget.balance);
|
||||
|
||||
stage('bank_and_partial_payment');
|
||||
const supplierId = current.quotes[0].supplier_id;
|
||||
await post(buyer, `/fornecedores/${supplierId}/dados-bancarios`, { account_key: crypto.randomUUID(), previous_id: 0,
|
||||
bank_name: 'Banco exclusivamente sintético HTTP QA', country: 'MZ', currency: 'MZN', beneficiary: 'Titular exclusivamente sintético',
|
||||
account_identifier: 'HTTP-OFFICE-ACCOUNT-QA', evidence_reference: 'Evidência bancária fictícia para o ensaio HTTP', reason: 'Preparação de conta fictícia sem operação bancária real' });
|
||||
current = await state();
|
||||
const bankId = current.bank.id;
|
||||
for (const bankReviewer of [finance, reviewer]) await post(bankReviewer, `/fornecedores/${supplierId}/dados-bancarios/${bankId}/validar`, {
|
||||
decision: 'approved', independently_verified: true, reason: 'Conferência independente de evidência exclusivamente sintética HTTP' });
|
||||
current = await state();
|
||||
check(current.bank.approved_reviews === 2, 'two independent native bank reviews');
|
||||
const payment = { supplier_bank_detail_id: bankId, amount: '40.00', paid_on: date(0), external_reference: 'HTTP-OFFICE-PARTIAL-QA',
|
||||
evidence_reference: 'Registo exclusivamente sintético de pagamento externo parcial, sem execução bancária' };
|
||||
await post(finance, `/facturas/${invoiceId}/pagamentos`, payment);
|
||||
current = await state();
|
||||
const paymentId = current.payments[0].id;
|
||||
const reviewPage = await reviewer.page(`/pagamentos?payment_id=${paymentId}`, 'payments/index');
|
||||
check(reviewPage.props.payments.data[0].canReview === true && reviewPage.props.focusPaymentId === paymentId, 'independent native payment review workspace');
|
||||
const registrationPage = await finance.page(`/pagamentos?invoice_id=${invoiceId}`, 'payments/index');
|
||||
check(registrationPage.props.focusInvoiceId === invoiceId && registrationPage.props.invoices[0].outstanding_minor === 10000, 'native payment registration workspace uses the authoritative invoice balance');
|
||||
const pending = current.financial_fingerprint;
|
||||
await post(finance, `/facturas/${invoiceId}/pagamentos`, payment);
|
||||
current = await state();
|
||||
check(current.payments.length === 1 && current.financial_fingerprint === pending, 'payment registration replay has no financial effect');
|
||||
await post(finance, `/pagamentos/${paymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Tentativa própria exclusivamente sintética que deve ser recusada' }, 403);
|
||||
check((await reviewer.request(`/pagamentos/${paymentId}/categorias`)).status === 409, 'unconfirmed payment cannot be attributed to expense categories');
|
||||
await post(reviewer, `/pagamentos/${paymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Conferência independente de evidência fictícia de pagamento parcial' });
|
||||
current = await state();
|
||||
check(current.payments[0].status === 'confirmed' && current.invoice.outstanding_minor === 6000, 'confirmed partial payment preserves the exact outstanding amount');
|
||||
const overpay = await post(finance, `/facturas/${invoiceId}/pagamentos`, { ...payment, amount: '60.01', external_reference: 'HTTP-OFFICE-OVERPAY-QA' }, 422);
|
||||
check(Object.hasOwn((await overpay.json()).errors ?? {}, 'payment'), 'overpayment is refused by the native financial rule');
|
||||
|
||||
const attribute = async (id, amount) => {
|
||||
const page = await reviewer.page(`/pagamentos/${id}/categorias`, 'payments/expense-allocation');
|
||||
const before = (await state()).financial_fingerprint;
|
||||
const data = { operation_key: crypto.randomUUID(), version: page.props.current?.version ?? 0, fingerprint: page.props.fingerprint,
|
||||
reason: 'Imputação explícita de Finanças de pagamento exclusivamente sintético HTTP', allocations: [{ category: office.category, amount }] };
|
||||
await post(reviewer, `/pagamentos/${id}/categorias`, data);
|
||||
await post(reviewer, `/pagamentos/${id}/categorias`, data);
|
||||
check((await state()).financial_fingerprint === before, 'explicit attribution and its replay never change financial or stock sources');
|
||||
};
|
||||
await attribute(paymentId, '40.00');
|
||||
|
||||
stage('settlement_and_privacy');
|
||||
await post(finance, `/facturas/${invoiceId}/pagamentos`, { ...payment, amount: '60.00', external_reference: 'HTTP-OFFICE-FINAL-QA' });
|
||||
current = await state();
|
||||
const finalPaymentId = current.payments.find(p => p.id !== paymentId).id;
|
||||
await post(reviewer, `/pagamentos/${finalPaymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Conferência independente do saldo exclusivamente sintético HTTP' });
|
||||
await attribute(finalPaymentId, '60.00');
|
||||
current = await state();
|
||||
check(current.invoice.outstanding_minor === 0 && current.payments.length === 2 && current.payments.every(p => p.status === 'confirmed'), 'two independently confirmed payments settle exactly 100 MZN');
|
||||
check(String(current.analytics.currencies[0].amount_minor) === '10000' && current.analytics.coverage.confirmed_payments === 2
|
||||
&& String(current.analytics.category_attribution.groups.data[0].amount_minor) === '10000', 'native confirmed-payment analytics and explicit category attribution agree');
|
||||
check(JSON.stringify(current.budget.balance) === consumedBudget && current.stock.quantity_milli === 1000 && current.stock.movements === 1 && current.journals === 0,
|
||||
'settlement preserves budget consumption, stock and documentary chart boundary');
|
||||
const process = await owner.request(`/requisicoes/${requestId}/processo`, { headers: { 'X-Inertia': 'true' } });
|
||||
check(process.status === 200, 'requester native process route');
|
||||
const report = await process.json();
|
||||
check(report.props.stages[7].state === 'restricted' && report.props.stages[8].state === 'restricted'
|
||||
&& !Object.hasOwn(report.props, 'invoices') && !Object.hasOwn(report.props, 'payments') && !Object.hasOwn(report.props, 'bank_snapshot'), 'requester process does not disclose financial or bank records');
|
||||
for (const client of Object.values(clients)) await client.logout();
|
||||
return { checks, native_post_requests: commands, fortify_sessions: Object.keys(clients).length,
|
||||
request_total_minor: current.request.total_minor, order_total_minor: current.order.total_minor, invoice_total_minor: current.invoice.total_minor,
|
||||
confirmed_payments_minor: current.payments.map(p => p.amount_minor), outstanding_minor: current.invoice.outstanding_minor,
|
||||
budget_consumed_minor: current.budget.balance.consumed_minor, budget_available_minor: current.budget.balance.available_minor,
|
||||
stock_quantity_milli: current.stock.quantity_milli, stock_movements: current.stock.movements, journals: current.journals,
|
||||
explicit_finance_category_total_minor: current.analytics.category_attribution.groups.data[0].amount_minor,
|
||||
all_business_mutations_via_native_http: true, assertions_use_readonly_transactions: true, budget_balance_via_native_http: true,
|
||||
selector_self_final_approval_refused: selectorRefused, synthetic_only: true,
|
||||
real_bank_or_sgf_operations: false, browser_visual_acceptance: false };
|
||||
}
|
||||
Reference in New Issue
Block a user