fix: 2026-06-09 full-codebase audit hardening
Validation: shared NaN-guarded Zod coercion helpers in schemas/common.ts replace the raw number|string transform idiom across every schema (the root-cause NaN bug class); emailOrEmpty + lenient isoDateString/timeString. Security: roles privilege-escalation closed; refresh-token family revocation on reuse; TOTP uses config params; read endpoints permission-guarded; received-invoices gross VAT on all paths; orders-pdf custom-items authz. Concurrency: $queryRaw SELECT...FOR UPDATE locks in ascending-id order (warehouse confirm/cancel, attendance lockUserRow); uniqueness checks moved into create transactions (TOCTOU -> 409); deterministic id tiebreak on second-precision timestamp ordering (plan resolveCell/resolveGrid, warehouse FIFO). Frontend: Rules-of-Hooks fixed across ~14 pages + PlanCellModal; UTC-date persisted fields; dashboard invalidation gaps; stale-closure confirm bugs. Tooling/tests: ESLint flat config (react-hooks/rules-of-hooks = error) + Prettier; tsconfig.test.json so tsc -b type-checks the tests; removed 3 dead deps; npm audit fix (8 -> 3). Suite 195 -> 247 (happy-path auth, FIFO oldest-first, flakiness fixes), isolated on app_test via .env.test with a hard-throw setup guard. Gates: tsc 0 | build 0 | vitest 247/247 | eslint 0 errors. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -45,7 +45,15 @@ export function getHolidays(year: number): string[] {
|
||||
`${y}-12-26`, // St. Stephen's Day
|
||||
];
|
||||
|
||||
// Easter-based
|
||||
// Easter-based.
|
||||
// TZ NOTE (audit finding addressed): `new Date("YYYY-MM-DD")` parses as UTC
|
||||
// midnight, but the ±2/±1 day shifts below mutate via the LOCAL-time setters
|
||||
// (setDate/getDate) and `localDateStr` reads back in local time. This is only
|
||||
// correct because the app forces `process.env.TZ = "Europe/Prague"` (a
|
||||
// positive UTC offset) in src/config/env.ts — UTC-midnight resolves to the
|
||||
// same local calendar day, so Good Friday/Easter Monday land on the right
|
||||
// dates. Under a NEGATIVE-offset timezone this would read one day early. Safe
|
||||
// given the forced Prague TZ; do not "fix" by mixing UTC and local accessors.
|
||||
const easterSunday = getEasterSunday(year);
|
||||
const easterDate = new Date(easterSunday);
|
||||
const goodFriday = new Date(easterDate);
|
||||
|
||||
@@ -5,8 +5,8 @@ const ALGORITHM = "aes-256-gcm";
|
||||
const IV_LENGTH = 12;
|
||||
const TAG_LENGTH = 16;
|
||||
|
||||
export function encrypt(plaintext: string): string {
|
||||
const key = Buffer.from(config.totp.encryptionKey, "hex");
|
||||
export function encryptWithKey(plaintext: string, keyHex: string): string {
|
||||
const key = Buffer.from(keyHex, "hex");
|
||||
const iv = crypto.randomBytes(IV_LENGTH);
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
|
||||
|
||||
@@ -20,8 +20,26 @@ export function encrypt(plaintext: string): string {
|
||||
return Buffer.concat([iv, encrypted, tag]).toString("base64");
|
||||
}
|
||||
|
||||
export function decrypt(ciphertext: string): string {
|
||||
const key = Buffer.from(config.totp.encryptionKey, "hex");
|
||||
export function encrypt(plaintext: string): string {
|
||||
return encryptWithKey(plaintext, config.totp.encryptionKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a ciphertext using an explicit 32-byte (hex-encoded) key.
|
||||
*
|
||||
* Format detection note (audit finding addressed):
|
||||
* The format is inferred from `split(":").length === 3` — the TS wire format is
|
||||
* `hex(iv):hex(ciphertext):hex(tag)`, while the PHP-legacy wire format is a
|
||||
* single base64 blob of `nonce + ciphertext + tag` (no colons). This heuristic
|
||||
* is intentionally left UNCHANGED: altering it (e.g. adding a version prefix)
|
||||
* would change the on-the-wire shape and break every TOTP secret already stored
|
||||
* in the database. The crypto itself is sound (random IV per encrypt, GCM tag
|
||||
* verified on decrypt, raw 32-byte key) and is also left untouched. A malformed
|
||||
* TS value that happens not to contain exactly two colons falls through to the
|
||||
* base64 branch and fails authentication there — which is the safe outcome.
|
||||
*/
|
||||
export function decryptWithKey(ciphertext: string, keyHex: string): string {
|
||||
const key = Buffer.from(keyHex, "hex");
|
||||
|
||||
// Detect format: PHP uses base64(nonce+ciphertext+tag), TS uses hex:hex:hex
|
||||
const parts = ciphertext.split(":");
|
||||
@@ -52,7 +70,11 @@ export function decrypt(ciphertext: string): string {
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
|
||||
decipher.setAuthTag(tag);
|
||||
|
||||
let decrypted = decipher.update(encrypted);
|
||||
const decrypted = decipher.update(encrypted);
|
||||
const final = decipher.final();
|
||||
return Buffer.concat([decrypted, final]).toString("utf8");
|
||||
}
|
||||
|
||||
export function decrypt(ciphertext: string): string {
|
||||
return decryptWithKey(ciphertext, config.totp.encryptionKey);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,33 @@
|
||||
import fs from "fs";
|
||||
import { Browser } from "puppeteer";
|
||||
|
||||
/**
|
||||
* Pick the first Chromium executable that actually exists on disk.
|
||||
* The previous `A || B || C` chain was dead: the second operand
|
||||
* ("/usr/bin/chromium-browser") is always truthy, so the third
|
||||
* ("/usr/bin/chromium") was never reached and launch failed on hosts
|
||||
* that only ship the `chromium` binary. We now probe each candidate
|
||||
* with fs.existsSync and fall through to the next.
|
||||
*/
|
||||
function resolveChromiumPath(): string | undefined {
|
||||
const candidates = [
|
||||
process.env.CHROMIUM_PATH,
|
||||
"/usr/bin/chromium-browser",
|
||||
"/usr/bin/chromium",
|
||||
].filter((p): p is string => Boolean(p));
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (fs.existsSync(candidate)) return candidate;
|
||||
} catch {
|
||||
// existsSync should not throw, but if it does treat as "not found"
|
||||
// and continue probing the next candidate.
|
||||
}
|
||||
}
|
||||
// Nothing on disk matched — fall back to the configured env value (if any)
|
||||
// so puppeteer-core surfaces a meaningful launch error instead of "undefined".
|
||||
return process.env.CHROMIUM_PATH || undefined;
|
||||
}
|
||||
|
||||
let browser: Browser | null = null;
|
||||
let launching: Promise<Browser> | null = null;
|
||||
|
||||
@@ -18,10 +46,7 @@ async function getBrowser(): Promise<Browser> {
|
||||
});
|
||||
} catch {
|
||||
const core = await import("puppeteer-core");
|
||||
const executablePath =
|
||||
process.env.CHROMIUM_PATH ||
|
||||
"/usr/bin/chromium-browser" ||
|
||||
"/usr/bin/chromium";
|
||||
const executablePath = resolveChromiumPath();
|
||||
browser = await core.default.launch({
|
||||
headless: true,
|
||||
executablePath,
|
||||
|
||||
@@ -1,6 +1,22 @@
|
||||
import { PaginationQuery, PaginationMeta } from "../types";
|
||||
|
||||
export function parsePagination(query: Record<string, unknown>): {
|
||||
/**
|
||||
* Parse common pagination/sort/search query params.
|
||||
*
|
||||
* SECURITY NOTE (trust boundary): `page` and `limit` are clamped here
|
||||
* (page ≥ 1, 1 ≤ limit ≤ 100), but `sort` and `search` are passed through
|
||||
* VERBATIM and are NOT validated against any schema. They originate from the
|
||||
* client. Callers that feed `sort` into a Prisma `orderBy` MUST allow-list it
|
||||
* against the set of sortable columns for that entity (e.g.
|
||||
* `const col = ALLOWED_SORTS.includes(sort) ? sort : "id"`), otherwise an
|
||||
* attacker-supplied field name reaches the query layer. `search` is only safe
|
||||
* when used through parameterized Prisma `contains` filters — never interpolate
|
||||
* it into raw SQL.
|
||||
*/
|
||||
export function parsePagination(
|
||||
query: Record<string, unknown>,
|
||||
opts?: { defaultLimit?: number; maxLimit?: number },
|
||||
): {
|
||||
page: number;
|
||||
limit: number;
|
||||
skip: number;
|
||||
@@ -8,12 +24,20 @@ export function parsePagination(query: Record<string, unknown>): {
|
||||
order: "asc" | "desc";
|
||||
search: string;
|
||||
} {
|
||||
// Defaults suit dense list views (25/page, capped at 100). Report endpoints
|
||||
// that render their full result set pass a generous defaultLimit/maxLimit so
|
||||
// they stay effectively complete while still bounded against a runaway scan.
|
||||
const defaultLimit = opts?.defaultLimit ?? 25;
|
||||
const maxLimit = opts?.maxLimit ?? 100;
|
||||
const page = Math.max(1, parseInt(String(query.page || "1"), 10) || 1);
|
||||
const limit = Math.min(
|
||||
100,
|
||||
maxLimit,
|
||||
Math.max(
|
||||
1,
|
||||
parseInt(String(query.limit || query.per_page || "25"), 10) || 25,
|
||||
parseInt(
|
||||
String(query.limit || query.per_page || String(defaultLimit)),
|
||||
10,
|
||||
) || defaultLimit,
|
||||
),
|
||||
);
|
||||
const sort = String(query.sort || "id");
|
||||
|
||||
Reference in New Issue
Block a user