Files
Crussell/scripts/check-env-docs.py
T
popertots 67cf5b9a45 fix: review round 6 — P0 deposit charge, idempotency rotation, dev-safety guard, 2FA/webhook hardening
Sixth fresh-eyes review pass (5 agents: goal, QA, code-quality, security,
context-mining). QA FAILED the deposit-required new-card flow; the P0 root
cause was backend + frontend, now fixed. All 20 packages green.

P0 money-safety:
- Deposit-required bookings now actually charge the deposit on new-card
  payment. Two-part fix: (1) CreateBookingHandler re-reads the
  trigger-maintained total_amount/total_duration_minutes from the DB after the
  booking_services insert (the INSERT..RETURNING row predates the recalc
  trigger, so TotalAmount serialized as 0 and DepositPaid computed TRUE on an
  unpaid booking — the frontend gate trusted deposit_paid:true, never charged,
  and confirmed the booking with zero payment rows); (2) BookingFlow.svelte
  gates the confirmation view on depositPaid and guards against re-creating a
  booking on retry. Regression test
  TestBookings_Create_DepositPaidFalseOnUnpaidBooking.

Payments (idempotency + money):
- deriveBookingPaymentIdempotencyKey: no-client-key fallback now advances a
  sequence for repeatable types (partial) and rotates past refunded completed
  rows, so refund-then-repay and equal-amount partials diverge onto distinct
  keys; an un-refunded completed row keeps its key (double-charge protection
  holds). Dedup hits on refunded rows now 409, never stale success.
- chargeFailureStatus default is 503 (ambiguous), never 402; table test.
- Flaky TestBookingPayment_FullPayment_SplitsIntoDepositAndBalance fixed
  (ORDER BY payment_type).
- resolveChargeSource: orphaned card-on-file disabled via DeleteCardOnFile
  when SaveCardForUser fails (best-effort, redacted log); retry path preserved.

Square client:
- Dev builds HARD-FAIL (panic) on SQUARE_ENVIRONMENT=production without
  SQUARE_ALLOW_REAL_API=1; sandbox routes with a loud banner.
- Mock fault-injection FailAfterCommit (commit-then-5xx) exercises the exact
  lost-response same-key retry; SimulateCardTokenUsed; 45-char idempotency-key
  cap parity; SquareEnvironment/SquareLocationID shared env helpers used by
  the sweep (env contract no longer comment-only).
- listRefunds truncation now errors (money-sensitive reconcile retries
  instead of over-refunding); getCardsOnFile truncation loudly logged.

Webhooks + 2FA:
- square-environment header checked fail-closed (403) when configured env is
  production/sandbox; dispatch DB work bounded by 30s timeout contexts.
- 2FA codes HMAC-SHA256 pepper'd (TWO_FACTOR_PEPPER) with legacy-hash
  migration + upgrade-on-verify; disable-flow mint cooldown (1/min, 429) caps
  the brute-force loop; in-lockout records never LRU-evicted.

Repo hygiene:
- env-docs CI gate green again (FRONTEND_ORIGIN + SQUARE_ALLOW_REAL_API +
  TWO_FACTOR_PEPPER documented; Vite DEV built-in allowlisted).
- Dead square_deposits schema dropped; obsidian/README/legal-page drift fixed
  (consumeradvice.scot signposting, CORS allowlist, p11 R3/P13, T1).
- 2FA disable residual documented; P6 email/SMS delivery and P12 sandbox
  smoke test remain the pre-go-live gates.

Verification: go test -tags test,dev -count=1 -parallel 8 ./... (20/20 ok),
go build ./... + -tags dev, go vet clean, svelte-check 0 errors, env-docs
gate OK, live deposit-required flow re-verified end-to-end (deposit £11
charged, square_payment_id recorded).
2026-08-22 00:34:49 +01:00

79 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""Check that all env vars used in the codebase are documented in .env.example."""
import os
import re
import sys
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def find_env_vars_in_code():
"""Find all os.Getenv() and import.meta.env.VITE_* calls in the codebase."""
env_vars = set()
# Search backend Go files for os.Getenv("VAR_NAME")
go_dir = os.path.join(REPO_ROOT, 'backend')
for root, dirs, files in os.walk(go_dir):
dirs[:] = [d for d in dirs if d not in ('vendor', '.git', 'node_modules')]
for f in files:
if f.endswith('.go'):
path = os.path.join(root, f)
with open(path) as fh:
for line in fh:
m = re.findall(r'os\.Getenv\(["\']([A-Z_][A-Z0-9_]*)["\']', line)
env_vars.update(m)
# Search frontend files for import.meta.env.VITE_* / import.meta.env.*
frontend_dir = os.path.join(REPO_ROOT, 'frontend')
for root, dirs, files in os.walk(frontend_dir):
dirs[:] = [d for d in dirs if d not in ('.git', 'node_modules', 'build')]
for f in files:
if f.endswith(('.ts', '.svelte', '.js')):
path = os.path.join(root, f)
with open(path) as fh:
for line in fh:
m = re.findall(r'import\.meta\.env\.([A-Z_][A-Z0-9_]*)', line)
env_vars.update(m)
# Vite built-ins (DEV, PROD, SSR, MODE, BASE_URL, BUILD) are provided by Vite
# itself and cannot be defined in .env.example — never treat them as user env vars.
env_vars -= {'DEV', 'PROD', 'SSR', 'MODE', 'BASE_URL', 'BUILD'}
return sorted(env_vars)
def find_documented_vars():
"""Find all env vars documented in .env.example."""
env_path = os.path.join(REPO_ROOT, '.env.example')
documented = set()
if os.path.exists(env_path):
with open(env_path) as fh:
for line in fh:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
var_name = line.split('=')[0].strip()
if var_name:
documented.add(var_name)
return documented
def main():
code_vars = find_env_vars_in_code()
documented = find_documented_vars()
undocumented = [v for v in code_vars if v not in documented]
if undocumented:
print("ERROR: The following env vars are used in code but not documented in .env.example:\n")
for v in undocumented:
print(f" {v}")
print(f"\nTotal: {len(undocumented)} undocumented vars out of {len(code_vars)} total")
sys.exit(1)
else:
print(f"OK: All {len(code_vars)} env vars used in code are documented in .env.example")
sys.exit(0)
if __name__ == '__main__':
main()