mirror of
https://github.com/Komediruzecki/token-circles.git
synced 2026-10-20 09:46:43 +02:00
* fix: apply audit security & data-integrity fixes (verified subset of #273) A CI-green subset of the enterprise-audit branch (audit/update-readiness-audit), carrying only the fixes that were independently verified correct and low-risk. The risky/undecided parts of that branch are intentionally left out (see below). Security / data integrity: - IDOR: validate account_id / transfer_account_id ownership before writes in worker + backend transaction create/update (new db.accountBelongsToProfile / baseRepo.accountBelongsToProfile helpers; reject cross-profile ids). - Worker transaction PUT: reverse the old row using baseAmount(oldTx) (local/base currency), not the raw amount — fixes balance corruption on FX edits. - Cross-profile leak: recalcGoalProgress / recalcGoalsByCategory now filter by the goal's own profile_id (backend). - reconciled coercion: string "false" no longer coerces to 1 (worker bulk + single PUT). - Frontend idb: preserve amount_local on partial updates; skip the balance adjustment for a transfer with no destination (money no longer vanishes) and update its unit test to match; use the by_date index for date-range scans (profile-scoped). - CSV export: escape embedded double-quotes ("" ) in description/notes. Compliance / correctness: - Stripe checkout: automatic_tax[enabled]=true (correct nested-param form; the branch's flat automatic_tax='enabled' left VAT off), plus billing_address_collection and tax_id_collection. - Worker account create/update: Number.isFinite() balance guard (rejects NaN/Infinity; negative balances still allowed). - Worker welcome-email and Stripe-customer-delete failures are now logged. Perf / cleanup: - Worker budgets from-expenses: single db.batch() instead of N+1 inserts. - Backend: extract shared parseDateString to lib/dates.js; simplify asyncHandler; clearCookie secure/httpOnly/sameSite; import accountIdMap restricted to the primary profile. - Frontend: QuickAddModal reads active profile / local currency (no hardcoded profile_id:1 / EUR); bulk delete uses the single bulk endpoint; edit-modal date input is editable again. - Remove tracked PWA build artifacts (already in .gitignore). Deliberately NOT included (needs decisions / tests / conflict resolution): - recurring populate + bills mark-paid refactor and the account_id migration (transfer-recurring destroys money; daily/biweekly next_date stall defeats the idempotency guard) — needs fixes + regression tests. - Non-negative transaction amount / account balance validation and strict account type/currency enums — breaks the existing contract (negative expenses, debit balances, unlisted types) and the test suite; a product decision. - Analytics by_date / Sankey handler changes — conflict with main's Sankey fix; must be re-applied on top of it, not merged wholesale. - Bulk PUT type-change balance reversal — pre-existing hole, needs its own fix. Verified: backend 458 tests pass, frontend 420 tests pass, frontend typecheck + lint clean. * test: regression tests for the audit security & data-integrity fixes - backend (cross-user.spec): IDOR — create/update reject an account_id or transfer_account_id owned by another profile (403), with a same-profile control that still succeeds. - frontend (idb.test): updateTransaction preserves amount_local on a partial update and clears it on explicit override; date-range listTransactions stays scoped to the current profile (by_date index spans profiles). - frontend (balance-deltas): computeBalanceDeltas uses amount_local (base) for the delta on foreign-currency expense and transfer rows. - frontend (localHandlers.transactions): CSV export doubles embedded quotes and quotes comma-bearing fields (RFC-4180 round-trip). - worker (currency-balances): PUT reverses a foreign-currency row using its base amount_local, so editing an unrelated field nets zero and changing amount_local re-bases the balance exactly (covers the base-amount PUT fix; run with `pnpm -C worker test`). Verified: backend 462 tests pass, frontend 424 tests pass, typecheck + lint clean. Worker tests authored against the existing Miniflare/D1 harness (worker deps can't install in this sandbox; not gated by CI — run locally to confirm).
87 lines
2.5 KiB
JavaScript
87 lines
2.5 KiB
JavaScript
/**
|
|
* Standardized error handling for the Finance Manager API.
|
|
*
|
|
* Usage:
|
|
* throw new AppError('Transaction not found', 404);
|
|
* throw new AppError('Validation failed', 400, { fields: ['name', 'amount'] });
|
|
*
|
|
* router.get('/api/data', asyncHandler(async (req, res) => {
|
|
* // errors thrown here automatically go to next(err)
|
|
* }));
|
|
*/
|
|
|
|
/**
|
|
* Application-level error with HTTP status code.
|
|
* Throwing an AppError in an asyncHandler-wrapped route skips
|
|
* the try/catch boilerplate and goes straight to the global error handler.
|
|
*/
|
|
class AppError extends Error {
|
|
/**
|
|
* @param {string} message - Human-readable error message
|
|
* @param {number} statusCode - HTTP status code (default 500)
|
|
* @param {object} [details] - Optional structured details (field names, etc.)
|
|
*/
|
|
constructor(message, statusCode = 500, details = null) {
|
|
super(message);
|
|
this.name = 'AppError';
|
|
this.statusCode = statusCode;
|
|
this.details = details;
|
|
this.isOperational = true; // distinguishes expected errors from programming bugs
|
|
Error.captureStackTrace(this, this.constructor);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Subclass for 400 Bad Request errors (validation, missing params, etc.)
|
|
*/
|
|
class ValidationError extends AppError {
|
|
constructor(message = 'Validation failed', details = null) {
|
|
super(message, 400, details);
|
|
this.name = 'ValidationError';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Subclass for 404 Not Found errors.
|
|
*/
|
|
class NotFoundError extends AppError {
|
|
constructor(message = 'Resource not found', details = null) {
|
|
super(message, 404, details);
|
|
this.name = 'NotFoundError';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Subclass for 401 Unauthorized errors.
|
|
*/
|
|
class UnauthorizedError extends AppError {
|
|
constructor(message = 'Authentication required', details = null) {
|
|
super(message, 401, details);
|
|
this.name = 'UnauthorizedError';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Wraps an async Express route handler so that any thrown error
|
|
* (or rejected promise) is forwarded to `next(err)`, eliminating
|
|
* the need for try/catch in every route handler.
|
|
*
|
|
* Works with both async functions and regular functions that return Promises.
|
|
*
|
|
* @param {Function} fn - The route handler function (req, res, next) => Promise|void
|
|
* @returns {Function} Express middleware that catches errors and calls next(err)
|
|
*/
|
|
function asyncHandler(fn) {
|
|
return (req, res, next) => {
|
|
Promise.resolve(fn(req, res, next)).catch(next);
|
|
};
|
|
}
|
|
|
|
module.exports = {
|
|
AppError,
|
|
ValidationError,
|
|
NotFoundError,
|
|
UnauthorizedError,
|
|
asyncHandler,
|
|
};
|