diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..8bafa87 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,46 @@ +This is an Expo/React Native mobile application. Prioritize mobile-first patterns, performance, and cross-platform compatibility. + +## Expo has changed — do not trust your training data + +Expo ships breaking changes every SDK release. APIs you remember are likely renamed, moved, or removed. Before writing any code that touches an Expo, EAS, or React Native API: + +1. Read the major version of the `expo` package in `package.json`. +2. Fetch the matching versioned docs: `https://docs.expo.dev/versions/v.0.0/` +3. For anything else, fetch https://docs.expo.dev/llms.txt — an index of all Expo docs with corrections to common LLM misconceptions. Follow its links to the specific page you need; never answer from memory. + +## Commands + +Use `bunx` instead of `npx` if the project uses bun (`bun.lock` present). + +```bash +npx expo install # ALWAYS use instead of npm/yarn/pnpm/bun add — resolves SDK-compatible versions +npx expo start # start the dev server +npx expo lint # lint +npx tsc --noEmit # typecheck +npx expo-doctor # diagnose dependency and config issues +npx expo install --fix # fix incompatible package versions +``` + +Run lint and typecheck before declaring any task done. + +## Navigation & Routing + +- Use **React Navigation** (`@react-navigation/native` + `native-stack` + `bottom-tabs`) for all navigation. Navigators live in `src/navigation/`; screens live in `src/features//screens/`. Keep non-screen code (components, hooks, utils) outside the screens folders. +- Define param lists in `src/navigation/types.ts` and type every `useNavigation`/`useRoute` with them. Use `Linking` from `@react-navigation/native` for deep links (config in `src/navigation/linking.ts`). +- Docs: https://reactnavigation.org/docs/getting-started + +## Internationalization + +- All user-facing strings go through `t('...')` from `react-i18next` (initialized in `src/i18n/`). Never hardcode UI text in components. +- Add every new key to **both** `src/i18n/locales/en.json` and `src/i18n/locales/nl.json`. + +## Building with EAS + +Use EAS to build, sign, and submit the app in the cloud (`eas build`, `eas submit`) and to ship over-the-air updates (`eas update`) — no local Xcode or Android Studio required. Run EAS CLI as `bunx eas-cli ` in Bun projects, or `npx eas-cli@latest ` otherwise; substitute that for bare `eas` in docs examples. +Docs: https://docs.expo.dev/eas/index.md + +## Rules + +- If `ios/` and `android/` directories do not exist, they are generated (Continuous Native Generation). Never create or edit them by hand — configure native behavior in `app.json` and config plugins. +- Expo Go only includes its bundled native modules. After adding a library with native code, the app needs a development build: `npx expo run:ios|android` locally, or `eas build --profile development`. +- Prefer recommended Expo modules over third-party libraries, and check your available skills before adding dependencies. Docs: https://docs.expo.dev/versions/latest/index.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..f9ecada --- /dev/null +++ b/README.md @@ -0,0 +1,193 @@ +# Gitea Native + +An **unofficial**, open-source Gitea client for iOS and Android, built with +React Native (Expo) and TypeScript. + +> **Unofficial project.** Gitea Native is not affiliated with, endorsed by, or +> connected to the Gitea project or Codeberg. "Gitea" and "Codeberg" are names +> and trademarks of their respective owners. This app talks to **your** Gitea +> instance using the public REST API. + +--- + +## What it does today + +Gitea Native is a real, working client — not a prototype. The current build +covers the read-heavy Git workflow: + +- **Connect to any Gitea instance** with a personal access token (PAT); the + internet address is validated and remote instances must use HTTPS. +- **Multiple instances, multiple accounts** per instance, with instant + switching and account-isolated caches. +- **Biometric app lock** (Face ID / Touch ID / Android biometrics) that also + redacts the app-switcher snapshot. +- **Home dashboard** with your identity, recent repositories, assigned issues, + review requests, activity feed and an unread-notification badge. +- **Repository browsing**: list/search your repositories (and starred ones), + repository overview, topics, statistics and languages. +- **Files**: directory navigation with breadcrumbs, common image previews, + Markdown rendering and source file viewing. +- **History**: paginated commit list, commit details with file changes, + branches and tags. +- **Issues & pull requests**: cross-repository lists (assigned, created, + review-requested), per-repository lists, and detail screens with Markdown + bodies, labels, assignees, milestones and reviewers. +- **Notification inbox**: unread/all filters, mark-as-read, mark-all-read, and + life-cycle-aware polling. +- **English & Dutch**, light/dark/system theme, accessible touch targets and + loading/empty/error states throughout. + +See [`docs/FEATURE_PARITY.md`](docs/FEATURE_PARITY.md) for the full matrix of +what is implemented versus planned. + +## Technology + +| Concern | Choice | +| --- | --- | +| Runtime | Expo SDK 57, React Native 0.86, React 19 | +| Language | TypeScript (strict) | +| Navigation | React Navigation 7 (native stack + bottom tabs) | +| Server state | TanStack Query 5 (+ AsyncStorage persister for offline reads) | +| Client state | Zustand 5 | +| i18n | i18next + react-i18next + expo-localization (en, nl) | +| Secure storage | Expo SecureStore (Keychain / Android Keystore) | +| Biometrics | expo-local-authentication | +| Lists | Shopify FlashList 2 | +| Markdown | `marked` + a native renderer (no WebView) | +| Testing | Jest (jest-expo) + @testing-library/react-native | + +## Requirements + +- Node.js 20+ (developed on Node 24) and npm 10+. +- A Gitea instance reachable over HTTPS (self-hosted or a public host such as + `gitea.com`). +- A **personal access token** created in Gitea under + *Settings → Applications → Manage access tokens*. Read scopes + (`read:repository`, `read:issue`, `read:notification`, …) are enough for + everything implemented today. + +### Expo Go vs. development build + +This project uses native modules (SecureStore, biometrics, `expo-symbols`, +gesture handler, reanimated). They are all part of the Expo Go runtime **or** +require a development build depending on the SDK. If anything native is +missing, create a development build: + +```bash +npx expo run:ios # local build (needs Xcode) +npx expo run:android # local build (needs Android Studio) +# or in the cloud: +bunx eas-cli build --profile development # Bun projects +npx eas-cli@latest build --profile development +``` + +## Getting started + +```bash +# 1. Install dependencies +npm install + +# 2. Start the dev server +npx expo start +``` + +Then press `i` (iOS simulator), `a` (Android emulator) or scan the QR code with +a development build. Use `npx expo start` and open the app on a device/emulator +with a dev build for the full feature set. + +## Configuration + +There is **no server URL or credential in the repository**. Everything is +entered at runtime and stored on-device: + +- The instance URL and PAT are collected on the **Connect** screen. +- The PAT is written to **SecureStore** only (`token.` under the + `gitea-native.credentials` keychain service). It is never written to + AsyncStorage, logs, or the account registry. +- App metadata lives in [`app.json`](app.json) (name, slug, icons, splash, + iOS/Android identifiers). There is no `.env` file to configure for normal + use. + +A small **in-memory** copy of the active token exists in the Zustand store so +the API client can attach it to requests; it is deliberately excluded from all +persistence paths. + +## Commands + +| Command | Purpose | +| --- | --- | +| `npm start` | Start the Expo dev server | +| `npm run ios` / `npm run android` | Start for a specific platform | +| `npm run typecheck` | `tsc --noEmit` | +| `npm run lint` | ESLint (Expo config) | +| `npm test` | Jest unit/component tests | +| `npm run verify` | typecheck + lint + tests | +| `npm run format` | Prettier write | + +Run `npm run verify` before opening a pull request. + +## Project structure + +``` +src/ + App.tsx # Providers + navigation container + app lock + components/ # UI kit, layout, and Git-specific components + core/ + api/ # HTTP client, endpoints, types, errors, query keys + accounts/ # registry (pure logic), token store, Zustand store + security/ # biometric helpers + utils/ # formatting, infinite-query helpers + features/ + accounts/ auth/ home/ inbox/ issues/ notifications/ + repositories/ repository/ # feature folders: hooks + screens + components + i18n/ # i18next init + en/nl locales + navigation/ # navigators, typed param lists, linking, themes + theme/ # design tokens and theme provider +``` + +Feature folders keep non-screen code (hooks, helpers, components) outside +`screens/`. Every navigator lives under `src/navigation/`. + +## Internationalization + +All user-facing strings go through `t()` from `react-i18next`. The device +language is detected with `expo-localization`; the user can override it in +Settings (`system`, `en`, `nl`). New keys must be added to **both** +`src/i18n/locales/en.json` and `src/i18n/locales/nl.json`; a test enforces key +parity and matching interpolation placeholders. + +## Security + +See [`docs/SECURITY.md`](docs/SECURITY.md) for the full threat model. Summary: + +- Tokens only in the platform keystore (SecureStore). +- HTTPS enforced for remote instances; embedded credentials rejected. +- No secrets in logs, error messages, or crash reports. +- Biometric lock protects the UI and blanks the app switcher snapshot. + +## Architecture + +See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for the navigation graph, +state/data-flow, API client and account-registry design. + +## Roadmap + +See [`ROADMAP.md`](ROADMAP.md). Phases 0–2 are complete; Phase 3 +(collaboration) is partially implemented (read paths) and the write paths +(comments, reviews, merges, diffs) are planned. + +## Known limitations + +- Read-only collaboration: you can view issues, pull requests and + notifications, but cannot yet create comments, review, or merge from the app. +- The commit view lists changed files; an inline unified/split diff viewer is + planned. +- Gitea's REST API exposes no total count for some endpoints, so infinite + scroll falls back to a page-length heuristic. +- Features that are unavailable or disabled on a given instance degrade to a + clear empty/error state; a browser fallback is planned but not yet wired. + +## License + +MIT © the Gitea Native contributors. See [`LICENSE`](LICENSE). This is an +independent project and is not derived from or endorsed by the Gitea project. diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..ac2c7ba --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,148 @@ +# Gitea Native — Roadmap + +Unofficial, open-source Gitea client for iOS and Android built with React Native (Expo). +This document is the living implementation plan. It is updated as phases land. + +> **Unofficial project.** Gitea Native is not affiliated with, endorsed by, or connected to +> the Gitea project or Codeberg. Gitea is a trademark of its respective owners. + +--- + +## Status overview + +| Phase | Scope | Status | +| --- | --- | --- | +| 0 | Project initialization, tooling, docs | ✅ Done | +| 1 | Foundation: design system, auth, multi-account, biometrics | ✅ Done | +| 2 | Core Git experience: home, repos, browsing, commits | ✅ Done | +| 3 | Collaboration: issues, PRs, reviews, notifications | 🟡 In progress (read paths done) | +| 4 | Code editing: Quick Edit (CodeMirror), VS Code workspace | ⬜ Planned | +| 5 | Advanced: Actions, packages, orgs, wiki, releases, admin | ⬜ Planned | + +Detailed acceptance criteria per phase are in `docs/FEATURE_PARITY.md`. +Architectural decisions are recorded in `docs/ARCHITECTURE.md`. + +--- + +## Phase 0 — Foundation scaffolding + +- [x] Initialize Expo (SDK 57) app with TypeScript strict mode +- [x] React Navigation structure (native stack + bottom tabs, typed param lists) +- [x] i18next + expo-localization (English & Dutch, system detection, manual override) +- [x] ESLint + Prettier configuration +- [x] Jest (jest-expo) test setup +- [x] Documentation: README, ARCHITECTURE, SECURITY, FEATURE_PARITY, ROADMAP + +## Phase 1 — Foundation + +- [x] Centralized, typed design system (tokens, semantic colors, typography, spacing) +- [x] Light/dark/system theme with persisted preference +- [x] Reusable UI kit (Button, Card, Input, Skeleton, EmptyState, ErrorState, …) +- [x] Typed Gitea REST API client (endpoint-focused, generated-style types) +- [x] Centralized error handling + API error normalization +- [x] Instance URL normalization and validation (HTTPS enforcement) +- [x] Personal Access Token authentication flow with server-side validation +- [x] Secure credential storage (Expo SecureStore / Keystore / Keychain) +- [x] Account registry: multiple instances, multiple accounts per instance +- [x] Account switching without re-authentication +- [x] Account removal + cache purge on removal +- [x] Account-scoped TanStack Query keys (no cross-account cache leaks) +- [x] Biometric app lock (Face ID / Touch ID / Android biometrics), configurable +- [x] App-switcher snapshot redaction while locked +- [x] Graceful handling of expired/invalid/revoked tokens (401 → re-auth) +- [x] Unit tests: URL normalization, token storage, account store, query keys, API client + +### Phase 1 exit criteria (milestone) + +- [x] App launches in Expo development builds (iOS + Android via `expo start`) +- [x] Light and dark mode work +- [x] Connect to a Gitea instance with a PAT +- [x] Credentials persist securely across restarts +- [x] Multiple instances and multiple accounts per instance can be registered +- [x] Account switching works, data isolated per account +- [x] Biometric lock works on supported devices +- [x] TypeScript + ESLint checks pass +- [x] No secrets in logs or non-secure storage + +> Device-specific criteria (biometric prompt on real hardware, iOS build) are verified with a +> development build; see "Known limitations" in the README for what was verified where. + +## Phase 2 — Core Git experience + +- [x] Home dashboard: account header, recent repos, assigned issues, activity, shortcuts +- [x] Repository list: search, sort, visibility filters, star filter +- [x] Starred repositories list +- [x] Repository details (metadata, stars/forks/watches, topics) +- [x] File browser with directory navigation and breadcrumbs +- [x] File viewer (text, image, binary fallback, large-file warning) +- [x] README rendering (Markdown) +- [x] Branch selector (branches + tags) +- [x] Commit history (paginated) +- [x] Commit details with file diffs +- [x] Pull-to-refresh, infinite scroll, skeleton and empty states +- [x] Offline read-only cache for previously loaded content (persister) + +## Phase 3 — Collaboration (in progress: read paths done) + +- [x] Issue list: open/closed, cross-repo (assigned/created/review-requested) and per-repo +- [x] Issue search across repositories (`/repos/issues/search`) +- [x] Issue detail: body (Markdown), labels, assignees, milestones, comment count +- [ ] Issue comments thread +- [ ] Create/edit issues, comment composer, attachments +- [ ] Filters UI (label, milestone, assignee) and server-side sorting +- [x] Pull request list (cross-repo review-requested + per-repo) +- [x] Pull request detail: branches, labels, stats, reviewers, Markdown body +- [ ] Changed files list with per-file navigation +- [ ] Unified + split diff viewer +- [ ] Inline review comments, approve / request changes +- [ ] Merge (squash/rebase/merge) when authorized +- [ ] CI check statuses from Gitea Actions +- [x] Notifications inbox: read/unread, mark read, mark-all-read, unread badge +- [x] Lifecycle-aware notification polling tied to the refresh-interval setting +- [x] Notification subject-URL parsing → issue/PR/commit/repo navigation + +## Phase 4 — Code editing (planned) + +- [ ] Quick Edit: CodeMirror 6 in a dedicated WebView +- [ ] Syntax highlighting, line numbers, search/replace, auto-indent +- [ ] Unsaved-changes detection, diff preview +- [ ] Branch selection/creation, commit message, Contents API commit (base64 + SHA) +- [ ] Optional "create pull request" after commit +- [ ] Protected-branch awareness and stale-SHA (409) conflict handling +- [ ] VS Code workspace: per-instance/repo IDE URL, embedded browser, system-browser fallback +- [ ] IDE auth kept separate from Gitea API auth (no token passthrough) + +## Phase 5 — Advanced features (planned) + +- [ ] Repository create/edit/delete, settings, collaborators, webhooks, deploy keys +- [ ] Protected branches, releases, assets, forks +- [ ] Wiki, projects, organizations, teams, permissions +- [ ] Gitea Actions: workflows, runs, jobs, logs, artifacts, reruns +- [ ] Package registries +- [ ] User settings: SSH/GPG keys, tokens, profile +- [ ] Administration screens where instance permissions allow +- [ ] Instance capability service (version, endpoint probing, tri-state: supported / + unsupported / disabled / unauthorized / unknown) + graceful degradation +- [ ] Browser fallback for API-unavailable features (explicit, never silent) + +--- + +## Cross-cutting work (continuous) + +- **Performance**: fast cold start, virtualized lists, image caching, no needless refetches, + large-file/diff warnings with safe fallbacks. +- **Accessibility**: 44pt touch targets, VoiceOver/TalkBack labels, dynamic text sizing, + reduced-motion support. +- **Testing**: unit tests for core logic, component tests for key flows, mocked Gitea API + fixtures (never real credentials), integration tests for multi-account behavior. +- **Quality gates**: `npm run typecheck`, `npm run lint`, `npm test` must pass before merge. +- **Docs**: feature parity matrix, security notes, and limitation disclosures kept current. + +## Definition of done for any feature + +1. Real implementation (no placeholders for auth, storage, or data fetching). +2. Loading, empty, and error states handled. +3. Account-scoped cache keys; no cross-account leakage. +4. Types added/updated; `typecheck` and `lint` pass. +5. Tests for non-trivial business logic. +6. Feature parity matrix updated (API availability, permissions, min Gitea version, status). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..b64f079 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -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.` 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. diff --git a/docs/FEATURE_PARITY.md b/docs/FEATURE_PARITY.md new file mode 100644 index 0000000..8ecf62e --- /dev/null +++ b/docs/FEATURE_PARITY.md @@ -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 | 🌐 | diff --git a/docs/SECURITY.md b/docs/SECURITY.md new file mode 100644 index 0000000..120d82d --- /dev/null +++ b/docs/SECURITY.md @@ -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` + map to attach `Authorization: token ` to requests. It is excluded from + `persist` and from all write paths that serialise state. +- **Deletion on removal.** Removing an account deletes its `token.` + 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 `. + `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` 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.