Files
NightSpire/web-next/lib/security-history.ts
T
Inna cccc70338d Quitar el prefijo home_ de las 41 tablas del portal
El prefijo venía del nombre de la app Django (`home`), jubilada y borrada hoy,
así que ya no significaba nada: home_stripelog -> stripelog. La BD se sigue
llamando django_wow por historia (renombrarla es otra operación).

Comprobado antes de tocar nada: 0 colisiones con nombres existentes, 0 palabras
reservadas (contrastado contra las 260 de MySQL), sin vistas ni triggers que
dependieran de ellas. El RENAME va en una sola sentencia porque así es atómico,
y MySQL reapunta solo las 4 claves ajenas entre estas tablas.

170 referencias actualizadas en 37 ficheros. Se dejó a propósito
sql/drop_home_securitytoken_authuser_fk.sql sin tocar: es una migración ya
aplicada y reescribirla sería falsear el historial.

De paso salió un fallo previo: prices.ts consultaba `home_restoreitemprice`,
una tabla que NO existe. El try/catch de priceFrom se comía el error y devolvía
siempre el precio por defecto, así que el precio de restaurar objetos nunca fue
configurable. Se deja documentado en el código; crear la tabla es otra decisión.

Verificado tras aplicar: 0 tablas home_, las 51 siguen ahí, y el conteo exacto
de filas cuadra con el volcado previo (store_item 3068, item_data 44873,
stripelog 35, store_order 26, noticia 50). La web responde 200 en todas las
rutas y la portada carga las noticias sin errores.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 14:49:19 +00:00

107 lines
3.8 KiB
TypeScript

import type { RowDataPacket } from 'mysql2'
import { db, DB } from './db'
export interface ActivityEntry {
user: string
actionKey: string // clave de acción traducible (p.ej. 'tokenRequested')
ip: string
date: Date
}
export interface RealmConnection {
ip: string
date: Date
}
export interface WebConnection {
user: string
statusKey: 'success' | 'wrongPassword' | 'other'
statusRaw: string // texto original (para el caso 'other')
ip: string
date: Date
}
/** Clasifica el estado guardado del intento de login web en una clave traducible. */
function webStatusKey(raw: string): 'success' | 'wrongPassword' | 'other' {
const s = (raw || '').toLowerCase()
if (s.includes('exito') || s.includes('éxito') || s.includes('success')) return 'success'
if (s.includes('fracaso') || s.includes('fail') || s.includes('incorrect')) return 'wrongPassword'
return 'other'
}
/**
* Historial de seguridad de una cuenta, en tres bloques:
* - **Actividad**: acciones de seguridad (solicitudes de token) desde `securitytoken`.
* - **Conexiones (Reino)**: `acore_auth.logs_ip_actions` (histórico de IP) + la última
* conexión conocida (`account.last_ip`/`last_login`) si aporta una IP nueva.
* - **Conexiones (Web)**: cada intento de login web desde `loginattempt`.
* Cada consulta es tolerante a fallos (devuelve [] si la tabla no existe).
*/
export async function getSecurityHistory(
accountId: number,
displayUser: string,
email: string,
limit = 100,
): Promise<{ activity: ActivityEntry[]; realm: RealmConnection[]; web: WebConnection[] }> {
const activity: ActivityEntry[] = []
const realm: RealmConnection[] = []
const web: WebConnection[] = []
if (!accountId) return { activity, realm, web }
// 1) Actividad: solicitudes de token de seguridad.
try {
const [rows] = await db(DB.default).query<RowDataPacket[]>(
'SELECT created_at, ip_address FROM securitytoken WHERE user_id = ? ORDER BY created_at DESC LIMIT ?',
[accountId, limit],
)
for (const r of rows) {
activity.push({ user: displayUser, actionKey: 'tokenRequested', ip: String(r.ip_address || '—'), date: new Date(r.created_at) })
}
} catch {
/* tabla ausente */
}
// 2) Conexiones al reino: histórico de IP + última conexión conocida.
try {
const [rows] = await db(DB.auth).query<RowDataPacket[]>(
'SELECT ip, unixtime FROM logs_ip_actions WHERE account_id = ? ORDER BY unixtime DESC LIMIT ?',
[accountId, limit],
)
for (const r of rows) realm.push({ ip: String(r.ip), date: new Date(Number(r.unixtime) * 1000) })
} catch {
/* tabla ausente */
}
try {
const [acc] = await db(DB.auth).query<RowDataPacket[]>(
'SELECT last_ip, last_login FROM account WHERE id = ? LIMIT 1',
[accountId],
)
const a = acc[0]
if (a && a.last_ip && a.last_login) {
// Añade la última conexión si no coincide con la IP más reciente ya listada.
if (realm.length === 0 || realm[0].ip !== String(a.last_ip)) {
realm.unshift({ ip: String(a.last_ip), date: new Date(a.last_login) })
}
}
} catch {
/* tabla ausente */
}
realm.sort((x, y) => y.date.getTime() - x.date.getTime())
// 3) Conexiones web: intentos de login (por email de la cuenta).
if (email) {
try {
const [rows] = await db(DB.default).query<RowDataPacket[]>(
'SELECT username, status, ip_address, timestamp FROM loginattempt WHERE username = ? ORDER BY timestamp DESC LIMIT ?',
[email, limit],
)
for (const r of rows) {
const raw = String(r.status || '')
web.push({ user: displayUser, statusKey: webStatusKey(raw), statusRaw: raw, ip: String(r.ip_address || '—'), date: new Date(r.timestamp) })
}
} catch {
/* tabla ausente */
}
}
return { activity, realm, web }
}