- README: features, tech stack, install/run, config, commands, structure, security summary, known limitations - ARCHITECTURE: navigation graph, state model, data flow, cross-cutting notes - SECURITY: credential storage, transport, biometrics, account isolation - FEATURE_PARITY: implemented vs planned matrix per API area - ROADMAP: Phase 3 read paths marked done; write paths still planned
7.9 KiB
7.9 KiB
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, ...].purgeAccountCacheremoves 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.RepositoryNavigatormanages the repository-scoped stack (RepoOverview, Files, FileViewer, Commits, CommitDetail, Branches, Tags, RepoIssues, IssueDetail, RepoPulls, PullDetail).SettingsNavigatorandAccountsNavigatorback root modals.linking.tsdefines 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 overAccountState(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 keystoken.<accountId>underkeychainService: '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-storageand mirrors the active token in memory (tokensmap).registerAccount,switchAccount,removeAccount,removeInstance,updateProfileall 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 typedGiteaClientbound 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 viaapiBaseUrl(baseUrl)→…/api/v1/path, setsAuthorization: token <PAT>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 toApiError(withkind,status,retryAfterSeconds,serverMessage). Errors are never enriched with the token. - Errors (
src/core/api/errors.ts):ApiErrorandtoApiError. Kinds:network | timeout | aborted | unauthorized | forbidden | not-found | conflict | rate-limit | server | client | invalid-response. - Endpoints (
src/core/api/endpoints.ts): thin wrappers overGiteaClientreturning 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 andpurgeAccountCache(removes every key whose first two segments match the account). - Caching/persistence (
src/core/api/query-client.ts):QueryClientconfigured with conservativestaleTimeand 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.useNotificationsanduseUnreadCountusepollIntervalfrom settings; the inbox marks items read on open.
UI & theme
- Design system (
src/theme/*): semantic color palette (light/dark), spacing/radius/typography,fontFamilyuses a monospace font for code/git.AppThemeProviderappliesuserInterfaceStyleand observes the system scheme. - Settings (
src/features/settings/settings-store.ts): persiststheme,language(system|en|nl),biometricsEnabled,pollIntervalSecondsandcacheClearedAt. Language is applied on boot and when changed (via i18n). - Internationalization (
src/i18n/*): i18next initialised with localesen.json,nl.json. A conditional polyfill forIntl.PluralRuleson older Hermes runtimes.LanguagePreferencerespected, withdetectDeviceLanguagefalling back toen. - Biometric app lock (
src/core/security/biometrics.ts,AppLockGateinsrc/features/auth/app-lock.tsx): tracks support viagetBiometricSupport(), arms only whenbiometricsEnabled && 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→hasMorefalls back toitems.length === limit(heuristic). Keep that in mind when scrolling. - Image viewing:
expo-imageis used; when a private file is rendered the client attachesAuthorization: token <PAT>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:
ErrorStateandapiErrorMessagenormalise 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 nativeios/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.