Compare commits

...
Author SHA1 Message Date
admin 4c01cf6ffe fix: alinear health con API 0.21.0-2 2026-09-05 22:27:29 -03:00
admin 66333fb5dd ops: blindar reset preservando configuración estructural 2026-09-05 22:17:45 -03:00
admin 06f809b4c8 ops: versionar API 0.21.0-2 para reset limpio 2026-09-05 22:15:10 -03:00
admin 343c889250 ops: preparar reset limpio de datos operativos 2026-09-05 22:12:18 -03:00
admin 1b57dcc850 maintenance: retirar diagnóstico Android temporal 2026-09-05 20:12:53 -03:00
admin 77d750992d maintenance: localizar fuente Android en VPS
Diagnóstico temporal de solo lectura para localizar fuentes/artefactos Android en el VPS y publicar el resultado en deploy-status.
2026-09-05 20:11:19 -03:00
admin b30cc1a294 maintenance: corregir diagnóstico Android de solo lectura 2026-09-05 20:07:58 -03:00
admin a7a6680cf8 maintenance: descubrir fuente Android en VPS sin modificar datos 2026-09-05 20:07:40 -03:00
admin 44570ad457 maintenance: retirar fresh-start temporal
Restaura migration:run y deploy-github estándar y elimina la herramienta fresh-start luego de la limpieza exitosa.
2026-09-05 20:04:46 -03:00
admin 8caed06362 maintenance: retirar herramienta destructiva temporal 2026-09-05 20:01:48 -03:00
admin e3db3d6cd7 maintenance: restaurar deploy estándar tras fresh-start 2026-09-05 20:01:37 -03:00
admin fb7b29cd94 maintenance: retirar hook de fresh-start 2026-09-05 20:01:08 -03:00
admin 0a11a452b5 maintenance: ejecutar fresh-start definitivo
Fresh-start único: backup integral de DB/source/media, limpieza de datos operativos y usuarios no-admin, reset de configuración editable, vaciado de archivos y verificación final.
2026-09-05 19:57:49 -03:00
admin 1d661e2e48 maintenance: respaldar y vaciar volumen de archivos en fresh-start 2026-09-05 19:54:48 -03:00
admin 2ee956665f maintenance: armar ejecución definitiva del fresh-start 2026-09-05 19:54:11 -03:00
admin 0d5db42c77 maintenance: cerrar whitelist del fresh-start
Ajusta el preview para limpiar también Departamentos importados, conservar sólo estructura sembrada y reiniciar configuración institucional editable. Reactiva FK antes de eliminar usuarios.
2026-09-05 19:50:46 -03:00
admin 21127b8cff maintenance: limpiar departamentos importados y resetear configuración editable 2026-09-05 19:47:42 -03:00
admin 50a9dc5183 maintenance: preservar configuración estructural y reforzar FK 2026-09-05 19:46:35 -03:00
admin a69df1d2d6 maintenance: preview seguro de limpieza integral
Agrega un fresh-start protegido y ejecuta únicamente el modo preview durante el paso de migraciones para inventariar la base real antes de borrar datos.
2026-09-05 19:41:46 -03:00
4 changed files with 176 additions and 251 deletions
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "dhv2-api",
"version": "0.21.0-1",
"version": "0.21.0-2",
"private": true,
"license": "UNLICENSED",
"scripts": {
@@ -9,11 +9,10 @@
"start:dev": "nest start --watch",
"typecheck": "tsc --noEmit",
"test": "tsc -p tsconfig.test.json --noEmit && node --import tsx --test test/**/*.test.ts",
"migration:run": "node dist/database/migration-cli.js run && node dist/cli/fresh-start-reset.js --preview",
"migration:run": "node dist/database/migration-cli.js run",
"migration:show": "node dist/database/migration-cli.js show",
"migration:revert": "node dist/database/migration-cli.js revert",
"bootstrap:admin": "node dist/cli/bootstrap-admin.js",
"maintenance:fresh-start": "node dist/cli/fresh-start-reset.js",
"dev:seed:mendoza-demo": "node dist/cli/dev-seed-mendoza-demo.js"
},
"dependencies": {
-247
View File
@@ -1,247 +0,0 @@
import 'reflect-metadata';
import { promises as fs } from 'node:fs';
import { migrationDataSource } from '../database/data-source';
const APPLY_TOKEN = 'DHV2-FRESH-START-20260905';
const PRESERVED_TABLES = new Set([
'typeorm_migrations',
'spatial_ref_sys',
'users',
'user_roles',
'roles',
'role_permissions',
'permissions',
'asset_types',
'asset_type_parent_rules',
'asset_attribute_definitions',
'finding_categories',
'finding_catalog_items',
'finding_catalog_item_asset_types',
'finding_catalog_asset_type_profiles',
]);
type AdminRow = {
id: string;
username: string;
email: string | null;
status: string;
};
type TableRow = { table_name: string };
type CountRow = { count: string | number };
function quoteIdentifier(value: string): string {
return `"${value.replaceAll('"', '""')}"`;
}
function requestedMode(): 'preview' | 'apply' {
const args = process.argv.slice(2);
if (args.length === 1 && args[0] === '--preview') return 'preview';
if (args.length === 2 && args[0] === '--apply' && args[1] === APPLY_TOKEN) {
return 'apply';
}
throw new Error(
`Uso inválido. Permitido: --preview o --apply ${APPLY_TOKEN}`,
);
}
async function rowCount(table: string): Promise<number> {
const result = (await migrationDataSource.query(
`SELECT COUNT(*)::bigint AS count FROM public.${quoteIdentifier(table)}`,
)) as CountRow[];
return Number(result[0]?.count ?? 0);
}
async function clearMediaStorage(): Promise<void> {
const root = process.env.ASSET_MEDIA_ROOT;
if (!root) {
process.stdout.write('MEDIA: ASSET_MEDIA_ROOT no configurado; no se tocaron archivos.\n');
return;
}
try {
const entries = await fs.readdir(root, { withFileTypes: true });
for (const entry of entries) {
await fs.rm(`${root}/${entry.name}`, { recursive: true, force: true });
}
await fs.mkdir(`${root}/imports`, { recursive: true });
process.stdout.write(`MEDIA: almacenamiento limpiado en ${root}\n`);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
process.stdout.write(`MEDIA WARNING: no se pudo limpiar completamente ${root}: ${message}\n`);
}
}
async function main(): Promise<void> {
const mode = requestedMode();
await migrationDataSource.initialize();
try {
await migrationDataSource.query(
`SELECT pg_advisory_lock(hashtext('dhv2-fresh-start-reset'))`,
);
const admins = (await migrationDataSource.query(`
SELECT DISTINCT user_row.id, user_row.username, user_row.email, user_row.status
FROM users user_row
INNER JOIN user_roles user_role ON user_role.user_id = user_row.id
INNER JOIN roles role ON role.id = user_role.role_id
WHERE role.code = 'admin'
ORDER BY user_row.username
`)) as AdminRow[];
if (admins.length !== 1) {
throw new Error(
`Se esperaba exactamente 1 usuario con rol admin y se encontraron ${admins.length}. Limpieza abortada.`,
);
}
const admin = admins[0];
const tables = (await migrationDataSource.query(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
ORDER BY table_name
`)) as TableRow[];
const existingTables = tables.map((row) => row.table_name);
const tablesToClear = existingTables.filter(
(table) => !PRESERVED_TABLES.has(table),
);
const tablesToPreserve = existingTables.filter((table) =>
PRESERVED_TABLES.has(table),
);
process.stdout.write('\n============================================================\n');
process.stdout.write(` DH V2 · FRESH START · ${mode.toUpperCase()}\n`);
process.stdout.write('============================================================\n');
process.stdout.write(
`ADMIN PRESERVADO: ${admin.username} · ${admin.email ?? 'sin email'} · ${admin.id}\n`,
);
process.stdout.write('\n========== TABLAS ESTRUCTURALES CONSERVADAS ==========\n');
for (const table of tablesToPreserve) {
process.stdout.write(`KEEP ${table.padEnd(46)} ${await rowCount(table)}\n`);
}
process.stdout.write('\n========== DATOS A ELIMINAR ==========\n');
let rowsToDelete = 0;
for (const table of tablesToClear) {
const count = await rowCount(table);
rowsToDelete += count;
process.stdout.write(`CLEAR ${table.padEnd(46)} ${count}\n`);
}
const userCount = await rowCount('users');
const nonAdminUsers = Math.max(0, userCount - 1);
process.stdout.write(`CLEAR ${'users (excepto admin)'.padEnd(46)} ${nonAdminUsers}\n`);
rowsToDelete += nonAdminUsers;
process.stdout.write(`TOTAL FILAS OPERATIVAS/USUARIOS A RETIRAR: ${rowsToDelete}\n`);
if (mode === 'preview') {
process.stdout.write('\nPREVIEW_OK: no se modificó ningún dato.\n');
return;
}
await migrationDataSource.transaction(async (manager) => {
await manager.query(`SET LOCAL session_replication_role = replica`);
for (const table of tablesToClear) {
await manager.query(`DELETE FROM public.${quoteIdentifier(table)}`);
}
await manager.query(
`DELETE FROM user_roles WHERE user_id <> $1::uuid`,
[admin.id],
);
await manager.query(
`
DELETE FROM user_roles user_role
USING roles role
WHERE user_role.user_id = $1::uuid
AND role.id = user_role.role_id
AND role.code <> 'admin'
`,
[admin.id],
);
await manager.query(`DELETE FROM users WHERE id <> $1::uuid`, [admin.id]);
await manager.query(
`
UPDATE users
SET status = 'ACTIVE',
failed_login_attempts = 0,
locked_until = NULL,
created_by = CASE WHEN created_by = $1::uuid THEN created_by ELSE NULL END,
updated_by = $1::uuid,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1::uuid
`,
[admin.id],
);
await manager.query(
`
UPDATE user_roles user_role
SET assigned_by = $1::uuid
FROM roles role
WHERE user_role.user_id = $1::uuid
AND role.id = user_role.role_id
AND role.code = 'admin'
`,
[admin.id],
);
});
const usersAfter = await rowCount('users');
if (usersAfter !== 1) {
throw new Error(`Verificación falló: users=${usersAfter}, esperado=1`);
}
const adminAfter = (await migrationDataSource.query(
`
SELECT COUNT(DISTINCT user_row.id)::integer AS count
FROM users user_row
INNER JOIN user_roles user_role ON user_role.user_id = user_row.id
INNER JOIN roles role ON role.id = user_role.role_id
WHERE role.code = 'admin'
`,
)) as CountRow[];
if (Number(adminAfter[0]?.count ?? 0) !== 1) {
throw new Error('Verificación falló: el administrador no quedó correctamente asignado');
}
for (const table of tablesToClear) {
const count = await rowCount(table);
if (count !== 0) {
throw new Error(`Verificación falló: ${table} conserva ${count} fila(s)`);
}
}
await clearMediaStorage();
process.stdout.write('\n========== VERIFICACIÓN FRESH START ==========\n');
process.stdout.write(`Usuarios: 1 (${admin.username})\n`);
process.stdout.write('Datos operativos/importados: 0\n');
process.stdout.write('Roles/permisos/tipos/catálogos estructurales: conservados\n');
process.stdout.write('FRESH_START_OK\n');
} finally {
if (migrationDataSource.isInitialized) {
try {
await migrationDataSource.query(
`SELECT pg_advisory_unlock(hashtext('dhv2-fresh-start-reset'))`,
);
} catch {
// La conexión se destruirá de todas formas.
}
await migrationDataSource.destroy();
}
}
}
main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`FRESH_START_ERROR: ${message}\n`);
process.exitCode = 1;
});
@@ -0,0 +1,173 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
/**
* One-time production reset requested before the first clean Android rollout.
*
* Keeps only structural product configuration plus the single `admin` account.
* Operational/business data is removed. Recovery is intentionally performed
* from the deploy PRE backup, not through a synthetic down migration.
*/
export class ResetProductionOperationalData1788652800000 implements MigrationInterface {
name = 'ResetProductionOperationalData1788652800000';
public async up(queryRunner: QueryRunner): Promise<void> {
const adminRows: Array<{ id: string; username: string }> = await queryRunner.query(`
SELECT id, username
FROM users
WHERE lower(trim(username)) = 'admin'
ORDER BY id
`);
if (adminRows.length !== 1) {
throw new Error(
`Production reset aborted: expected exactly one username admin, found ${adminRows.length}`,
);
}
const adminId = adminRows[0].id;
const structuralTables = [
'roles',
'permissions',
'role_permissions',
'asset_types',
'asset_attribute_definitions',
'asset_type_parent_rules',
'finding_categories',
'finding_catalog_items',
'finding_catalog_item_asset_types',
'finding_catalog_asset_type_profiles',
];
// Snapshot structural row counts so TRUNCATE ... CASCADE can never silently
// remove product configuration while still leaving operational tables empty.
const structuralCounts = new Map<string, string>();
for (const table of structuralTables) {
const safeTable = `"${table.replace(/"/g, '""')}"`;
const rows: Array<{ total: string }> = await queryRunner.query(
`SELECT count(*)::text AS total FROM ${safeTable}`,
);
structuralCounts.set(table, rows[0]?.total ?? '0');
}
const adminRolesBefore: Array<{ total: string }> = await queryRunner.query(
`SELECT count(*)::text AS total FROM user_roles WHERE user_id = $1`,
[adminId],
);
const adminRoleCount = adminRolesBefore[0]?.total ?? '0';
if (adminRoleCount === '0') {
throw new Error('Production reset aborted: admin has no assigned role');
}
// Product configuration that must survive a clean operational start.
const preservedTables = new Set([
'typeorm_migrations',
'users',
'user_roles',
...structuralTables,
]);
const tableRows: Array<{ table_name: string }> = await queryRunner.query(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
ORDER BY table_name
`);
const operationalTables = tableRows
.map((row) => row.table_name)
.filter((table) => !preservedTables.has(table));
if (operationalTables.length > 0) {
const quoted = operationalTables
.map((table) => `"${table.replace(/"/g, '""')}"`)
.join(', ');
await queryRunner.query(`TRUNCATE TABLE ${quoted} RESTART IDENTITY CASCADE`);
}
// Remove every user except the explicitly validated administrator.
// user_roles for removed users follow their FK cascade.
await queryRunner.query(`DELETE FROM users WHERE id <> $1`, [adminId]);
// A reset must invalidate every prior login token, including admin's.
// auth_sessions is operational and was truncated above; admin simply logs in again.
await queryRunner.query(
`
UPDATE users
SET failed_login_attempts = 0,
locked_until = NULL,
last_login_at = NULL,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1
`,
[adminId],
);
const finalUsers: Array<{ total: string; admins: string }> = await queryRunner.query(`
SELECT
count(*)::text AS total,
count(*) FILTER (WHERE lower(trim(username)) = 'admin')::text AS admins
FROM users
`);
if (finalUsers[0]?.total !== '1' || finalUsers[0]?.admins !== '1') {
throw new Error('Production reset verification failed: users table is not admin-only');
}
const finalAdminRoles: Array<{ total: string; foreign_users: string }> = await queryRunner.query(
`
SELECT
count(*) FILTER (WHERE user_id = $1)::text AS total,
count(*) FILTER (WHERE user_id <> $1)::text AS foreign_users
FROM user_roles
`,
[adminId],
);
if (
finalAdminRoles[0]?.total !== adminRoleCount ||
finalAdminRoles[0]?.foreign_users !== '0'
) {
throw new Error('Production reset verification failed: admin role assignments changed');
}
// Assert every structural table kept exactly the same number of rows.
for (const table of structuralTables) {
const safeTable = `"${table.replace(/"/g, '""')}"`;
const rows: Array<{ total: string }> = await queryRunner.query(
`SELECT count(*)::text AS total FROM ${safeTable}`,
);
const before = structuralCounts.get(table) ?? '0';
if (rows[0]?.total !== before) {
throw new Error(
`Production reset verification failed: structural table ${table} changed (${before} -> ${rows[0]?.total ?? 'unknown'})`,
);
}
}
// Assert that every operational table is empty. This makes the migration
// fail atomically if a table was repopulated during the reset transaction.
for (const table of operationalTables) {
const safeTable = `"${table.replace(/"/g, '""')}"`;
const rows: Array<{ total: string }> = await queryRunner.query(
`SELECT count(*)::text AS total FROM ${safeTable}`,
);
if (rows[0]?.total !== '0') {
throw new Error(`Production reset verification failed: ${table} is not empty`);
}
}
// Keep a concise server-side record in the migration log for deploy diagnostics.
// eslint-disable-next-line no-console
console.log(
`[production-reset] kept admin=${adminRows[0].username} (${adminId}); preserved ${structuralTables.length} structural tables; cleared ${operationalTables.length} operational tables`,
);
}
public async down(): Promise<void> {
throw new Error(
'ResetProductionOperationalData is irreversible by migration; restore the deploy PRE database backup instead.',
);
}
}
+1 -1
View File
@@ -1,2 +1,2 @@
export const API_VERSION = '0.21.0-1';
export const API_VERSION = '0.21.0-2';
export const API_PHASE = 'F2.1';