mirror of
https://origin.cursor.com/mrdevmx/panels.git
synced 2026-10-09 11:23:18 +00:00
Fase 2 (driver): - api/pg.ts: adaptador delgado sobre postgres.js (prepare/get/all/run, placeholders ? -> $n, withTenant con set_config para RLS), con parsers de tipo custom (numeric/date/timestamp(tz)/bigint) para que el resto del codigo heredado de SQLite (fechas/montos como string, ids como number) siga funcionando sin reescribir cada call-site a mano. - api/platform_db.ts, api/iam_db.ts (nuevo), api/db.ts: pools separados por base/esquema (panels_platform, panels_product.iam, panels_product.core), owner pool para bootstrap/scripts/lookups administrativos que cruzan tenant a proposito. - api/redis.ts: clientes iam/core separados (ACL panels_iam_redis / panels_core_redis). - api/sessions.ts + auth.ts: sesiones ahora en Redis (cookie = id opaco, no HMAC autocontenido); revocacion real (logout, cambio de password). - api/storage.ts (Fase 4c): documentos/PDFs via Contabo Object Storage (S3), con fallback a disco local si no hay credenciales S3 (dev). - api/scope.ts: middleware withCoreScope/requireCoreAuth que abre la transaccion con app.tenant_id fijado (RLS) para cada request. - api/cache.ts (Fase 4e): cache Redis con tenant_id obligatorio en la llave; aplicado a /v1/catalogs. Fase 3 (reescritura SQL, ~80 endpoints en main.ts/companies.ts/budget.ts/ payroll.ts/payroll_http.ts/excel.ts/saas.ts/smtp.ts): - Todo async/await, sintaxis Postgres (COALESCE, ~ regex, ON CONFLICT, now()/current_date, booleanos reales, RETURNING via lastInsertId()). - IDOR cross-tenant cerrado: GET/PATCH /v1/projects/:id, /v1/workers/:id ya no dependen de que el handler recuerde el WHERE tenant_id -- Row Level Security lo hace estructuralmente (verificado con un segundo tenant real: 404 en vez de fuga de datos). - API key ya no ve todos los tenants: ahora exige X-Tenant-Id explicito. Fase 3b (tests): api/test_helpers.ts corre cada test en una transaccion que siempre se revierte, contra el mismo baseline de Liquibase que produccion (ya no un esquema SQLite escrito a mano). payroll_test.ts reescrito con fixtures reales; 11/11 pasan contra Postgres. Fase 4 (IAM/RBAC): iam.roles/permissions/role_permissions formalizados (ver db/iam ya en fase 1); uploaded_by/created_by ahora son snapshot desnormalizado (uploaded_by_id/name); seed() en runtime eliminado, reemplazado por scripts/bootstrap-admin.ts (one-shot). Fase 4d (zona horaria): nuevo endpoint /v1/configuracion (GET/PUT), PAYROLL_TZ hardcodeado reemplazado por tenant_settings.timezone, document_validity.ts ya no usa new Date() crudo. Verificado end-to-end contra Postgres+Redis reales: login, sesiones, catalogos con cache, alta de trabajador, subida/descarga de documento cifrado, y el fix de IDOR probado con un segundo tenant real (403/404 en vez de fuga de datos). Co-authored-by: alberto.martinez <alberto.martinez@mrdev.mx>
73 lines
2.3 KiB
TypeScript
73 lines
2.3 KiB
TypeScript
const encoder = new TextEncoder();
|
|
const decoder = new TextDecoder();
|
|
|
|
function toHex(buf: ArrayBuffer | Uint8Array): string {
|
|
const u8 = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
|
|
return [...u8].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
}
|
|
|
|
function fromHex(hex: string): Uint8Array {
|
|
const clean = hex.replace(/^0x/, "");
|
|
const out = new Uint8Array(clean.length / 2);
|
|
for (let i = 0; i < out.length; i++) {
|
|
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export async function hashPassword(password: string): Promise<string> {
|
|
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
const key = await crypto.subtle.importKey(
|
|
"raw",
|
|
encoder.encode(password),
|
|
"PBKDF2",
|
|
false,
|
|
["deriveBits"],
|
|
);
|
|
const bits = await crypto.subtle.deriveBits(
|
|
{ name: "PBKDF2", salt: salt as BufferSource, iterations: 120_000, hash: "SHA-256" },
|
|
key,
|
|
256,
|
|
);
|
|
return `pbkdf2$${toHex(salt)}$${toHex(bits)}`;
|
|
}
|
|
|
|
/** Contraseña temporal segura (16 chars, sin ambiguos). */
|
|
export function generateSecurePassword(length = 16): string {
|
|
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@$%*?";
|
|
const bytes = crypto.getRandomValues(new Uint8Array(length));
|
|
let out = "";
|
|
for (let i = 0; i < length; i++) out += alphabet[bytes[i]! % alphabet.length];
|
|
return out;
|
|
}
|
|
|
|
export async function verifyPassword(password: string, stored: string): Promise<boolean> {
|
|
const parts = stored.split("$");
|
|
if (parts.length !== 3 || parts[0] !== "pbkdf2") return false;
|
|
const salt = fromHex(parts[1]);
|
|
const expected = fromHex(parts[2]);
|
|
const key = await crypto.subtle.importKey(
|
|
"raw",
|
|
encoder.encode(password),
|
|
"PBKDF2",
|
|
false,
|
|
["deriveBits"],
|
|
);
|
|
const bits = new Uint8Array(
|
|
await crypto.subtle.deriveBits(
|
|
{ name: "PBKDF2", salt: salt as BufferSource, iterations: 120_000, hash: "SHA-256" },
|
|
key,
|
|
256,
|
|
),
|
|
);
|
|
if (bits.length !== expected.length) return false;
|
|
let diff = 0;
|
|
for (let i = 0; i < bits.length; i++) diff |= bits[i] ^ expected[i];
|
|
return diff === 0;
|
|
}
|
|
|
|
export async function sha256Hex(data: Uint8Array): Promise<string> {
|
|
return toHex(await crypto.subtle.digest("SHA-256", data as BufferSource));
|
|
}
|
|
|
|
export { toHex, fromHex, encoder, decoder };
|