Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 10:30 UTC
arena/2d4eda07-aram
add-index-html-10623938925177053894
arena/094f314c-aram
arena/2d4eda07-aram
chatgpt-phase1b2-autopilot
codex/adr-future-connectors-pi-v1
codex/aram-account-note-source-trace-20261031
codex/aram-actions-node24-maintenance-20261031
codex/aram-analyst-review-workbook-20261031
codex/aram-bs-candidate-statement-20261031
codex/aram-cash-flow-direct-candidate-20261031
codex/aram-clean-reference-year-integrity-20261030
codex/aram-cross-statement-controls-20261031
codex/aram-equity-changes-candidate-20261031
codex/aram-five-statement-cli-20261031
codex/aram-five-statement-integration-20261031
codex/aram-five-statement-orchestrator-20261031
codex/aram-gate3-coverage-target-guard-20261030
codex/aram-gate3-hidden-xlsx-guard-20261030
codex/aram-gate3-integration-validation-20261030
codex/aram-gate3-mapping-change-preview-20261030
codex/aram-gate3-stale-note-guard-20261030
codex/aram-income-statement-candidate-20261031
codex/aram-manifest-referential-integrity-20261031
codex/aram-mapping-source-parser-20261101
codex/aram-multidimensional-mapping-20261101
codex/aram-multistatement-mapping-20261031
codex/aram-pipeline-manifest-schema-20261031
codex/aram-readonly-mapping-coverage-20261031
codex/aram-reconciliation-review-gate-20261031
codex/aram-same-flush-fiscal-lock-20261030
codex/aram-synthetic-windows-demo-20261031
codex/aram-trial-balance-diagnostic-20261031
codex/aram-windows-background-detail-search-20261031
codex/aram-windows-detail-review-20261031
codex/aram-windows-five-statement-pilot-20261031
codex/aram-windows-statement-figures-20261031
codex/gate-2a-pilot-workbook
codex/gate-2a-pilot-workbook-6864754244772568979
codex/gate3-authenticated-principal-boundary-20261030
codex/gate3-authored-draft-staging-20261030
codex/gate3-carry-forward-preview-20261023
codex/gate3-draft-staging-audit-20261030
codex/gate3-mapping-batch-freshness-20261030
codex/gate3-mapping-batch-review-20261030
codex/gate3-mapping-core
codex/gate3-mapping-coverage-20261023
codex/gate3-mapping-excel-20261023
codex/gate3-note-mapping-review-20261023
codex/gate3-signed-year-scope-20261030
codex/gate3-unapproved-proposal-storage-20261030
codex/payvast-mapping-discovery-20261023
codex/phase-2a-backend-foundation
codex/phase-2b-post-merge-record
codex/phase-2b-source-registration
codex/phase-2b-source-registration-12955190277775369594
codex/post-gate2a-control-reconciliation
codex/post-pr18-acceptance-record
codex/project-control-foundation
codex/t1-repo-hygiene-20261023
codex/t2-ci-hardening-20261023
codex/t3-explicit-migrations-20261023
codex/t6a-readonly-diagnostics-20261023
codex/v1-01-safety-gate-hardening
codex/v1-year-isolation-followup-20261023
codex/windows-native-pilot-shell-20261030
docs/aram-master-control-plan-20261111
docs/aram-roadmap-dashboard-20261030
docs/financial-statement-reconciliation-1402-1404-20261110
feat/gate3-governed-mapping-20261101
feat/gate3-package9-1-security-20261103
feat/gate3-package9-isolated-20261103
fix/password-unicode-validation-20261111
governance/aram-5-1-3-controls-20261030
governance/role-based-operating-model
jules-1168663913887856558-73b8a885
jules-gate-2b-mapping-workflow-foundation-4137724387867065330
phase-1b1-audit-report-7365389436990903239
phase-2a-backend-foundation-10237597358138521261
phase1b2-postmerge-metadata-fix
refactor/drg-parent-year-id-15088443704684163304
source-data-cleanup
| 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 | ] |