diff --git a/backend/src/db/migrate.js b/backend/src/db/migrate.js new file mode 100644 index 0000000..af45618 --- /dev/null +++ b/backend/src/db/migrate.js @@ -0,0 +1,68 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { config } from '../config.js'; +import { hashPassword } from '../services/passwords.js'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_DIR = path.join(__dirname, 'migrations'); + +// Advisory lock: si algún día corren varias réplicas del API, solo una +// aplica migraciones; las demás esperan y ven todo ya aplicado. +const MIGRATION_LOCK_KEY = 74220251; + +export async function runMigrations(db, log) { + const client = await db.getClient(); + try { + await client.query('SELECT pg_advisory_lock($1)', [MIGRATION_LOCK_KEY]); + + await client.query(` + CREATE TABLE IF NOT EXISTS schema_migrations ( + filename TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + `); + + const { rows } = await client.query('SELECT filename FROM schema_migrations'); + const applied = new Set(rows.map((r) => r.filename)); + + const files = fs + .readdirSync(MIGRATIONS_DIR) + .filter((f) => f.endsWith('.sql')) + .sort(); + + for (const file of files) { + if (applied.has(file)) continue; + const sql = fs.readFileSync(path.join(MIGRATIONS_DIR, file), 'utf8'); + await client.query('BEGIN'); + try { + await client.query(sql); + await client.query('INSERT INTO schema_migrations (filename) VALUES ($1)', [file]); + await client.query('COMMIT'); + log.info({ file }, 'Migración aplicada'); + } catch (err) { + await client.query('ROLLBACK'); + log.error({ file, err: err.message }, 'Migración falló — rollback'); + throw err; + } + } + } finally { + await client.query('SELECT pg_advisory_unlock($1)', [MIGRATION_LOCK_KEY]); + client.release(); + } +} + +export async function seedSupervisora(db, log) { + const { usuario, passwordInicial } = config.supervisora; + const { rows } = await db.query('SELECT 1 FROM supervisoras WHERE usuario = $1', [usuario]); + if (rows.length > 0) { + log.info({ usuario }, 'Supervisora ya existe — seed omitido'); + return; + } + const passwordHash = await hashPassword(passwordInicial); + await db.query('INSERT INTO supervisoras (usuario, password_hash) VALUES ($1, $2)', [ + usuario, + passwordHash, + ]); + log.info({ usuario }, 'Supervisora creada desde SUPERVISORA_USER / SUPERVISORA_PASSWORD_INICIAL'); +} diff --git a/backend/src/db/migrations/001_initial.sql b/backend/src/db/migrations/001_initial.sql new file mode 100644 index 0000000..8b5a64d --- /dev/null +++ b/backend/src/db/migrations/001_initial.sql @@ -0,0 +1,149 @@ +-- ═══════════════════════════════════════════════════════════ +-- Taboada Becarios — Schema inicial +-- Timestamps en UTC (TIMESTAMPTZ); presentación en America/Mexico_City +-- la hace el backend, nunca la DB ni el frontend. +-- ═══════════════════════════════════════════════════════════ + +-- Para UUIDs nativos sin extensión extra +CREATE EXTENSION IF NOT EXISTS "pgcrypto"; + +-- ══════════════ SUPERVISORAS ══════════════ +-- Una sola cuenta hoy (seed desde env); la tabla permite más en el futuro. +CREATE TABLE supervisoras ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + usuario TEXT NOT NULL UNIQUE, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +-- ══════════════ BECARIOS ══════════════ +CREATE TABLE becarios ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + nombre TEXT NOT NULL, + matricula TEXT, + institucion TEXT, + meta_horas INTEGER NOT NULL DEFAULT 480 CHECK (meta_horas > 0), + estado TEXT NOT NULL DEFAULT 'activo' CHECK (estado IN ('activo', 'baja')), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_becarios_activos ON becarios(estado) WHERE estado = 'activo'; + +-- ══════════════ DISPOSITIVOS ══════════════ +-- Identidad del becario = vínculo de dispositivo (§3). Se guarda el hash +-- del token del dispositivo, nunca el token en claro. +CREATE TABLE dispositivos ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + becario_id UUID NOT NULL REFERENCES becarios(id), + token_hash TEXT NOT NULL UNIQUE, + user_agent TEXT, + estado TEXT NOT NULL DEFAULT 'pendiente' + CHECK (estado IN ('pendiente', 'aprobado', 'revocado')), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_dispositivos_becario ON dispositivos(becario_id); +-- Regla §10.5: un solo dispositivo aprobado por becario +CREATE UNIQUE INDEX uq_dispositivo_aprobado_por_becario + ON dispositivos(becario_id) WHERE estado = 'aprobado'; + +-- ══════════════ CHECADAS — INMUTABLE ══════════════ +-- Registro crudo de cada escaneo válido. Nunca se actualiza ni se borra +-- (trigger al final del archivo); las correcciones viven en jornadas/ajustes. +CREATE TABLE checadas ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + becario_id UUID NOT NULL REFERENCES becarios(id), + tipo TEXT NOT NULL CHECK (tipo IN ('entrada', 'salida')), + ts TIMESTAMPTZ NOT NULL DEFAULT NOW(), + origen TEXT NOT NULL CHECK (origen IN ('nfc', 'qr', 'manual')), + meta JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_checadas_becario_ts ON checadas(becario_id, ts); + +-- ══════════════ JORNADAS ══════════════ +-- Materializadas a partir de checadas (entrada + salida). La supervisora +-- puede editar tiempos (editada = TRUE, respaldo en bitácora). +CREATE TABLE jornadas ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + becario_id UUID NOT NULL REFERENCES becarios(id), + entrada_ts TIMESTAMPTZ NOT NULL, + salida_ts TIMESTAMPTZ, + checada_entrada_id UUID NOT NULL REFERENCES checadas(id), + checada_salida_id UUID REFERENCES checadas(id), + estado TEXT NOT NULL DEFAULT 'abierta' + CHECK (estado IN ('abierta', 'cerrada', 'revision')), + editada BOOLEAN NOT NULL DEFAULT FALSE, + CHECK (salida_ts IS NULL OR salida_ts >= entrada_ts) +); + +CREATE INDEX idx_jornadas_becario ON jornadas(becario_id); +CREATE INDEX idx_jornadas_no_cerradas ON jornadas(estado) WHERE estado <> 'cerrada'; +-- Regla §4 (toggle): máximo una jornada abierta por becario +CREATE UNIQUE INDEX uq_jornada_abierta_por_becario + ON jornadas(becario_id) WHERE estado = 'abierta'; + +-- ══════════════ AJUSTES ══════════════ +-- Suma/resta de minutos con motivo obligatorio (§4). Solo supervisora. +CREATE TABLE ajustes ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + becario_id UUID NOT NULL REFERENCES becarios(id), + minutos INTEGER NOT NULL CHECK (minutos <> 0), + motivo TEXT NOT NULL CHECK (length(trim(motivo)) > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_ajustes_becario ON ajustes(becario_id); + +-- ══════════════ BITÁCORA — INMUTABLE ══════════════ +-- Toda mutación administrativa y todo rechazo de token quedan aquí (§10). +CREATE TABLE bitacora ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + actor TEXT NOT NULL, + accion TEXT NOT NULL, + entidad TEXT NOT NULL, + entidad_id UUID, + antes JSONB, + despues JSONB, + ts TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_bitacora_entidad ON bitacora(entidad, entidad_id); +CREATE INDEX idx_bitacora_ts ON bitacora(ts); + +-- ══════════════ TOKENS_CHECADA ══════════════ +-- Token de un solo uso generado por el servidor en cada escaneo (§2). +-- becario_id y checada_id se llenan al consumirlo. +CREATE TABLE tokens_checada ( + token TEXT PRIMARY KEY, + origen TEXT NOT NULL CHECK (origen IN ('nfc', 'qr')), + expira_ts TIMESTAMPTZ NOT NULL, + usado_ts TIMESTAMPTZ, + becario_id UUID REFERENCES becarios(id), + checada_id UUID REFERENCES checadas(id), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_tokens_expira ON tokens_checada(expira_ts); + +-- ══════════════ TRIGGERS DE INMUTABILIDAD ══════════════ +-- Regla §10.2: checadas y bitácora son append-only a nivel DB, no solo +-- por convención del backend. +CREATE OR REPLACE FUNCTION prohibir_mutacion() +RETURNS TRIGGER AS $$ +BEGIN + RAISE EXCEPTION 'La tabla % es inmutable (append-only): % no permitido', + TG_TABLE_NAME, TG_OP; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_checadas_inmutable + BEFORE UPDATE OR DELETE ON checadas + FOR EACH ROW + EXECUTE FUNCTION prohibir_mutacion(); + +CREATE TRIGGER trg_bitacora_inmutable + BEFORE UPDATE OR DELETE ON bitacora + FOR EACH ROW + EXECUTE FUNCTION prohibir_mutacion(); diff --git a/backend/src/index.js b/backend/src/index.js index d85a640..2154108 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -2,6 +2,7 @@ import Fastify from 'fastify'; import cors from '@fastify/cors'; import { config } from './config.js'; import { db } from './db/client.js'; +import { runMigrations, seedSupervisora } from './db/migrate.js'; const fastify = Fastify({ logger: { @@ -57,6 +58,9 @@ if (!dbOk) { } fastify.log.info('DB connection OK'); +await runMigrations(db, fastify.log); +await seedSupervisora(db, fastify.log); + fastify.decorate('db', db); try { diff --git a/backend/src/services/passwords.js b/backend/src/services/passwords.js new file mode 100644 index 0000000..260855d --- /dev/null +++ b/backend/src/services/passwords.js @@ -0,0 +1,16 @@ +import argon2 from 'argon2'; + +// argon2id según §6. El paquete argon2 trae prebuilds musl (armv8/x64), +// así que no necesita toolchain de compilación en Alpine. + +export function hashPassword(plain) { + return argon2.hash(plain, { type: argon2.argon2id }); +} + +export async function verifyPassword(hash, plain) { + try { + return await argon2.verify(hash, plain); + } catch { + return false; + } +}