docs: README, architecture, security, feature parity and roadmap

- 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
This commit is contained in:
JustZoe101 committed 2026-10-09 16:41:24 +02:00
1 parent df0ac71bc3
commit f641238b6f
6 files changed
+756

No files matched your search

+141
View File
@@ -0,0 +1,141 @@
# 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.<accountId>` 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 <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 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 <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**: `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.
+122
View File
@@ -0,0 +1,122 @@
# Feature parity matrix
Status legend:
| Symbol | Meaning |
| --- | --- |
| ✅ | Implemented and working in-app |
| 🟡 | Partially implemented (read-only or limited) |
| ⬜ | Planned, not started |
| 🌐 | Planned via explicit browser fallback |
"Min version" refers to the Gitea server version that exposes the endpoint; the
client does not hard-gate on a version yet (see the capability-probe item in the
roadmap).
## Authentication & accounts
| Feature | Status | API | Notes |
| --- | --- | --- | --- |
| PAT sign-in | ✅ | `GET /user` | Token validated before persisting |
| Instance URL validation | ✅ | — | HTTPS enforced for remote hosts |
| Secure token storage | ✅ | — | SecureStore (Keychain/Keystore) |
| Multiple instances | ✅ | — | Non-sensitive registry in AsyncStorage |
| Multiple accounts per instance | ✅ | — | Unique `(instanceId, login)` |
| Account switching | ✅ | — | Account-scoped query keys |
| Account/instance removal | ✅ | — | Token + cache purge |
| Biometric app lock | ✅ | — | On-device only |
| OAuth / device flow | ⬜ | — | PAT only for now |
## Repository browsing
| Feature | Status | API | Notes |
| --- | --- | --- | --- |
| My repositories | ✅ | `GET /user/repos` | visibility filter |
| Search repositories | ✅ | `GET /repos/search` | server-side |
| Starred repositories | ✅ | `GET /user/starred` | |
| Repository overview | ✅ | `GET /repos/{o}/{r}` | metadata, topics, stats |
| Languages | ✅ | `GET /repos/{o}/{r}/languages` | breakdown bar |
| README | ✅ | `GET /repos/{o}/{r}/contents/{path}` | located by name; no `/readme` endpoint exists |
| Directory browsing | ✅ | `GET …/contents` | breadcrumbs, ref query |
| File viewer | ✅ | `GET …/contents` + raw | text, images, symlink/submodule |
| Branch list & selector | ✅ | `GET …/branches` | |
| Tags | ✅ | `GET …/tags` | |
| Commit history | ✅ | `GET …/commits` | paginated, ref/branch |
| Commit detail | ✅ | `GET …/git/commits/{sha}` | changed files, verification |
| Code search | ⬜ | `GET /repos/search`? | planned |
| Releases | ⬜ | `GET …/releases` | planned |
| Wiki | ⬜ | `GET …/wiki` | planned |
| Star/unstar/watch/fork | ⬜ | `PUT/DELETE` | planned (write) |
## Issues
| Feature | Status | API | Notes |
| --- | --- | --- | --- |
| Cross-repo issue list | ✅ | `GET /repos/issues/search` | assigned/created/review_requested, `type=issues` |
| Repo issue list | ✅ | `GET /repos/{o}/{r}/issues` | open/closed filter |
| Issue detail | ✅ | `GET /repos/{o}/{r}/issues/{n}` | Markdown body, labels, assignees, milestone |
| Issue comments | 🟡 | `GET …/issues/{n}/comments` | count shown; thread not yet rendered |
| Create/edit issue | ⬜ | `POST/PATCH` | planned |
| Comment composer | ⬜ | `POST …/comments` | planned |
| Labels/milestones management | ⬜ | various | planned |
| Reactions/subscriptions | ⬜ | various | planned |
## Pull requests
| Feature | Status | API | Notes |
| --- | --- | --- | --- |
| Review-requested PR list | ✅ | `GET /repos/issues/search` | `type=pulls`, `review_requested` |
| Repo PR list | ✅ | `GET /repos/{o}/{r}/pulls` | open/closed |
| PR detail | ✅ | `GET …/pulls/{n}` | title, branches, labels, stats, reviewers |
| Changed files + diff viewer | 🟡 | `GET …/pulls/{n}.diff` | file count only; inline diff viewer planned |
| Inline review comments | ⬜ | `GET …/pulls/{n}/reviews` | planned |
| Approve / request changes | ⬜ | `POST …/reviews` | planned |
| Merge | ⬜ | `POST …/merge` | planned |
| CI checks (Actions) | ⬜ | `GET …/commits/{sha}/status` | planned |
## Notifications
| Feature | Status | API | Notes |
| --- | --- | --- | --- |
| Notification inbox | ✅ | `GET /notifications` | unread/all filter |
| Unread badge | ✅ | `GET /notifications/new` | polled |
| Mark thread read | ✅ | `PUT /notifications/threads/{id}` | on open |
| Mark all read | ✅ | `PUT /notifications` | |
| Polling interval | ✅ | — | manual/30/60/300s setting |
| Notification navigation | ✅ | — | resolves subject URL to issue/PR/commit/repo |
| Push notifications | ⬜ | — | planned |
## Home & shell
| Feature | Status | Notes |
| --- | --- | --- |
| Home dashboard | ✅ | identity, shortcuts, recent repos, assigned issues, review PRs, activity |
| Tabs (5) | ✅ | Home, Repositories, Issues, Pull Requests, Inbox |
| Account switcher | ✅ | header + Accounts modal |
| Deep links | ✅ | `giteanative://` scheme |
| Offline read cache | ✅ | AsyncStorage query persister |
| Theme (light/dark/system) | ✅ | persisted |
| i18n (en/nl) | ✅ | device detection + override |
| Loading/empty/error states | ✅ | shared components |
## Code editing (planned)
| Feature | Status | Notes |
| --- | --- | --- |
| Quick Edit (CodeMirror WebView) | ⬜ | syntax highlight, search/replace |
| Commit via Contents API | ⬜ | base64 + SHA, 409 conflict handling |
| Create PR after commit | ⬜ | |
| VS Code workspace | 🌐 | per-instance IDE URL, no token passthrough |
## Advanced (planned)
| Feature | Status |
| --- | --- |
| Repo create/edit/settings/webhooks | ⬜ |
| Protected branches / releases / forks | ⬜ |
| Wiki / projects / orgs / teams | ⬜ |
| Gitea Actions (runs, jobs, logs) | ⬜ |
| Package registries | ⬜ |
| User settings (SSH/GPG keys, tokens) | ⬜ |
| Admin screens | ⬜ |
| Capability probe + browser fallback | 🌐 |
+106
View File
@@ -0,0 +1,106 @@
# Security
Gitea Native is built to handle personal access tokens and account metadata. This
document states the intended security posture.
## Credential storage
- **Platform keystore only.** All PATs are stored with Expo SecureStore:
`SecureStore.setItemAsync(tokenKey(accountId), token, { keychainService: 'gitea-native.credentials' })`.
- **No plaintext persistence.** Tokens are **never** written to AsyncStorage,
`react-native-mmkv` (not used), the accounts registry, JSON files or logs.
- **Non-sensitive metadata.** Instance and account records (`InstanceRecord`,
`AccountRecord`) contain `baseUrl`, `login`, `avatarUrl`, timestamps — no
tokens, no passwords, no refresh tokens.
- **In-memory only.** The Zustand store keeps a `tokens: Record<string,string>`
map to attach `Authorization: token <PAT>` to requests. It is excluded from
`persist` and from all write paths that serialise state.
- **Deletion on removal.** Removing an account deletes its `token.<accountId>`
entry. Removing an instance cascades to all of its accounts' tokens.
## Transport & network
- **HTTPS enforced for remote instances.** `normalizeInstanceUrl` rejects plain
`http://` except for loopback hosts: `localhost`, `127.0.0.1`, `::1`, `0.0.0.0`,
`10.0.2.2`. Embedded credentials (`user:pass@`) are rejected to prevent token
smuggling. Only `http/https` schemes are accepted.
- **No token in URLs.** The REST calls always go to `Authorization: token <PAT>`.
`buildQuery` never attaches a `token` parameter. The client does not log the
full URL with sensitive fragments.
- **Sub-path support.** Gitea installations under a sub-path (e.g.
`https://example.com/git`) are preserved and become
`…/git/api/v1` — correct for reverse proxies.
- **Timeouts & aborts.** Each `fetch` is wrapped with `AbortController` and a
per-request timeout. Navigation unmounts/cancellations use `signal.aborted`.
- **Private assets.** When rendering images from `download_url`, the app only
sends the token header if the host matches the instance host. This avoids
leaking credentials to third-party CDNs.
## Error handling & logging
- **Centralised errors.** `ApiError` carries `kind` and `status`; `serverMessage`
is taken from the JSON body but never augmented with the token.
- **No secret leakage in errors.** The tests explicitly assert that no
occurrence of the PAT appears in `error.message` or `error.serverMessage`.
- **Defensive fallbacks.** Network/timeout/401/403 map to safe, translated
messages. `invalid-response` catches HTML replies (mitigates MITM/proxy
surprises).
- **No analytics by default.** The project contains no remote telemetry or crash
reporting hooks.
## Biometric app lock
- **UI gating only.** `AppLockGate` wraps the navigators. It does not encrypt
on-disk storage; it protects access to the UI on the running device.
- **Arming conditions.** Locks only when `biometricsEnabled`, the account store
has accounts, and `LocalAuthentication` reports `usable === true` (hardware +
enrolled).
- **Background → locked.** On `AppState` change to `background`, `locked` is set
to `true`.
- **Foreground → prompt.** When `effectiveLocked` becomes true and the app is
active, an automatic prompt runs. `prompting.current` prevents duplicate
prompts.
- **Correct failure semantics.** If the user cancels or authentication fails,
the app remains locked. If `unavailable`/no credentials, the gate never
forcibly traps the user (state remains unlocked).
- **App switcher redaction.** Expo's app metadata (`ios.infoPlist`, native build
behaviour) plus the locked overlay helps prevent showing account lists in the
recent-apps preview. The app treats screenshots/recents as a surface to
minimise.
## Account isolation
- **Cache keys include accountId.** `queryKeys.repo('acct-a', …)` differs from
`'acct-b'`. Two different accounts cannot accidentally share React Query data.
- **Purge on removal.** `purgeAccountCache(client, accountId)` clears all
queries and mutations for that account (notifications, repositories, issues,
home activity, unread counts).
- **Session swap.** Switching accounts updates `activeAccountId` and returns a
new `GiteaClient` with the new token — no shared mutable client state leaked
between accounts.
- **Connect flow is order-safe.** `connectToInstance` normalises the URL and does
a best-effort `/version` probe (non-fatal), then calls `GET /user` to
validate the token. Only after a successful user probe does
`registerAccount` write the token to SecureStore and mutate the store.
## Input validation
- **Base URL.** `new URL(normalized)` is used after normalisation; fragment and
query stripped from the base URL. Trailing slashes collapsed.
- **Account IDs.** `tokenKey` enforces `/^[A-Za-z0-9._-]+$/` — matches
SecureStore's safe character set.
- **API boundaries.** `RawResponse<T>` is the transport shape; feature code
narrows to domain types. Unknown fields are ignored rather than blindly
trusted.
## Known gaps (not a complete list)
- Write actions (comment, edit issue/PR, merge, review, quick-edit commit) are
not implemented yet. When added, they must reuse the same auth header, enforce
HTTPS, validate 409/stale-SHA and never echo payload secrets.
- `expo-doctor` passes. Any new native dependency must be checked against Expo
SDK 57 compatibility.
- The inline diff viewer is planned; rendering untrusted diffs should avoid
executing embedded scripts (Markdown renderer already doesn't run scripts).
- A capability probe (server version, supported endpoints) is a planned hardening
to gracefully degrade on older Gitea releases.