سامانه صدور فاکتور و حسابداری
qa/finora-identity-rpc-security-tripwire-20261122
Issue229 / ADR216 — precise P0 fix handoff to Codex-main
Status: implementation guidance and accepted QA evidence only; NOT IMPLEMENTED. This document is subordinate to PROJECT_STATE.md, accepted docs/adr/0216-draft-first-document-identity.md and docs/superpowers/specs/2026-11-13-draft-first-accounting.md. It is neither a competing accounting engine nor permission to migrate posted financial history. Review the cited current PR231 candidate, not just protected main.
Proven outcome (do not confuse CI SUCCESS with product acceptance)
Code SHA bd244962915824d0ad825e99b5cda4d530f18402 of Draft PR231 passed WP2 45019982974, WP1 45019983033, Quality 45019982985, and Security 45019982983 (conditional Dependency Review SKIPPED). Two existing Issue229 browser cases are intentionally test.fail. Those green runs are successful reproduction of a P0 contract failure.
The same real, non-owner Auth JWT with commerce:create, without accounting:approve or reusable assigned roles, successfully POSTED both a sale and a credit purchase. PostgreSQL readback verified source posted, one linked posted voucher each, balanced journal lines, matching actor audit and server final-number counter. The WP2 job emitted both FINORA_ISSUE229_APPROVAL_EXPECTED_RED and FINORA_ISSUE229_PURCHASE_APPROVAL_EXPECTED_RED. The purchase account mapping is expense debit 170 / payable credit 170. This is not a simulated RLS-only result.
Exact, verified integration and permission fault line
| Owner target | Current candidate anchor | Proven failure / required intervention |
|---|---|---|
| Purchase Save (new) | js/purchases.js:282-352, especially 327-340 |
purSave inserts a locally marked draft purchase but immediately calls jeRpcAutoPost('purchase', record.id) at 332, then reports posted. Save must instead atomically commit source + linked journal draft, without posting or final number. |
| Purchase correction Save | js/purchases.js:100-115 |
purchaseSaveSeamless reverses and then calls finalizePurchasePilotDraft(newId) at 113, coupling ordinary correction Save to posting. Keep original posted and reversal history immutable, but make correction draft finalization explicit and separately authorized. |
| Purchase explicit Finalize | js/purchases.js:189-205 and 230-235 |
Existing finalizePurchasePilotDraft only tests client requireWrite and jeRpcAutoPost; a client guard is not a server approval boundary. |
| Sales draft vs posting | js/invoices.js:383-405, 513-632 |
New sale Save persists a business-only draft; finalizeInvoiceDocument posts with jeRpcAutoPost. Bring it into the same source + linked journal draft contract as purchases, not a separate engine. |
| Display projection | js/invoices.js:367-375; js/purchases.js:64-72 |
Sales treats any journalVoucherId as posted, even if linked voucher is still draft. Purchase returns legacy_review for a linked draft. Treat linked effective draft as draft only after scope/link validation. Never infer posted from link existence alone. |
| Shared client RPC | js/journal-rpc.js:211-239, 241-313 |
jeRpcPersistSourceRecord flushes a business source alone via generic sync, then jeRpcAutoPostOnce calls finora_journal_autopost at 285-288, creating + posting in one separate call. Replace with server atomic draft-saving and separate finalize RPC; retain freeze/reconcile for ambiguous transport outcomes. |
| Source-linking SQL | supabase/migrations/20261117110000_wp1_autopost_source_link_atomic.sql:3-104 |
The existing SECURITY DEFINER autopost RPC accepts private.finora_phase1a_authorize(org,'create',typ) at 21, creates journal at 77, calls private.finora_phase1a_post_core(...,true) at 91, then writes source posted at 94-101. Its source-link atomicity is a useful invariant; its authorization and direct-post semantics violate draft-first. |
| SQL authorization split | supabase/migrations/20261016101500_phase1a_journal_core.sql:40-68,228-298; later override 20261016103100_phase1a_autopost_server_authority.sql:49-122 |
finora_phase1a_authorize resolves sale/purchase to commerce, and post_core(p_auto=true) chooses create for source vouchers (later override 63-79), while p_auto=false requires accounting approve. An approver-only Finalize path must check approval server-side regardless of client flag or sourceType. Do not edit applied historical migration files; use controlled additive migration after preflight/rollback review. |
Required atomic command contracts (implementation owner: Codex-main)
- Save/Create/Edit commercial source with generated draft: one server transaction, scoped to Auth user + active organization/company/fiscal year. Validate source identity, fields, version, required accounts/dimensions, and approved immutable posting-profile snapshot. Generate/upsert exactly one draft journal with matching source/version and balanced journal lines, bidirectional link, provisional number and permanent attachment reservation per ADR216. No posted timestamp, posted actor or final-number consumption on Save. Retry with stable idempotency identity; concurrent Save gets deterministic winner/version error. Failed call rolls back both source and draft; never show false success.
- Finalize existing source-linked draft: distinct explicit server RPC, requiring
accounting:approveon actual membership/entitlement for every sale/purchase path, not merelycommerce:createor any JSrequireWrite. Validate source and voucher version under lock; check organization/company/owner linkage, fiscal locks, debit/credit, dimensions, source state, and number reservation. In one transaction change voucher and source to posted; allocate exactly one final number; audit the real approver. A legitimate accounting-only approver may need a scoped accounting read path to validate the source; do not silently require commerce CREATE to approve. - Block legacy bypass: once draft-first RPCs exist, no direct
finora_journal_autopostentry may allowcommerce:create-only JWT to finalize. Prefer explicit versioned deprecation/restriction of the public RPC over a client-only toggle. Audit all other paths that reachpost_core(p_auto=true)(including reversal workflows) for intended independent permissions; avoid blanket changes that silently break other source types. - Update/Delete: only linked drafts can mutate with optimistic versions, atomic recomputation and audit. Source deletion and generated draft tombstone are one transaction. Direct generated-voucher delete is rejected. Posted and reversed source/voucher/lines stay immutable; corrections use approved reversal + new linked draft, never mass
posted→draftrewrites. Keep permanent attachment numbers reserved after deletion and separate fiscal numbering. - UI/report projections: on successful Save, show source draft + linked journal draft, route explicit Finalize to authorized approver with clear denial for seller, and render draft/posted/reversed accurately in purchase/sale/report filters. Avoid duplicate stock or expense effects by counting a single business event once. Prevent edited drafts from being mistaken for posted because they have
journalVoucherId.
Executable acceptance matrix — product acceptance, not xfail success
| Probe | Mandatory result |
|---|---|
| Real JWT seller: commerce:create yes, accounting:approve no; purchase + sale Save | 2xx linked draft only; exactly one matching journal draft per source; valid balanced lines, source+draft audit, no posted journal/final number |
| Same seller: Finalize, including old autopost RPC | 403/SQLSTATE 42501 for approval boundary; source/journal/lines/audit/final counter unchanged |
| Real distinct approver: accounting:approve yes, source linked draft | Explicit Finalize 2xx, one posted voucher + consistent source status, original business fields unchanged, actor = approver, counter +1; correct debit/credit and fiscal lock |
| Replay / same idempotency key / lost-response retry | Original source/voucher/attachment/final-number identity returned, no duplicate posting or audit; state reconciled |
| Stale version, concurrent approvals, wrong tenant/company, locked year, invalid lines | Deterministic reject and complete rollback; zero partial posting or counter consumption |
| Draft edit/delete; posted mutation/reversal | Atomic draft and generated-voucher update/tombstone; immutable posted history, audited reversal/correction and permanent attachment retention |
| Legacy history conversion | No mass posted/reversed downgrade or silent deletion; graph inventory, fingerprints, dry-run reconciliation, rollback and owner release approval |
| Browser + real DB | Remove BOTH test.fail annotations from scripts/accounting-document-workflow.spec.js only after actual fixed behaviour is shown. Convert scripts/wp2-source-approval-boundary-jwt-e2e.mjs from two expected-product-RED probes into normal negative-seller/positive-approver contract tests. Then re-run exact SHA Quality, WP1, WP2, Security and independent review. |
Safety/rollback: run migration UP/DOWN/UP and historical snapshot comparison only on disposable database first. Before any authorized production cutover, perform read-only source graph inventory, backup + verified restoration point, existing old-RPC caller census, controlled feature-flag rollout and rollback plan that does not reverse posted history or reuse numbers. Keep Issue216 and Issue229 P0 OPEN until these criteria pass. PR231 remains Draft/unmerged. No real financial data accessed or modified while writing this handoff.