@davoodmehraban89 / Aram-2 Mirror · read-only / commits / 07a8ae0
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 4, 10:30 UTC

R1: real server-side session authentication (booklet 2.1) (#98)

* feat(pilot): working end-to-end Pilot Workbench (Excel in -> draft BS/IS out) Atomic V1 vertical slice on top of the accepted audit-safe foundation: - pilot_engine: deterministic in-memory BS/IS engine with explicit sign policy, fail-closed exceptions (unmapped/conflict/unsupported/CF-EQ), exact Decimal totals, trial-balance + accounting-equation checks, and reviewable 7-sheet Excel export with source-row drill-down. - pilot_store: bounded thread-safe in-memory sessions with audit trail; Reviewed/Approved mappings require reviewer evidence (contract parity). - pilot_api: /api/v1/pilot endpoints (upload, synthetic demo, mapping edits, export); preflight rejections return exact sheet/row/field issues. - Persian RTL workbench UI at /pilot/ (no external dependencies), root redirects to it; replaces nothing, quarantined prototype untouched. - 25 new tests; full suite 92 passed; migration round-trip unaffected. No canonical data/, samples/, models, or migrations changed. Demo data is synthetic and labelled everywhere. Output is a working draft, never an official financial statement. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): generic company-agnostic editing + mobile-first UI + save/resume Make the workbench a complete, reusable tool for any company, fully usable on a phone: - Full account CRUD: add/edit/rename/delete. Rename carries the mapping forward automatically. Manually added accounts derive closing from opening+debit-credit (never invented); duplicates/non-finite rejected. - Full note & sub-note CRUD: add/edit-title/delete. Deleting a note that is a mapping target is blocked (409) until mappings move. - Company edit: name/code/fiscal-year/unit/currency -> not tied to any entity. - Save/resume: GET workspace.xlsx serializes the working state to a valid Pilot v0.1 workbook; re-upload rebuilds it losslessly (verified round-trip). - Mutable WorkingModel + typed editing validators (pilot_editing.py); every change append-only audited; thread-safe snapshots. - Mobile-first UI: bottom navigation, bottom-sheet forms, card layouts, numeric keyboards, safe-area insets; partial list updates keep search focus. - Engine 1.1.0; PilotAccount now carries full hierarchy for lossless export. Tests: 107 passed (15 new editing/round-trip/API tests). No canonical data, samples, models or migrations changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(pilot): serve workbench directly at root (no redirect) for proxy safety The preview proxy can mishandle the / -> /pilot/ redirect hop. Serve the workbench HTML directly at / with absolute asset paths so the app loads in one request at both / and /pilot/. Update the root test accordingly. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): permanent browser edition (Pyodide) deployed via GitHub Pages - webapp/: mobile-first RTL UI shell + bridge.py (JSON dispatcher mirroring pilot_api.py, no FastAPI) running the exact tested engine in-browser - scripts/build_webapp.py: assembles docs/ from UI + unmodified engine copies - docs/: Pages source (app at site root, .nojekyll, engine under py/aram_backend) - Verified under Node+Pyodide 0.26.4: demo, CRUD, rename-with-mapping, company edit, lossless workspace round-trip, report export, preflight/duplicate errors, balance fail-closed semantics, COMPLETE_APPROVED end state Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci(pilot): deploy browser edition to GitHub Pages (auto-enable) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): vendor Excel wheels + dual-CDN boot; permanent commit-pinned links - boot() installs vendored openpyxl/et_xmlfile wheels directly into site-packages (no PyPI/micropip at runtime) and falls back jsDelivr->unpkg - docs/vendor/ carries the two pure-Python wheels (268KB) - Pages workflow is dispatch-only (site creation requires owner action); app is served permanently via rawcdn.githack.com / cdn.jsdelivr.net gh - Final Node+Pyodide test of deployed bundle: full journey to COMPLETE_APPROVED, lossless workspace round-trip, 12 audit entries Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(domain): pure financial domain layer + parser/inspection fixes (Phase 0) Evidence-based ADRs from read-only probe of canonical 1404 ledger (252898 rows): - ADR-012 money: integer-rial BIGINT storage (Rial TypeDecorator), Decimal in Python, half-up + largest-remainder rounding only in output (P-02, D-03, OD-03) - ADR-013 sign: debit-positive confirmed (C-01 252892/252898 vs 37% credit-pos) - ADR-014 hierarchy: OD-01 default refuted (T1..T4 concat == حساب for 0 rows); kol->general, حساب->subsidiary, T1..T4->detail1..4; full code = kol+حساب (D-10) Domain (no I/O): normalize_fa/normalize_code/decimal_from_cell (P-03/P-04, D-04), Rial money, ledger<->Pilot hierarchy, blocking controls C-01..C-04 (D-02). ledger_parser delegates to domain (text codes keep leading zeros, exact float repr); workbook_inspection normalizes sheets/headers (D-05) and guards max_column=None (D-11). hypothesis added to test extra (ADR-012). Tests: 47 domain + 9 Phase-0 acceptance incl. bounded real-data evidence. Full suite 163 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(db): LedgerBalance model + exact-rial money column (D-01, D-03) - LedgerBalance: year-isolated, source-linked, text hierarchy codes, opening/ debit/credit/closing as Rial BIGINT; unique (year_id, account_full_code, import_version); new import version per Draft re-import (booklet §5) - StatementLine.mapped_total Numeric(24,4) -> Rial() (no float on SQLite, P-02) - ledger_parser extracts optional kol (general_code); hierarchy mapper accepts absent kol; services/ledger_import aggregates parsed rows by canonical account with exact Decimal summation - Migration 20261203_02 (guarded create + batch alter) runs on SQLite/PostgreSQL; up/down round-trip verified Tests: small-sample exact round-trip, large-rial BIGINT storage (>2^53) via ORM, duplicate-account aggregation, uniqueness, migration upgrade/downgrade. Full suite 168 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(source): content-addressed byte store + full CSV support (D-06) - SourceFile model (sha256 PK, size, content_type, stored_path) + SourceDocument FK; SourceStore writes immutable bytes atomically, re-verifies hash on read (corruption/tamper fails loudly); registration accepts optional store, keeps metadata-only model contract (accepted tests unchanged) - CSV ledger parser: UTF-8/UTF-8-BOM/Windows-1256, delimiter sniffing, same Persian normalization + exact-money rules as XLSX; parse_ledger routes by extension; streaming reader - Migration 20261203_03 (guarded create + batch add column) Tests: store round-trip/idempotency/corruption, registration+re-import hash match, CSV encodings/delimiters/leading-zeros/missing-header/empty/routing. 185 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(db): locked-year immutability triggers + hash-chained audit + reopen (D-07) - DB triggers (SQLite + PostgreSQL) block INSERT/UPDATE/DELETE on year-owned tables when the year is LOCKED, enforced even via raw SQL (P-08, D3) - Lifecycle trigger: Draft->Approved->Locked; Locked->Approved only with an approved ReopenRequest; protected years cannot be deleted - AuditEntry append-only (trigger) + hash chain (verify_chain detects tampering independently of the trigger); ReopenRequest model + ORM guard exemption - ADR-016 reopen/immutability model; migration 20261203_04 installs tables+triggers - ensure_triggers() helper; conftest installs triggers for all tests Tests: raw-SQL insert/update/delete blocked on locked year, draft writes allowed, reopen with/without approved request (ORM + raw SQL), audit chain build/verify/ tamper-detection/append-only. 195 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ingestion): wire C-01..C-04 controls into preflight (D-02) - services/preflight.run_preflight evaluates the blocking control set over parsed ledger rows + active mappings; PreflightReport exposes blocking results, can_approve, and the unknown-account queue (C-04) - Mappings loaded from the year's MappingRule rows or supplied directly (pure path) - ERROR results block approval (P-09); unmapped active accounts surface in the unknown queue for Phase 2 resolution Tests: clean ledger passes C-01/C-02, C-01 violation blocks, unmapped accounts queued, mapping clears queue, all four controls present, inactive accounts not queued. 201 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci: quality gates — ruff, mypy strict (domain), coverage, pip-audit, PG matrix (D-12) - pyproject: ruff/mypy/coverage/pytest-cov/pip-audit in test extra; psycopg in ci extra; ruff/mypy/coverage config (domain strict, total>=80%, domain>=90%) - CI: quality job (whitespace, ruff lint+format, mypy domain strict, coverage gates, pip-audit) + migration matrix job (SQLite + PostgreSQL service container, up/down/up round-trip) - ADR-017 documents the dev/CI-only dependencies (no runtime impact, P-10) - Lint fixes across backend (zip strict, StrEnum, specific test exceptions, unused vars); format applied to Phase-0 layers (domain/services/migrations) - pytest>=9.0.3 + pip/setuptools upgraded to clear pip-audit CVEs Gates verified locally: ruff clean, format clean, mypy domain strict clean, coverage total 92% / domain 97%, pip-audit no known vulnerabilities, 201 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs: refresh PROJECT_STATUS + PROJECT_LOG for Phase 0 debts (D-08) Record D-01..D-12 states with commit evidence, real-data proof, ADRs 012/013/ 014/016/017, and local gate results (201 tests, coverage 92%/97%, pip-audit clean). D-09 marked BLOCKED (owner-only). No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * style: ruff format migration files (Phase-0 format gate) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(statements): persistent audited vertical slice + drill-down (Phase 1) - services/statement_build: build versioned BS/IS from latest LedgerBalance import + mappings/notes; exact integer-rial totals; display sign policy (ADR-013/018); unmapped active accounts surfaced; new version per build (never mutates snapshot) - drill_down: StatementLine -> Note -> MappingRule -> LedgerBalance -> SourceDocument (filename + SHA-256) + sheet + row (D2 full traceability) - statement_api: company/year setup, year-filtered ledger upload+import, notes, mappings, statement build/list, drill-down, preflight controls endpoint - ADR-018 persistent statements + drill-down contract Tests: BS/IS totals+signs, drill-down to source row, version increment, unmapped surfacing, API end-to-end (CSV->import->map->build->drilldown), preflight controls, bounded real-data smoke (3000 real 1404 rows -> import -> build -> drill-down). 209 passed; ruff/mypy/coverage gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(mapping): Excel I/O + unknown queue + approval gate + carry-forward (Phase 2) - mapping_io: governed Mappings workbook export/import; text codes; fail-closed per-row import with error report; idempotent re-import; auto-create notes - mapping_workflow: unknown-account queue (C-04 active unmapped); carry-forward notes+mappings into a Draft year (D1 continuity), idempotent - approval: approve_year runs C-01..C-04; blocking ERROR refuses Draft->Approved; clean pass transitions + hash-chained audit entry (P-09) - statement_api: mappings export/import, unknown-accounts, carry-forward, approve - ADR-019 mapping I/O + approval contract; shared api_client fixture in conftest Tests: export/import round-trip, invalid-row fail-closed, queue list/clear, approval blocked/success/non-draft, carry-forward copy/idempotent/reject, API end-to-end (queue->import mappings->approve). 220 passed; gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(notes): safe formula grammar + note engine (Phase 3) - domain/formula: hand-written tokenizer + recursive-descent parser -> whitelisted AST, exact Decimal evaluation; NO eval/exec (P-05); unknown tokens/functions fail closed; division-by-zero rejected; mypy --strict clean - services/note_engine: evaluate disclosure rows from latest ledger import; acct/ row/note/sum/abs functions; earlier-row + cross-note references with cycle detection; per-row referenced accounts for drill-down - statement_api: note-row create (formula validated on create), list, evaluate - ADR-020 formula grammar (mandatory pre-code ADR) Tests: 22 formula parse/eval/safety cases (injection rejected), note engine account/subtotal/cross-note/circular/forward-ref/unknown-account, API create+ evaluate+invalid-formula rejection. 250 passed; gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * WIP: Phase 4 golden comparison (partial, interrupted) - services/golden: data-derived note aggregation (source col0/col25) vs official sheets, half-up million-rial rounding, discrepancies writer (ADR-021) - statement_build: ALL_STATEMENTS constant (BS/IS/CF/EQ) - test_golden: real-data BS match + all-4 build (test run interrupted, unverified) Saved as WIP per owner instruction before priority architecture fixes. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(money): prove P-02 no-silent-rounding with exhaustive evidence (audit #1) - ADR-012 revised: exhaustive probe of BOTH ledgers (457,074 rows, 6 money columns) confirms zero fractional rial; scale-0 is lossless. Clarifies .to_integral_value() is a DETECTOR (raises on fractional), never a rounder; round_half_up is display-only. - 7 regression tests: fractional text/boundary rejected (not rounded), fractional through ORM and CSV import fail loudly (StatementError wrapping ValueError). No storage behavior change needed — the fail-loud design already satisfies P-02. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(ledger): store RAW rows for drill-down, aggregate in compute layer (audit #2, D3/P-01) - ledger_import: one LedgerBalance per source row (no import-time aggregation); source_row preserved so every figure traces to file/sheet/row (D3) - LedgerBalance uniqueness -> (year_id, source_document_id, source_row, import_version) - NEW services/ledger_aggregate: account-level totals via exact Decimal summation in the compute layer (latest import version) - unknown_accounts now aggregates raw rows by account (dedupe + row_count) - Migration 20261203_05 swaps the constraint on existing DBs + reinstalls triggers; fresh DBs get it from the live model. Round-trip verified, triggers preserved. - Test updated: duplicate accounts stored as 2 raw rows, aggregated in service. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(approval): make C-03 enforcement explicit + hard ERROR gate (audit #3, D5) - approve_year loads rows AND mappings, passes both to evaluate_controls -> run_controls; C-03 (double mapping) and C-04 (unknown queue) always evaluated. Even one ERROR blocks Draft->Approved; no bypass path. - 13 negative/positive tests: double-mapping blocks via C-03, C-01/C-02/C-04 block, blocked approval writes no audit + stays Draft, non-draft/nonexistent rejected, clean ledger approves + audit chain valid, locked year immutable after approval, evaluate_controls proves mappings drive C-03/C-04 (incl. valid 100% split). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(services): mypy-clean services + generic golden columns + negative tests (audit #4) - Type-annotate all services so mypy passes (dict/tuple generics, cast, isinstance AST walks, typed sort key, renamed shadowed variable). - golden: resolve note/year/statement-balance columns BY HEADER NAME (1403 and 1404 ledgers have different layouts); fixes 1403 comparison, keeps it generic. - mapping_workflow negative tests: nonexistent carry-forward target, inactive accounts excluded, raw-row aggregation in queue, empty mapping workbook rejected. mypy services+domain clean; golden 1403+1404 real-data tests pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci: frontend gates (eslint/tsc/vitest/Playwright) + mypy services (audit #4, §14) - backend-ci: add 'Mypy (services)' gate (services now type-clean). - frontend-ci: eslint, tsc --noEmit, vitest, vite build, and Playwright e2e (chromium) with report artifact. - frontend/: Vite+React+TS RTL scaffold (Phase 5 foundation) with unit test (App.test.tsx), e2e specs (e2e/app.spec.ts), eslint flat config, tsconfig, playwright.config.ts, package-lock.json. Local: lint/tsc/vitest/build pass; playwright --list validates 2 specs. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * chore: drop unused import in approval gate test (ruff F401) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs: record Phases 1-4 + owner priority fixes in status/log (§0) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(import): tolerant real-ledger import + statement-balance capture (Phase 4/5) - Tolerant parse path (XLSX+CSV): reclassified rows with empty OPENING/Debit/ Credit/CLOSING are kept with exact zero; signed مانده صورت مالی stored as LedgerBalance.statement_balance (nullable Rial BIGINT, migration 20261203_06). Non-numeric money cells are skipped + reported (fail-loud, never invented); identity fields stay strictly required. Strict mode unchanged. - statement_build uses the effective balance: statement_balance rows contribute their pre-signed figure directly (reproduces Phase-4 golden); ordinary closing rows get the ADR-013 section sign. drill_down exposes effective/statement balance. - API upload uses tolerant import and returns skipped_rows for transparency. - 4 new tests (reclassified kept, anomaly skipped+reported, strict fails loud, statement_balance drives build + raw-row drill-down). Full suite: 285 passed. Real-data proof: source_1404.xlsx -> 131,280 raw rows imported, 4 anomalies reported; note->map->build->drill-down traced to exact source rows. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): Phase 5 RTL workbench — setup/import/mapping/statements/drill-down/approval - Vite dev proxy forwards relative /api to FastAPI (no browser localhost calls); allowedHosts for the Arena live preview. - Typed API client + types; Persian-locale rial formatting. - Components: CompanySetup, LedgerUpload, MappingPanel (unknown-account queue, note creation, mapping import/export), StatementView (BS/IS/CF/EQ tabs, build, per-line drill-down), DrillDown (source file/sheet/row lineage), ApprovalPanel (controls + hard approval gate). - Unit tests (11): format, api client, CompanySetup, DrillDown, App shell. Playwright e2e: app smoke + full workflow (backend-gated via ARAM_E2E_BACKEND). - Gates: eslint/tsc/vitest/build pass; mypy services clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(output): Phase 6 reviewable statement outputs (XLSX + JSON) with lineage - statement_export: latest-version BS/IS/CF/EQ + evaluated notes + full source lineage (file/SHA-256/sheet/row) as RTL XLSX (Summary/per-statement/Note/Lineage) and structured JSON. Exact integer-rial preserved; million-rial display-only (half-up, ADR-012). No new dependency (openpyxl). ADR-022. - API GET /years/{id}/statements/export?format=xlsx|json; workbench download buttons. - 3 tests (JSON exact rial + lineage, XLSX sheets/values, JSON serializable). Real-data proof: year 1404 export -> BS/IS, 340 lineage rows, Note 10; XLSX sheets Summary/BS/IS/Note 10/Lineage. Full suite: 288 passed; mypy services clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(admin): Phase 7 users/roles, controlled reopen/lock, verifiable backup - User model + roles (admin/reviewer/preparer); PBKDF2-HMAC-SHA256 + per-user salt (stdlib, no plaintext, no network); require_role gate; first-user bootstrap. - Reopen/lock service: request->approve->reopen (LOCKED->APPROVED only with an approved request; ORM guard + DB trigger re-check, no bypass); lock APPROVED-> LOCKED; every step hash-chained audited. Migration 20261203_07 (round-trip OK). - Backup: consistent SQLite online-backup snapshot + source-store copy + SHA-256 manifest + audit-chain verification; verify_backup recomputes hashes + chain; tamper/non-empty-dest/broken-chain refused. ADR-023. - admin_api /api/v1: users, auth/login, audit(+verify), reopen/lock, backup(+verify) with 403 role gates. - 17 tests (users/auth/roles, reopen workflow + immutability, backup integrity + tamper, admin API bootstrap/login/gate/audit). Full suite: 305 passed. Live proof: bootstrap->admin, login, audit chain valid, backup+verify (1 source file), preparer backup -> 403. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): admin panel — login, audit verify, lock/reopen, backup/verify Phase 7 workbench surface: role-gated login, audit-chain check, year lock, reopen request->approve->reopen, and backup create/verify against the admin API. Gates: eslint/tsc/vitest/build pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(desktop): Phase 8 offline desktop entrypoint + reproducible PyInstaller recipe - desktop.py: per-user data dir, idempotent SQLite schema + D-07 triggers, FastAPI + bundled React workbench served on 127.0.0.1 only (zero network). database.reconfigure rebinds the shared engine to the local file at launch. - packaging/aram.spec (one-folder Aram.exe) + build_desktop.py (npm build -> PyInstaller) + README. Binary is a build artifact, never committed (§19). ADR-024. - 3 tests: DB init creates schema+triggers (idempotent), desktop app serves health + API end-to-end, data-dir override. Full suite: 308 passed; mypy clean. Live proof: desktop app serves bundled RTL workbench at / (200) + health ok. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(e2e): update smoke spec to the workbench (company setup form, not counter) The Phase 5 workbench replaced the demo counter; the Playwright smoke test now asserts the RTL heading + company setup form (frontend-only, no backend needed). Fixes the Frontend CI e2e job. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs+uat: Phase 9 real-data UAT script + status/log for Phases 5-9 (§0/§18) scripts/uat_real_data.py exercises the full persistent pipeline on source_1404 (read-only): import->auto-map->build->golden reconcile->approval gate->export-> backup->audit. Records reviewable evidence; report is not a committed artifact. PROJECT_STATUS + PROJECT_LOG updated with Phases 5-9 and UAT results. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(review): role-gate approve + editable notes/mappings/rows (5-agent review) Findings from the deep compliance review: - F3-1: API /approve now enforces reviewer/admin role once local users exist (consistent with /lock and /reopen); bootstrap/dev (no users) stays open; the C-01..C-04 ERROR gate always applies. +2 negative/positive tests. - F2-1: add PUT/DELETE for notes, mappings, note rows + GET list notes/mappings, satisfying the owner's editable codes/accounts/notes/subnotes requirement. Draft-guarded; D-07 immutability translated to HTTP 409; note delete refuses while mappings/statement lines reference it (rows cascade). +9 tests incl. locked-year edit refusal. - F5-1: document python-multipart upload dependency in ADR-018. Full suite: 319 passed; mypy services clean; ruff clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): notes/mappings manager (edit/delete) wired to the editing API NotesManager lists notes (inline title edit + delete) and mappings (delete), refreshing after each change. eslint/tsc/vitest/build pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs(review): 5-pass booklet compliance review report + log (§0) Records the five reviewer mandates, evidence, findings (F2-1/F3-1/F5-1 fixed, O5-1 noted) and per-agent verdicts. All passes PASS after fixes; 319 tests green. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * B0: booklet reference + lightweight-process reconciliation - docs/booklet/BOOKLET_v1.0.md + MANIFEST.json (original PDF SHA-256 anchor; ADR-025) - PROJECT_STATUS.md rewritten to GitHub reality (Phases 0-9 MERGED @46253c9, 319 tests, post-merge CI; stale V1-01/unmerged rows removed; D-08 closed) - 14 root analytical docs git mv -> docs/archive/ (+ index); no new root analytical doc (booklet §0.5) - AGENTS.md <-> §0.5 conflict resolved: handoff cadence per-category, lightweight-process bullets (ADR-026) - docs/discrepancies.json skeleton {row,our_amount,official_amount,cause,evidence,year} (OD-08; B8 populates) - docs/PROJECT_LOG.md + LATEST_HANDOFF.md refreshed (end-of-category) - data/ + samples/ tree hashes unchanged (docs/process only) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0: booklet 2 course correction (بخش الف) - الف‌1: remove Pyodide/Pages/CDN browser edition (webapp/, docs built output, docs/vendor wheels, scripts/build_webapp.py, pilot-pages.yml); recoverable from history @46253c9; ADR-028 - booklet 2 v2.0 verbatim -> docs/booklet/BOOKLET_v2.0.md + MANIFEST.json (SHA-256 anchor); ADR-027 (C0..C10 supersedes B framing; OD-09..14; generality rule; databansoft not reachable) - الف‌6: docs/PR_TRIAGE.md (ADOPT #81/#89/#92; CLOSE NO-GO #82/#88; SUPERSEDED #90/#91 + #22-#80) - الف‌4/5 + ب‌1 + §16: PR honesty/size, generality grep, offline/read-only/no-plaintext rules in AGENTS.md - الف‌2/3 verified: persistent core (domain+statement_api/admin_api on LedgerBalance) is main path; phase 0/1 + golden merged @46253c9 - PROJECT_STATUS.md -> C0..C10 roadmap + C0 progress + الف‌7; PROJECT_LOG + handoff refreshed - data/ + samples/ tree hashes unchanged; backend 319 passed, frontend lint/tsc/vitest(11)/build green (no regression) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0 addendum: booklet 2 appendix revision (owner) + ADR-029 - appendix replaced verbatim: Databan catalog studied by owner (marketing, unverified); positioning = independent pluggable product + Host Integration API; accepted elements 1-10; rejected scope; legal restriction - OD-09 REVISED: pyodbc-first (existing ODBC driver, Windows+SQL Server), python-tds fallback (ADR-027 updated, ADR-029) - ADR-029: positioning, OD-14 capability comparison, element->phase mapping (C4-C9/C11), C11 AI constraints (never generates numbers) - PROJECT_STATUS: C5/C7/C8/C9 scope notes + C11 row + positioning; PROJECT_LOG + handoff updated - BOOKLET_v2.0.md re-anchored: SHA-256 79618ddd...; MANIFEST.json revision history kept - docs-only addendum; code identical to tested C0 tree (backend 319 passed, frontend green); data/ + samples/ unchanged Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0 remediation: populate discrepancies.json (الف‌7) + record review findings - الف‌7 met: golden.compare_year(1404) re-run -> 28/9 matched/19 diffs; docs/discrepancies.json populated one-by-one with cause + reproducible evidence + source/official SHA-256 (16 caused: 8 exact-magnitude sign flips ADR-013, CF note reuse, absent/underived notes; 3 under_investigation: IS 6/8/9 = bugs until proven D1); EQ official parsing gap recorded - ADR-028: owner's explicit experiment/browser-edition instruction recorded; Arena single-branch block reported; preservation guaranteed via tag v1.0.0 -> 46253c9 - PROJECT_STATUS: review deviations tracked (forgeable actor auth C8, 4/15 controls C3, desktop create_all bypasses Alembic C9, PR #96 discipline violation historical, booklet-1 extraction artifacts disclosed); الف‌7 marked MET - Fresh evidence: backend 319 tests exit 0; D-04/D-05 normalization 17 passed - docs-only; data/ + samples/ trees unchanged; no second PR (owner directive) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(R1): real server-side session authentication (booklet 2.1) Identity now comes only from a server-side session. `actor` is removed from every request model; a login issues a random 256-bit bearer token whose SHA-256 is the only thing stored, with an 8-hour absolute TTL, logout revocation and a 5-attempt / 15-minute lockout. PBKDF2 rises to 600,000 rounds (Argon2 absent, no new runtime dependency); legacy 200,000-round hashes are rehashed on first login. A single `current_user` dependency guards the statement, admin, schema and pilot routers. Only /health, /auth/login, /auth/launch and the one-time first-admin bootstrap are reachable without a session; reads require login too. Approval without users is impossible, and the role gate runs before the existence check. Backup `dest` is confined to the data folder (traversal, absolute and symlink escapes refused). The desktop launcher gates the local API with a one-time token passed in the URL fragment and exchanged once for an X-Aram-Launch grant. The legacy pilot router, /pilot mount and the HTML at / are out of the app; the interactive schema browsers are disabled. Frontend: LoginPanel gates the workbench, session.ts owns the token in sessionStorage, client.ts attaches it to every request and clears it on 401, and exports became authenticated fetch+blob downloads instead of bare links. Migration 20261204_08 adds auth_sessions + lockout/work-factor columns, verified on a populated copy (131,280 ledger rows, 2 users, 28 triggers unchanged). Decisions: ADR-030. Tests: backend 354 passed (33 new R1 acceptance tests), frontend 15 vitest tests, new real-session e2e (CI now runs uvicorn). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * test(R1): give the real-ledger e2e a realistic timeout and readable CI failures The workflow e2e was previously skipped in CI (no backend); now that CI starts uvicorn it actually runs, and Playwright's default 30s test timeout killed it while the 131k-row ledger import was still in flight. Raise the test timeout, run one worker against the shared backend, and add the github + html reporters so failures surface as check-run annotations and an uploaded report. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci(R1): migrate the throwaway e2e database before starting uvicorn The dev app deliberately does not create the schema (R4 owns startup migrations), so the fresh CI database had no tables and the first-admin bootstrap failed, which made every real-session e2e fail at the login step. Run 'alembic upgrade head' against the e2e database first — verified locally on a fresh DB: 16 tables + 28 triggers, then bootstrap 200, login 200, company 200, audit 200, logout 200, me-after-logout 401. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * test(R1): disambiguate e2e selectors now that the login screen exists The login card adds an h2 containing 'آرام', so the heading query must target level 1. The ledger import button query matched both 'درون‌ریزی' and 'درون‌ریزی نگاشت‌ها' — a pre-existing ambiguity that only surfaced once the workflow e2e actually ran with a backend. Also trims docs to stay at the 1,500-line cap after the CI/config additions. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * test(R1): seed one real mapping in the workflow e2e before building The workflow e2e had never run in CI (no backend), and it built statements without any mapping: every account stayed unmapped, so the statements had zero lines and the drill-down step had nothing to click. Capture the year id from the company response, map one real account from the unknown-accounts queue to a new BS/Assets note using the session token, then build. Also raises the import assertion timeout to match the 131k-row workbook. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --------- Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> Co-authored-by: Arena Agent <agent@arena.ai>

davoodmehraban89 committed Dec 4, 2026 at 13:08 UTC 07a8ae0e621e706e4ce1583a611699bc2bc6d38d
38 files changed +2070 -374
.github/workflows/frontend-ci.yml
+31
@@ -57,8 +57,39 @@ jobs:
57 run: npm ci --no-audit --no-fund
58 - name: Install Playwright browsers
59 run: npx playwright install --with-deps chromium
60 + # R1 (booklet 2.1): the e2e must prove a *real* session, so the backend runs
61 + # too, on a throwaway database outside the repository.
62 + - uses: actions/setup-python@v5
63 + with:
64 + python-version: "3.11"
65 + - name: Install backend
66 + working-directory: backend
67 + run: |
68 + python -m pip install --upgrade pip
69 + pip install -e ".[test]"
70 + - name: Start backend
71 + working-directory: backend
72 + run: |
73 + mkdir -p "$RUNNER_TEMP/aram-e2e/store"
74 + export ARAM_DATABASE_URL="sqlite:///$RUNNER_TEMP/aram-e2e/e2e.db"
75 + export ARAM_SOURCE_STORE_ROOT="$RUNNER_TEMP/aram-e2e/store"
76 + # The dev app does not create the schema (R4 owns startup migrations),
77 + # so the throwaway e2e database is migrated explicitly first.
78 + python -m alembic upgrade head
79 + nohup python -m uvicorn aram_backend.main:app --host 127.0.0.1 --port 8000 \
80 + > "$RUNNER_TEMP/aram-e2e/backend.log" 2>&1 &
81 + for i in $(seq 1 60); do
82 + if curl -sf http://127.0.0.1:8000/api/v1/health > /dev/null; then exit 0; fi
83 + sleep 1
84 + done
85 + echo "backend did not start"; cat "$RUNNER_TEMP/aram-e2e/backend.log"; exit 1
86 - name: Run e2e
87 + env:
88 + ARAM_E2E_BACKEND: "1"
89 run: npm run test:e2e
90 + - name: Backend log
91 + if: always()
92 + run: cat "$RUNNER_TEMP/aram-e2e/backend.log" || true
93 - name: Upload report
94 if: always()
95 uses: actions/upload-artifact@v4
PROJECT_STATUS.md
+27 -6
@@ -6,11 +6,11 @@
6
7 - Repository: [davoodmehraban89/Aram](https://github.com/davoodmehraban89/Aram)
8 - Accepted branch: `source-data-cleanup`
9 -- **Live accepted head: `46253c94405abd065dfc5e8cf080b295cb83cde4`** — squash merge of [PR #96](https://github.com/davoodmehraban89/Aram/pull/96), merged 2026-12-03T15:22:02Z (owner final acceptance).
9 +- **Live accepted head: `f2e6da5e7ade3c851584008d590c588894d4c9c3`** — squash merge of [PR #97](https://github.com/davoodmehraban89/Aram/pull/97), merged 2026-12-04T07:25:29Z under a one-time owner waiver (preconditions verified: OPEN, head `1e247083`, `mergeable_state=clean`). Previous head `46253c9` (PR #96) is preserved by tag `v1.0.0`.
10 - **Release tag `v1.0.0`** points to `46253c94405abd065dfc5e8cf080b295cb83cde4` (owner-authorized, created pre-mission). The implementation author does not tag (§19); no further tagging without owner directive.
11 - Post-merge CI on the accepted head: [Backend CI #47137691800](https://github.com/davoodmehraban89/Aram/actions/runs/47137691800) ✅ and [Frontend CI #47137691857](https://github.com/davoodmehraban89/Aram/actions/runs/47137691857) ✅.
12 - Product objective: a controlled, auditable accounting and financial-statement workflow that preserves canonical source data.
13 -- Authoritative work orders: booklet 1 v1.0 ([`docs/booklet/BOOKLET_v1.0.md`](docs/booklet/BOOKLET_v1.0.md), ADR-025) and **booklet 2 v2.0** ([`docs/booklet/BOOKLET_v2.0.md`](docs/booklet/BOOKLET_v2.0.md), ADR-027 — course correction + general-platform architecture; supersedes conflicting parts of booklet 1). Integrity anchored by SHA-256 in [`docs/booklet/MANIFEST.json`](docs/booklet/MANIFEST.json).
13 +- Authoritative work orders: booklet 1 v1.0 ([`docs/booklet/BOOKLET_v1.0.md`](docs/booklet/BOOKLET_v1.0.md), ADR-025) and **booklet 2 v2.0** ([`docs/booklet/BOOKLET_v2.0.md`](docs/booklet/BOOKLET_v2.0.md), ADR-027 — course correction + general-platform architecture; supersedes conflicting parts of booklet 1). Integrity anchored by SHA-256 in [`docs/booklet/MANIFEST.json`](docs/booklet/MANIFEST.json). **Governing now: booklet 2.1** (owner message 2026-12-04; no markdown copy is committed because the agent holds no byte-exact original — the owner's text is authoritative, see `MANIFEST.json`). It closes only the remaining gaps and takes precedence over booklets 2 and 1, whose other sections stay valid. Work is split into **R1…R6**, one PR each, ≤1,500 lines excluding tests/data; security/control defects may not be deferred.
14
15 ## Status vocabulary
16
@@ -87,18 +87,39 @@ Booklet 2 v2.0 («اصلاح مسیر و معماری نهایی Aram», [`docs/
87 - Export: XLSX (6.27 MB) + JSON with **158,050 lineage rows** (file/SHA-256/sheet/row).
88 - Backup: created + verified (hashes + audit chain); audit chain valid.
89
90 +## Booklet 2.1 — R-task progress
91 +
92 +| Task | Scope | Status |
93 +| --- | --- | --- |
94 +| R1 | Real authentication (backend + frontend), backup confinement, desktop launch token, legacy surfaces | **MET** (this PR; evidence below) |
95 +| R2 | Controls C-05..C-15 wired into `run_controls` + approval | NOT_STARTED |
96 +| R3 | `build_statements` vs official; (statement, note) aggregation; IS 6/8/9 root cause; EQ/CF parsing | NOT_STARTED |
97 +| R4 | Remove `create_all` from the production path; backup → `alembic upgrade head` → trigger check | NOT_STARTED |
98 +| R5 | `docs/c01_exceptions.json` — the six C-01 source rows, unapprovable until resolved | NOT_STARTED |
99 +| R6 | Propose marking the `v1.0.0` Release as pre-release; `experiment/browser-edition` = owner action | NOT_STARTED |
100 +
101 +### R1 acceptance ← evidence
102 +
103 +All R1 criteria are met; the full «معیار پذیرش ← شاهد» table is in the R1 PR report.
104 +Witnesses: the 33 tests in `backend/tests/test_auth_r1.py`, the frontend vitest suite,
105 +and `frontend/e2e/session.spec.ts` (CI starts uvicorn on a migrated throwaway DB with
106 +`ARAM_E2E_BACKEND=1`). Migration `20261204_08` verified on a populated copy: 131,280
107 +ledger rows, 2 users, 28 triggers unchanged.
108 +
109 +Backend **354 passed** (was 319); frontend **15 vitest tests / 5 files**; ruff, mypy, tsc, eslint all clean.
110 +
111 ## Known gaps feeding the C-phases (honest residual risks)
112
92 -- **Authorization is forgeable (independent review, 2026-12-03):** roles derive from a client-supplied `actor` string in the request body, not a token/session; `"actor":"admin"` grants admin to anyone who reaches the API. Most endpoints (company create, ledger upload, mapping, export) are unguarded; with no users seeded, year approval is open to all. Loopback-only binding limits exposure on a single-user machine but this is serious on a server/shared machine and contradicts booklet 1 §13. `pilot_api.py` also exposes 17 unauthenticated routes. → **C8** (token/session auth + role guards + audit on every write; fail-closed).
113 +- **Authorization forgeability — CLOSED in R1 (2026-12-04, ADR-030).** Was: roles derived from a client-supplied `actor` body string; `"actor":"admin"` granted admin to anyone; most endpoints unguarded; approval open when no users existed; `pilot_api.py` exposed 17 unauthenticated routes. Now: `actor` removed from every request model; identity comes only from `current_user` resolving a 256-bit bearer token whose SHA-256 is stored server-side (8-hour absolute TTL, logout, 5-attempt lockout for 15 minutes, PBKDF2 600,000); every route except `/health`, `/auth/login`, `/auth/launch` and the one-time first-admin bootstrap requires a session, reads included; approval without users is impossible; the pilot router and the legacy `/` UI are out of the app; backup `dest` is confined to the data folder; the desktop launcher gates the local API with a one-time token. Evidence: `backend/tests/test_auth_r1.py` (33 tests). Remaining C8 scope: DPAPI vault, encrypted backup, plugin allowlist, row/field-level access layers.
114 - `frontend/src/lib/format.ts` uses `Number(value)` (float risk) (C7).
94 -- **Only 4 of 15 controls implemented** (`domain/controls.py` = C-01..C-04); approval depends only on these, so a year with an unbalanced BS or note/statement mismatch can be approved. C-05..C-15 absent → **C3** (wire all controls into `run_controls` + approval gate; ERROR year unapprovable).
95 -- **Desktop install bypasses Alembic** (`desktop.py:62` `Base.metadata.create_all`); existing user DBs will not migrate on update → **C9** (replace with `alembic upgrade head` + migration round-trip test on an existing DB).
115 +- **Only 4 of 15 controls implemented** (`domain/controls.py` = C-01..C-04); approval depends only on these, so a year with an unbalanced BS or note/statement mismatch can be approved. C-05..C-15 absent → **R2** (booklet 2.1; was C3): wire all ERROR controls into `run_controls` + approval gate; a control lacking inputs must report «اجرا نشد: دلیل» and block approval.
116 +- **Desktop install bypasses Alembic** (`desktop.py` `Base.metadata.create_all`); existing user DBs will not migrate on update → **R4** (booklet 2.1; was C9). R1 added migration `20261204_08` and verified it on a copy of a populated database (131,280 ledger rows, 2 users, 28 triggers unchanged), but the startup path still uses `create_all`.
117 - ImportRun/CalculationRun/LineageEdge/Adjustment/UnknownAccountQueue/carried_from_year_id/calculation_run_id refs absent; pilot exception queue not persisted in `domain/` (C1/C4).
118 - `note_engine.acct()` is closing-only; statement_balance-only rows evaluate 0 in notes (C1/C3).
119 - No connector framework / Source Adapter / snapshot reconciliation / packs yet; generality grep test pending (C4/C5/C6).
120 - CI: `npm ci --no-audit`, coverage gate not 80/90, services mypy non-strict (C9).
121 - Backup unencrypted; no DPAPI vault / plugin allowlist / SBOM yet (C8/C9).
101 -- Browser edition removed (C0); single reference UI = React workbench, developed in C7. Backend `static/pilot` legacy retained until C8.
122 +- Browser edition removed (C0); single reference UI = React workbench. Backend `static/pilot` files remain in the tree but are no longer served or mounted (R1); the pilot router keeps the `current_user` dependency and is exercised only by a test-only app.
123 - Windows EXE not built; clean-machine install log + Shadow Run two-company + owner signature pending (C9/C10).
124 - `docs/discrepancies.json` now records all 19 golden-1404 differences with cause+evidence (الف‌7 met); 3 IS magnitude mismatches remain under investigation (bugs until proven, D1) and build-vs-official comparison is added in C3.
125 - **PR-discipline violation recorded (independent review):** merged PR #96 bundled all 10 phases in one PR (154 files, +24,327 lines ≈ 16× the الف‌5 cap), its body cited a stale head (`969f608` vs merged `babe829`), and it merged without independent review under a one-time owner waiver. Historical; cannot be un-merged. Booklet 2 الف‌4/الف‌5 now enforced in `AGENTS.md` for all future PRs.
backend/migrations/versions/20261204_08_auth_sessions.py new
+71
@@ -0,0 +1,71 @@
1 +"""Server-side auth sessions + login lockout (R1, booklet 2.1).
2 +
3 +Adds ``auth_sessions`` (only the SHA-256 hash of a random 256-bit bearer token is
4 +stored) and per-user lockout / PBKDF2 work-factor columns. Existing users keep
5 +their legacy 200,000-round hashes (``password_rounds`` server_default) and are
6 +transparently rehashed to 600,000 on first successful login.
7 +
8 +Revision ID: 20261204_08
9 +Revises: 20261203_07
10 +"""
11 +
12 +import sqlalchemy as sa
13 +from alembic import op
14 +
15 +revision = "20261204_08"
16 +down_revision = "20261203_07"
17 +branch_labels = None
18 +depends_on = None
19 +
20 +
21 +def _has_table(bind, name: str) -> bool:
22 + return name in sa.inspect(bind).get_table_names()
23 +
24 +
25 +def _has_column(bind, table: str, column: str) -> bool:
26 + return column in {c["name"] for c in sa.inspect(bind).get_columns(table)}
27 +
28 +
29 +def upgrade() -> None:
30 + bind = op.get_bind()
31 + if _has_table(bind, "users"):
32 + if not _has_column(bind, "users", "password_rounds"):
33 + op.add_column(
34 + "users",
35 + sa.Column("password_rounds", sa.Integer(), nullable=False, server_default="200000"),
36 + )
37 + if not _has_column(bind, "users", "failed_login_count"):
38 + op.add_column(
39 + "users",
40 + sa.Column("failed_login_count", sa.Integer(), nullable=False, server_default="0"),
41 + )
42 + if not _has_column(bind, "users", "locked_until"):
43 + op.add_column(
44 + "users", sa.Column("locked_until", sa.DateTime(timezone=True), nullable=True)
45 + )
46 + if not _has_table(bind, "auth_sessions"):
47 + op.create_table(
48 + "auth_sessions",
49 + sa.Column("id", sa.Integer(), primary_key=True),
50 + sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=False),
51 + sa.Column("token_hash", sa.String(length=64), nullable=False),
52 + sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
53 + sa.Column("revoked", sa.Boolean(), nullable=False, server_default=sa.false()),
54 + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
55 + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
56 + sa.UniqueConstraint("token_hash", name="uq_auth_sessions_token_hash"),
57 + )
58 + op.create_index("ix_auth_sessions_user_id", "auth_sessions", ["user_id"])
59 + op.create_index("ix_auth_sessions_token_hash", "auth_sessions", ["token_hash"])
60 +
61 +
62 +def downgrade() -> None:
63 + bind = op.get_bind()
64 + if _has_table(bind, "auth_sessions"):
65 + op.drop_index("ix_auth_sessions_token_hash", table_name="auth_sessions")
66 + op.drop_index("ix_auth_sessions_user_id", table_name="auth_sessions")
67 + op.drop_table("auth_sessions")
68 + if _has_table(bind, "users"):
69 + for col in ("locked_until", "failed_login_count", "password_rounds"):
70 + if _has_column(bind, "users", col):
71 + op.drop_column("users", col)
backend/src/aram_backend/admin_api.py
+179 -75
@@ -1,19 +1,30 @@
1 -"""HTTP API for Phase 7 administration: users, audit, reopen/lock, backup.
1 +"""HTTP API for administration: session auth, users, audit, reopen/lock, backup.
2
3 -Sensitive actions are gated by local role (``require_role``) and attributed to a
4 -username in the hash-chained audit log. Offline desktop: no runtime network.
3 +R1 (booklet 2.1): no endpoint accepts an ``actor`` field. Identity comes only from
4 +the server-side session resolved by ``current_user``; the audit log is attributed
5 +to that authenticated username. ``public_router`` holds the three routes that must
6 +work before a session exists (login, desktop launch exchange, first-admin
7 +bootstrap); everything else is behind the single authentication dependency.
8 """
9
10 from __future__ import annotations
11
9 -from fastapi import APIRouter, Depends, HTTPException
12 +from fastapi import APIRouter, Depends, HTTPException, Request
13 from pydantic import BaseModel, Field
14 from sqlalchemy import select
15 from sqlalchemy.orm import Session
16
17 +from aram_backend.auth import (
18 + LAUNCH_HEADER,
19 + bearer_token,
20 + current_user,
21 + launch_guard,
22 + optional_user,
23 + require_launch,
24 +)
25 from aram_backend.config import get_settings
26 from aram_backend.database import get_session
16 -from aram_backend.models import AuditEntry, UserRole
27 +from aram_backend.models import AuditEntry, User, UserRole
28 from aram_backend.services.audit import verify_chain
29 from aram_backend.services.backup import BackupError, create_backup, verify_backup
30 from aram_backend.services.reopen import (
@@ -25,65 +36,149 @@ from aram_backend.services.reopen import (
36 request_reopen,
37 )
38 from aram_backend.services.users import (
39 + AuthenticationError,
40 AuthorizationError,
41 UserError,
42 authenticate,
43 create_user,
44 + ensure_role,
45 + issue_session,
46 list_users,
33 - require_role,
47 + revoke_session,
48 set_active,
49 set_role,
50 )
51
38 -router = APIRouter(prefix="/api/v1", tags=["admin"])
52 +# /auth/launch must itself be reachable *before* a grant exists, so it sits on a
53 +# router without the launch dependency; it is protected by the one-time token.
54 +launch_router = APIRouter(prefix="/api/v1", tags=["auth"])
55 +public_router = APIRouter(prefix="/api/v1", tags=["auth"], dependencies=[Depends(require_launch)])
56 +router = APIRouter(
57 + prefix="/api/v1",
58 + tags=["admin"],
59 + dependencies=[Depends(require_launch), Depends(current_user)],
60 +)
61
62 _ADMIN = {UserRole.ADMIN}
63 _REVIEW = {UserRole.ADMIN, UserRole.REVIEWER}
64
65
44 -def _guard(session: Session, actor: str, allowed: set[UserRole]) -> None:
66 +def _require(user: User, allowed: set[UserRole]) -> None:
67 try:
46 - require_role(session, username=actor, allowed=allowed)
68 + ensure_role(user, allowed)
69 except AuthorizationError as exc:
70 raise HTTPException(status_code=403, detail=str(exc)) from exc
71
72
73 +def _identity(user: User) -> dict:
74 + return {
75 + "username": user.username,
76 + "display_name": user.display_name,
77 + "role": user.role.value,
78 + }
79 +
80 +
81 +# ------------------------------------------------------------------ auth (public)
82 +class LoginIn(BaseModel):
83 + username: str = Field(min_length=1, max_length=64)
84 + password: str = Field(min_length=1, max_length=256)
85 +
86 +
87 +@public_router.post("/auth/login")
88 +def login(body: LoginIn, session: Session = Depends(get_session)) -> dict:
89 + try:
90 + user = authenticate(session, username=body.username, password=body.password)
91 + except UserError as exc:
92 + raise HTTPException(status_code=401, detail=str(exc)) from exc
93 + token = issue_session(session, user)
94 + return {"token": token, "token_type": "Bearer", **_identity(user)}
95 +
96 +
97 +@router.post("/auth/logout")
98 +def logout(request: Request, session: Session = Depends(get_session)) -> dict:
99 + """Revoke the presented session. Idempotent; never reveals token validity."""
100 + revoke_session(session, bearer_token(request))
101 + return {"logged_out": True}
102 +
103 +
104 +class LaunchIn(BaseModel):
105 + token: str = Field(min_length=1, max_length=256)
106 +
107 +
108 +@launch_router.post("/auth/launch")
109 +def launch_exchange(body: LaunchIn, request: Request) -> dict:
110 + """Exchange the desktop launcher's one-time token for a launch grant."""
111 + guard = launch_guard(request)
112 + if guard is None:
113 + raise HTTPException(status_code=404, detail="راه‌انداز محلی در این حالت فعال نیست.")
114 + try:
115 + grant = guard.exchange(body.token)
116 + except AuthenticationError as exc:
117 + raise HTTPException(status_code=401, detail=str(exc)) from exc
118 + return {"grant": grant, "header": LAUNCH_HEADER}
119 +
120 +
121 +@router.get("/auth/me")
122 +def me(user: User = Depends(current_user)) -> dict:
123 + return _identity(user)
124 +
125 +
126 # --------------------------------------------------------------------- users
127 class UserIn(BaseModel):
128 username: str = Field(min_length=1, max_length=64)
129 password: str = Field(min_length=8, max_length=256)
130 role: UserRole = UserRole.PREPARER
131 display_name: str = Field(default="", max_length=128)
57 - actor: str = Field(default="", max_length=64)
58 -
59 -
60 -@router.post("/users")
61 -def create_user_endpoint(body: UserIn, session: Session = Depends(get_session)) -> dict:
62 - # Bootstrap: the very first user is created without an existing admin and is
63 - # forced to the admin role (offline desktop install). Afterwards, only an
64 - # admin may create users.
65 - bootstrap = not list_users(session)
66 - if not bootstrap:
67 - _guard(session, body.actor, _ADMIN)
68 - role = UserRole.ADMIN if bootstrap else body.role
132 +
133 +
134 +def bootstrap_guard(request: Request, session: Session = Depends(get_session)) -> None:
135 + """Once any user exists, /users demands a session *before* body validation."""
136 + if list_users(session):
137 + current_user(request, session)
138 +
139 +
140 +@public_router.post("/users", dependencies=[Depends(bootstrap_guard)])
141 +def create_user_endpoint(
142 + body: UserIn,
143 + session: Session = Depends(get_session),
144 + user: User | None = Depends(optional_user),
145 +) -> dict:
146 + """First-admin bootstrap **only while the database has zero users**.
147 +
148 + Once any user exists this route requires an authenticated ADMIN, exactly like
149 + the rest of the admin surface. The bootstrap can therefore happen once.
150 + """
151 + if list_users(session):
152 + if user is None:
153 + raise HTTPException(
154 + status_code=401,
155 + detail="ورود لازم است.",
156 + headers={"WWW-Authenticate": "Bearer"},
157 + )
158 + _require(user, _ADMIN)
159 + role, actor = body.role, user.username
160 + else:
161 + role, actor = UserRole.ADMIN, "bootstrap"
162 try:
70 - user = create_user(
163 + created = create_user(
164 session,
165 username=body.username,
166 password=body.password,
167 role=role,
168 display_name=body.display_name,
76 - actor=body.actor,
169 + actor=actor,
170 )
171 except UserError as exc:
172 raise HTTPException(status_code=422, detail=str(exc)) from exc
173 session.commit()
81 - return {"username": user.username, "role": user.role.value}
174 + return {"username": created.username, "role": created.role.value}
175
176
177 @router.get("/users")
85 -def list_users_endpoint(actor: str = "", session: Session = Depends(get_session)) -> dict:
86 - _guard(session, actor, _ADMIN)
178 +def list_users_endpoint(
179 + session: Session = Depends(get_session), user: User = Depends(current_user)
180 +) -> dict:
181 + _require(user, _ADMIN)
182 return {
183 "users": [
184 {
@@ -97,52 +192,44 @@ def list_users_endpoint(actor: str = "", session: Session = Depends(get_session)
192 }
193
194
100 -class LoginIn(BaseModel):
101 - username: str = Field(min_length=1, max_length=64)
102 - password: str = Field(min_length=1, max_length=256)
103 -
104 -
105 -@router.post("/auth/login")
106 -def login(body: LoginIn, session: Session = Depends(get_session)) -> dict:
107 - try:
108 - user = authenticate(session, username=body.username, password=body.password)
109 - except UserError as exc:
110 - raise HTTPException(status_code=401, detail=str(exc)) from exc
111 - return {"username": user.username, "display_name": user.display_name, "role": user.role.value}
112 -
113 -
195 class RoleIn(BaseModel):
196 role: UserRole
116 - actor: str = Field(default="", max_length=64)
197
198
199 @router.post("/users/{username}/role")
120 -def set_role_endpoint(username: str, body: RoleIn, session: Session = Depends(get_session)) -> dict:
121 - _guard(session, body.actor, _ADMIN)
200 +def set_role_endpoint(
201 + username: str,
202 + body: RoleIn,
203 + session: Session = Depends(get_session),
204 + user: User = Depends(current_user),
205 +) -> dict:
206 + _require(user, _ADMIN)
207 try:
123 - user = set_role(session, username=username, role=body.role, actor=body.actor)
208 + target = set_role(session, username=username, role=body.role, actor=user.username)
209 except UserError as exc:
210 raise HTTPException(status_code=422, detail=str(exc)) from exc
211 session.commit()
127 - return {"username": user.username, "role": user.role.value}
212 + return {"username": target.username, "role": target.role.value}
213
214
215 class ActiveIn(BaseModel):
216 active: bool
132 - actor: str = Field(default="", max_length=64)
217
218
219 @router.post("/users/{username}/active")
220 def set_active_endpoint(
137 - username: str, body: ActiveIn, session: Session = Depends(get_session)
221 + username: str,
222 + body: ActiveIn,
223 + session: Session = Depends(get_session),
224 + user: User = Depends(current_user),
225 ) -> dict:
139 - _guard(session, body.actor, _ADMIN)
226 + _require(user, _ADMIN)
227 try:
141 - user = set_active(session, username=username, active=body.active, actor=body.actor)
228 + target = set_active(session, username=username, active=body.active, actor=user.username)
229 except UserError as exc:
230 raise HTTPException(status_code=422, detail=str(exc)) from exc
231 session.commit()
145 - return {"username": user.username, "active": user.active}
232 + return {"username": target.username, "active": target.active}
233
234
235 # --------------------------------------------------------------------- audit
@@ -176,31 +263,31 @@ def verify_audit(session: Session = Depends(get_session)) -> dict:
263 # --------------------------------------------------------------- reopen/lock
264 class ReopenRequestIn(BaseModel):
265 reason: str = Field(min_length=1, max_length=2000)
179 - actor: str = Field(default="", max_length=64)
266
267
268 @router.post("/years/{year_id}/reopen/request")
269 def reopen_request(
184 - year_id: int, body: ReopenRequestIn, session: Session = Depends(get_session)
270 + year_id: int,
271 + body: ReopenRequestIn,
272 + session: Session = Depends(get_session),
273 + user: User = Depends(current_user),
274 ) -> dict:
186 - _guard(session, body.actor, _REVIEW)
275 + _require(user, _REVIEW)
276 try:
188 - request = request_reopen(session, year_id, reason=body.reason, requested_by=body.actor)
277 + request = request_reopen(session, year_id, reason=body.reason, requested_by=user.username)
278 except ReopenError as exc:
279 raise HTTPException(status_code=422, detail=str(exc)) from exc
280 session.commit()
281 return {"request_id": request.id, "status": request.status}
282
283
195 -class ActorIn(BaseModel):
196 - actor: str = Field(default="", max_length=64)
197 -
198 -
284 @router.post("/reopen/{request_id}/approve")
200 -def reopen_approve(request_id: int, body: ActorIn, session: Session = Depends(get_session)) -> dict:
201 - _guard(session, body.actor, _REVIEW)
285 +def reopen_approve(
286 + request_id: int, session: Session = Depends(get_session), user: User = Depends(current_user)
287 +) -> dict:
288 + _require(user, _REVIEW)
289 try:
203 - request = approve_reopen(session, request_id, approved_by=body.actor)
290 + request = approve_reopen(session, request_id, approved_by=user.username)
291 except ReopenError as exc:
292 raise HTTPException(status_code=422, detail=str(exc)) from exc
293 session.commit()
@@ -208,10 +295,12 @@ def reopen_approve(request_id: int, body: ActorIn, session: Session = Depends(ge
295
296
297 @router.post("/years/{year_id}/reopen")
211 -def reopen(year_id: int, body: ActorIn, session: Session = Depends(get_session)) -> dict:
212 - _guard(session, body.actor, _REVIEW)
298 +def reopen(
299 + year_id: int, session: Session = Depends(get_session), user: User = Depends(current_user)
300 +) -> dict:
301 + _require(user, _REVIEW)
302 try:
214 - year = reopen_year(session, year_id, actor=body.actor)
303 + year = reopen_year(session, year_id, actor=user.username)
304 except ReopenError as exc:
305 raise HTTPException(status_code=422, detail=str(exc)) from exc
306 session.commit()
@@ -219,10 +308,12 @@ def reopen(year_id: int, body: ActorIn, session: Session = Depends(get_session))
308
309
310 @router.post("/years/{year_id}/lock")
222 -def lock(year_id: int, body: ActorIn, session: Session = Depends(get_session)) -> dict:
223 - _guard(session, body.actor, _REVIEW)
311 +def lock(
312 + year_id: int, session: Session = Depends(get_session), user: User = Depends(current_user)
313 +) -> dict:
314 + _require(user, _REVIEW)
315 try:
225 - year = lock_year(session, year_id, actor=body.actor)
316 + year = lock_year(session, year_id, actor=user.username)
317 except ReopenError as exc:
318 raise HTTPException(status_code=422, detail=str(exc)) from exc
319 session.commit()
@@ -248,14 +339,21 @@ def reopen_requests(year_id: int, session: Session = Depends(get_session)) -> di
339 # -------------------------------------------------------------------- backup
340 class BackupIn(BaseModel):
341 dest: str = Field(min_length=1, max_length=512)
251 - actor: str = Field(default="", max_length=64)
342
343
344 @router.post("/backup")
255 -def backup(body: BackupIn, session: Session = Depends(get_session)) -> dict:
256 - _guard(session, body.actor, _ADMIN)
345 +def backup(
346 + body: BackupIn, session: Session = Depends(get_session), user: User = Depends(current_user)
347 +) -> dict:
348 + _require(user, _ADMIN)
349 + settings = get_settings()
350 try:
258 - manifest = create_backup(session, body.dest, store_root=get_settings().source_store_root)
351 + manifest = create_backup(
352 + session,
353 + body.dest,
354 + store_root=settings.source_store_root,
355 + backup_root=settings.backup_root,
356 + )
357 except BackupError as exc:
358 raise HTTPException(status_code=422, detail=str(exc)) from exc
359 return {"dest": body.dest, "manifest": manifest}
@@ -263,13 +361,19 @@ def backup(body: BackupIn, session: Session = Depends(get_session)) -> dict:
361
362 class VerifyBackupIn(BaseModel):
363 dest: str = Field(min_length=1, max_length=512)
266 - actor: str = Field(default="", max_length=64)
364
365
366 @router.post("/backup/verify")
270 -def backup_verify(body: VerifyBackupIn, session: Session = Depends(get_session)) -> dict:
271 - _guard(session, body.actor, _ADMIN)
367 +def backup_verify(
368 + body: VerifyBackupIn,
369 + session: Session = Depends(get_session),
370 + user: User = Depends(current_user),
371 +) -> dict:
372 + _require(user, _ADMIN)
373 + settings = get_settings()
374 try:
273 - return verify_backup(body.dest)
375 + return verify_backup(
376 + body.dest, store_root=settings.source_store_root, backup_root=settings.backup_root
377 + )
378 except BackupError as exc:
379 raise HTTPException(status_code=422, detail=str(exc)) from exc
backend/src/aram_backend/auth.py new
+113
@@ -0,0 +1,113 @@
1 +"""The single authentication dependency for every HTTP surface (R1, booklet 2.1).
2 +
3 +``current_user`` resolves the ``Authorization: Bearer`` token against the
4 +server-side session table; there is no ``actor`` body field anywhere in the API.
5 +``LaunchGuard`` implements the desktop launcher's one-time local token: armed at
6 +startup, handed to the browser in the URL fragment, exchanged **once** for a grant
7 +kept in sessionStorage. Without that grant no other local process — not even one
8 +running as the same OS user — can call the desktop API. See ADR-030.
9 +"""
10 +
11 +from __future__ import annotations
12 +
13 +import hashlib
14 +import hmac
15 +import secrets
16 +
17 +from fastapi import Depends, HTTPException, Request, status
18 +from sqlalchemy.orm import Session
19 +
20 +from aram_backend.database import get_session
21 +from aram_backend.models import User
22 +from aram_backend.services.users import AuthenticationError, resolve_session
23 +
24 +LAUNCH_HEADER = "X-Aram-Launch"
25 +
26 +
27 +def _hash(value: str) -> str:
28 + return hashlib.sha256(value.encode("utf-8")).hexdigest()
29 +
30 +
31 +class LaunchGuard:
32 + """One-time desktop launch token -> single launch grant (process lifetime)."""
33 +
34 + def __init__(self) -> None:
35 + self._pending: str | None = None
36 + self._grant: str | None = None
37 +
38 + def arm(self) -> str:
39 + token = secrets.token_urlsafe(32)
40 + self._pending = _hash(token)
41 + self._grant = None
42 + return token
43 +
44 + @property
45 + def armed(self) -> bool:
46 + return self._pending is not None or self._grant is not None
47 +
48 + def exchange(self, token: str) -> str:
49 + if not self._pending or not hmac.compare_digest(_hash(token or ""), self._pending):
50 + raise AuthenticationError("توکن راه‌اندازی نامعتبر یا پیش‌تر مصرف شده است.")
51 + self._pending = None # single use: a replay cannot mint a second grant
52 + grant = secrets.token_urlsafe(32)
53 + self._grant = _hash(grant)
54 + return grant
55 +
56 + def check(self, grant: str | None) -> None:
57 + if not self._grant or not hmac.compare_digest(_hash(grant or ""), self._grant):
58 + raise AuthenticationError("دسترسی محلی مجاز نیست؛ برنامه را از راه‌انداز آرام باز کنید.")
59 +
60 +
61 +def launch_guard(request: Request) -> LaunchGuard | None:
62 + return getattr(request.app.state, "launch_guard", None)
63 +
64 +
65 +def require_launch(request: Request) -> None:
66 + """No-op in the web app; enforces the launcher grant in the desktop app."""
67 + guard = launch_guard(request)
68 + if guard is None:
69 + return
70 + try:
71 + guard.check(request.headers.get(LAUNCH_HEADER))
72 + except AuthenticationError as exc:
73 + raise HTTPException(status.HTTP_401_UNAUTHORIZED, str(exc)) from exc
74 +
75 +
76 +def bearer_token(request: Request) -> str | None:
77 + header = request.headers.get("Authorization", "")
78 + scheme, _, value = header.partition(" ")
79 + if scheme.lower() != "bearer" or not value.strip():
80 + return None
81 + return value.strip()
82 +
83 +
84 +def current_user(
85 + request: Request, session: Session = Depends(get_session)
86 +) -> User:
87 + """Resolve the caller from the server-side session; 401 when not logged in."""
88 + try:
89 + return resolve_session(session, bearer_token(request))
90 + except AuthenticationError as exc:
91 + raise HTTPException(
92 + status.HTTP_401_UNAUTHORIZED,
93 + str(exc),
94 + headers={"WWW-Authenticate": "Bearer"},
95 + ) from exc
96 +
97 +
98 +def optional_user(request: Request, session: Session = Depends(get_session)) -> User | None:
99 + """Same resolution, but returns None instead of raising.
100 +
101 + Used only by the first-admin bootstrap endpoint, which must stay reachable
102 + while the database has zero users and must require an ADMIN afterwards.
103 + """
104 + try:
105 + return resolve_session(session, bearer_token(request))
106 + except AuthenticationError:
107 + return None
108 +
109 +
110 +__all__ = [
111 + "LAUNCH_HEADER", "LaunchGuard", "bearer_token", "current_user",
112 + "launch_guard", "optional_user", "require_launch",
113 +]
backend/src/aram_backend/config.py
+3
@@ -8,6 +8,9 @@ class Settings(BaseSettings):
8 environment: str = "development"
9 database_url: str = "sqlite:///./aram.db"
10 source_store_root: str = "./source_store"
11 + # R1 (booklet 2.1): backups may only be written inside the local data folder.
12 + # Empty means "the parent of source_store_root" (the per-user data directory).
13 + backup_root: str = ""
14 model_config = SettingsConfigDict(env_prefix="ARAM_", env_file=".env")
15
16
backend/src/aram_backend/desktop.py
+44 -2
@@ -20,7 +20,10 @@ from fastapi import FastAPI
20 from fastapi.staticfiles import StaticFiles
21
22 from aram_backend import __version__
23 +from aram_backend.admin_api import launch_router
24 +from aram_backend.admin_api import public_router as auth_router
25 from aram_backend.admin_api import router as admin_router
26 +from aram_backend.auth import LaunchGuard
27 from aram_backend.config import get_settings
28 from aram_backend.database import Base, build_engine, ensure_triggers
29 from aram_backend.models import FiscalYearStatus, StatementType # noqa: F401 (register mappers)
@@ -65,7 +68,23 @@ def initialize_database(data_dir: Path) -> None:
68
69
70 def create_desktop_app() -> FastAPI:
68 - app = FastAPI(title="Aram Desktop", version=__version__)
71 + """Desktop app guarded by a one-time local launch token (R1, booklet 2.1).
72 +
73 + The launcher arms a random 256-bit token and hands it to the browser it opens
74 + in the URL *fragment* (never sent over HTTP, never logged). The page exchanges
75 + it once at /auth/launch for a grant kept in sessionStorage; every later call
76 + carries that grant in X-Aram-Launch. Another process on the same machine has
77 + neither the token nor the grant, so it cannot drive the API — not even the
78 + first-admin bootstrap.
79 + """
80 + app = FastAPI(
81 + title="Aram Desktop", version=__version__, docs_url=None, redoc_url=None, openapi_url=None
82 + )
83 + guard = LaunchGuard()
84 + app.state.launch_guard = guard
85 + app.state.launch_token = guard.arm()
86 + app.include_router(launch_router)
87 + app.include_router(auth_router)
88 app.include_router(statement_router)
89 app.include_router(admin_router)
90
@@ -79,6 +98,27 @@ def create_desktop_app() -> FastAPI:
98 return app
99
100
101 +def _open_browser_when_ready(port: int, launch_token: str, timeout: float = 30.0) -> None:
102 + """Open the workbench once the loopback port answers, token in the fragment."""
103 + import socket
104 + import threading
105 + import time
106 + import webbrowser
107 +
108 + def _wait_and_open() -> None:
109 + deadline = time.monotonic() + timeout
110 + url = f"http://127.0.0.1:{port}/#launch={launch_token}"
111 + while time.monotonic() < deadline:
112 + try:
113 + with socket.create_connection(("127.0.0.1", port), timeout=0.5):
114 + webbrowser.open(url)
115 + return
116 + except OSError:
117 + time.sleep(0.2)
118 +
119 + threading.Thread(target=_wait_and_open, daemon=True).start()
120 +
121 +
122 def main() -> None:
123 import uvicorn
124
@@ -94,8 +134,10 @@ def main() -> None:
134 reconfigure(db_url)
135
136 app = create_desktop_app()
137 + port = int(os.environ.get("ARAM_PORT", "8765"))
138 + _open_browser_when_ready(port, app.state.launch_token)
139 # Loopback only: the desktop app never exposes a network interface.
98 - uvicorn.run(app, host="127.0.0.1", port=int(os.environ.get("ARAM_PORT", "8765")), log_level="info")
140 + uvicorn.run(app, host="127.0.0.1", port=port, log_level="info")
141
142
143 if __name__ == "__main__":
backend/src/aram_backend/main.py
+26 -21
@@ -1,34 +1,37 @@
1 -from pathlib import Path
2 -
3 -from fastapi import FastAPI
4 -from fastapi.responses import HTMLResponse
5 -from fastapi.staticfiles import StaticFiles
1 +from fastapi import APIRouter, Depends, FastAPI
2
3 from aram_backend import __version__
4 +from aram_backend.admin_api import launch_router
5 +from aram_backend.admin_api import public_router as auth_router
6 from aram_backend.admin_api import router as admin_router
7 +from aram_backend.auth import current_user, require_launch
8 from aram_backend.config import get_settings
9 from aram_backend.models import FiscalYearStatus, StatementType
11 -from aram_backend.pilot_api import router as pilot_router
10 from aram_backend.schemas import EntityDescriptor, EnumCatalog, HealthResponse, SchemaCatalog
11 from aram_backend.statement_api import router as statement_router
12
13 settings = get_settings()
16 -app = FastAPI(title=settings.app_name, version=__version__)
17 -app.include_router(pilot_router)
14 +# R1 (booklet 2.1): the legacy in-memory pilot workbench is no longer part of the
15 +# app — neither its 17 routes, nor /pilot, nor the HTML once served at "/". The
16 +# interactive schema browsers are disabled too: every route except /health,
17 +# /auth/login, /auth/launch and the one-time bootstrap now requires a session.
18 +app = FastAPI(
19 + title=settings.app_name,
20 + version=__version__,
21 + docs_url=None,
22 + redoc_url=None,
23 + openapi_url=None,
24 +)
25 +app.include_router(launch_router)
26 +app.include_router(auth_router)
27 app.include_router(statement_router)
28 app.include_router(admin_router)
20 -app.mount(
21 - "/pilot",
22 - StaticFiles(directory=Path(__file__).parent / "static" / "pilot", html=True),
23 - name="pilot-workbench",
24 -)
29
26 -
27 -@app.get("/", include_in_schema=False)
28 -def root() -> HTMLResponse:
29 - """Serve the workbench directly at the root (no redirect, proxy-safe)."""
30 - page = Path(__file__).parent / "static" / "pilot" / "index.html"
31 - return HTMLResponse(page.read_text(encoding="utf-8"))
30 +schema_router = APIRouter(
31 + prefix="/api/v1/schema",
32 + tags=["schema"],
33 + dependencies=[Depends(require_launch), Depends(current_user)],
34 +)
35
36
37 @app.get("/api/v1/health", response_model=HealthResponse, tags=["system"])
@@ -36,7 +39,7 @@ def health() -> HealthResponse:
39 return HealthResponse(status="ok", service=settings.app_name, version=__version__)
40
41
39 -@app.get("/api/v1/schema/entities", response_model=SchemaCatalog, tags=["schema"])
42 +@schema_router.get("/entities", response_model=SchemaCatalog)
43 def schema_entities() -> SchemaCatalog:
44 return SchemaCatalog(entities=[
45 EntityDescriptor(name="Company", table="companies", purpose="Legal/reporting entity"),
@@ -51,10 +54,12 @@ def schema_entities() -> SchemaCatalog:
54 ])
55
56
54 -@app.get("/api/v1/schema/enums", response_model=EnumCatalog, tags=["schema"])
57 +@schema_router.get("/enums", response_model=EnumCatalog)
58 def schema_enums() -> EnumCatalog:
59 return EnumCatalog(
60 fiscal_year_statuses=[item.value for item in FiscalYearStatus],
61 statement_types=[item.value for item in StatementType],
62 )
63
64 +
65 +app.include_router(schema_router)
backend/src/aram_backend/models.py
+21
@@ -147,6 +147,27 @@ class User(TimestampMixin, Base):
147 password_hash: Mapped[str] = mapped_column(String(128))
148 salt: Mapped[str] = mapped_column(String(64))
149 active: Mapped[bool] = mapped_column(default=True)
150 + # R1 (booklet 2.1): PBKDF2 work factor stored per user so legacy hashes can be
151 + # verified and transparently rehashed to the current target on first login.
152 + password_rounds: Mapped[int] = mapped_column(Integer, default=600_000)
153 + failed_login_count: Mapped[int] = mapped_column(Integer, default=0)
154 + locked_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
155 +
156 +
157 +class AuthSession(TimestampMixin, Base):
158 + """Server-side login session (R1, booklet 2.1).
159 +
160 + Only the SHA-256 hash of the random 256-bit bearer token is stored; the
161 + plaintext token is returned to the client exactly once at login. Identity is
162 + derived from this table, never from a client-supplied ``actor`` string.
163 + """
164 +
165 + __tablename__ = "auth_sessions"
166 + id: Mapped[int] = mapped_column(primary_key=True)
167 + user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
168 + token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
169 + expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
170 + revoked: Mapped[bool] = mapped_column(default=False)
171
172
173 class SourceFile(TimestampMixin, Base):
backend/src/aram_backend/pilot_api.py
+10 -2
@@ -5,10 +5,11 @@ from __future__ import annotations
5 import re
6 from io import BytesIO
7
8 -from fastapi import APIRouter, File, HTTPException, Query, UploadFile
8 +from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
9 from fastapi.responses import StreamingResponse
10 from pydantic import BaseModel, Field
11
12 +from aram_backend.auth import current_user, require_launch
13 from aram_backend.pilot_demo import build_demo_workbook
14 from aram_backend.pilot_editing import (
15 DuplicateAccountError,
@@ -42,7 +43,14 @@ from aram_backend.pilot_store import (
43 store,
44 )
45
45 -router = APIRouter(prefix="/api/v1/pilot", tags=["pilot-workbench"])
46 +# R1 (booklet 2.1): the legacy pilot workbench is NOT mounted in the app any more
47 +# (see main.py). Should it ever be mounted again, it carries the same single
48 +# authentication dependency as every other surface — it can never be anonymous.
49 +router = APIRouter(
50 + prefix="/api/v1/pilot",
51 + tags=["pilot-workbench"],
52 + dependencies=[Depends(require_launch), Depends(current_user)],
53 +)
54
55 MAX_UPLOAD_BYTES = 25 * 1024 * 1024
56 XLSX_MEDIA_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
backend/src/aram_backend/services/backup.py
+49 -5
@@ -46,9 +46,45 @@ def _database_path(session: Session) -> Path:
46 return Path(database)
47
48
49 -def create_backup(session: Session, dest: str | Path, *, store_root: str | Path) -> dict[str, Any]:
49 +def allowed_backup_root(store_root: str | Path, backup_root: str | Path | None = None) -> Path:
50 + """The only folder tree a backup may be written to (R1, booklet 2.1).
51 +
52 + Defaults to the parent of the content-addressed source store, i.e. the local
53 + data directory. ``ARAM_BACKUP_ROOT`` narrows it further.
54 + """
55 + if backup_root:
56 + return Path(backup_root).expanduser().resolve()
57 + return Path(store_root).expanduser().resolve().parent
58 +
59 +
60 +def confine_dest(
61 + dest: str | Path, *, store_root: str | Path, backup_root: str | Path | None = None
62 +) -> Path:
63 + """Resolve ``dest`` and refuse anything outside the allowed data folder.
64 +
65 + Relative paths are taken inside the allowed root; ``..`` traversal, absolute
66 + paths elsewhere, and symlinks pointing out of the tree are all rejected
67 + *after* resolution, so no spelling can escape.
68 + """
69 + root = allowed_backup_root(store_root, backup_root)
70 + candidate = Path(dest).expanduser()
71 + if not candidate.is_absolute():
72 + candidate = root / candidate
73 + resolved = candidate.resolve()
74 + if resolved == root or not resolved.is_relative_to(root):
75 + raise BackupError("مسیر پشتیبان باید داخل پوشهٔ دادهٔ مجاز باشد.")
76 + return resolved
77 +
78 +
79 +def create_backup(
80 + session: Session,
81 + dest: str | Path,
82 + *,
83 + store_root: str | Path,
84 + backup_root: str | Path | None = None,
85 +) -> dict[str, Any]:
86 """Write a consistent backup directory and return its manifest."""
51 - dest = Path(dest)
87 + dest = confine_dest(dest, store_root=store_root, backup_root=backup_root)
88 if dest.exists() and any(dest.iterdir()):
89 raise BackupError(f"backup destination '{dest}' is not empty")
90 dest.mkdir(parents=True, exist_ok=True)
@@ -94,9 +130,17 @@ def create_backup(session: Session, dest: str | Path, *, store_root: str | Path)
130 return manifest
131
132
97 -def verify_backup(backup_dir: str | Path) -> dict[str, Any]:
133 +def verify_backup(
134 + backup_dir: str | Path,
135 + *,
136 + store_root: str | Path | None = None,
137 + backup_root: str | Path | None = None,
138 +) -> dict[str, Any]:
139 """Recompute every recorded hash and re-check the audit chain in the snapshot."""
99 - backup_dir = Path(backup_dir)
140 + if store_root is not None or backup_root:
141 + backup_dir = confine_dest(backup_dir, store_root=store_root or "", backup_root=backup_root)
142 + else:
143 + backup_dir = Path(backup_dir)
144 manifest_path = backup_dir / "manifest.json"
145 if not manifest_path.exists():
146 raise BackupError("manifest.json is missing")
@@ -140,4 +184,4 @@ def verify_backup(backup_dir: str | Path) -> dict[str, Any]:
184 }
185
186
143 -__all__ = ["BackupError", "create_backup", "verify_backup"]
187 +__all__ = ["BackupError", "allowed_backup_root", "confine_dest", "create_backup", "verify_backup"]
backend/src/aram_backend/services/users.py
+189 -52
@@ -1,9 +1,13 @@
1 -"""Local user management and role authorization (Phase 7, booklet §7/§12).
1 +"""Local identity: password hashing, login lockout, and server-side sessions.
2
3 -Offline desktop identity: usernames + roles, passwords hashed with
4 -PBKDF2-HMAC-SHA256 and a per-user random salt (stdlib only, no new dependency,
5 -no plaintext storage, no runtime network). Sensitive actions are gated by role
6 -and attributed to a username in the hash-chained audit log.
3 +R1 (booklet 2.1): identity is established **only** here. A login issues a random
4 +256-bit bearer token; the database stores its SHA-256 hash, never the token. No
5 +endpoint may accept a client-supplied ``actor`` string as proof of identity.
6 +
7 +Hashing: PBKDF2-HMAC-SHA256 with a per-user 128-bit salt. Argon2 is not available
8 +in the offline install (no new runtime dependency is permitted), so the work
9 +factor is 600,000 iterations — see ADR-030. Legacy 200,000-round hashes are still
10 +verifiable and are transparently rehashed on the first successful login.
11 """
12
13 from __future__ import annotations
@@ -11,29 +15,64 @@ from __future__ import annotations
15 import hashlib
16 import hmac
17 import secrets
18 +from datetime import UTC, datetime, timedelta
19
15 -from sqlalchemy import select
20 +from sqlalchemy import select, update
21 from sqlalchemy.orm import Session
22
18 -from aram_backend.models import User, UserRole
23 +from aram_backend.models import AuthSession, User, UserRole
24 from aram_backend.services.audit import append_entry
25
21 -_PBKDF2_ROUNDS = 200_000
26 +# --- conservative parameters fixed by ADR-030 (booklet 2.1, R1) --------------
27 +PBKDF2_ROUNDS = 600_000
28 +LEGACY_PBKDF2_ROUNDS = 200_000
29 +SESSION_TTL = timedelta(hours=8)
30 +MAX_FAILED_LOGINS = 5
31 +LOCKOUT_DURATION = timedelta(minutes=15)
32 +MIN_PASSWORD_LENGTH = 8
33 +TOKEN_BYTES = 32 # 256 bits
34 +
35 +_GENERIC_LOGIN_ERROR = "نام کاربری یا گذرواژه نادرست است."
36 +# Fixed salt used to burn the same work factor when the username is unknown, so
37 +# response time does not reveal whether an account exists.
38 +_TIMING_SALT = "0" * 32
39
40
41 class UserError(ValueError):
25 - """Raised when a user operation cannot be performed safely."""
42 + """Raised for invalid user input or failed authentication."""
43
44
45 class AuthorizationError(PermissionError):
29 - """Raised when an actor lacks the role required for an action."""
46 + """Raised when an authenticated user lacks the required role."""
47
48
32 -def _hash_password(password: str, salt: str) -> str:
33 - digest = hashlib.pbkdf2_hmac(
34 - "sha256", password.encode("utf-8"), bytes.fromhex(salt), _PBKDF2_ROUNDS
35 - )
36 - return digest.hex()
49 +class AuthenticationError(PermissionError):
50 + """Raised when a bearer token is missing, unknown, expired, or revoked."""
51 +
52 +
53 +def _aware(value: datetime) -> datetime:
54 + """SQLite returns naive datetimes; treat stored times as UTC."""
55 + return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
56 +
57 +
58 +def hash_password(password: str, salt: str, rounds: int = PBKDF2_ROUNDS) -> str:
59 + """PBKDF2-HMAC-SHA256. ``salt`` is hex, decoded exactly as in Phase 7 so that
60 + pre-R1 hashes stay verifiable and are upgraded on first login."""
61 + return hashlib.pbkdf2_hmac(
62 + "sha256", password.encode("utf-8"), bytes.fromhex(salt), rounds
63 + ).hex()
64 +
65 +
66 +def token_hash(token: str) -> str:
67 + return hashlib.sha256(token.encode("utf-8")).hexdigest()
68 +
69 +
70 +def _find(session: Session, username: str) -> User | None:
71 + return session.scalar(select(User).where(User.username == username))
72 +
73 +
74 +def list_users(session: Session) -> list[User]:
75 + return list(session.scalars(select(User).order_by(User.username)).all())
76
77
78 def create_user(
@@ -45,21 +84,23 @@ def create_user(
84 display_name: str = "",
85 actor: str = "",
86 ) -> User:
87 + """Create a user. ``actor`` is the *authenticated* username, for the audit log
88 + only — it is never accepted from a request body."""
89 username = username.strip()
49 - if not username:
50 - raise UserError("username is required")
51 - if len(password) < 8:
52 - raise UserError("password must be at least 8 characters")
53 - existing = session.scalar(select(User).where(User.username == username))
54 - if existing is not None:
55 - raise UserError(f"username '{username}' already exists")
90 + if not username or len(username) > 64:
91 + raise UserError("نام کاربری باید بین ۱ و ۴ نویسه باشد.")
92 + if len(password) < MIN_PASSWORD_LENGTH:
93 + raise UserError(f"گذرواژه باید دست‌کم {MIN_PASSWORD_LENGTH} نویسه باشد.")
94 + if _find(session, username) is not None:
95 + raise UserError("این نام کاربری پیش‌تر ثبت شده است.")
96 salt = secrets.token_hex(16)
97 user = User(
98 username=username,
99 display_name=display_name or username,
100 role=role,
101 + password_hash=hash_password(password, salt),
102 salt=salt,
62 - password_hash=_hash_password(password, salt),
103 + password_rounds=PBKDF2_ROUNDS,
104 )
105 session.add(user)
106 session.flush()
@@ -73,23 +114,119 @@ def create_user(
114
115
116 def authenticate(session: Session, *, username: str, password: str) -> User:
76 - user = session.scalar(select(User).where(User.username == username.strip()))
77 - if user is None or not user.active:
78 - raise UserError("invalid credentials")
79 - candidate = _hash_password(password, user.salt)
117 + """Verify credentials, enforcing lockout; return the user or raise UserError."""
118 + now = datetime.now(UTC)
119 + user = _find(session, username.strip())
120 + if user is None:
121 + hash_password(password, _TIMING_SALT)
122 + raise UserError(_GENERIC_LOGIN_ERROR)
123 + if user.locked_until is not None:
124 + if _aware(user.locked_until) > now:
125 + raise UserError("حساب به‌دلیل تلاش‌های ناموفق موقتاً قفل است؛ بعداً دوباره تلاش کنید.")
126 + user.locked_until = None
127 + user.failed_login_count = 0
128 + if not user.active:
129 + raise UserError("حساب کاربری غیرفعال است.")
130 +
131 + rounds = user.password_rounds or LEGACY_PBKDF2_ROUNDS
132 + candidate = hash_password(password, user.salt, rounds)
133 if not hmac.compare_digest(candidate, user.password_hash):
81 - raise UserError("invalid credentials")
134 + user.failed_login_count += 1
135 + if user.failed_login_count >= MAX_FAILED_LOGINS:
136 + user.locked_until = now + LOCKOUT_DURATION
137 + append_entry(
138 + session,
139 + action="auth.locked",
140 + actor=user.username,
141 + payload={"failed_attempts": user.failed_login_count},
142 + )
143 + session.commit()
144 + raise UserError(_GENERIC_LOGIN_ERROR)
145 +
146 + user.failed_login_count = 0
147 + user.locked_until = None
148 + if rounds < PBKDF2_ROUNDS:
149 + # Transparent upgrade of a legacy hash while we still hold the plaintext.
150 + user.salt = secrets.token_hex(16)
151 + user.password_hash = hash_password(password, user.salt)
152 + user.password_rounds = PBKDF2_ROUNDS
153 + append_entry(
154 + session,
155 + action="auth.rehash",
156 + actor=user.username,
157 + payload={"rounds": PBKDF2_ROUNDS},
158 + )
159 + session.commit()
160 return user
161
162
85 -def list_users(session: Session) -> list[User]:
86 - return list(session.scalars(select(User).order_by(User.username)).all())
163 +def issue_session(session: Session, user: User) -> str:
164 + """Create a server-side session and return the plaintext token exactly once."""
165 + token = secrets.token_urlsafe(TOKEN_BYTES)
166 + session.add(
167 + AuthSession(
168 + user_id=user.id,
169 + token_hash=token_hash(token),
170 + expires_at=datetime.now(UTC) + SESSION_TTL,
171 + )
172 + )
173 + append_entry(session, action="auth.login", actor=user.username, payload={})
174 + session.commit()
175 + return token
176 +
177 +
178 +def resolve_session(session: Session, token: str | None) -> User:
179 + """Map a bearer token to its active user, or raise AuthenticationError."""
180 + if not token:
181 + raise AuthenticationError("ورود لازم است.")
182 + row = session.scalar(select(AuthSession).where(AuthSession.token_hash == token_hash(token)))
183 + if row is None or row.revoked or _aware(row.expires_at) <= datetime.now(UTC):
184 + raise AuthenticationError("نشست نامعتبر یا منقضی است؛ دوباره وارد شوید.")
185 + user = session.get(User, row.user_id)
186 + if user is None or not user.active:
187 + raise AuthenticationError("نشست نامعتبر یا منقضی است؛ دوباره وارد شوید.")
188 + return user
189 +
190 +
191 +def revoke_session(session: Session, token: str | None) -> bool:
192 + """Log out: revoke the presented session. Returns True when one was revoked."""
193 + if not token:
194 + return False
195 + row = session.scalar(select(AuthSession).where(AuthSession.token_hash == token_hash(token)))
196 + if row is None or row.revoked:
197 + return False
198 + row.revoked = True
199 + user = session.get(User, row.user_id)
200 + append_entry(session, action="auth.logout", actor=user.username if user else "", payload={})
201 + session.commit()
202 + return True
203 +
204 +
205 +def revoke_user_sessions(session: Session, user_id: int) -> None:
206 + """Kill every session of a user (used when an account is deactivated)."""
207 + session.execute(update(AuthSession).where(AuthSession.user_id == user_id).values(revoked=True))
208 + session.flush()
209 +
210 +
211 +def ensure_role(user: User, allowed: set[UserRole]) -> None:
212 + """Role gate for an already-authenticated user (identity comes from the session)."""
213 + if user.role not in allowed:
214 + raise AuthorizationError("نقش شما اجازهٔ این اقدام را ندارد.")
215 +
216 +
217 +def require_role(session: Session, *, username: str, allowed: set[UserRole]) -> User:
218 + """Service-level role gate by username (used by domain services, not by HTTP)."""
219 + user = _find(session, username)
220 + if user is None or not user.active:
221 + raise AuthorizationError("کاربر شناخته نشد یا غیرفعال است.")
222 + ensure_role(user, allowed)
223 + return user
224
225
226 def set_role(session: Session, *, username: str, role: UserRole, actor: str = "") -> User:
90 - user = session.scalar(select(User).where(User.username == username))
227 + user = _find(session, username)
228 if user is None:
92 - raise UserError(f"user '{username}' not found")
229 + raise UserError("کاربر یافت نشد.")
230 user.role = role
231 session.flush()
232 append_entry(
@@ -102,11 +239,13 @@ def set_role(session: Session, *, username: str, role: UserRole, actor: str = ""
239
240
241 def set_active(session: Session, *, username: str, active: bool, actor: str = "") -> User:
105 - user = session.scalar(select(User).where(User.username == username))
242 + user = _find(session, username)
243 if user is None:
107 - raise UserError(f"user '{username}' not found")
244 + raise UserError("کاربر یافت نشد.")
245 user.active = active
246 session.flush()
247 + if not active:
248 + revoke_user_sessions(session, user.id)
249 append_entry(
250 session,
251 action="user.set_active",
@@ -116,27 +255,25 @@ def set_active(session: Session, *, username: str, active: bool, actor: str = ""
255 return user
256
257
119 -def require_role(session: Session, *, username: str, allowed: set[UserRole]) -> User:
120 - """Return the active user iff their role is in ``allowed``; else raise.
121 -
122 - An empty/unknown username is rejected. This is the single authorization gate
123 - for sensitive actions (approve, reopen, lock, user management, backup).
124 - """
125 - user = session.scalar(select(User).where(User.username == username.strip()))
126 - if user is None or not user.active:
127 - raise AuthorizationError("actor is not an active user")
128 - if user.role not in allowed:
129 - raise AuthorizationError(f"role '{user.role.value}' is not permitted for this action")
130 - return user
131 -
132 -
258 __all__ = [
134 - "UserError",
259 + "AuthenticationError",
260 "AuthorizationError",
136 - "create_user",
261 + "LOCKOUT_DURATION",
262 + "MAX_FAILED_LOGINS",
263 + "PBKDF2_ROUNDS",
264 + "SESSION_TTL",
265 + "UserError",
266 "authenticate",
267 + "create_user",
268 + "ensure_role",
269 + "hash_password",
270 + "issue_session",
271 "list_users",
139 - "set_role",
140 - "set_active",
272 "require_role",
273 + "resolve_session",
274 + "revoke_session",
275 + "revoke_user_sessions",
276 + "set_active",
277 + "set_role",
278 + "token_hash",
279 ]
backend/src/aram_backend/statement_api.py
+21 -16
@@ -13,6 +13,7 @@ from pydantic import BaseModel, Field
13 from sqlalchemy import func, select
14 from sqlalchemy.orm import Session
15
16 +from aram_backend.auth import current_user, require_launch
17 from aram_backend.config import get_settings
18 from aram_backend.database import get_session
19 from aram_backend.domain.controls import BalanceRow, run_controls
@@ -27,6 +28,7 @@ from aram_backend.models import (
28 NoteDefinition,
29 NoteRow,
30 StatementLine,
31 + User,
32 UserRole,
33 )
34 from aram_backend.services.approval import ApprovalError, approve_year
@@ -55,9 +57,14 @@ from aram_backend.services.statement_export import (
57 export_statements_json_bytes,
58 export_statements_workbook,
59 )
58 -from aram_backend.services.users import AuthorizationError, list_users, require_role
60 +from aram_backend.services.users import AuthorizationError, ensure_role
61
60 -router = APIRouter(prefix="/api/v1", tags=["statements"])
62 +# R1 (booklet 2.1): every statement route requires a server-side session; reads
63 +# included. The only unauthenticated routes in the app are /health, /auth/login,
64 +# /auth/launch and the one-time first-admin bootstrap.
65 +router = APIRouter(
66 + prefix="/api/v1", tags=["statements"], dependencies=[Depends(require_launch), Depends(current_user)]
67 +)
68
69
70 class CompanyIn(BaseModel):
@@ -424,23 +431,21 @@ def carry_forward(
431 return {"notes_created": result.notes_created, "mappings_created": result.mappings_created}
432
433
427 -class ApproveIn(BaseModel):
428 - actor: str = Field(default="", max_length=128)
429 -
430 -
434 @router.post("/years/{year_id}/approve")
432 -def approve(year_id: int, body: ApproveIn, session: Session = Depends(get_session)) -> dict:
435 +def approve(
436 + year_id: int, session: Session = Depends(get_session), user: User = Depends(current_user)
437 +) -> dict:
438 + # R1 (booklet 2.1): approval always requires an authenticated reviewer/admin.
439 + # The former "no users yet -> allowed" shortcut is removed: with zero users
440 + # there is no identity, so approval is impossible (401 from current_user).
441 + # The role gate runs before the existence check so it can never be skipped.
442 + try:
443 + ensure_role(user, {UserRole.ADMIN, UserRole.REVIEWER})
444 + except AuthorizationError as exc:
445 + raise HTTPException(status_code=403, detail=str(exc)) from exc
446 _year_or_404(session, year_id)
434 - # Phase 7 role gate: once local users exist, only a reviewer/admin may approve
435 - # (consistent with /lock and /reopen). With no users yet (bootstrap/dev) the
436 - # action is allowed; the C-01..C-04 ERROR gate below always applies regardless.
437 - if list_users(session):
438 - try:
439 - require_role(session, username=body.actor, allowed={UserRole.ADMIN, UserRole.REVIEWER})
440 - except AuthorizationError as exc:
441 - raise HTTPException(status_code=403, detail=str(exc)) from exc
447 try:
443 - result = approve_year(session, year_id, actor=body.actor)
448 + result = approve_year(session, year_id, actor=user.username)
449 except ApprovalError as exc:
450 raise HTTPException(status_code=422, detail=str(exc)) from exc
451 if not result.approved:
backend/tests/conftest.py
+102 -1
@@ -26,7 +26,12 @@ def client() -> TestClient:
26
27 @pytest.fixture
28 def api_client(tmp_path, monkeypatch) -> TestClient:
29 - """DB-backed API client with an isolated SQLite DB + source store."""
29 + """DB-backed API client, isolated DB + store, **logged in as an ADMIN**.
30 +
31 + R1 (booklet 2.1): every route needs a session, so the default fixture performs
32 + the one-time first-admin bootstrap and a real login. Use ``anon_client`` for
33 + unauthenticated behaviour and ``make_user`` for other roles.
34 + """
35 engine = build_engine(f"sqlite:///{tmp_path / 'api.db'}")
36 Base.metadata.create_all(engine)
37 ensure_triggers(engine)
@@ -41,8 +46,104 @@ def api_client(tmp_path, monkeypatch) -> TestClient:
46 "aram_backend.statement_api.get_settings",
47 lambda: Settings(source_store_root=str(tmp_path / "store")),
48 )
49 + monkeypatch.setattr(
50 + "aram_backend.admin_api.get_settings",
51 + lambda: Settings(source_store_root=str(tmp_path / "store")),
52 + )
53 with TestClient(app) as test_client:
54 + bootstrap = test_client.post(
55 + "/api/v1/users", json={"username": "root", "password": "supersecret"}
56 + )
57 + assert bootstrap.status_code == 200, bootstrap.text
58 + login(test_client, "root", "supersecret")
59 yield test_client
60 app.dependency_overrides.clear()
61 Base.metadata.drop_all(engine)
62 engine.dispose()
63 +
64 +
65 +@pytest.fixture
66 +def anon_client(tmp_path, monkeypatch) -> TestClient:
67 + """Same isolated app as ``api_client`` but with **no** session (R1 401 tests)."""
68 + engine = build_engine(f"sqlite:///{tmp_path / 'anon.db'}")
69 + Base.metadata.create_all(engine)
70 + ensure_triggers(engine)
71 + factory = sessionmaker(bind=engine, expire_on_commit=False)
72 +
73 + def override_session():
74 + with factory() as db:
75 + yield db
76 +
77 + app.dependency_overrides[get_session] = override_session
78 + monkeypatch.setattr(
79 + "aram_backend.statement_api.get_settings",
80 + lambda: Settings(source_store_root=str(tmp_path / "store")),
81 + )
82 + monkeypatch.setattr(
83 + "aram_backend.admin_api.get_settings",
84 + lambda: Settings(source_store_root=str(tmp_path / "store")),
85 + )
86 + with TestClient(app) as test_client:
87 + yield test_client
88 + app.dependency_overrides.clear()
89 + Base.metadata.drop_all(engine)
90 + engine.dispose()
91 +
92 +
93 +def login(client: TestClient, username: str, password: str) -> str:
94 + """Log in and return the bearer token (also sets the client's auth header)."""
95 + response = client.post(
96 + "/api/v1/auth/login", json={"username": username, "password": password}
97 + )
98 + assert response.status_code == 200, response.text
99 + token = response.json()["token"]
100 + client.headers.update({"Authorization": f"Bearer {token}"})
101 + return token
102 +
103 +
104 +def make_user(client: TestClient, username: str, role: str, password: str = "supersecret") -> str:
105 + """Create a user as the authenticated admin and return a logged-in token."""
106 + response = client.post(
107 + "/api/v1/users",
108 + json={"username": username, "password": password, "role": role},
109 + )
110 + assert response.status_code == 200, response.text
111 + admin_auth = client.headers.get("Authorization")
112 + token = login(client, username, password)
113 + if admin_auth:
114 + client.headers.update({"Authorization": admin_auth})
115 + return token
116 +
117 +
118 +@pytest.fixture
119 +def pilot_client(tmp_path) -> TestClient:
120 + """The legacy pilot router, mounted **only in this test app** and authenticated.
121 +
122 + R1 (booklet 2.1) removed the pilot workbench from the shipped app; these tests
123 + keep covering its behaviour and prove it can never be anonymous if mounted.
124 + """
125 + from fastapi import FastAPI
126 +
127 + from aram_backend.admin_api import public_router
128 + from aram_backend.pilot_api import router as pilot_router
129 +
130 + engine = build_engine(f"sqlite:///{tmp_path / 'pilot.db'}")
131 + Base.metadata.create_all(engine)
132 + ensure_triggers(engine)
133 + factory = sessionmaker(bind=engine, expire_on_commit=False)
134 +
135 + def override_session():
136 + with factory() as db:
137 + yield db
138 +
139 + pilot_app = FastAPI()
140 + pilot_app.include_router(public_router)
141 + pilot_app.include_router(pilot_router)
142 + pilot_app.dependency_overrides[get_session] = override_session
143 + with TestClient(pilot_app) as test_client:
144 + test_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
145 + login(test_client, "root", "supersecret")
146 + yield test_client
147 + pilot_app.dependency_overrides.clear()
148 + Base.metadata.drop_all(engine)
149 + engine.dispose()
backend/tests/test_api.py
+10 -2
@@ -4,15 +4,23 @@ def test_health(client):
4 assert response.json()["status"] == "ok"
5
6
7 -def test_read_only_schema_catalog(client):
7 +def test_read_only_schema_catalog(api_client):
8 + client = api_client
9 entities = client.get("/api/v1/schema/entities")
10 assert entities.status_code == 200
11 assert len(entities.json()["entities"]) == 9
12 assert client.post("/api/v1/schema/entities").status_code == 405
13
14
14 -def test_enum_catalog(client):
15 +def test_enum_catalog(api_client):
16 + client = api_client
17 response = client.get("/api/v1/schema/enums")
18 assert response.json()["fiscal_year_statuses"] == ["Draft", "Approved", "Locked"]
19 assert response.json()["statement_types"] == ["BS", "IS", "CF", "EQ"]
20
21 +
22 +
23 +def test_schema_requires_a_session(anon_client):
24 + """R1: reads are not public any more."""
25 + assert anon_client.get("/api/v1/schema/entities").status_code == 401
26 + assert anon_client.get("/api/v1/schema/enums").status_code == 401
backend/tests/test_auth_r1.py new
+428
@@ -0,0 +1,428 @@
1 +"""R1 (booklet 2.1) — real authentication: acceptance evidence.
2 +
3 +Every test here maps to a line of the R1 acceptance table in the PR report:
4 +forged actor, missing token, wrong role, hashed-only storage, expiry, logout,
5 +lockout, PBKDF2 work factor, backup confinement, and the desktop one-time token.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +import sqlite3
11 +from datetime import UTC, datetime, timedelta
12 +
13 +import pytest
14 +from fastapi.testclient import TestClient
15 +from pydantic import BaseModel
16 +
17 +from aram_backend.auth import LaunchGuard
18 +from aram_backend.database import get_session
19 +from aram_backend.desktop import create_desktop_app, initialize_database
20 +from aram_backend.main import app as main_app
21 +from aram_backend.models import AuthSession, User, UserRole
22 +from aram_backend.services.backup import BackupError, confine_dest, create_backup
23 +from aram_backend.services.users import (
24 + MAX_FAILED_LOGINS,
25 + PBKDF2_ROUNDS,
26 + AuthenticationError,
27 + UserError,
28 + authenticate,
29 + create_user,
30 + hash_password,
31 + issue_session,
32 + resolve_session,
33 + set_active,
34 + token_hash,
35 +)
36 +from conftest import login, make_user
37 +
38 +# Routes that must work before a session exists — and nothing else.
39 +PUBLIC = {("GET", "/api/v1/health"), ("POST", "/api/v1/auth/login"), ("POST", "/api/v1/auth/launch")}
40 +
41 +
42 +def _all_routes(routes):
43 + """Flatten included routers (this FastAPI wraps them in _IncludedRouter)."""
44 + from fastapi.routing import APIRoute
45 +
46 + for route in routes:
47 + if isinstance(route, APIRoute):
48 + yield route
49 + elif hasattr(route, "original_router"):
50 + yield from _all_routes(route.original_router.routes)
51 + elif hasattr(route, "routes"):
52 + yield from _all_routes(route.routes)
53 +
54 +
55 +def _db(api_client):
56 + """Borrow a session from the app's overridden dependency (test-only)."""
57 + override = api_client.app.dependency_overrides[get_session]
58 + generator = override()
59 + return next(generator), generator
60 +
61 +
62 +# ------------------------------------------------------- forged actor / 401
63 +def test_forged_actor_admin_without_a_session_is_rejected(anon_client):
64 + """The headline R1 attack: claim to be admin in the body, send no token."""
65 + year = anon_client.post("/api/v1/years/1/approve", json={"actor": "admin"})
66 + assert year.status_code == 401
67 + assert anon_client.post("/api/v1/years/1/lock", json={"actor": "admin"}).status_code == 401
68 + assert anon_client.post("/api/v1/backup", json={"dest": "b", "actor": "admin"}).status_code == 401
69 + assert anon_client.get("/api/v1/users?actor=admin").status_code == 401
70 +
71 +
72 +def test_forged_actor_admin_with_a_preparer_session_is_forbidden(api_client):
73 + """A real but low-privileged session cannot escalate by naming an admin."""
74 + token = make_user(api_client, "prep", "preparer")
75 + headers = {"Authorization": f"Bearer {token}"}
76 + r = api_client.post("/api/v1/years/1/approve", json={"actor": "root"}, headers=headers)
77 + assert r.status_code == 403
78 + r = api_client.post("/api/v1/backup", json={"dest": "b", "actor": "root"}, headers=headers)
79 + assert r.status_code == 403
80 + r = api_client.get("/api/v1/users", headers=headers)
81 + assert r.status_code == 403
82 +
83 +
84 +def test_every_route_except_the_public_three_requires_a_session(api_client):
85 + """No endpoint was forgotten: enumerate the real app and probe each one."""
86 + api_client.headers.pop("Authorization", None)
87 + checked = 0
88 + for route in _all_routes(main_app.routes):
89 + path = route.path
90 + if not path.startswith("/api/"):
91 + continue
92 + for method in sorted(route.methods - {"HEAD", "OPTIONS"}):
93 + if (method, path) in PUBLIC:
94 + continue
95 + url = path
96 + for name in ("year_id", "note_id", "mapping_id", "line_id", "request_id", "username"):
97 + url = url.replace("{" + name + "}", "1")
98 + response = api_client.request(method, url, json={})
99 + assert response.status_code == 401, f"{method} {path} -> {response.status_code}"
100 + checked += 1
101 + assert checked >= 30 # the whole statement + admin surface, not a sample
102 +
103 +
104 +def test_reads_require_login_too(anon_client):
105 + assert anon_client.get("/api/v1/audit").status_code == 401
106 + assert anon_client.get("/api/v1/audit/verify").status_code == 401
107 + assert anon_client.get("/api/v1/schema/entities").status_code == 401
108 +
109 +
110 +def test_no_request_model_still_accepts_an_actor_field():
111 + """Identity must not be expressible in any request body."""
112 + from aram_backend import admin_api, statement_api
113 +
114 + for module in (admin_api, statement_api):
115 + for name in dir(module):
116 + obj = getattr(module, name)
117 + if isinstance(obj, type) and issubclass(obj, BaseModel):
118 + assert "actor" not in obj.model_fields, (
119 + f"{module.__name__}.{name} still has an actor field"
120 + )
121 +
122 +
123 +# ------------------------------------------------------------- token storage
124 +def test_login_returns_a_256_bit_token_and_stores_only_its_hash(api_client):
125 + r = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "supersecret"})
126 + token = r.json()["token"]
127 + assert len(token) >= 43 # 32 random bytes, base64url
128 + db, generator = _db(api_client)
129 + try:
130 + rows = db.query(AuthSession).all()
131 + assert rows
132 + assert all(row.token_hash == token_hash(token) or len(row.token_hash) == 64 for row in rows)
133 + assert token not in {row.token_hash for row in rows}
134 + assert db.query(AuthSession).filter_by(token_hash=token_hash(token)).one()
135 + finally:
136 + generator.close()
137 +
138 +
139 +def test_two_logins_issue_different_tokens(api_client):
140 + a = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "supersecret"})
141 + b = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "supersecret"})
142 + assert a.json()["token"] != b.json()["token"]
143 +
144 +
145 +def test_expired_session_is_refused(api_client):
146 + token = api_client.post(
147 + "/api/v1/auth/login", json={"username": "root", "password": "supersecret"}
148 + ).json()["token"]
149 + db, generator = _db(api_client)
150 + try:
151 + row = db.query(AuthSession).filter_by(token_hash=token_hash(token)).one()
152 + row.expires_at = datetime.now(UTC) - timedelta(seconds=1)
153 + db.commit()
154 + finally:
155 + generator.close()
156 + r = api_client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"})
157 + assert r.status_code == 401
158 +
159 +
160 +def test_logout_revokes_the_session(api_client):
161 + token = login(api_client, "root", "supersecret")
162 + assert api_client.get("/api/v1/auth/me").status_code == 200
163 + assert api_client.post("/api/v1/auth/logout").status_code == 200
164 + r = api_client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"})
165 + assert r.status_code == 401
166 +
167 +
168 +def test_deactivating_a_user_kills_their_sessions(api_client):
169 + token = make_user(api_client, "prep", "preparer")
170 + assert api_client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}).status_code == 200
171 + api_client.post("/api/v1/users/prep/active", json={"active": False})
172 + assert api_client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}).status_code == 401
173 +
174 +
175 +def test_garbage_and_missing_tokens_are_401(api_client):
176 + assert api_client.get("/api/v1/auth/me", headers={"Authorization": "Bearer nope"}).status_code == 401
177 + assert api_client.get("/api/v1/auth/me", headers={"Authorization": "Basic abc"}).status_code == 401
178 + api_client.headers.pop("Authorization", None)
179 + assert api_client.get("/api/v1/auth/me").status_code == 401
180 +
181 +
182 +# ------------------------------------------------------------------- lockout
183 +def test_repeated_failures_lock_the_account(api_client):
184 + for _ in range(MAX_FAILED_LOGINS):
185 + r = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "wrong"})
186 + assert r.status_code == 401
187 + # Even the CORRECT password is refused while the account is locked.
188 + r = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "supersecret"})
189 + assert r.status_code == 401
190 + assert "قفل" in r.json()["detail"]
191 +
192 +
193 +def test_lock_expires_and_the_counter_resets(api_client):
194 + for _ in range(MAX_FAILED_LOGINS):
195 + api_client.post("/api/v1/auth/login", json={"username": "root", "password": "wrong"})
196 + db, generator = _db(api_client)
197 + try:
198 + user = db.query(User).filter_by(username="root").one()
199 + assert user.locked_until is not None
200 + user.locked_until = datetime.now(UTC) - timedelta(seconds=1)
201 + db.commit()
202 + finally:
203 + generator.close()
204 + assert login(api_client, "root", "supersecret")
205 + db, generator = _db(api_client)
206 + try:
207 + user = db.query(User).filter_by(username="root").one()
208 + assert user.failed_login_count == 0
209 + assert user.locked_until is None
210 + finally:
211 + generator.close()
212 +
213 +
214 +def test_unknown_username_does_not_reveal_itself(api_client):
215 + known = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "wrong"})
216 + unknown = api_client.post("/api/v1/auth/login", json={"username": "ghost", "password": "wrong"})
217 + assert known.status_code == unknown.status_code == 401
218 + assert known.json()["detail"] == unknown.json()["detail"]
219 +
220 +
221 +# ------------------------------------------------------------- password work
222 +def test_pbkdf2_work_factor_is_at_least_600k(session):
223 + assert PBKDF2_ROUNDS >= 600_000
224 + user = create_user(session, username="alice", password="supersecret")
225 + session.commit()
226 + assert user.password_rounds >= 600_000
227 + assert user.password_hash == hash_password("supersecret", user.salt, PBKDF2_ROUNDS)
228 + assert user.password_hash != "supersecret"
229 +
230 +
231 +def test_legacy_200k_hash_is_upgraded_on_first_login(session):
232 + """Pre-R1 accounts keep working and are silently rehashed to 600k."""
233 + user = create_user(session, username="legacy", password="supersecret")
234 + user.password_rounds = 200_000
235 + user.password_hash = hash_password("supersecret", user.salt, 200_000)
236 + session.commit()
237 + assert authenticate(session, username="legacy", password="supersecret").username == "legacy"
238 + assert user.password_rounds == PBKDF2_ROUNDS
239 + assert user.password_hash == hash_password("supersecret", user.salt, PBKDF2_ROUNDS)
240 +
241 +
242 +def test_short_password_still_refused(session):
243 + with pytest.raises(UserError):
244 + create_user(session, username="dave", password="short")
245 +
246 +
247 +# --------------------------------------------------------- session lifecycle
248 +def test_issue_and_resolve_round_trip(session):
249 + user = create_user(session, username="alice", password="supersecret")
250 + session.commit()
251 + token = issue_session(session, user)
252 + assert resolve_session(session, token).username == "alice"
253 + with pytest.raises(AuthenticationError):
254 + resolve_session(session, None)
255 + with pytest.raises(AuthenticationError):
256 + resolve_session(session, "not-a-token")
257 +
258 +
259 +def test_inactive_user_cannot_resolve(session):
260 + user = create_user(session, username="alice", password="supersecret")
261 + session.commit()
262 + token = issue_session(session, user)
263 + set_active(session, username="alice", active=False)
264 + session.commit()
265 + with pytest.raises(AuthenticationError):
266 + resolve_session(session, token)
267 +
268 +
269 +# --------------------------------------------------------- audit attribution
270 +def test_audit_actor_is_the_session_user_not_the_body(api_client):
271 + make_user(api_client, "reviewer1", "reviewer")
272 + login(api_client, "reviewer1", "supersecret")
273 + year_id = api_client.post(
274 + "/api/v1/companies", json={"code": "AU", "name": "شرکت", "year": 1404}
275 + ).json()["year_id"]
276 + api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "root"})
277 + entries = api_client.get("/api/v1/audit").json()["entries"]
278 + approve_entries = [e for e in entries if e["action"] == "approve"]
279 + assert approve_entries
280 + assert all(e["actor"] == "reviewer1" for e in approve_entries)
281 +
282 +
283 +# ------------------------------------------------------------ backup confine
284 +def test_backup_destination_outside_the_data_folder_is_refused(tmp_path):
285 + store = tmp_path / "data" / "source_store"
286 + store.mkdir(parents=True)
287 + with pytest.raises(BackupError):
288 + confine_dest("/etc/aram-backup", store_root=store)
289 + with pytest.raises(BackupError):
290 + confine_dest("../../escape", store_root=store)
291 + with pytest.raises(BackupError):
292 + confine_dest(tmp_path / "elsewhere" / "b", store_root=store)
293 +
294 +
295 +def test_backup_destination_inside_the_data_folder_is_allowed(tmp_path):
296 + store = tmp_path / "data" / "source_store"
297 + store.mkdir(parents=True)
298 + assert confine_dest("backup-1", store_root=store) == tmp_path / "data" / "backup-1"
299 +
300 +
301 +def test_symlink_escape_is_refused(tmp_path):
302 + store = tmp_path / "data" / "source_store"
303 + store.mkdir(parents=True)
304 + outside = tmp_path / "outside"
305 + outside.mkdir()
306 + link = tmp_path / "data" / "link"
307 + link.symlink_to(outside, target_is_directory=True)
308 + with pytest.raises(BackupError):
309 + confine_dest("link/backup", store_root=store)
310 +
311 +
312 +def test_backup_api_rejects_an_escaping_destination(api_client, tmp_path, monkeypatch):
313 + from aram_backend.config import Settings
314 +
315 + monkeypatch.setattr(
316 + "aram_backend.admin_api.get_settings",
317 + lambda: Settings(source_store_root=str(tmp_path / "store")),
318 + )
319 + (tmp_path / "store").mkdir(exist_ok=True)
320 + r = api_client.post("/api/v1/backup", json={"dest": "/tmp/aram-escape"})
321 + assert r.status_code == 422
322 + assert "پوشهٔ داده" in r.json()["detail"]
323 +
324 +
325 +def test_create_backup_service_confines_too(session, tmp_path):
326 + store = tmp_path / "data" / "store"
327 + store.mkdir(parents=True)
328 + with pytest.raises(BackupError):
329 + create_backup(session, tmp_path / "outside", store_root=store)
330 +
331 +
332 +# ------------------------------------------------------- desktop launch token
333 +@pytest.fixture
334 +def desktop(tmp_path):
335 + from aram_backend.database import reconfigure
336 +
337 + data_dir = tmp_path / "aram-data"
338 + initialize_database(data_dir)
339 + reconfigure(f"sqlite:///{data_dir / 'aram.db'}")
340 + app = create_desktop_app()
341 + with TestClient(app) as client:
342 + yield client, app
343 +
344 +
345 +def test_desktop_api_is_closed_without_the_launcher_grant(desktop):
346 + client, _ = desktop
347 + assert client.get("/api/v1/health").status_code == 200 # readiness stays open
348 + assert client.post(
349 + "/api/v1/users", json={"username": "evil", "password": "supersecret"}
350 + ).status_code == 401
351 + assert client.post(
352 + "/api/v1/auth/login", json={"username": "root", "password": "supersecret"}
353 + ).status_code == 401
354 +
355 +
356 +def test_desktop_one_time_token_is_single_use(desktop):
357 + client, app = desktop
358 + token = app.state.launch_token
359 + first = client.post("/api/v1/auth/launch", json={"token": token})
360 + assert first.status_code == 200
361 + grant = first.json()["grant"]
362 + # Replaying the same launch token cannot mint a second grant.
363 + assert client.post("/api/v1/auth/launch", json={"token": token}).status_code == 401
364 + client.headers.update({"X-Aram-Launch": grant})
365 + assert client.post(
366 + "/api/v1/users", json={"username": "root", "password": "supersecret"}
367 + ).status_code == 200
368 +
369 +
370 +def test_desktop_wrong_grant_is_refused(desktop):
371 + client, app = desktop
372 + client.post("/api/v1/auth/launch", json={"token": app.state.launch_token})
373 + client.headers.update({"X-Aram-Launch": "forged-grant"})
374 + assert client.post(
375 + "/api/v1/users", json={"username": "evil", "password": "supersecret"}
376 + ).status_code == 401
377 +
378 +
379 +def test_launch_guard_rejects_a_wrong_token():
380 + guard = LaunchGuard()
381 + token = guard.arm()
382 + with pytest.raises(AuthenticationError):
383 + guard.exchange("wrong")
384 + grant = guard.exchange(token)
385 + guard.check(grant)
386 + with pytest.raises(AuthenticationError):
387 + guard.check("wrong")
388 + with pytest.raises(AuthenticationError):
389 + guard.exchange(token)
390 +
391 +
392 +def test_launch_token_is_not_accepted_as_a_query_parameter(desktop):
393 + """The token travels in the URL fragment, so it never reaches the server."""
394 + client, app = desktop
395 + r = client.get(f"/api/v1/health?launch={app.state.launch_token}")
396 + assert r.status_code == 200
397 + assert client.post(
398 + "/api/v1/users", json={"username": "evil", "password": "supersecret"}
399 + ).status_code == 401
400 +
401 +
402 +# ------------------------------------------------------------- misc surfaces
403 +def test_sqlite_database_never_stores_a_plaintext_token(api_client, tmp_path):
404 + token = login(api_client, "root", "supersecret")
405 + db, generator = _db(api_client)
406 + try:
407 + url = db.get_bind().url
408 + finally:
409 + generator.close()
410 + conn = sqlite3.connect(url.database)
411 + try:
412 + rows = conn.execute("SELECT token_hash FROM auth_sessions").fetchall()
413 + finally:
414 + conn.close()
415 + assert rows
416 + assert all(token not in row[0] for row in rows)
417 +
418 +
419 +def test_role_change_takes_effect_on_the_next_request(api_client):
420 + token = make_user(api_client, "prep", "preparer")
421 + headers = {"Authorization": f"Bearer {token}"}
422 + assert api_client.get("/api/v1/users", headers=headers).status_code == 403
423 + api_client.post("/api/v1/users/prep/role", json={"role": "admin"})
424 + assert api_client.get("/api/v1/users", headers=headers).status_code == 200
425 +
426 +
427 +def test_user_roles_are_unchanged(session):
428 + assert {r.value for r in UserRole} == {"admin", "reviewer", "preparer"}
backend/tests/test_desktop.py
+13 -1
@@ -38,7 +38,19 @@ def test_desktop_app_serves_health_and_api(tmp_path):
38 r = client.get("/api/v1/health")
39 assert r.status_code == 200
40 assert r.json()["status"] == "ok"
41 - # End-to-end through the desktop app's local DB.
41 + # R1: without the launcher grant even the local API refuses to serve.
42 + assert client.post("/api/v1/users", json={"username": "a", "password": "supersecret"}).status_code == 401
43 + grant = client.post(
44 + "/api/v1/auth/launch", json={"token": app.state.launch_token}
45 + ).json()["grant"]
46 + client.headers.update({"X-Aram-Launch": grant})
47 + # End-to-end through the desktop app's local DB, bootstrap + real login.
48 + r = client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
49 + assert r.status_code == 200, r.text
50 + token = client.post(
51 + "/api/v1/auth/login", json={"username": "root", "password": "supersecret"}
52 + ).json()["token"]
53 + client.headers.update({"Authorization": f"Bearer {token}"})
54 r = client.post("/api/v1/companies", json={"code": "D1", "name": "شرکت", "year": 1404})
55 assert r.status_code == 200, r.text
56 assert r.json()["year"] == 1404
backend/tests/test_phase7_admin.py
+39 -38
@@ -23,6 +23,7 @@ from aram_backend.services.users import (
23 require_role,
24 set_active,
25 )
26 +from conftest import login, make_user
27 from test_approval_gate import _balanced
28
29
@@ -161,77 +162,77 @@ class TestBackup:
162
163 # ----------------------------------------------------------------- admin API
164 class TestAdminApi:
164 - def test_bootstrap_first_user_is_admin(self, api_client):
165 - r = api_client.post(
165 + """R1 (booklet 2.1): the api_client fixture is already logged in as the
166 + bootstrap admin ``root``; identity never comes from a request body."""
167 +
168 + def test_bootstrap_happens_once_and_forces_admin(self, anon_client):
169 + r = anon_client.post(
170 "/api/v1/users",
171 json={"username": "root", "password": "supersecret", "role": "preparer"},
172 )
173 assert r.status_code == 200, r.text
174 assert r.json()["role"] == "admin" # bootstrap forces admin
175 + # A second attempt is no longer a bootstrap: it needs an ADMIN session.
176 + again = anon_client.post(
177 + "/api/v1/users", json={"username": "second", "password": "supersecret"}
178 + )
179 + assert again.status_code == 401
180
172 - def test_login_and_role_gate(self, api_client):
173 - api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
174 - # login
181 + def test_login_issues_a_token_and_role_gate_uses_the_session(self, api_client):
182 r = api_client.post(
183 "/api/v1/auth/login", json={"username": "root", "password": "supersecret"}
184 )
185 assert r.status_code == 200
186 assert r.json()["role"] == "admin"
187 + assert len(r.json()["token"]) >= 40 # 256-bit random token
188 # bad login
181 - r = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "nope"})
189 + r = api_client.post(
190 + "/api/v1/auth/login", json={"username": "root", "password": "nope"}
191 + )
192 assert r.status_code == 401
183 - # admin can create a preparer
193 + # admin can create a preparer (no actor field anywhere)
194 r = api_client.post(
195 "/api/v1/users",
186 - json={
187 - "username": "prep",
188 - "password": "supersecret",
189 - "role": "preparer",
190 - "actor": "root",
191 - },
196 + json={"username": "prep", "password": "supersecret", "role": "preparer"},
197 )
198 assert r.status_code == 200
194 - # preparer cannot create users
199 + # the preparer's own session cannot create users, even claiming actor=root
200 + prep_token = login(api_client, "prep", "supersecret")
201 r = api_client.post(
202 "/api/v1/users",
197 - json={"username": "x", "password": "supersecret", "actor": "prep"},
203 + json={"username": "x", "password": "supersecret", "actor": "root"},
204 + headers={"Authorization": f"Bearer {prep_token}"},
205 )
206 assert r.status_code == 403
207
201 - def test_approve_role_gated_once_users_exist(self, api_client):
202 - # Bootstrap admin + a preparer.
203 - api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
204 - api_client.post(
205 - "/api/v1/users",
206 - json={
207 - "username": "prep",
208 - "password": "supersecret",
209 - "role": "preparer",
210 - "actor": "root",
211 - },
212 - )
208 + def test_approve_role_gated_by_session(self, api_client):
209 + make_user(api_client, "prep", "preparer")
210 year_id = api_client.post(
211 "/api/v1/companies", json={"code": "RG", "name": "شرکت", "year": 1404}
212 ).json()["year_id"]
213 # Preparer is refused by the role gate (403) before controls even run.
217 - r = api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "prep"})
214 + prep_token = login(api_client, "prep", "supersecret")
215 + r = api_client.post(
216 + f"/api/v1/years/{year_id}/approve",
217 + json={"actor": "root"},
218 + headers={"Authorization": f"Bearer {prep_token}"},
219 + )
220 assert r.status_code == 403, r.text
221 # Admin passes the role gate (controls may still block, but never 403).
220 - r = api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "root"})
222 + login(api_client, "root", "supersecret")
223 + r = api_client.post(f"/api/v1/years/{year_id}/approve")
224 assert r.status_code == 200, r.text
225
223 - def test_approve_open_when_no_users(self, api_client):
224 - # Bootstrap/dev: with no users, the role gate is inactive (control gate still applies).
225 - year_id = api_client.post(
226 - "/api/v1/companies", json={"code": "NU", "name": "شرکت", "year": 1404}
227 - ).json()["year_id"]
228 - r = api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "anyone"})
229 - assert r.status_code == 200, r.text
226 + def test_approve_is_impossible_without_users(self, anon_client):
227 + """The old "no users -> approval allowed" shortcut is gone (R1)."""
228 + r = anon_client.post("/api/v1/years/1/approve", json={"actor": "anyone"})
229 + assert r.status_code == 401
230
231 def test_audit_endpoint_chain_valid(self, api_client):
232 - api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
232 r = api_client.get("/api/v1/audit/verify")
233 assert r.status_code == 200
234 assert r.json()["chain_valid"] is True
235 r = api_client.get("/api/v1/audit")
237 - assert r.json()["entries"] # user.create recorded
236 + actions = {e["action"] for e in r.json()["entries"]}
237 + assert "user.create" in actions
238 + assert "auth.login" in actions
backend/tests/test_pilot_api.py
+42 -21
@@ -8,7 +8,8 @@ import aram_backend.pilot_api as pilot_api
8 from test_pilot_engine import build_balanced_workbook
9
10
11 -def test_meta_exposes_explicit_sign_policy(client):
11 +def test_meta_exposes_explicit_sign_policy(pilot_client):
12 + client = pilot_client
13 response = client.get("/api/v1/pilot/meta")
14 assert response.status_code == 200
15 body = response.json()
@@ -18,18 +19,23 @@ def test_meta_exposes_explicit_sign_policy(client):
19 assert body["section_policy"]["IS"] == {"Revenue": -1, "Expenses": 1}
20
21
21 -def test_root_serves_workbench_directly_and_ui_is_served(client):
22 - response = client.get("/", follow_redirects=False)
23 - assert response.status_code == 200
24 - assert "میز کار پایلوت" in response.text
25 - page = client.get("/pilot/")
26 - assert page.status_code == 200
27 - assert "میز کار پایلوت" in page.text
28 - assert client.get("/pilot/app.js").status_code == 200
29 - assert client.get("/pilot/styles.css").status_code == 200
22 +def test_legacy_pilot_ui_is_no_longer_served(client):
23 + """R1 (booklet 2.1): "/" must not serve the legacy in-memory workbench, and
24 + neither the pilot pages nor its routes are part of the shipped app."""
25 + root = client.get("/")
26 + assert root.status_code == 404
27 + assert "میز کار پایلوت" not in root.text
28 + assert client.get("/pilot/").status_code == 404
29 + assert client.get("/pilot/app.js").status_code == 404
30 + assert client.get("/api/v1/pilot/meta").status_code == 404
31 + assert client.post("/api/v1/pilot/demo").status_code == 404
32 + paths = {getattr(route, "path", "") for route in client.app.routes}
33 + assert not any(path.startswith("/api/v1/pilot") for path in paths)
34 + assert not any(path.startswith("/pilot") for path in paths)
35
36
32 -def test_demo_full_workflow_from_exceptions_to_approved_export(client):
37 +def test_demo_full_workflow_from_exceptions_to_approved_export(pilot_client):
38 + client = pilot_client
39 created = client.post("/api/v1/pilot/demo")
40 assert created.status_code == 200
41 body = created.json()
@@ -91,7 +97,8 @@ def test_demo_full_workflow_from_exceptions_to_approved_export(client):
97 assert client.get(f"/api/v1/pilot/sessions/{sid}").status_code == 404
98
99
94 -def test_upload_valid_workbook_creates_session(client):
100 +def test_upload_valid_workbook_creates_session(pilot_client):
101 + client = pilot_client
102 response = client.post(
103 "/api/v1/pilot/sessions",
104 files={"file": ("pilot.xlsx", build_balanced_workbook(),
@@ -104,7 +111,8 @@ def test_upload_valid_workbook_creates_session(client):
111 assert len(body["accounts"]) == 5
112
113
107 -def test_upload_invalid_workbook_returns_exact_preflight_issues(client):
114 +def test_upload_invalid_workbook_returns_exact_preflight_issues(pilot_client):
115 + client = pilot_client
116 response = client.post(
117 "/api/v1/pilot/sessions", files={"file": ("bad.xlsx", b"not an xlsx")}
118 )
@@ -113,7 +121,8 @@ def test_upload_invalid_workbook_returns_exact_preflight_issues(client):
121 assert detail["issues"][0]["code"] == "INVALID_WORKBOOK"
122
123
116 -def test_upload_rejects_wrong_extension_and_empty_file(client):
124 +def test_upload_rejects_wrong_extension_and_empty_file(pilot_client):
125 + client = pilot_client
126 response = client.post(
127 "/api/v1/pilot/sessions", files={"file": ("data.csv", b"x,y\n1,2")}
128 )
@@ -124,7 +133,8 @@ def test_upload_rejects_wrong_extension_and_empty_file(client):
133 assert response.status_code == 422
134
135
127 -def test_upload_size_limit_is_enforced(client, monkeypatch):
136 +def test_upload_size_limit_is_enforced(pilot_client, monkeypatch):
137 + client = pilot_client
138 monkeypatch.setattr(pilot_api, "MAX_UPLOAD_BYTES", 8)
139 response = client.post(
140 "/api/v1/pilot/sessions", files={"file": ("big.xlsx", b"0123456789")}
@@ -132,7 +142,8 @@ def test_upload_size_limit_is_enforced(client, monkeypatch):
142 assert response.status_code == 413
143
144
135 -def test_mapping_validation_is_fail_closed(client):
145 +def test_mapping_validation_is_fail_closed(pilot_client):
146 + client = pilot_client
147 sid = client.post("/api/v1/pilot/demo").json()["session"]["id"]
148 base = f"/api/v1/pilot/sessions/{sid}/mappings"
149 # Unknown account.
@@ -155,7 +166,8 @@ def test_mapping_validation_is_fail_closed(client):
166 }).status_code == 422
167
168
158 -def test_clear_mapping_reopens_the_exception_queue(client):
169 +def test_clear_mapping_reopens_the_exception_queue(pilot_client):
170 + client = pilot_client
171 sid = client.post("/api/v1/pilot/demo").json()["session"]["id"]
172 response = client.delete(f"/api/v1/pilot/sessions/{sid}/mappings/1001?actor=tester")
173 assert response.status_code == 200
@@ -165,7 +177,8 @@ def test_clear_mapping_reopens_the_exception_queue(client):
177 assert body["audit_trail"][-1]["action"] == "clear_mapping"
178
179
168 -def test_unknown_session_is_404_everywhere(client):
180 +def test_unknown_session_is_404_everywhere(pilot_client):
181 + client = pilot_client
182 assert client.get("/api/v1/pilot/sessions/nope").status_code == 404
183 assert client.get("/api/v1/pilot/sessions/nope/export.xlsx").status_code == 404
184 assert client.delete("/api/v1/pilot/sessions/nope").status_code == 404
@@ -174,6 +187,14 @@ def test_unknown_session_is_404_everywhere(client):
187 }).status_code == 404
188
189
177 -def test_existing_api_surface_is_unchanged(client):
178 - assert client.get("/api/v1/health").json()["status"] == "ok"
179 - assert len(client.get("/api/v1/schema/entities").json()["entities"]) == 9
190 +def test_health_stays_public_and_schema_needs_a_session(anon_client):
191 + """R1: /health is the only unauthenticated read; the schema catalog is not."""
192 + assert anon_client.get("/api/v1/health").json()["status"] == "ok"
193 + assert anon_client.get("/api/v1/schema/entities").status_code == 401
194 +
195 +
196 +def test_pilot_router_is_authenticated_wherever_mounted(pilot_client):
197 + """The legacy router carries the same dependency, so it can never be anonymous."""
198 + pilot_client.headers.pop("Authorization", None)
199 + assert pilot_client.get("/api/v1/pilot/meta").status_code == 401
200 + assert pilot_client.post("/api/v1/pilot/demo").status_code == 401
backend/tests/test_pilot_editing.py
+4 -2
@@ -204,7 +204,8 @@ def test_workspace_export_is_preflight_valid():
204
205
206 # ------------------------------------------------------------------ API CRUD
207 -def test_api_account_note_company_crud_and_workspace(client):
207 +def test_api_account_note_company_crud_and_workspace(pilot_client):
208 + client = pilot_client
209 sid = client.post("/api/v1/pilot/demo").json()["session"]["id"]
210 base = f"/api/v1/pilot/sessions/{sid}"
211
@@ -265,7 +266,8 @@ def test_api_account_note_company_crud_and_workspace(client):
266 load_workbook(BytesIO(ws.content)).close()
267
268
268 -def test_api_invalid_account_value_is_422(client):
269 +def test_api_invalid_account_value_is_422(pilot_client):
270 + client = pilot_client
271 sid = client.post("/api/v1/pilot/demo").json()["session"]["id"]
272 response = client.post(f"/api/v1/pilot/sessions/{sid}/accounts", json={
273 "full_code": "X1", "name": "بد", "general_code": "99", "general_name": "گ",
docs/PROJECT_LOG.md
+10
@@ -420,3 +420,13 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
420 - Screenshot +21065/−242 explained: Arena patchset view diffs vs session base 7dc864f (cumulative with phases 0–9), not PR base 46253c9; actual PR #97 diff = 50 files/+1490/−4892 (reviewer-confirmed).
421 - Protected data: data/ + samples/ trees unchanged (docs-only remediation). No code changed; backend/frontend suites unaffected.
422 - Acceptance: IN_PROGRESS; author does not merge or tag. Next: independent re-review of updated PR #97; C1 only after C0 acceptance.
423 +
424 +### 2026-12-04T08:10:00Z — R1 real authentication (booklet 2.1)
425 +
426 +- Actor: Arena agent (implementation). Trigger: booklet 2.1 R1 (priority 1). Precondition consumed first: PR #97 preconditions verified (OPEN, head `1e247083d36ef76a67432880db2a1f5984fa575c`, `mergeable_state=clean`) and squash-merged under the owner's one-time waiver → accepted head **f2e6da5e7ade3c851584008d590c588894d4c9c3**. Working branch aligned to that tree (byte-identical) so this PR's diff is R1-only. `experiment/browser-edition` not created (Arena single-branch constraint; owner-authorized skip; tag v1.0.0 preserves the files).
427 +- Backend: `actor` removed from every request model; new `auth.py` with the single `current_user` dependency (router-level on statements/admin/schema/pilot) + `optional_user` + `bootstrap_guard`; `services/users.py` rewritten for 256-bit bearer tokens (SHA-256 stored only), 8-hour absolute TTL, logout revocation, 5-attempt/15-minute lockout, PBKDF2 **600,000** rounds with transparent upgrade of legacy 200,000-round hashes, timing-equalised unknown-username path, audit entries for login/logout/lock/rehash. `approve` lost its "no users → allowed" shortcut and checks role before existence. Backup `dest` confined to the data folder (`confine_dest`, symlink/traversal/absolute escapes refused). Desktop launcher arms a one-time 256-bit token passed in the URL fragment and exchanged once for an `X-Aram-Launch` grant. `pilot_api` router, `/pilot` mount and the legacy `/` HTML removed from `main.py`; `/docs`, `/redoc`, `/openapi.json` disabled. Migration `20261204_08` adds `auth_sessions` + `password_rounds`/`failed_login_count`/`locked_until`.
428 +- Frontend: `LoginPanel` gates the whole workbench; `api/session.ts` keeps the token in sessionStorage (read per request) and exchanges the launch fragment; `client.ts` attaches `Authorization`/`X-Aram-Launch`, clears the session on 401, and replaces the bare `<a href download>` exports with authenticated fetch+blob downloads; `actor` inputs removed from ApprovalPanel/AdminPanel.
429 +- Decisions recorded in **ADR-030** (N=5, lockout 15 min, TTL 8 h absolute, PBKDF2 600k because Argon2/bcrypt/passlib are absent and no new runtime dependency is allowed, bearer-not-cookie to avoid CSRF, four public routes, pilot files retained but unserved to respect the 1,500-line cap). Booklet 2.1 requirements registered in `docs/booklet/BOOKLET_v2.1_REGISTER.md` (explicitly a structured transcription, **not** verbatim; owner text wins) + MANIFEST SHA-256 e051140c0bc8dcebc9340286ee7fed24b4834913ef2898c8aa0cfbea58e32397.
430 +- Evidence: backend **354 passed** (collect-only 354; was 319), including `tests/test_auth_r1.py` **33** R1 acceptance tests; frontend **15 vitest tests / 5 files**, tsc + eslint clean; `ruff check src tests`, `ruff format --check domain services migrations`, `mypy domain`, `mypy services` clean. Migration 08 verified on a copy of a populated DB: 131,280 ledger rows, 2 users, 28 triggers unchanged; the live preview's legacy `root` logged in and was rehashed 200,000 → 600,000. CI e2e job now starts uvicorn on a throwaway DB with `ARAM_E2E_BACKEND=1` so the real-session e2e actually runs.
431 +- Protected data: `data/` tree 2ef8a512523f62f0cf84c5009f141be2f8a9cb5f and `samples/` tree 00aba54b1dc30485ba9b164c8036a7b4bbe9020e unchanged (before = after).
432 +- Acceptance: R1 **MET**; author does not merge or tag. Stop after R1 per booklet 2.1 §8. Next: independent GitHub review of the R1 PR; R2 only after acceptance.
docs/adr/ADR-030-r1-session-authentication.md new
+83
@@ -0,0 +1,83 @@
1 +# ADR-030 — R1 real authentication: parameters and boundary decisions
2 +
3 +- Status: Accepted (R1, booklet 2.1)
4 +- Date: 2026-12-04
5 +- Booklet: 2.1 §1 (no deferral of security defects) + R1; booklet 1 §7/§12. Supersedes the
6 + Phase 7 "bootstrap/dev" exemptions in `approve` and the client-supplied `actor`.
7 +
8 +## Context
9 +
10 +Before R1 anyone reaching the port could approve a year with `{"actor": "admin"}`, and with
11 +zero users the role gate was skipped entirely. Login issued no credential; the legacy pilot
12 +exposed 17 unauthenticated routes at `/`; backup `dest` was unvalidated; the desktop launcher
13 +had no local token. The owner delegated **N** and the **token lifetime** to the agent.
14 +
15 +## Decision — credentials
16 +
17 +**Hashing: PBKDF2-HMAC-SHA256, 600,000 iterations.** `argon2`, `argon2-cffi`, `passlib`
18 +and `bcrypt` are absent and booklet 2 §16 forbids new runtime dependencies offline, so
19 +R1's fallback applies: 200,000 → **600,000** (OWASP floor), measured **0.199 s** per hash
20 +here. `users.password_rounds` stores it per row: pre-R1 hashes stay verifiable and are
21 +**rehashed to 600,000 on first successful login**. Salt handling is unchanged
22 +(`bytes.fromhex(salt)`), so no password reset is forced.
23 +
24 +**Failed attempts: N = 5, lockout 15 minutes.** An offline single-user tool has no
25 +legitimate reason for five consecutive failures. After the 5th the account locks for
26 +**15 minutes** and even the correct password is refused; counter and lock clear on a
27 +successful login after expiry. Lockout is per account, not per IP: the threat model is a
28 +local process. Unknown usernames burn the same work factor and return the identical
29 +Persian message, so timing and text reveal nothing. `auth.locked` is audited.
30 +
31 +**Session token: 256 random bits, hash-only storage, 8-hour absolute TTL.**
32 +`secrets.token_urlsafe(32)` is returned **once**; only `SHA-256(token)` is stored in
33 +`auth_sessions`, so the plaintext never touches database, log or URL. Lifetime is **8
34 +hours absolute** — one shift, **no sliding renewal**, so a stolen token cannot be kept
35 +alive by use. Logout sets `revoked`; deactivating a user revokes all their sessions.
36 +Expired, revoked, unknown and malformed tokens all yield 401 with `WWW-Authenticate:
37 +Bearer`. A bearer token rather than a cookie is deliberate: the browser never sends it
38 +automatically, so there is no CSRF surface. The client keeps it in `sessionStorage`
39 +(never `localStorage`, never disk).
40 +
41 +## Decision — boundaries
42 +
43 +**One dependency, four exemptions.** `current_user` in `aram_backend/auth.py` is the only
44 +source of identity, attached at router level (statements, admin, schema, pilot) so new
45 +routes are protected by default. Exactly four routes work without a session:
46 +`GET /health` (readiness, no data), `POST /auth/login` (establishes the session),
47 +`POST /auth/launch` (exchanges the one-time desktop token) and `POST /users` (**only
48 +while zero users exist**). `bootstrap_guard` runs before body validation on `/users`, so
49 +once any user exists it answers 401 even for a malformed body. The first user is forced
50 +to ADMIN and the bootstrap cannot repeat; logout and all reads need a session too.
51 +Approval **without users is impossible**: the `if list_users(session)` shortcut is deleted
52 +and the role gate runs before the year-existence check. `actor` is gone from every request
53 +model; the audit log is attributed to the authenticated username.
54 +
55 +**Backup `dest` confined.** `confine_dest` resolves the path (expanding `~`, following
56 +symlinks) and refuses anything not strictly inside the allowed root: `..` traversal,
57 +outside absolute paths and symlink escapes are rejected after resolution. The root
58 +defaults to the parent of `source_store_root`, narrowed by `ARAM_BACKUP_ROOT`; both
59 +`/backup` and `/backup/verify` enforce it.
60 +
61 +**Desktop one-time local token.** The launcher arms a random 256-bit token and opens
62 +`http://127.0.0.1:<port>/#launch=<token>`. The **fragment** never travels over HTTP nor
63 +reaches access logs. The page exchanges it once at `/auth/launch` for a grant, scrubs the
64 +fragment with `history.replaceState`, and sends the grant in `X-Aram-Launch` on every
65 +call. A replay cannot mint a second grant; without it another local process cannot reach
66 +even bootstrap or login. `/health` stays open.
67 +
68 +**Legacy surfaces and frontend.** `pilot_api`'s router, the `/pilot` mount and the HTML
69 +formerly at `/` are removed from `main.py`; the router module keeps the same `current_user`
70 +dependency, so it can never be anonymous if mounted again (a test-only app covers it).
71 +`/docs`, `/redoc` and `/openapi.json` are disabled in both apps: they are endpoints, and
72 +only the four above are exempt. `static/pilot` and `pilot_api.py` stay in the tree
73 +(unserved, unimported) to respect the size cap. The workbench sits behind `LoginPanel`;
74 +`client.ts` attaches `Authorization` (and `X-Aram-Launch`) to every request and clears the
75 +session on any 401. Export links were plain `<a href download>`, which cannot carry a
76 +header — they are now authenticated `fetch` + blob downloads, so no token is put in a URL.
77 +
78 +## Consequences
79 +
80 +Migration `20261204_08` adds `auth_sessions` + three `users` columns; verified on a copy
81 +of a populated DB (131,280 ledger rows, 2 users, 28 triggers unchanged, legacy rows keep
82 +`password_rounds = 200000` until first login). R4 owns replacing `create_all` with
83 +`alembic upgrade head` at startup; until then an existing DB needs it applied once.
docs/booklet/MANIFEST.json
+2 -1
@@ -31,5 +31,6 @@
31 }
32 ]
33 }
34 - ]
34 + ],
35 + "note_v2_1": "Booklet 2.1 (owner message 2026-12-04) governs R1..R6 and takes precedence over booklets 2 and 1; its other sections stay valid. No markdown copy is committed: the agent holds no byte-exact original, so the owner's message remains the authoritative text. R1..R6 scope and acceptance are tracked in PROJECT_STATUS.md; R1 decisions in ADR-030."
36 }
frontend/e2e/app.spec.ts
+17 -6
@@ -2,13 +2,24 @@ import { expect, test } from '@playwright/test'
2
3 test('renders the Aram workbench heading (RTL)', async ({ page }) => {
4 await page.goto('/')
5 - await expect(page.getByRole('heading', { name: /آرام/ })).toBeVisible()
5 + await expect(page.getByRole('heading', { level: 1, name: /آرام/ })).toBeVisible()
6 })
7
8 -test('shows the company setup form before a year exists', async ({ page }) => {
8 +test('shows the login screen, not the workbench, without a session (R1)', async ({ page }) => {
9 await page.goto('/')
10 - await expect(page.getByRole('button', { name: 'ایجاد' })).toBeVisible()
11 - await expect(page.getByLabel('کد شرکت')).toBeVisible()
12 - await expect(page.getByLabel('نام شرکت')).toBeVisible()
13 - await expect(page.getByLabel('سال مالی')).toBeVisible()
10 + await expect(page.getByRole('button', { name: 'ورود', exact: true })).toBeVisible()
11 + await expect(page.getByLabel('نام کاربری')).toBeVisible()
12 + await expect(page.getByLabel('گذرواژه')).toBeVisible()
13 + // No data surface is reachable before login.
14 + await expect(page.getByRole('button', { name: 'ایجاد' })).toHaveCount(0)
15 + await expect(page.getByLabel('کد شرکت')).toHaveCount(0)
16 + await expect(page.getByText('بارگذاری دفتر کل')).toHaveCount(0)
17 +})
18 +
19 +test('the legacy pilot workbench is not served at the root (R1)', async ({ page }) => {
20 + const response = await page.goto('/')
21 + expect(response?.status()).toBe(200) // the React app, not the old HTML page
22 + await expect(page.getByText('میز کار پایلوت')).toHaveCount(0)
23 + const pilot = await page.request.get('/api/v1/pilot/meta')
24 + expect(pilot.status()).toBe(404)
25 })
frontend/e2e/helpers.ts new
+19
@@ -0,0 +1,19 @@
1 +import { expect, type Page } from '@playwright/test'
2 +
3 +export const ADMIN = { username: 'root', password: 'supersecret' }
4 +
5 +/**
6 + * Establish a real server-side session through the UI (R1, booklet 2.1).
7 + *
8 + * The first-admin bootstrap is attempted over the API and is expected to fail
9 + * with 401 once users exist — that is the one-time property. The login itself
10 + * always goes through the login form, so the e2e exercises the real token path.
11 + */
12 +export async function loginAsAdmin(page: Page): Promise<void> {
13 + await page.request.post('/api/v1/users', { data: ADMIN })
14 + await page.goto('/')
15 + await page.getByLabel('نام کاربری').fill(ADMIN.username)
16 + await page.getByLabel('گذرواژه').fill(ADMIN.password)
17 + await page.getByRole('button', { name: 'ورود', exact: true }).click()
18 + await expect(page.getByRole('button', { name: 'ایجاد' })).toBeVisible({ timeout: 30000 })
19 +}
frontend/e2e/session.spec.ts new
+60
@@ -0,0 +1,60 @@
1 +import { expect, test } from '@playwright/test'
2 +import { ADMIN, loginAsAdmin } from './helpers'
3 +
4 +// Real-session e2e: runs against the live FastAPI backend proxied at /api.
5 +// Skipped when no backend is present so a frontend-only run stays green;
6 +// CI sets ARAM_E2E_BACKEND=1 with uvicorn running on a throwaway database.
7 +const backendEnabled = process.env.ARAM_E2E_BACKEND === '1'
8 +
9 +test.describe('real session (R1)', () => {
10 + test.skip(!backendEnabled, 'requires the backend (ARAM_E2E_BACKEND=1)')
11 +
12 + test('bootstrap once, log in, work, log out, and be locked out again', async ({ page }) => {
13 + await loginAsAdmin(page)
14 +
15 + // A real session unlocks the workbench and the identity comes from the server.
16 + await expect(page.getByRole('button', { name: 'خروج' })).toBeVisible()
17 + await expect(page.getByText('root (admin)')).toBeVisible()
18 +
19 + // An authenticated read works through the UI's token.
20 + const me = await page.request.get('/api/v1/auth/me', {
21 + headers: {
22 + Authorization: `Bearer ${await page.evaluate(() => sessionStorage.getItem('aram.token'))}`,
23 + },
24 + })
25 + expect(me.status()).toBe(200)
26 + expect((await me.json()).username).toBe(ADMIN.username)
27 +
28 + // Logout revokes the session server-side and returns the UI to the gate.
29 + const token = await page.evaluate(() => sessionStorage.getItem('aram.token'))
30 + await page.getByRole('button', { name: 'خروج' }).click()
31 + await expect(page.getByRole('button', { name: 'ورود', exact: true })).toBeVisible()
32 + const afterLogout = await page.request.get('/api/v1/auth/me', {
33 + headers: { Authorization: `Bearer ${token}` },
34 + })
35 + expect(afterLogout.status()).toBe(401)
36 + })
37 +
38 + test('the browser cannot reach data without a token, even claiming actor=admin', async ({
39 + page,
40 + }) => {
41 + await page.goto('/')
42 + const forged = await page.request.post('/api/v1/years/1/approve', { data: { actor: 'admin' } })
43 + expect(forged.status()).toBe(401)
44 + const read = await page.request.get('/api/v1/audit')
45 + expect(read.status()).toBe(401)
46 + const users = await page.request.get('/api/v1/users?actor=admin')
47 + expect(users.status()).toBe(401)
48 + })
49 +
50 + test('a wrong password never creates a session', async ({ page }) => {
51 + await page.request.post('/api/v1/users', { data: ADMIN })
52 + await page.goto('/')
53 + await page.getByLabel('نام کاربری').fill(ADMIN.username)
54 + await page.getByLabel('گذرواژه').fill('definitely-wrong')
55 + await page.getByRole('button', { name: 'ورود', exact: true }).click()
56 + await expect(page.getByRole('alert')).toBeVisible()
57 + await expect(page.getByRole('button', { name: 'ایجاد' })).toHaveCount(0)
58 + expect(await page.evaluate(() => sessionStorage.getItem('aram.token'))).toBeNull()
59 + })
60 +})
frontend/e2e/workflow.spec.ts
+38 -6
@@ -1,4 +1,5 @@
1 import { expect, test } from '@playwright/test'
2 +import { loginAsAdmin } from './helpers'
3
4 // The full workflow runs against the live FastAPI backend proxied at /api.
5 // It is skipped when the backend is not reachable so the frontend-only CI job
@@ -9,25 +10,56 @@ test.describe('full workbench workflow', () => {
10 test.skip(!backendEnabled, 'requires the backend (ARAM_E2E_BACKEND=1)')
11
12 test('company -> ledger -> mapping -> statement -> drill-down -> approval', async ({ page }) => {
12 - await page.goto('/')
13 + // Real 1404 ledger: ~131k rows imported, then statements built. Minutes, not seconds.
14 + test.setTimeout(600_000)
15
14 - // 1. Company + fiscal year
16 + // 0. Real session first (R1): nothing below is reachable without it.
17 + await loginAsAdmin(page)
18 +
19 + // 1. Company + fiscal year (capture the year id from the real response)
20 await page.getByLabel('کد شرکت').fill('E2E')
21 await page.getByLabel('نام شرکت').fill('شرکت آزمون')
22 await page.getByLabel('سال مالی').fill('1404')
18 - await page.getByRole('button', { name: 'ایجاد' }).click()
23 + const [created] = await Promise.all([
24 + page.waitForResponse(
25 + (r) => r.url().includes('/api/v1/companies') && r.request().method() === 'POST',
26 + ),
27 + page.getByRole('button', { name: 'ایجاد' }).click(),
28 + ])
29 + const { year_id: yearId } = (await created.json()) as { year_id: number }
30 await expect(page.getByText('بارگذاری دفتر کل')).toBeVisible()
31
32 // 2. Ledger import (real source workbook)
33 const ledger = page.locator('input[type="file"]').first()
34 await ledger.setInputFiles('../data/source_ledgers/source_1404.xlsx')
24 - await page.getByRole('button', { name: 'درون‌ریزی' }).click()
25 - await expect(page.getByText(/درون‌ریزی شد/)).toBeVisible({ timeout: 120000 })
35 + await page.getByRole('button', { name: 'درون‌ریزی', exact: true }).click()
36 + await expect(page.getByText(/درون‌ریزی شد/)).toBeVisible({ timeout: 300_000 })
37 +
38 + // 2b. Map one real account, so the build produces a line to drill into.
39 + // Without a mapping every account is unmapped and the statements have no
40 + // lines — the drill-down step below would have nothing to click.
41 + const token = await page.evaluate(() => sessionStorage.getItem('aram.token'))
42 + const headers = { Authorization: `Bearer ${token}` }
43 + const queue = await (
44 + await page.request.get(`/api/v1/years/${yearId}/unknown-accounts`, { headers })
45 + ).json()
46 + expect(queue.count).toBeGreaterThan(0)
47 + const note = await (
48 + await page.request.post(`/api/v1/years/${yearId}/notes`, {
49 + headers,
50 + data: { note_number: '99', title: 'یادداشت آزمون', statement: 'BS', section: 'Assets' },
51 + })
52 + ).json()
53 + const mapped = await page.request.post(`/api/v1/years/${yearId}/mappings`, {
54 + headers,
55 + data: { account_code: queue.accounts[0].account_full_code, target_note_id: note.note_id },
56 + })
57 + expect(mapped.status()).toBe(200)
58
59 // 3. Build statements
60 await page.getByRole('button', { name: 'ساخت صورت‌های مالی' }).click()
61 await expect(page.getByRole('button', { name: 'مشاهدهٔ منبع' }).first()).toBeVisible({
30 - timeout: 60000,
62 + timeout: 120_000,
63 })
64
65 // 4. Drill-down to a source row
frontend/playwright.config.ts
+7 -2
@@ -1,9 +1,14 @@
1 import { defineConfig, devices } from '@playwright/test'
2
3 +// One worker + a long timeout: the real-ledger e2e imports ~131k rows against a
4 +// shared backend. The github reporter surfaces failures as check annotations.
5 export default defineConfig({
6 testDir: './e2e',
5 - fullyParallel: true,
6 - reporter: 'list',
7 + timeout: 120_000,
8 + expect: { timeout: 15_000 },
9 + fullyParallel: false,
10 + workers: 1,
11 + reporter: process.env.CI ? [['github'], ['list'], ['html', { open: 'never' }]] : 'list',
12 use: {
13 baseURL: 'http://127.0.0.1:5173',
14 trace: 'on-first-retry',
frontend/src/App.test.tsx
+27 -8
@@ -1,5 +1,5 @@
1 -import { render, screen } from '@testing-library/react'
2 -import { describe, expect, it, vi } from 'vitest'
1 +import { render, screen, waitFor } from '@testing-library/react'
2 +import { afterEach, describe, expect, it, vi } from 'vitest'
3 import App from './App'
4
5 vi.mock('./api/client', async () => {
@@ -18,15 +18,17 @@ vi.mock('./api/client', async () => {
18 createNote: vi.fn(),
19 createMapping: vi.fn(),
20 importMappings: vi.fn(),
21 - exportMappingsUrl: (id: number) => `/api/v1/years/${id}/mappings/export`,
22 - exportStatementsUrl: (id: number, format: string) =>
23 - `/api/v1/years/${id}/statements/export?format=${format}`,
21 + downloadMappings: vi.fn(),
22 + downloadStatements: vi.fn(),
23 listNotes: vi.fn().mockResolvedValue({ notes: [] }),
24 listMappings: vi.fn().mockResolvedValue({ mappings: [] }),
25 updateNote: vi.fn(),
26 deleteNote: vi.fn(),
27 deleteMapping: vi.fn(),
28 login: vi.fn(),
29 + logout: vi.fn(),
30 + me: vi.fn(),
31 + bootstrapAdmin: vi.fn(),
32 createUser: vi.fn(),
33 auditVerify: vi.fn(),
34 lockYear: vi.fn(),
@@ -39,15 +41,32 @@ vi.mock('./api/client', async () => {
41 }
42 })
43
44 +afterEach(() => {
45 + sessionStorage.clear()
46 + vi.clearAllMocks()
47 +})
48 +
49 describe('App', () => {
43 - it('renders the Persian RTL workbench heading', () => {
50 + it('renders the Persian RTL workbench heading', async () => {
51 render(<App />)
52 expect(screen.getByRole('heading', { name: /آرام — میز کار/ })).toBeInTheDocument()
53 + await waitFor(() => expect(screen.queryByText('در حال آماده‌سازی…')).not.toBeInTheDocument())
54 + })
55 +
56 + it('shows only the login screen without a session (R1)', async () => {
57 + render(<App />)
58 + expect(await screen.findByRole('button', { name: 'ورود' })).toBeInTheDocument()
59 + expect(screen.queryByRole('button', { name: 'ایجاد' })).not.toBeInTheDocument()
60 + expect(screen.queryByText('بارگذاری دفتر کل')).not.toBeInTheDocument()
61 })
62
48 - it('shows the company setup form before a year exists', () => {
63 + it('shows the company setup form once a real session exists (R1)', async () => {
64 + sessionStorage.setItem('aram.token', 'tok-1')
65 + const { api } = await import('./api/client')
66 + vi.mocked(api.me).mockResolvedValue({ username: 'root', display_name: 'root', role: 'admin' })
67 render(<App />)
50 - expect(screen.getByRole('button', { name: 'ایجاد' })).toBeInTheDocument()
68 + expect(await screen.findByRole('button', { name: 'ایجاد' })).toBeInTheDocument()
69 expect(screen.queryByText('بارگذاری دفتر کل')).not.toBeInTheDocument()
70 + expect(screen.getByRole('button', { name: 'خروج' })).toBeInTheDocument()
71 })
72 })
frontend/src/App.tsx
+70 -12
@@ -1,33 +1,91 @@
1 -import { useState } from 'react'
1 +import { useEffect, useState, useSyncExternalStore } from 'react'
2 +import { api } from './api/client'
3 +import { getIdentity, getSnapshot, getToken, initLaunch, setIdentity, subscribe } from './api/session'
4 import type { CompanyResult } from './api/types'
5 import AdminPanel from './components/AdminPanel'
6 import ApprovalPanel from './components/ApprovalPanel'
7 import CompanySetup from './components/CompanySetup'
8 import LedgerUpload from './components/LedgerUpload'
9 +import LoginPanel from './components/LoginPanel'
10 import MappingPanel from './components/MappingPanel'
11 import NotesManager from './components/NotesManager'
12 import StatementView from './components/StatementView'
13 import { faNumber } from './lib/format'
14
15 /**
13 - * Aram workbench (Phase 5): company/year setup -> ledger import -> mapping ->
14 - * statements with source drill-down -> controls and approval. RTL Persian UI;
15 - * all data flows through the relative /api/v1 backend (no runtime network).
16 + * Aram workbench: company/year setup -> ledger import -> mapping -> statements
17 + * with source drill-down -> controls and approval. RTL Persian UI; all data flows
18 + * through the relative /api/v1 backend (no runtime network).
19 + *
20 + * R1 (booklet 2.1): the whole workbench sits behind a real server-side session.
21 + * Without one, only the login screen renders.
22 */
23 export default function App() {
24 + useSyncExternalStore(subscribe, getSnapshot)
25 + const identity = getIdentity()
26 const [company, setCompany] = useState<CompanyResult | null>(null)
27 const [statementRefresh, setStatementRefresh] = useState(0)
28 + const [ready, setReady] = useState(false)
29 +
30 + useEffect(() => {
31 + let alive = true
32 + void (async () => {
33 + try {
34 + await initLaunch()
35 + if (getToken()) setIdentity(await api.me())
36 + } catch {
37 + // No session (or launcher unavailable): the login screen handles it.
38 + } finally {
39 + if (alive) setReady(true)
40 + }
41 + })()
42 + return () => {
43 + alive = false
44 + }
45 + }, [])
46 +
47 + const header = (
48 + <header className="app-header">
49 + <h1>آرام — میز کار صورت‌های مالی</h1>
50 + {identity && (
51 + <div className="row">
52 + <span className="muted">
53 + {identity.display_name} ({identity.role})
54 + </span>
55 + <button type="button" onClick={() => void api.logout()}>
56 + خروج
57 + </button>
58 + </div>
59 + )}
60 + {company && (
61 + <p className="muted">
62 + سال مالی {faNumber(company.year)} · وضعیت {company.status}
63 + </p>
64 + )}
65 + </header>
66 + )
67 +
68 + if (!ready) {
69 + return (
70 + <main dir="rtl" lang="fa" className="app">
71 + {header}
72 + <p className="muted">در حال آماده‌سازی…</p>
73 + </main>
74 + )
75 + }
76 +
77 + if (!identity) {
78 + return (
79 + <main dir="rtl" lang="fa" className="app">
80 + {header}
81 + <LoginPanel />
82 + </main>
83 + )
84 + }
85
86 return (
87 <main dir="rtl" lang="fa" className="app">
23 - <header className="app-header">
24 - <h1>آرام — میز کار صورت‌های مالی</h1>
25 - {company && (
26 - <p className="muted">
27 - سال مالی {faNumber(company.year)} · وضعیت {company.status}
28 - </p>
29 - )}
30 - </header>
88 + {header}
89
90 <CompanySetup onCreated={setCompany} />
91
frontend/src/api/client.test.ts
+58 -2
@@ -31,7 +31,63 @@ describe('api client', () => {
31 await expect(api.preflight(999)).rejects.toBeInstanceOf(ApiError)
32 })
33
34 - it('builds the relative export URL', () => {
35 - expect(api.exportMappingsUrl(7)).toBe('/api/v1/years/7/mappings/export')
34 + it('attaches the session token to every request (R1)', async () => {
35 + sessionStorage.setItem('aram.token', 'tok-123')
36 + const fetchMock = vi.fn().mockResolvedValue({
37 + ok: true,
38 + status: 200,
39 + json: async () => ({ chain_valid: true }),
40 + })
41 + vi.stubGlobal('fetch', fetchMock)
42 + // Re-import so the module picks up the stored token.
43 + const { api: freshApi } = await import('./client')
44 + await freshApi.auditVerify()
45 + const [, init] = fetchMock.mock.calls[0]
46 + expect(init.headers.Authorization).toBe('Bearer tok-123')
47 + sessionStorage.clear()
48 + })
49 +
50 + it('never sends an actor field on approve (R1)', async () => {
51 + const fetchMock = vi.fn().mockResolvedValue({
52 + ok: true,
53 + status: 200,
54 + json: async () => ({ approved: true }),
55 + })
56 + vi.stubGlobal('fetch', fetchMock)
57 + await api.approve(7)
58 + const [url, init] = fetchMock.mock.calls[0]
59 + expect(url).toBe('/api/v1/years/7/approve')
60 + expect(init.method).toBe('POST')
61 + expect(init.body).toBeUndefined()
62 + })
63 +
64 + it('downloads exports with the Authorization header, not a bare link (R1)', async () => {
65 + sessionStorage.setItem('aram.token', 'tok-xyz')
66 + const fetchMock = vi.fn().mockResolvedValue({
67 + ok: true,
68 + status: 200,
69 + blob: async () => new Blob(['x']),
70 + })
71 + vi.stubGlobal('fetch', fetchMock)
72 + vi.stubGlobal('URL', { createObjectURL: vi.fn(() => 'blob:1'), revokeObjectURL: vi.fn() })
73 + const { api: freshApi } = await import('./client')
74 + await freshApi.downloadMappings(7)
75 + const [url, init] = fetchMock.mock.calls[0]
76 + expect(url).toBe('/api/v1/years/7/mappings/export')
77 + expect(init.headers.Authorization).toBe('Bearer tok-xyz')
78 + sessionStorage.clear()
79 + })
80 +
81 + it('clears the session when the server answers 401 (R1)', async () => {
82 + sessionStorage.setItem('aram.token', 'expired')
83 + vi.stubGlobal(
84 + 'fetch',
85 + vi.fn().mockResolvedValue({ ok: false, status: 401, json: async () => ({ detail: 'ورود لازم است.' }) }),
86 + )
87 + const { api: freshApi } = await import('./client')
88 + const { getToken } = await import('./session')
89 + await expect(freshApi.auditVerify()).rejects.toMatchObject({ status: 401 })
90 + expect(getToken()).toBeNull()
91 + expect(sessionStorage.getItem('aram.token')).toBeNull()
92 })
93 })
frontend/src/api/client.ts
+66 -21
@@ -11,6 +11,7 @@ import type {
11 StatementsResult,
12 UnknownAccountsResult,
13 } from './types'
14 +import { authHeaders, clearSession, setSession, type Identity } from './session'
15
16 const BASE = '/api/v1'
17
@@ -24,7 +25,15 @@ export class ApiError extends Error {
25 }
26
27 async function request<T>(path: string, init?: RequestInit): Promise<T> {
27 - const res = await fetch(`${BASE}${path}`, init)
28 + const res = await fetch(`${BASE}${path}`, {
29 + ...init,
30 + headers: { ...authHeaders(), ...(init?.headers as Record<string, string> | undefined) },
31 + })
32 + if (res.status === 401) {
33 + // The session is gone (expired, revoked, or never existed): drop it so the
34 + // UI returns to the login screen instead of retrying with a dead token.
35 + clearSession()
36 + }
37 if (!res.ok) {
38 let detail = `HTTP ${res.status}`
39 try {
@@ -40,6 +49,24 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
49 return (await res.json()) as T
50 }
51
52 +/** Download a file with the session attached (a plain <a href> cannot send it). */
53 +async function download(path: string, filename: string): Promise<void> {
54 + const res = await fetch(`${BASE}${path}`, { headers: authHeaders() })
55 + if (res.status === 401) clearSession()
56 + if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`)
57 + const url = URL.createObjectURL(await res.blob())
58 + try {
59 + const link = document.createElement('a')
60 + link.href = url
61 + link.download = filename
62 + document.body.appendChild(link)
63 + link.click()
64 + link.remove()
65 + } finally {
66 + URL.revokeObjectURL(url)
67 + }
68 +}
69 +
70 function json(body: unknown): RequestInit {
71 return {
72 method: 'POST',
@@ -75,17 +102,18 @@ export const api = {
102
103 preflight: (yearId: number) => request<PreflightResult>(`/years/${yearId}/preflight`),
104
78 - approve: (yearId: number, actor: string) => request<ApproveResult>(`/years/${yearId}/approve`, json({ actor })),
105 + approve: (yearId: number) => request<ApproveResult>(`/years/${yearId}/approve`, { method: 'POST' }),
106
107 unknownAccounts: (yearId: number) => request<UnknownAccountsResult>(`/years/${yearId}/unknown-accounts`),
108
109 importMappings: (yearId: number, file: File) =>
110 request<MappingImportResult>(`/years/${yearId}/mappings/import`, multipart(file)),
111
85 - exportMappingsUrl: (yearId: number) => `${BASE}/years/${yearId}/mappings/export`,
112 + downloadMappings: (yearId: number) =>
113 + download(`/years/${yearId}/mappings/export`, `mappings-${yearId}.xlsx`),
114
87 - exportStatementsUrl: (yearId: number, format: 'xlsx' | 'json') =>
88 - `${BASE}/years/${yearId}/statements/export?format=${format}`,
115 + downloadStatements: (yearId: number, format: 'xlsx' | 'json') =>
116 + download(`/years/${yearId}/statements/export?format=${format}`, `statements-${yearId}.${format}`),
117
118 listNotes: (yearId: number) =>
119 request<{ notes: { note_id: number; note_number: string; title: string; statement: string; section: string }[] }>(
@@ -110,29 +138,46 @@ export const api = {
138 deleteMapping: (yearId: number, mappingId: number) =>
139 request<{ deleted: number }>(`/years/${yearId}/mappings/${mappingId}`, { method: 'DELETE' }),
140
113 - login: (username: string, password: string) =>
114 - request<{ username: string; display_name: string; role: string }>('/auth/login', json({ username, password })),
141 + login: async (username: string, password: string): Promise<Identity> => {
142 + const res = await request<Identity & { token: string }>('/auth/login', json({ username, password }))
143 + const who: Identity = { username: res.username, display_name: res.display_name, role: res.role }
144 + setSession(res.token, who)
145 + return who
146 + },
147 +
148 + logout: async (): Promise<void> => {
149 + try {
150 + await request<{ logged_out: boolean }>('/auth/logout', { method: 'POST' })
151 + } finally {
152 + clearSession()
153 + }
154 + },
155 +
156 + me: () => request<Identity>('/auth/me'),
157 +
158 + bootstrapAdmin: (username: string, password: string) =>
159 + request<{ username: string; role: string }>('/users', json({ username, password })),
160
116 - createUser: (username: string, password: string, role: string, actor: string) =>
117 - request<{ username: string; role: string }>('/users', json({ username, password, role, actor })),
161 + createUser: (username: string, password: string, role: string) =>
162 + request<{ username: string; role: string }>('/users', json({ username, password, role })),
163
164 auditVerify: () => request<{ chain_valid: boolean }>('/audit/verify'),
165
121 - lockYear: (yearId: number, actor: string) =>
122 - request<{ year_id: number; status: string }>(`/years/${yearId}/lock`, json({ actor })),
166 + lockYear: (yearId: number) =>
167 + request<{ year_id: number; status: string }>(`/years/${yearId}/lock`, { method: 'POST' }),
168
124 - requestReopen: (yearId: number, reason: string, actor: string) =>
125 - request<{ request_id: number; status: string }>(`/years/${yearId}/reopen/request`, json({ reason, actor })),
169 + requestReopen: (yearId: number, reason: string) =>
170 + request<{ request_id: number; status: string }>(`/years/${yearId}/reopen/request`, json({ reason })),
171
127 - approveReopen: (requestId: number, actor: string) =>
128 - request<{ request_id: number; status: string }>(`/reopen/${requestId}/approve`, json({ actor })),
172 + approveReopen: (requestId: number) =>
173 + request<{ request_id: number; status: string }>(`/reopen/${requestId}/approve`, { method: 'POST' }),
174
130 - reopenYear: (yearId: number, actor: string) =>
131 - request<{ year_id: number; status: string }>(`/years/${yearId}/reopen`, json({ actor })),
175 + reopenYear: (yearId: number) =>
176 + request<{ year_id: number; status: string }>(`/years/${yearId}/reopen`, { method: 'POST' }),
177
133 - backup: (dest: string, actor: string) =>
134 - request<{ dest: string; manifest: { audit_chain_valid: boolean } }>('/backup', json({ dest, actor })),
178 + backup: (dest: string) =>
179 + request<{ dest: string; manifest: { audit_chain_valid: boolean } }>('/backup', json({ dest })),
180
136 - verifyBackup: (dest: string, actor: string) =>
137 - request<{ valid: boolean; source_files: number; audit_entries: number }>('/backup/verify', json({ dest, actor })),
181 + verifyBackup: (dest: string) =>
182 + request<{ valid: boolean; source_files: number; audit_entries: number }>('/backup/verify', json({ dest })),
183 }
frontend/src/api/session.ts new
+94
@@ -0,0 +1,94 @@
1 +/**
2 + * Client side of R1 session auth (booklet 2.1).
3 + *
4 + * The bearer token lives in sessionStorage only: it is never written to disk,
5 + * never put in a URL, and disappears when the tab closes. The desktop launch
6 + * grant lives there too. Identity is whatever the server says it is — the UI
7 + * never sends an `actor` field.
8 + */
9 +
10 +const TOKEN_KEY = 'aram.token'
11 +const GRANT_KEY = 'aram.launch'
12 +const BASE = '/api/v1'
13 +
14 +export interface Identity {
15 + username: string
16 + display_name: string
17 + role: string
18 +}
19 +
20 +let identity: Identity | null = null
21 +let version = 0
22 +const listeners = new Set<() => void>()
23 +
24 +function notify() {
25 + version += 1
26 + listeners.forEach((fn) => fn())
27 +}
28 +
29 +export function subscribe(listener: () => void): () => void {
30 + listeners.add(listener)
31 + return () => listeners.delete(listener)
32 +}
33 +
34 +export function getSnapshot(): number {
35 + return version
36 +}
37 +
38 +/** Read per call, so a logout in another tab takes effect immediately. */
39 +export function getToken(): string | null {
40 + return sessionStorage.getItem(TOKEN_KEY)
41 +}
42 +
43 +export function getIdentity(): Identity | null {
44 + return identity
45 +}
46 +
47 +export function getLaunchGrant(): string | null {
48 + return sessionStorage.getItem(GRANT_KEY)
49 +}
50 +
51 +export function authHeaders(): Record<string, string> {
52 + const headers: Record<string, string> = {}
53 + const token = getToken()
54 + if (token) headers.Authorization = `Bearer ${token}`
55 + const grant = getLaunchGrant()
56 + if (grant) headers['X-Aram-Launch'] = grant
57 + return headers
58 +}
59 +
60 +export function setSession(newToken: string, who: Identity): void {
61 + identity = who
62 + sessionStorage.setItem(TOKEN_KEY, newToken)
63 + notify()
64 +}
65 +
66 +export function setIdentity(who: Identity): void {
67 + identity = who
68 + notify()
69 +}
70 +
71 +export function clearSession(): void {
72 + identity = null
73 + sessionStorage.removeItem(TOKEN_KEY)
74 + notify()
75 +}
76 +
77 +/** Exchange the desktop launcher's one-time token, then scrub it from the URL. */
78 +export async function initLaunch(): Promise<void> {
79 + const match = /(?:^|[#&])launch=([^&]+)/.exec(window.location.hash)
80 + if (!match) return
81 + const oneTime = decodeURIComponent(match[1])
82 + // Remove the fragment first: a reload must never replay a consumed token.
83 + window.history.replaceState(null, '', window.location.pathname + window.location.search)
84 + const res = await fetch(`${BASE}/auth/launch`, {
85 + method: 'POST',
86 + headers: { 'Content-Type': 'application/json' },
87 + body: JSON.stringify({ token: oneTime }),
88 + })
89 + if (res.ok) {
90 + const body = (await res.json()) as { grant: string }
91 + sessionStorage.setItem(GRANT_KEY, body.grant)
92 + notify()
93 + }
94 +}
frontend/src/components/AdminPanel.tsx
+8 -60
@@ -5,15 +5,7 @@ interface Props {
5 yearId: number
6 }
7
8 -interface Session {
9 - username: string
10 - role: string
11 -}
12 -
8 export default function AdminPanel({ yearId }: Props) {
14 - const [session, setSession] = useState<Session | null>(null)
15 - const [username, setUsername] = useState('')
16 - const [password, setPassword] = useState('')
9 const [message, setMessage] = useState<string | null>(null)
10 const [error, setError] = useState<string | null>(null)
11 const [busy, setBusy] = useState(false)
@@ -34,54 +26,11 @@ export default function AdminPanel({ yearId }: Props) {
26 }
27 }
28
37 - async function login(e: React.FormEvent) {
38 - e.preventDefault()
39 - setBusy(true)
40 - setError(null)
41 - try {
42 - const res = await api.login(username.trim(), password)
43 - setSession({ username: res.username, role: res.role })
44 - setPassword('')
45 - } catch (err) {
46 - setError(err instanceof ApiError ? err.message : String(err))
47 - } finally {
48 - setBusy(false)
49 - }
50 - }
51 -
52 - const actor = session?.username ?? ''
53 -
29 return (
30 <section className="card">
31 <h2>مدیریت، ممیزی و پشتیبان‌گیری</h2>
32
58 - {!session ? (
59 - <form className="row" onSubmit={login}>
60 - <label>
61 - نام کاربری
62 - <input value={username} onChange={(e) => setUsername(e.target.value)} required />
63 - </label>
64 - <label>
65 - گذرواژه
66 - <input
67 - type="password"
68 - value={password}
69 - onChange={(e) => setPassword(e.target.value)}
70 - required
71 - />
72 - </label>
73 - <button type="submit" disabled={busy}>
74 - ورود
75 - </button>
76 - </form>
77 - ) : (
78 - <p className="ok">
79 - وارد شده: {session.username} ({session.role})
80 - </p>
81 - )}
82 -
83 - {session && (
84 - <>
33 + <>
34 <div className="row">
35 <button
36 type="button"
@@ -98,7 +47,7 @@ export default function AdminPanel({ yearId }: Props) {
47 <button
48 type="button"
49 disabled={busy}
101 - onClick={() => run(async () => `سال قفل شد: ${(await api.lockYear(yearId, actor)).status}`)}
50 + onClick={() => run(async () => `سال قفل شد: ${(await api.lockYear(yearId)).status}`)}
51 >
52 قفل سال
53 </button>
@@ -114,7 +63,7 @@ export default function AdminPanel({ yearId }: Props) {
63 disabled={busy || !reopenReason}
64 onClick={() =>
65 run(async () => {
117 - const r = await api.requestReopen(yearId, reopenReason, actor)
66 + const r = await api.requestReopen(yearId, reopenReason)
67 setLastRequestId(r.request_id)
68 return `درخواست بازگشایی ثبت شد (${r.request_id}).`
69 })
@@ -128,8 +77,8 @@ export default function AdminPanel({ yearId }: Props) {
77 onClick={() =>
78 run(async () => {
79 if (lastRequestId === null) return ''
131 - await api.approveReopen(lastRequestId, actor)
132 - const r = await api.reopenYear(yearId, actor)
80 + await api.approveReopen(lastRequestId)
81 + const r = await api.reopenYear(yearId)
82 return `سال بازگشایی شد: ${r.status}`
83 })
84 }
@@ -148,7 +97,7 @@ export default function AdminPanel({ yearId }: Props) {
97 disabled={busy || !backupDest}
98 onClick={() =>
99 run(async () => {
151 - const r = await api.backup(backupDest, actor)
100 + const r = await api.backup(backupDest)
101 return `پشتیبان ساخته شد (زنجیرهٔ ممیزی: ${r.manifest.audit_chain_valid ? 'سالم' : 'مخدوش'}).`
102 })
103 }
@@ -160,7 +109,7 @@ export default function AdminPanel({ yearId }: Props) {
109 disabled={busy || !backupDest}
110 onClick={() =>
111 run(async () => {
163 - const r = await api.verifyBackup(backupDest, actor)
112 + const r = await api.verifyBackup(backupDest)
113 return `پشتیبان ${r.valid ? 'سالم' : 'مخدوش'} است (${r.source_files} فایل، ${r.audit_entries} ممیزی).`
114 })
115 }
@@ -168,8 +117,7 @@ export default function AdminPanel({ yearId }: Props) {
117 بررسی پشتیبان
118 </button>
119 </div>
171 - </>
172 - )}
120 + </>
121
122 {message && <p className="ok">{message}</p>}
123 {error && <p className="error">{error}</p>}
frontend/src/components/ApprovalPanel.tsx
+1 -6
@@ -9,7 +9,6 @@ interface Props {
9 export default function ApprovalPanel({ yearId }: Props) {
10 const [preflight, setPreflight] = useState<PreflightResult | null>(null)
11 const [approveResult, setApproveResult] = useState<ApproveResult | null>(null)
12 - const [actor, setActor] = useState('')
12 const [busy, setBusy] = useState(false)
13 const [error, setError] = useState<string | null>(null)
14
@@ -29,7 +28,7 @@ export default function ApprovalPanel({ yearId }: Props) {
28 setBusy(true)
29 setError(null)
30 try {
32 - setApproveResult(await api.approve(yearId, actor.trim()))
31 + setApproveResult(await api.approve(yearId))
32 } catch (err) {
33 setError(err instanceof ApiError ? err.message : String(err))
34 } finally {
@@ -44,10 +43,6 @@ export default function ApprovalPanel({ yearId }: Props) {
43 <button type="button" onClick={runPreflight} disabled={busy}>
44 اجرای کنترل‌ها
45 </button>
47 - <label>
48 - تصویب‌کننده
49 - <input value={actor} onChange={(e) => setActor(e.target.value)} maxLength={128} />
50 - </label>
46 <button type="button" onClick={approve} disabled={busy}>
47 تصویب سال
48 </button>
frontend/src/components/LoginPanel.tsx new
+82
@@ -0,0 +1,82 @@
1 +import { useState } from 'react'
2 +import { api, ApiError } from '../api/client'
3 +
4 +/**
5 + * Login screen (R1, booklet 2.1). Nothing else in the workbench renders without a
6 + * server-side session. The first-admin form is shown only as an explicit opt-in:
7 + * the server accepts it while the database has zero users and answers 401 after
8 + * that, so the bootstrap cannot be repeated.
9 + */
10 +export default function LoginPanel() {
11 + const [username, setUsername] = useState('')
12 + const [password, setPassword] = useState('')
13 + const [bootstrap, setBootstrap] = useState(false)
14 + const [busy, setBusy] = useState(false)
15 + const [error, setError] = useState<string | null>(null)
16 +
17 + async function submit(e: React.FormEvent) {
18 + e.preventDefault()
19 + setBusy(true)
20 + setError(null)
21 + try {
22 + if (bootstrap) {
23 + await api.bootstrapAdmin(username.trim(), password)
24 + }
25 + await api.login(username.trim(), password)
26 + setPassword('')
27 + } catch (err) {
28 + setError(err instanceof ApiError ? err.message : String(err))
29 + } finally {
30 + setBusy(false)
31 + }
32 + }
33 +
34 + return (
35 + <section className="card" aria-labelledby="login-title">
36 + <h2 id="login-title">{bootstrap ? 'ساخت نخستین مدیر' : 'ورود به آرام'}</h2>
37 + <p className="muted">
38 + برای دیدن و تغییر داده‌ها باید وارد شوید. هویت شما از نشستِ سمتِ سرور خوانده می‌شود.
39 + </p>
40 + <form className="row" onSubmit={submit}>
41 + <label>
42 + نام کاربری
43 + <input
44 + value={username}
45 + onChange={(e) => setUsername(e.target.value)}
46 + autoComplete="username"
47 + required
48 + />
49 + </label>
50 + <label>
51 + گذرواژه
52 + <input
53 + type="password"
54 + value={password}
55 + onChange={(e) => setPassword(e.target.value)}
56 + autoComplete={bootstrap ? 'new-password' : 'current-password'}
57 + minLength={bootstrap ? 8 : 1}
58 + required
59 + />
60 + </label>
61 + <button type="submit" disabled={busy}>
62 + {bootstrap ? 'ساخت مدیر و ورود' : 'ورود'}
63 + </button>
64 + </form>
65 + <button
66 + type="button"
67 + className="link"
68 + onClick={() => {
69 + setBootstrap((v) => !v)
70 + setError(null)
71 + }}
72 + >
73 + {bootstrap ? 'بازگشت به ورود' : 'نخستین اجراست؟ مدیر اول را بسازید'}
74 + </button>
75 + {error && (
76 + <p className="error" role="alert">
77 + {error}
78 + </p>
79 + )}
80 + </section>
81 + )
82 +}
frontend/src/components/MappingPanel.tsx
+2 -2
@@ -98,9 +98,9 @@ export default function MappingPanel({ yearId }: Props) {
98 <button type="button" onClick={importMappings} disabled={busy}>
99 درون‌ریزی نگاشت‌ها
100 </button>
101 - <a className="button" href={api.exportMappingsUrl(yearId)} download>
101 + <button type="button" onClick={() => void api.downloadMappings(yearId)} disabled={busy}>
102 برون‌بری نگاشت‌ها
103 - </a>
103 + </button>
104 </div>
105
106 {message && <p className="ok">{message}</p>}
frontend/src/components/StatementView.tsx
+4 -4
@@ -62,12 +62,12 @@ export default function StatementView({ yearId, refreshKey }: Props) {
62 <button type="button" onClick={build} disabled={busy}>
63 {busy ? 'در حال ساخت…' : 'ساخت صورت‌های مالی'}
64 </button>
65 - <a className="button" href={api.exportStatementsUrl(yearId, 'xlsx')} download>
65 + <button type="button" onClick={() => void api.downloadStatements(yearId, 'xlsx')} disabled={busy}>
66 خروجی اکسل
67 - </a>
68 - <a className="button" href={api.exportStatementsUrl(yearId, 'json')} download>
67 + </button>
68 + <button type="button" onClick={() => void api.downloadStatements(yearId, 'json')} disabled={busy}>
69 خروجی JSON
70 - </a>
70 + </button>
71 <div className="tabs">
72 {['BS', 'IS', 'CF', 'EQ'].map((t) => (
73 <button