سامانه صدور فاکتور و حسابداری
audit/wp0-hardening-baseline-20261102
audit-remediation-wave3-4-20261002
audit-remediation-wave3-verify-20261002
audit-remediation-wave4-20261002
audit-remediation-wave4b-20261002
audit-remediation-wave5a-identity-20261002
audit-remediation-wave5b-offboarding-20261002
audit-remediation-wave5c-authorization-20261002
audit-security-intent-review-20261002
audit/finora-financial-core-20261115
audit/finora-master-prompt-phase0-20261016
audit/finora-stage3-legacy-source-readonly-20261023
audit/full-controls-20261030
audit/owner-live-state-reconcile-20261012
audit/owner-review-20261007
audit/phase1-live-permissions-readonly-20261013
audit/reconcile-live-state-20261006
audit/reconcile-state-20261002
audit/wp0-hardening-baseline-20261102
branding-login-favicon-20261002
c8-workflow-task1
c8-workflow-task2
c8-workflow-task3
chore/wave0-pages-gate-closeout
claude-code-plugins-setup
design/finora-c01-authoritative-source-draft-20261124
docs-wave4b-verified-20261002
docs/active-company-invoice-release-evidence-20261014
docs/agent-operating-model-20261114
docs/chart-taxpayer-release-evidence-20261004
docs/cloud-only-agent-orchestration-20261115
docs/confirm-finora-product-charter-20261115
docs/continuation-20261030
docs/d4a-verified
docs/external-work-review-20261121
docs/finora-audit-continuity-20261014
docs/finora-backup-merge-evidence-20261014
docs/finora-ci-reconciliation-20261122
docs/finora-codex-master-prompt
docs/finora-eight-phase-plan-20261011
docs/finora-f002-live-buyer-filter-verified-20261015
docs/finora-license-race-release-evidence-20261014
docs/finora-license-rollout-acceptance-20261015
docs/finora-phase0-repeat-and-pages-nav-verified-20261015
docs/finora-phase0-repeat-evidence-20261015
docs/finora-selectors-release-and-fixture-qa-20261015
docs/finora-stagea-pr240-ci-triage-20261123
docs/finora-test-license-live-pass-20261015
docs/finora-v2-m01-coverage-20261124
docs/handoff-charter-v2-20261124
docs/invoice-product-search-release-20261011
docs/invoice-workspace-release-20261007
docs/phase-status-20261031
docs/phase0-acceptance-release-evidence-20261012
docs/phase0-admin-provision-release-evidence-20261012
docs/phase0-core-bundle-owner-login-open-20261013
docs/phase0-duplicate-js-release-20261016
docs/phase0-f001-auth-rest-shared-timeout-20261013
docs/phase0-f001-owner-login-observed-20261013
docs/phase0-f001-second-device-fail-40s-20261013
docs/phase0-f003-release-verification-20261011
docs/phase0-f004-print-release-evidence-20261012
docs/phase0-f004-watermark-release-evidence-20261012
docs/phase0-f005-large-selector-release-20261012
docs/phase0-f005-release-evidence-20261012
docs/phase0-f006-dark-release-evidence-20261012
docs/phase0-f008-final-pr-closure-evidence-20261012
docs/phase0-f008-reconcile-stale-prs-20261012
docs/phase0-f107-production-evidence-20261012
docs/phase0-kavenegar-otp-preflight-release-20261012
docs/phase0-login-release-evidence-20261012
docs/phase0-login-rest-bootstrap-stage-release-20261012
docs/phase0-owner-app-assets-bundle-release-20261013
docs/phase0-owner-login-csp-release-20261012
docs/phase0-reconcile-postmerge-evidence-20261012
docs/phase0-site-probe-release-evidence-20261012
docs/phase0-startup-release-evidence-20261012
docs/phase3-treasury-release-evidence-20261014
docs/pilot-posted-correction-release-evidence-20261014
docs/pilot-purchase-correction-release-evidence-20261014
docs/print-persian-release-verification-20261011
docs/qa-ci-triage-218-20261122
docs/real-account-qa-20261030
docs/release-state-20261007
docs/seamless-amendment-release-20261014
docs/seamless-document-correction-release-20261014
docs/settings-login-release-20261025
docs/stripe-qa-deployment-evidence-20261011
docs/ux-f2-release-evidence-20261011
docs/ux-f2-release-verification-20261011
docs/wave0-closeout
docs/wave2-closeout
exec-phase1-architecture
exec-phase1-implementation
exec-phase1-qa
exec-phase1-security-release
exec-phase1-ux
feat/accounting-document-draft-approval-20261011
feat/accounting-document-release-candidate-20261011
feat/active-company-strict-isolation-20261014
feat/admin-provisioning-reconciled-20261011
feat/admin-secure-user-provisioning-20261011
feat/admin-user-provisioning-merged-20261011
feat/d4a-request-work-queue
feat/document-lifecycle-atf-20261118
feat/document-lifecycle-temp-permanent-atef
feat/draft-first-attachment-lifecycle-216
feat/finora-offline-encrypted-backup-20261014
feat/finora-phase-a-navigation-20261023
feat/finora-stripe-sandbox-edge-gate
feat/immutable-attachment-temporary-vouchers
feat/iran-accounting-design-audit
feat/journal-document-lifecycle-20261118
feat/journal-rpc-repository-adapter-20261117
feat/office-c7-fulltext-ocr-provenance
feat/password-recovery-admin-reset-20261025
feat/pilot-expense-income-inplace-amendment-20261014
feat/pilot-journal-invoice-correction-20261014
feat/pilot-purchase-correction-20261014
feat/pilot-treasury-unallocated-correction-20261014
feat/retain-document-editor-after-save-20261014
feat/seamless-financial-document-correction-20261014
feat/slice-b-tenant-rbac
feat/stripe-sandbox-invoice-probe
feature/accounting-core-p0
feature/accounting-product-guidance
feature/admin-identity-phone-auth
feature/commercial-rnd
feature/finora-phase1a-supabase-cli-20261016
feature/finora-stage2-manual-canary-20261017
feature/finora-stage3-commercial-payload-20261023
feature/finora-stage3-enforce-invoice-rpc-20261023
feature/finora-stage3-enforce-purchase-red-20261023
feature/invoice-workspace-cleanup
feature/phase0-kavenegar-otp-preflight-20261012
feature/ux-commerce-settings-r2
fix-shell-scroll-live-cache-20261002
fix-shell-scrollbar-explicit-ownership-20261002
fix-shell-scrollbar-ownership-20261002
fix-shell-scrollbar-right-edge-20261002
fix/about-bug-report-20261114
fix/active-company-invoice-scope-20261014
fix/active-company-isolation-reconcile-20261014
fix/admin-central-password-reset-20261028
fix/auth-network-diagnostics
fix/chart-taxpayer-reference-20261003
fix/combobox-enter-reliability
fix/combobox-live-search
fix/combobox-production-cache
fix/combobox-release-asset-v2
fix/company-edit-action-20261028
fix/company-edit-pilot-delete-20261014
fix/company-form-action-state-20261014
fix/company-form-action-state-rebased-20261014
fix/contact-operational-balance-20261111
fix/dark-theme-contrast
fix/financial-lifecycle-recovery-20261124
fix/finora-accounting-test-organization-readiness-20261015
fix/finora-b01-safe-org-switch-20261124
fix/finora-b02-sync-recovery-20261124
fix/finora-b03-conflict-review-20261124
fix/finora-org-license-bootstrap-race-20261014
fix/finora-stage3-posted-source-immutable-20261023
fix/finora-v2-b03-r2-qa-20261124
fix/finora-v2-b03-r3-readonly-20261124
fix/g01-asof-financial-position-20261128
fix/invoice-product-search-rehydrate-20261011
fix/invoice-search-cache-bust
fix/issue229-linked-draft-status-20261122
fix/login-assets-retry-20261014
fix/login-inert-startup-20261110
fix/login-member-access-20261101
fix/login-resilience-20261017
fix/login-short-viewport-20261028
fix/login-startup-readiness-20261024
fix/navigation-utilities-placement-20261105
fix/office-c7-source-ref-binding
fix/office-c7-source-ref-binding-v2
fix/owner-login-network-20261026
fix/password-recovery-invalid-cancel-20261026
fix/payment-amount-format-20261111
fix/phase0-admin-provision-seat-bootstrap-20261012
fix/phase0-auth-bundled-assets-for-unstable-isp-20261013
fix/phase0-auth-handler-binding-stalled-session-20261012
fix/phase0-login-context-stage-visibility-20261012
fix/phase0-login-single-local-bundle-20261013
fix/phase0-login-site-probe-clarity-20261012
fix/phase0-login-ui-ready-20261012
fix/phase0-modal-dashboard-drill-20261011
fix/phase0-pages-blocking-core-bundles-20261013
fix/phase0-print-no-draft-watermark-20261012
fix/phase0-startup-parallel-asset-load-20261012
fix/phase3-behavioral-verification
fix/preserve-pending-edits-20261121
fix/print-persian-digit-consistency-20261011
fix/recovery-login-startup-20261027
fix/report-opening-balance-release-20261130
fix/settings-checkbox-persistence-20261024
fix/taxpayer-arithmetic-20261004
fix/ux-keyboard-search-f2-20261011
fix/wave2-request-input-integrity
hardening/c01-source-draft-20261129
hardening/global-draft-conversion-20261113
hardening/wp1-ledger-integrity-20261102
integration/finora-execution-20261124
integration/issue229-ui-qa-20261122
integration/wp1-ledger-core-20261115
integration/wp2-manual-journal-rpc-20261116
main
ops-heartbeat-v2-20261002
ops-progress-heartbeat-rule-20261002
ops/wave4-production-20261003
plan/financial-core-phase1-approval-20261016
qa/attachment-allocator-two-session-20261122
qa/draft-first-save-red-evidence-20261122
qa/finora-autopost-retry-identity-red-20261122
qa/finora-identity-rpc-security-tripwire-20261122
qa/finora-issue223-manual-kardex-browser-red-20261123
qa/finora-issue223-stock-real-jwt-20261123
qa/finora-issue238-inventory-count-browser-red-20261123
qa/finora-issue238-save-browser-red-20261122
qa/finora-login-cors-header-preflight-20261025
qa/finora-phase0-saved-session-repeat-20261015
qa/finora-phase5-posted-insert-jwt-red-20261123
qa/finora-stage3-ui-jwt-autopost-20261023
qa/finora-v2-g01-report-reconciliation-20261125
qa/free-supabase-local-wp2-20261116
qa/issue229-approval-boundary-jwt-20261122
qa/issue229-sale-save-linked-draft-red-20261122
qa/phase0-acceptance-start-20261012
qa/phase0-f005-account-project-contract-stress-20261012
qa/phase0-f005-selector-stress-20261012
qa/phase0-f006-dark-contrast-20261012
qa/post-wave4-verification-20261003
qa/posted-source-immutable-jwt-20261122
qa/pr219-wp1-disposable-dburl-proof-20261123
qa/purchase-source-jwt-20261122
qa/real-settings-acceptance-20261025
qa/recovery-mail-acceptance-20261026
qa/source-autopost-jwt-atomicity-20261122
qa/wave0-negative-gate-proof
qa/wp2-auth-tenant-e2e-20261117
qa/wp2-authorized-journal-write-20261122
qa/wp2-financial-paths-reconciliation-20261122
qa/wp3-financial-tenant-isolation-20261117
remediation/wave0-liveqa-wave1
remediation/wave2-request-integrity
staging/finora-stage22-free-20261022
state-scroll-verified-20261002
state-wave4b-production-20261002
state-wave5a-production-20261002
test/finora-accounting-boot-readiness-20261015
test/finora-f0-02-production-selectors-20261015
test/finora-pages-commerce-event-wiring-20261015
test/finora-pages-invoice-selectors-readonly-20261015
test/finora-stage3-jwt-source-post-20261023
test/phase0-invoice-fixture-bootstrap-20261016
test/phase0-invoice-persistence-20261011
test/phase0-pages-delayed-dispatcher-20261016
ux-scroll-ownership-20261002
work/finora-stage3-enforce-purchase-green-20261023
work/finora-stage3-enforce-sale-green-20261023
work/finora-stage3-payload-green-20261023
| 1 | FINORA — Hardening & Completion Master Prompt (for Codex) |
| 2 | Paste this whole document into Codex as the task, but run ONE work package per session: start with WP0 + WP1 only, read its report, then continue with the next. Execute the work packages in order. Report to the owner in Persian. Code, commands, paths, URLs and identifiers stay in English. |
| 3 | 0. Mission and honesty contract |
| 4 | You are the implementer of Finora (Persian/RTL ERP for Iran). Repo: davoodmehraban89/Factor-easy. Production Supabase project: hcsixhqbyuhpshfwqpjx. Live site: factoreasy.ir (GitHub Pages from main). The owner (Davood) is a non-developer who wants a product he can sell. He cannot pay for foreign services or buy a domain, so do not require paid or card-based services. |
| 5 | Mission: close every deficiency listed in section 1 with evidence, without breaking what already works. |
| 6 | Honesty contract (violations void the work): |
| 7 | "Done" means: code merged or PR-ready, tests added that failed before the fix and pass after, all repo gates green, and evidence recorded. A menu, form or doc existing is not done. |
| 8 | Never delete, skip, weaken or loosen a test or assertion to make a gate pass. |
| 9 | Never claim production behaviour you did not observe. If you cannot observe something, write "NOT VERIFIED" and why. |
| 10 | Never fabricate data, results, logs, approvals, or connections. |
| 11 | Never print secrets, keys, tokens, connection strings or passwords in chat, logs, commits or docs. |
| 12 | 1. Verified baseline (re-verify each item yourself before relying on it) |
| 13 | Independent read-only audit, 2026-11-01, main at 4416794: |
| 14 | Repo: 1267 commits; 56 JS files in js/ (~890 KB, very long lines up to ~1200 chars); 81 migration files; 23 SQL tests; 124 docs; PROJECT_STATE.md ~88 KB. |
| 15 | 32 node-based gates (scripts/*-check.mjs, syntax-check, quality-check, etc.) all PASS locally. Playwright specs were not run in the audit. |
| 16 | Production DB: 6 auth users, 1 admin, 777 records rows (20 invoices, 11 journalVouchers, 22 journalLines), 18 public tables all with RLS, 82 applied migrations, last 20261012075507. |
| 17 | Tenant isolation PASSED a two-user negative test (user B could not read, insert, update, delete in A's organization, self-promote, extend license, call admin_set_license, or see other profiles/licenses/members). |
| 18 | Ledger integrity FAILED: with a valid authenticated user, the server accepted (T2) a journalVouchers record with status='posted' whose journalLines were unbalanced (Dr 1000 / Cr 300), and (T3) a NEW journalLines row inserted into an already-posted voucher. Existing triggers finora_guard_posted_journal, finora_guard_posted_journal_children, finora_guard_posted_source_records fire only BEFORE UPDATE OR DELETE; no function in public/private references debit/credit balancing. Double-entry is enforced only in browser JS. |
| 19 | Server-side financial core (Phase 1A, Stage 1-3, finora_sync_records_v2, posting RPCs) exists only on unmerged branches/PRs (#162-#173 chain) and is NOT on production. |
| 20 | Migration drift: production ledger has 20261007165208 phone_identity_profile; main has no matching file (stale PR #58 has a different timestamp). |
| 21 | CSP in index.html: script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net. ~403 inline event-handler attributes, 339 of them onclick= handlers; ~107 window.x = function overrides; wrappers like js/patches.js wrap window.commitSaveInvoice. |
| 22 | Supabase Auth: Leaked Password Protection OFF. Advisor: 21 SECURITY DEFINER RPCs callable by authenticated (all inspected ones check auth.uid()/is_admin()/org capability; none callable by anon); 3 private office-workflow tables have RLS but no policy; per docs/FINORA_PHASE1_SECURITY_READONLY_AUDIT_2026-10-13.md only 3/10 private tables have RLS. |
| 23 | Not accepted per the repo's own registers: real-account acceptance, real printer, two concurrent users, owner-device login stability (Issue #106), real production backup + restore drill, purchase correct/cancel path under ENFORCE (returnPostedPurchaseAsDraft, cancelPostedPurchasePilot, purchaseSaveSeamless). |
| 24 | Not implemented: real Moodian (Iran tax authority) API submission. |
| 25 | 2. Non-negotiable engineering rules |
| 26 | Production is live with real data. Additive, backward-compatible migrations only (expand/contract). Never DROP/TRUNCATE/rewrite existing records. Never mutate posted history; corrections are reversal/adjustment documents. |
| 27 | Every DB change is proven first on a disposable PostgreSQL 17 (the repo already does this in CI: see identity-wave5a-database in .github/workflows/quality.yml and supabase/tests/). Never run experiments on production. Never use live financial rows for tests. |
| 28 | Shadow, then enforce. New strict guards ship first in shadow mode (log violations, do not block), driven by a server-side flag (e.g. a row in a locked settings table, changeable only by admin RPC). Audit existing production data in shadow mode, report violations, and only then enable enforcement. |
| 29 | Frontend must never call a server capability that production lacks. main auto-deploys to GitHub Pages. Feature-detect (capability probe/flag) and fall back to current behaviour until the owner confirms the DB migration is applied. |
| 30 | Keep existing security invariants: admin role is server-side only (profiles.role, no client path, not obtainable via username); email confirmation stays ON; RLS on every public table; no service_role key in client code. |
| 31 | Git: one branch and one PR per work package, small reviewable commits, never force-push main, never rewrite published history, do not merge stale/conflicting PRs blindly. If AGENTS.md/PROJECT_STATE.md record standing owner merge authority, follow it; otherwise open the PR and ask. |
| 32 | After every work package: update PROJECT_STATE.md (see WP9), keep it factual, mark anything unobserved as NOT VERIFIED. |
| 33 | Owner gates (stop and ask in Persian, with a ready checklist, only for these) |
| 34 | G1 applying any migration to production (after full proof + backup). |
| 35 | G2 Supabase dashboard settings (Leaked Password Protection, SMTP/SMS provider secrets, URL config). |
| 36 | G3 supplying a DB connection string for backup/restore drills (secret, via environment only). |
| 37 | G4 creating any test account/data on production. |
| 38 | G5 spending money or using a card-based service. |
| 39 | Everything else: decide and proceed. |
| 40 | 3. Work packages (execute sequentially; do not start the next until the previous passes its gate) |
| 41 | WP0 — Baseline, inventory, reconciliation (no behaviour change) |
| 42 | Read AGENTS.md, AI_BOOTSTRAP.md, PROJECT_STATE.md, docs/CURRENT_WORK_REGISTER_2026-10-30.md, docs/NAVIGATION_RECOVERY_2026-10-31.md, docs/audits/2026-10-31/. |
| 43 | Run all gates from .github/workflows/quality.yml, qa.yml, security.yml, release-gate.yml locally (including Playwright with npm install --no-save @playwright/test@1.55.0 pdf-lib@1.17.1 && npx playwright install --with-deps chromium). Record exact pass/fail counts. Any failure at baseline is reported first, not hidden. |
| 44 | List every open PR/branch with: purpose, base, conflicts with main, tests status, whether it is a prerequisite of the financial-core chain. Output a table; recommend merge/rebase/close per item; do not merge yet. |
| 45 | Migration drift: recover the exact executed SQL for 20261007165208 phone_identity_profile from the production migration ledger (read-only: select statements from supabase_migrations.schema_migrations where version='20261007165208') and archive it as supabase/migrations/20261007165208_phone_identity_profile.sql with a header comment that it is a post-hoc archive of an already-applied migration. Do NOT re-apply. Add a CI/check script that compares repo migration versions against a committed manifest so drift is detected. |
| 46 | Reproduce deficiencies D1 and D2 (Appendix A) on a disposable DB before any fix and save the failing output as evidence. |
| 47 | Gate: baseline report + reproduction evidence delivered in Persian. |
| 48 | WP1 — Server-side ledger integrity (P0, highest priority) |
| 49 | Goal: the database itself must make an unbalanced, mutable or inconsistent ledger impossible, regardless of which client writes. Restrict constraint triggers with a WHEN clause to the ledger collections so sync speed for other collections is unaffected, and make sure no client-callable function can set the posting flag. |
| 50 | Start from the existing chain (PRs #162-#173, finora_sync_records_v2, posting RPCs, Stage 1-3 SQL/tests). Review it, rebase onto current main, reconcile conflicts. Do not merge it as-is; port what is correct. Per docs/CURRENT_WORK_REGISTER_2026-10-30.md, PR164 and PR167 hold intentionally RED tests (not release-ready), and PR162 depends on finora_sync_records_v2, which was missing on production at the last recorded check. |
| 51 | Implement, additive and shadow-first: |
| 52 | posting RPC (e.g. finora_post_journal_voucher(p_organization_id, p_voucher_id)) executing in ONE transaction: validates ≥2 lines; every line has exactly one of debit/credit > 0; amounts are integers in the minor unit used by the app (rial: integer); no negatives; sum(debit)=sum(credit) exactly; all lines belong to the same organization/company/fiscal year as the voucher; account exists, is postable and active; fiscal period is open; assigns a gap-free per-company/per-year number under lock; sets status; writes audit event. |
| 53 | A constraint-style trigger (DEFERRABLE INITIALLY DEFERRED constraint trigger) on public.records that, at commit, rejects any voucher with status in ('posted','reversed') whose lines are unbalanced or missing, and rejects direct client writes that set status='posted' without going through the posting RPC (e.g. RPC sets a transaction-local setting finora.posting=on; the trigger checks it). Apply the same principle to journalLineDimensions. |
| 54 | Close D2: extend the existing guards so that INSERT of journalLines/journalLineDimensions into a voucher that is posted/reversed is rejected (today only UPDATE/DELETE is guarded). |
| 55 | Reversal RPC: creates a counter-voucher atomically, links both, original stays immutable. |
| 56 | Server-side idempotency (unique posted-source index already exists: keep it) and concurrency tests (parallel posting, duplicate numbers). |
| 57 | Legacy audit (read-only) in shadow mode: query production-shaped data for existing posted vouchers that are unbalanced/orphaned/duplicated-numbered. Output a report (counts and ids only, no business content). Never auto-fix posted history; propose reversal/adjustment entries and ask the owner. |
| 58 | Client: route posting/reversal through the RPC when the capability probe says it exists; otherwise keep the current path. No success toast unless the server confirmed. Show server rejection reasons in Persian. |
| 59 | Resolve the known blocker: make returnPostedPurchaseAsDraft, cancelPostedPurchasePilot, purchaseSaveSeamless correct under ENFORCE, with negative tests, before enabling enforcement for purchases. |
| 60 | Extend coverage source-by-source (sales invoices, purchase invoices, receipts/payments, cheques, expenses, opening/closing entries, COGS/inventory where modeled). For each source: automatic voucher, balanced by construction, reversible, tested. Anything not covered stays explicitly labelled "not yet server-enforced" in UI/docs. |
| 61 | Provide DOWN scripts for every migration and prove UP/DOWN/UP on the disposable DB. |
| 62 | Tests required (SQL in supabase/tests/, wired into CI with the disposable Postgres job; JS invariants in scripts/): |
| 63 | D1/D2 reproductions from Appendix A that fail on current main and pass after. |
| 64 | Balanced/unbalanced, single-sided, negative, zero-amount, rounding, multi-currency lines, closed period, wrong company/org, duplicate number under concurrency, reversal chain, immutable-after-post (insert/update/delete of lines and header), direct REST bypass attempt, idempotent re-post. |
| 65 | 1000-event journey with a final trial-balance equality check (repo already has related fixtures; extend them). |
| 66 | Gate: all new tests red-then-green; UP/DOWN/UP proven; shadow report delivered; G1 package prepared (ordered SQL, backup step, verification queries, rollback) but NOT applied without owner approval. |
| 67 | WP2 — Security hardening |
| 68 | CSP and inline handlers: introduce a single delegated event system (data-action attributes + one registry) and migrate the ~403 inline onclick=/on*= handlers module by module (also move any inline script blocks in index.html into files). Add a ratchet check (scripts/ gate) that fails if the count of inline handlers increases, then reaches zero. Target CSP: script-src 'self' (and https://cdn.jsdelivr.net only if still required; prefer vendoring with pinned versions and SRI), remove 'unsafe-inline' from script-src. Keep a documented, tested exception list for style-src. Verify with Playwright that every menu, dialog, print path and login flow still works with the stricter CSP (zero CSP violations in console). |
| 69 | Persistent two-user negative suite: convert the Appendix A isolation tests (T4-T14) into committed SQL tests run in CI on the disposable DB, plus tests for invitation, offboarding/revocation (revoked member's existing session must lose access), org-id spoofing in every one of the 21 authenticated-callable SECURITY DEFINER RPCs, and update_my_identity_profile cross-user mutation. |
| 70 | Private schema: for the 7 private tables without RLS, either enable RLS (deny-by-default) or document and test why they are unreachable by anon/authenticated. Add policies or an explicit deny-by-design comment for the 3 workflow tables flagged rls_enabled_no_policy. Keep supabase/tests/phase1_permissions_readonly.sql green. |
| 71 | Edge Functions (admin-user-management, finora-kavenegar-send-sms, finora-stripe-qa-read): review authn/authz, input validation, rate limiting, error leakage, secrets only via environment. Add negative tests. Remove or disable the Stripe QA function from production if it has no production purpose. |
| 72 | G2 checklist for the owner (prepare, do not perform): enable Leaked Password Protection; confirm Site URL/redirect URLs; confirm Auth rate limits. Re-run the Supabase advisors afterwards and record the result. |
| 73 | Auth reliability without paid email: the owner cannot buy a domain. Follow docs/FINORA_KAVENEGAR_OTP_PREPARATION_2026-10-12.md to finish the Iran-friendly SMS OTP path (Edge Function + signed hook + provider safety checks) up to the point where only owner-held secrets (G2/G5) are missing. Keep email OTP/password/Google working; show clear Persian errors for rate limits and network failures. Close or properly diagnose Issue #106 (intermittent login timeouts) with logs, not guesses. |
| 74 | Gate: CSP without unsafe-inline for scripts, ratchet at zero, security suite green in CI, advisors re-run, Playwright green. |
| 75 | WP3 — Code structure and maintainability (no big-bang rewrite) |
| 76 | Format-only PR first: add Prettier/ESLint config; reformat js/*.js in a separate commit that changes no behaviour. Prove with all gates + Playwright + an AST/behaviour-equivalence spot check. Add ESLint (no-undef, no-unused-vars, no-redeclare) as a gate for new/changed code. |
| 77 | Remove override chains: inventory every window.x = function / const old = window.x wrapper (e.g. js/patches.js, js/payments.js, js/purchases.js, js/ux-hardening-r2.js, js/idle-and-reports.js, js/commercial-rnd.js). Fold each wrapper's behaviour into the original function, delete the wrapper, keep tests green. Add a ratchet gate that fails if override-wrapper count increases. Delete patches.js when empty. |
| 78 | Replace silent catch(_){} blocks that can hide data loss (sync, save, print, auth) with logged, user-visible handling; keep the rest. |
| 79 | Write docs/ARCHITECTURE.md: module map, load order, global namespace contract, data flow (UI -> sync -> records -> RPCs), where each invariant is enforced (client vs server). Keep it under ~400 lines. |
| 80 | Gate: behaviour unchanged (all gates + Playwright), ratchets in place. |
| 81 | WP4 — Product focus and honest labelling |
| 82 | Define the sellable core: parties, products/services, sales invoices, purchase invoices, receipts/payments, cheques, chart of accounts, manual and automatic journal, core financial reports, professional print (A4 official / A5 informal), backup/export. Everything else (HR/payroll, office automation, workflow, holding/consolidation, etc.) must be hidden behind license modules as beta, off by default for new customers, and clearly labelled in the UI. No feature freeze exceptions: do not add new modules until WP1, WP2, WP5 are accepted. |
| 83 | Remove or relabel any UI that implies unimplemented capability (for example anything suggesting submission to the Taxpayer System without a real acknowledgment). |
| 84 | Make financial-state UX unambiguous: draft / pending / posted / reversed, the allowed next action, and a plain Persian explanation for every disabled button. Save status must distinguish "saved in browser", "pending sync", "server confirmed" per document, with no false success. |
| 85 | WP5 — Real acceptance (replace "mock passed" with observed behaviour) |
| 86 | Playwright end-to-end suites against a dedicated test Supabase project or local stack (never production) for: login (password, email OTP, Google mocked at the boundary), create/save/reload/edit/print sales and purchase invoices, receipt/payment allocation, manual journal, report totals tying out to the ledger, two concurrent users on the same organization (conflict handling), license expiry (read-only access preserved, writes blocked), offboarding/revocation, settings persistence across logout/login, large-list performance (1,000 and 10,000 documents), RTL/keyboard/focus/320px/200% zoom checks. |
| 87 | G4 checklist: a short, exact procedure for the owner to run the same acceptance on the real account (what to click, what result to expect, what to revert). Record results only if the owner reports them. |
| 88 | Re-run the button/menu sweep (docs/audits/2026-10-31/tools/) and drive "controls without test reference" (457 at audit time) toward zero for the sellable core; report the number honestly. |
| 89 | WP6 — Iran-specific correctness |
| 90 | Jalali date tests: Tehran timezone boundaries, leap years, month-end, fiscal-year rollover, conversion round-trips. No UTC-day bugs. |
| 91 | Rial formatting, Persian/Arabic digit input normalization, rounding rules, VAT/discount order, effective-dated tax rules (rates and thresholds are data with source + effective dates, never constants in journal logic). |
| 92 | Moodian/Taxpayer System: deliver an adapter interface, payload builder, hash/immutability and status model, sandbox/mock implementation and tests. The UI may say "submitted" only after a real acknowledged response. Real API credentials are an owner gate (G2); do not invent endpoints or payload details you cannot source; cite sources in the doc. |
| 93 | WP7 — Backup and recovery proof |
| 94 | Follow docs/FINORA_OFFLINE_BACKUP_FA.md (pg_dump -> age, hash check, off-GitHub storage). G3: ask for the connection string via environment only. pg_dump is read-only; do not run anything else on production. |
| 95 | Restore into a disposable Postgres 17, run scripts/finance-integrity-audit.mjs, row-count and trial-balance comparison. Save the evidence (counts, hashes, durations; no data). |
| 96 | Document RPO/RTO honestly and add a monthly checklist. |
| 97 | WP8 — Rollout (only after WP1-WP2 proofs) |
| 98 | Prepare the production rollout package for G1: ordered migrations, pre-checks, backup confirmation, verification queries, shadow-mode report, enforce-flag flip procedure, rollback. |
| 99 | After the owner confirms applying, run post-deploy verification queries (read-only), re-run the Supabase advisors, and record results. Flip enforcement per source only after its shadow report is clean. |
| 100 | Smoke-test production behaviour only with owner-approved, clearly labelled, reversible test data (G4). |
| 101 | WP9 — Continuity and documentation |
| 102 | Consolidate the three overlapping roadmaps into one docs/ROADMAP_CURRENT.md with phase, status, evidence link, and exit criterion per item. Archive superseded files under docs/archive/ (no deletion of history). |
| 103 | Shrink PROJECT_STATE.md to a current-state document (target <15 KB) with links to evidence; move history to the archive. Every claim carries a PR/commit/run link or is marked NOT VERIFIED. |
| 104 | Close stale PRs only with a written reason; keep a table of decisions. |
| 105 | Update README.md: remove obsolete setup text, state real known limitations. |
| 106 | 4. Definition of done (for the whole task) |
| 107 | WP1: unbalanced and post-hoc-mutated ledgers are impossible through any client path; D1/D2 tests are green in CI; purchase correct/cancel path proven; production rollout package ready. |
| 108 | WP2: no unsafe-inline in script-src; inline-handler count 0; persistent two-user suite green; advisors re-run; Edge Functions reviewed. |
| 109 | WP3: formatter/ESLint gates active; override wrappers 0; docs/ARCHITECTURE.md exists. |
| 110 | WP4-WP7: sellable core defined and labelled; Playwright acceptance green on a non-production stack; owner checklists delivered; Jalali/VAT tests; backup/restore evidence (or NOT VERIFIED with the missing gate named). |
| 111 | All repo gates + Playwright green on the final commit; Pages artifact check passes; no secrets in repo. |
| 112 | 5. Reporting format (Persian, after every work package) |
| 113 | وضعیت (انجام شد / ناقص / مسدود) with the exact reason. |
| 114 | شواهد: PR/commit links, CI run links, test names with before/after results, SQL output (no secrets, no business data). |
| 115 | تغییرات: files and migrations touched. |
| 116 | ریسکهای باقیمانده and what is NOT VERIFIED. |
| 117 | اقدام لازم از مالک (only G1-G5 items), as short numbered steps for a beginner. |
| 118 | گام بعدی. |
| 119 | If blocked by something outside the gates, finish the independent parts, state exactly what is missing, and continue with the next independent package. |
| 120 | Appendix A — Reproduction SQL (adapt to the disposable DB; run inside a transaction and roll back) |
| 121 | The production-shaped table is public.records(owner_id uuid, collection text, id text, data jsonb, updated_at timestamptz, organization_id uuid). Creating a row in auth.users bootstraps profile, organization and license through the signup trigger. Authenticated context is simulated with set local role authenticated plus request.jwt.claims/request.jwt.claim.sub. |
| 122 | do $$declare uA uuid := gen_random_uuid(); uB uuid := gen_random_uuid(); oA uuid; rep text := ''; n int;begin insert into auth.users (id,instance_id,aud,role,email,encrypted_password,email_confirmed_at,raw_app_meta_data,raw_user_meta_data,created_at,updated_at) values (uA,'00000000-0000-0000-0000-000000000000','authenticated','authenticated','zz.a@example.invalid','',now(),'{}','{}',now(),now()), (uB,'00000000-0000-0000-0000-000000000000','authenticated','authenticated','zz.b@example.invalid','',now(),'{}','{}',now(),now()); select id into oA from public.organizations where owner_user_id = uA; execute 'set local role authenticated'; perform set_config('request.jwt.claims', json_build_object('sub',uA,'role','authenticated')::text, true); perform set_config('request.jwt.claim.sub', uA::text, true); -- D1: unbalanced posted voucher must be REJECTED (currently ACCEPTED) begin insert into public.records(owner_id,collection,id,data,organization_id) values (uA,'journalVouchers','V1','{"id":"V1","status":"posted","companyId":"c","voucherNo":1}',oA); insert into public.records(owner_id,collection,id,data,organization_id) values (uA,'journalLines','L1','{"id":"L1","voucherId":"V1","lineNo":1,"accountId":"a","debit":1000,"credit":0}',oA), (uA,'journalLines','L2','{"id":"L2","voucherId":"V1","lineNo":2,"accountId":"b","debit":0,"credit":300}',oA); rep := rep || 'D1 FAIL: unbalanced posted voucher accepted' || E'\n'; exception when others then rep := rep || 'D1 PASS: rejected: ' || sqlerrm || E'\n'; end; -- D2: adding a NEW line to an already posted voucher must be REJECTED (currently ACCEPTED) begin insert into public.records(owner_id,collection,id,data,organization_id) values (uA,'journalLines','L3','{"id":"L3","voucherId":"V1","lineNo":3,"accountId":"c","debit":5000,"credit":0}',oA); rep := rep || 'D2 FAIL: line inserted into posted voucher' || E'\n'; exception when others then rep := rep || 'D2 PASS: rejected: ' || sqlerrm || E'\n'; end; -- Isolation (all currently PASS; must stay PASS). Now act as user B. perform set_config('request.jwt.claims', json_build_object('sub',uB,'role','authenticated')::text, true); perform set_config('request.jwt.claim.sub', uB::text, true); select count(*) into n from public.records where organization_id = oA; rep := rep || 'T4 read A rows=' || n || ' (expect 0)' || E'\n'; begin insert into public.records(owner_id,collection,id,data,organization_id) values (uB,'contacts','X1','{"id":"X1"}',oA); rep := rep || 'T5 FAIL insert into A org' || E'\n'; exception when others then rep := rep || 'T5 PASS blocked' || E'\n'; end; begin insert into public.records(owner_id,collection,id,data,organization_id) values (uA,'contacts','X2','{"id":"X2"}',oA); rep := rep || 'T6 FAIL spoofed owner insert' || E'\n'; exception when others then rep := rep || 'T6 PASS blocked' || E'\n'; end; update public.records set data='{"x":1}' where organization_id = oA; get diagnostics n = row_count; rep := rep || 'T7 update A rows=' || n || ' (expect 0)' || E'\n'; delete from public.records where organization_id = oA; get diagnostics n = row_count; rep := rep || 'T8 delete A rows=' || n || ' (expect 0)' || E'\n'; update public.profiles set role='admin' where id = uB; get diagnostics n = row_count; rep := rep || 'T9 self-promote rows=' || n || ' (expect 0)' || E'\n'; update public.licenses set plan='lifetime', ends_at='2099-01-01' where user_id = uB; get diagnostics n = row_count; rep := rep || 'T10 extend own license rows=' || n || ' (expect 0)' || E'\n'; begin perform public.admin_set_license(uB,'lifetime',3650,'active'); rep := rep || 'T11 FAIL admin_set_license allowed' || E'\n'; exception when others then rep := rep || 'T11 PASS forbidden' || E'\n'; end; select count(*) into n from public.profiles where id <> uB; rep := rep || 'T12 other profiles visible=' || n || ' (expect 0)' || E'\n'; select count(*) into n from public.licenses where user_id <> uB; rep := rep || 'T13 other licenses visible=' || n || ' (expect 0)' || E'\n'; select count(*) into n from public.organization_members where organization_id = oA; rep := rep || 'T14 A members visible=' || n || ' (expect 0)' || E'\n'; execute 'reset role'; raise exception E'REPORT\n%', rep; -- forces rollback and returns the reportend $$; |
| 123 | Convert this into committed SQL tests that assert (not just print) and fail the CI job on any deviation. Add the extra cases listed in WP1/WP2. Known limits of this reproduction: (1) D2 only runs meaningfully while D1 still succeeds, because a rejected V1 is rolled back by its exception block. After the fix, create the posted voucher through the posting RPC with a balanced pair of lines, then attempt the extra-line insert. (2) A deferred constraint trigger fires at commit, not per statement, and this block ends with a forced rollback, so run SET CONSTRAINTS ALL IMMEDIATE inside each block (or force a commit-time check) or the new guard will wrongly look like it accepts. (3) Replace the placeholder ids and numbers with the real shapes the final RPC and tables require. |