# Architecture This document records the significant architectural decisions and constraints for Gitea Native. ## Principles - **Secure by default.** Tokens live exclusively in Expo SecureStore (iOS Keychain / Android Keystore). They are never persisted in AsyncStorage, never emitted to logs and never embedded in URL query strings. - **Multi-account safety.** The TanStack Query cache is keyed by `['account', accountId, ...]`. `purgeAccountCache` removes only a single account's cache. The account registry keeps metadata non-sensitive. - **Mobile-first.** React Navigation (native stack + bottom tabs), accessible touch targets, theme aware, internationalised (en/nl) and resilient to offline reads via query persister. - **Type-safe at the boundaries.** Typed param lists for all navigators, a transport-layer HTTP client (`src/core/api/client.ts`) and hand-curated Gitea types (`src/core/api/types.ts`). - **Real implementation.** No stubs or placeholder auth/storage. 401 responses are interpreted correctly and flows degrade gracefully when a feature is unsupported. - **Untrusted inputs.** Instance URLs are normalised/validated before use (reject embedded credentials, force HTTPS for remote hosts, preserve sub-paths, only http(s)). All response bodies are treated as untrusted. ## Navigation The root stack (`src/navigation/root-navigator.tsx`) is conditional: `Auth | Main | Repository | Settings | Accounts(modal)`. It shows `Auth` when there are no accounts and no token; it shows `Main` when there is at least one account and an active token is available. This removes the need for "drill back" to `Connect` and keeps the first post-connect frame deterministic. - `MainTabs` (`main-tabs.tsx`) has five tabs: Home, Repositories, Issues, Pull Requests, Inbox. Each tab wraps its list/detail screens in its own native stack (`tab-stacks.tsx`) so screens can be pushed with standard iOS/Android headers. - `RepositoryNavigator` manages the repository-scoped stack (RepoOverview, Files, FileViewer, Commits, CommitDetail, Branches, Tags, RepoIssues, IssueDetail, RepoPulls, PullDetail). - `SettingsNavigator` and `AccountsNavigator` back root modals. - `linking.ts` defines deep links (`giteanative://…`) and maps screens to paths. Screen prop helpers (`src/navigation/typing.ts`) compose bottom-tab and root stack props so any screen can `navigate` to any other stack. Root-level navigation for Settings/Accounts uses a small `useRootNavigation` hook to avoid overload clashes between inner/outer stack route names. ## State model ### Accounts & sessions - **Non-sensitive registry** (`src/core/accounts/registry.ts`): pure state transitions over `AccountState` (instances, accounts, `activeAccountId`). Invariants: unique `(instanceId, login)` pairs, deterministic re-assignment when removing active account or an entire instance. - **Secure credentials** (`src/core/accounts/token-store.ts`): Expo SecureStore keys `token.` under `keychainService: 'gitea-native.credentials'`. Validates account IDs, never logs tokens. - **Zustand store** (`src/core/accounts/accounts-store.ts`): persists the non-sensitive registry via `@react-native-async-storage/async-storage` and mirrors the active token in memory (`tokens` map). `registerAccount`, `switchAccount`, `removeAccount`, `removeInstance`, `updateProfile` all read from the current state and write back both persistence and token store. - **Session** (`src/features/accounts/use-session.ts`): selects the active `{instance, account, token}` and returns a typed `GiteaClient` bound to that account. It guards against mismatches (nulls when not ready). ### Remote data - **Client** (`src/core/api/client.ts`): `GiteaClient.raw/get/post/…` builds URLs via `apiBaseUrl(baseUrl)` → `…/api/v1/path`, sets `Authorization: token ` only when a token is provided, serialises query params, applies a per-request timeout (AbortController), parses pagination (`X-Total-Count`) and maps transport/fetch failures to `ApiError` (with `kind`, `status`, `retryAfterSeconds`, `serverMessage`). Errors are never enriched with the token. - **Errors** (`src/core/api/errors.ts`): `ApiError` and `toApiError`. Kinds: `network | timeout | aborted | unauthorized | forbidden | not-found | conflict | rate-limit | server | client | invalid-response`. - **Endpoints** (`src/core/api/endpoints.ts`): thin wrappers over `GiteaClient` returning typed DTOs. Mapping to application types lives in feature hooks. - **Query keys** (`src/core/api/query-keys.ts`): hierarchical, all under `['account', accountId]`. Includes helpers for notifications root and `purgeAccountCache` (removes every key whose first two segments match the account). - **Caching/persistence** (`src/core/api/query-client.ts`): `QueryClient` configured with conservative `staleTime` and garbage collection. An AsyncStorage persister (`createAsyncStoragePersister`) caches previously loaded pages for offline reads (read-only reuse). - **Features** (`src/features/*/queries.ts`): TanStack Query hooks wrapping endpoints. `useNotifications` and `useUnreadCount` use `pollInterval` from settings; the inbox marks items read on open. ### UI & theme - **Design system** (`src/theme/*`): semantic color palette (light/dark), spacing/radius/typography, `fontFamily` uses a monospace font for code/git. `AppThemeProvider` applies `userInterfaceStyle` and observes the system scheme. - **Settings** (`src/features/settings/settings-store.ts`): persists `theme`, `language` (`system|en|nl`), `biometricsEnabled`, `pollIntervalSeconds` and `cacheClearedAt`. Language is applied on boot and when changed (via i18n). - **Internationalization** (`src/i18n/*`): i18next initialised with locales `en.json`, `nl.json`. A conditional polyfill for `Intl.PluralRules` on older Hermes runtimes. `LanguagePreference` respected, with `detectDeviceLanguage` falling back to `en`. - **Biometric app lock** (`src/core/security/biometrics.ts`, `AppLockGate` in `src/features/auth/app-lock.tsx`): tracks support via `getBiometricSupport()`, arms only when `biometricsEnabled && hasAccounts && support.usable`. When backgrounded it locks; when foregrounded and locked it prompts. On success it unlocks; cancelled/failed keep it locked (prevents bypass). When unusable (enrolled removed) the gate never traps the user. ## Cross-cutting - **Pagination**: some endpoints lack `X-Total-Count` → `hasMore` falls back to `items.length === limit` (heuristic). Keep that in mind when scrolling. - **Image viewing**: `expo-image` is used; when a private file is rendered the client attaches `Authorization: token ` only if the download URL shares the same instance host (defensive). - **Markdown**: native renderer (no WebView). Links open via `Linking.openURL`. Security-sensitive features are not rendered as remote images that could exfiltrate tokens. - **Account removal**: removes instance → cascades to all accounts on it, purges their caches, and deletes their tokens. Removing the active account reassigns the new active deterministically (most-recently-used survivor). - **Error surface**: `ErrorState` and `apiErrorMessage` normalise common cases (`unauthorized`, `forbidden`, `not-found`, `network`, `rate-limit`, `timeout`). - **Logging**: zero token leakage — only metadata (account id hash-ish or not at all), path and status appear in error messages. - **Development-only**: `src/__mocks__` not present (tests inline their own mocks). `example/` is ignored. No native `ios/` `android/` tracked (CNG-prepared; generated at build time). - **Testing**: 86 unit/component tests covering URL normalisation, token store contract, account registry invariants, query-key isolation, HTTP client contract (auth header + pagination + error mapping), connect flow (including insecure/network cases), locale parity and small UI components. No integration against a live instance; all HTTP is mocked.