mirror of
https://github.com/bitbaum/evig.git
synced 2026-12-04 05:37:00 +01:00
Phase V (critical, applied to Neon directly): - 083: bootstrap schema_migrations on Neon + backfill 001-082 (verified absent: SELECT EXISTS returned false; 92 rows now tracked) - 084: 4 missing performance indexes — notifications(user_id,is_read,created_at DESC), pool_memberships(pool_id,status), inventory_items(status,assigned_to), partial fundraising_foundations(created_at DESC) WHERE NOT archived (67MB largest table, 534ms seq scans → indexed) - V.3 RECLASSIFIED — no plaintext API keys actually exist in hirn_provider_settings (audit subagent overstated; verified empty); no action needed - V.4 — 6 test accounts disabled on Neon (renamed to __disabled-<uuid>@disabled.local, cleared staff/super-admin flags, emailVerified=NULL). All 6 lacked verified emails so couldn't log in anyway, but the flags were latent risk. Phase W (hardening): - W.1: .github/workflows/ci.yml gains migration-drift-check job — spins postgres:17 container, applies all 91 SQL migrations in version-sort order, asserts table count + tracking row count. Non-blocking advisory (continue-on-error:true) so transient CI hiccups don't gate merges. - W.2: scripts/db/check-orphans.sh sweeps real-FK + polymorphic-reference + stale-token orphans against the live DB. Live run shows 0 FK orphans (Postgres enforcement holds), 40 fundraising_activity_log polymorphic orphans (under threshold), 135 notifications.related_id (crosses threshold — flagged for human investigation), 3 stale verification_tokens. - W.3: docs/MONEY_CONVENTION.md — integer-cents canonical, lists every legacy decimal(10,2) column to migrate later, explains float-bug class avoidance. - W.4: docs/DISASTER_RECOVERY.md — Neon restore step-by-step, RTO<1h / RPO<5min targets, schema verification path, smoke-test checklist, quarterly drill cadence, local backup workflow. - W.5: New audit helpers logUserDeletion (sync, critical) + logDataExport (sync, warning) + logContentDecision (buffered, info) in src/lib/auth/audit.ts. Wired into admin user-delete route + content-approval route. Export route already self-audits via raw INSERT (left alone — works). - W.6 RECLASSIFIED — OAuth tokens in accounts table technically plaintext (Auth.js default) but app code never reads them after login (verified via grep). Real exfiltration risk minimal; provider-side revocation available. Documented in audit; encryption deferred to dedicated Auth.js-adapter-override session. Phase X (nice-to-have quick wins): - X.1: /api/cron/prune-audit-log + vercel.json cron entry (daily 02:00 UTC). Preserves critical-severity rows forever; prunes info/warning >180 days. - X.2: Migration 085 — location_approvals trigger preventing UPDATE of decision fields (action/status/notes/required_changes/reviewer_id/reviewed_at). Append-only audit trail. Applied to Neon. subscription_pools.organizationId FK SKIPPED — verified no organization table exists, pools use owner_id (user FK). Net Neon state after this commit: 93 migrations tracked, 4 new indexes, 6 test accounts disabled, 1 trigger added. Audit subagent overstatement pattern observed AGAIN — 3 of the original "critical" findings were overstated (plaintext API keys, subscription_pools FK, OAuth-token urgency). Documented per the audit_subagent_overflag memory pattern. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
3.8 KiB
3.8 KiB
Money representation — convention SSOT
Decision (2026-06-03): All new monetary columns and code should use integer cents (a/k/a "minor units"). Existing decimal(n, 2) columns stay until a dedicated migration sweeps them — documented here so no one accidentally extends the inconsistency.
Why integer cents
| Representation | Float math safety | Storage | DB-level constraints | Wire format |
|---|---|---|---|---|
integer cents (canonical) |
exact — no rounding | 4 bytes | trivial CHECK (amount >= 0) |
one number, no decimal points |
decimal(10, 2) (legacy) |
exact in DB; rounding risk on app side if cast to float | 5–14 bytes | enforced precision but ambiguous on app side | "12.34" string, easy to mis-parse |
real / double |
unsafe — never use for money | 4–8 bytes | none | scientific notation possible |
Cents wins on:
- Bug class eliminated. No
0.1 + 0.2 = 0.30000000000000004ever. Float-to-decimal conversion at API/UI boundary is the only place where things can go wrong, and we control that boundary. - Trivially summable.
SUM(amount_cents)is integer arithmetic; nonumericcasts needed in aggregates. - Wire format consistent. JSON serializes as a single number; UI divides by 100 for display. No string parsing, no locale ambiguity.
The convention
- New columns: name suffix
_cents(e.g.subtotal_cents,tax_cents,donation_amount_cents). - Type:
integer(rarelybigint— we're a Swiss nonprofit, not a hedge fund). - Currency: store separately in
currency_code(e.g.'CHF','EUR') with default'CHF'. Don't infer currency from column name. - Display: divide by 100 at the formatter (
formatCHF(cents)insrc/config/marketplace.ts).
Existing columns that don't follow yet
These are decimal(10, 2) or similar today. They work — float-conversion bugs haven't surfaced. Leave them alone until a dedicated migration sweep:
| Table.column | Current type |
|---|---|
listings.price_chf |
decimal(10, 2) |
payment_transactions.amount |
decimal(10, 2) |
refunds.amount |
decimal(10, 2) |
services.price |
decimal(10, 2) |
workshops.price |
decimal(10, 2) |
| ... and ~10 more | decimal(10, 2) |
A future migration will:
- Add
*_centscolumn alongside the olddecimalcolumn. - Backfill:
UPDATE tbl SET price_cents = (price_chf * 100)::int. - Update app code to read from
_cents. - Drop the
decimalcolumn after a deprecation window.
What's already in cents (don't migrate)
orders.subtotal_centsorders.tax_centsorders.shipping_centsorders.total_cents
These set the precedent. New tables should follow them.
Common mistakes to avoid
// WRONG — float math on decimals
const total = items.reduce((sum, item) => sum + item.price_chf, 0)
// 0.1 + 0.2 problem; .toFixed(2) hides bugs at scale.
// RIGHT — integer math on cents
const totalCents = items.reduce((sum, item) => sum + item.price_cents, 0)
const totalDisplay = formatCHF(totalCents) // formatter handles /100
// WRONG — letting a decimal column flow through JS as a number
const price = Number(row.price_chf) // string "12.34" → 12.34, but parse risk
// RIGHT — explicit conversion at boundary, use cents internally
const priceCents = Math.round(Number(row.price_chf) * 100)
Validation at API boundary
When accepting monetary input from a form / API:
const schema = z.object({
// Accept either decimal CHF (UI convenience) or cents (API native).
// Store as cents internally.
amount_cents: z.number().int().min(0),
})
If the UI sends CHF as a decimal, convert at the boundary:
amount_cents: Math.round(amountChf * 100)
Never let 0.1 + 0.2 math survive past the API layer.
Last updated: 2026-06-03 — convention established; sweep migration not yet scheduled.