diff --git a/src/core/accounts/accounts-store.ts b/src/core/accounts/accounts-store.ts new file mode 100644 index 0000000..fb885da --- /dev/null +++ b/src/core/accounts/accounts-store.ts @@ -0,0 +1,201 @@ +/** + * Zustand store for instances & accounts. + * + * - Non-sensitive metadata → AsyncStorage (via registry.ts). + * - Tokens → SecureStore, mirrored into an in-memory map only (never persisted, + * never logged, never part of any serializable state we write to disk). + * - Hydration happens once at app start; screens wait for `hydrated`. + */ + +import { create } from 'zustand'; + +import { normalizeInstanceUrl } from '@/core/api/instance-url'; +import { + addAccount, + getActive, + readAccountState, + removeAccount as removeAccountRecord, + removeInstance as removeInstanceRecord, + setActiveAccount, + updateAccountProfile, + upsertInstance, + writeAccountState, +} from './registry'; +import { tokenStore } from './token-store'; +import type { AccountRecord, AccountState, InstanceRecord } from './types'; + +export interface RegisterAccountInput { + /** Raw or normalized instance URL. */ + baseUrl: string; + label?: string; + token: string; + version?: string; + profile: { + login: string; + id?: number; + fullName?: string; + avatarUrl?: string; + }; +} + +export interface AccountsStore extends AccountState { + /** In-memory token mirror. Deliberately excluded from every persistence path. */ + tokens: Record; + hydrated: boolean; + hydrate: () => Promise; + registerAccount: (input: RegisterAccountInput) => Promise<{ instance: InstanceRecord; account: AccountRecord }>; + switchAccount: (accountId: string) => Promise; + removeAccount: (accountId: string) => Promise; + removeInstance: (instanceId: string) => Promise; + updateProfile: ( + accountId: string, + profile: Partial>, + ) => Promise; + setInstanceVersion: (instanceId: string, version: string) => Promise; + /** Returns the in-memory token for an account, or null. */ + getTokenFor: (accountId: string) => string | null; +} + +export const useAccountsStore = create((set, get) => { + async function persist(next: AccountState): Promise { + await writeAccountState(next); + set(next); + } + + return { + instances: [], + accounts: [], + activeAccountId: null, + tokens: {}, + hydrated: false, + + hydrate: async () => { + if (get().hydrated) return; + const state = await readAccountState(); + const tokens: Record = {}; + await Promise.all( + state.accounts.map(async (account) => { + const token = await tokenStore.get(account.id); + if (token) tokens[account.id] = token; + }), + ); + set({ ...state, tokens, hydrated: true }); + }, + + registerAccount: async ({ baseUrl, label, token, version, profile }) => { + const normalized = normalizeInstanceUrl(baseUrl); + // Secret first: a state write failure must never leave an account without a token + // retrievable on next launch... and a token without state is simply an orphaned secret + // we can clean up, not a broken UI. + const { state: withInstance, instance } = upsertInstance( + { + instances: get().instances, + accounts: get().accounts, + activeAccountId: get().activeAccountId, + }, + { baseUrl: normalized, label: label?.trim() || instanceDefaultLabel(normalized), version }, + ); + // Reserve/refresh the account id before storing its token so the key is stable + // when the same user re-adds an account (token rotation, not duplication). + const existing = withInstance.accounts.find( + (a) => + a.instanceId === instance.id && a.login.toLowerCase() === profile.login.toLowerCase(), + ); + const accountId = existing?.id ?? provisionalAccountId(); + await tokenStore.set(accountId, token); + + const { state, account } = addAccount(withInstance, { + instanceId: instance.id, + login: profile.login, + userId: profile.id, + fullName: profile.fullName, + avatarUrl: profile.avatarUrl, + }); + + // addAccount may have reused an existing id; ensure the secret sits under the final id. + if (account.id !== accountId) { + await tokenStore.set(account.id, token); + await tokenStore.remove(accountId); + } + + await persist(state); + set((s) => ({ tokens: { ...s.tokens, [account.id]: token } })); + return { instance, account }; + }, + + switchAccount: async (accountId) => { + const { state, account } = setActiveAccount(currentState(get), accountId); + if (!account) return; + await persist(state); + }, + + removeAccount: async (accountId) => { + const { state } = removeAccountRecord(currentState(get), accountId); + await tokenStore.remove(accountId); + set((s) => { + const tokens = { ...s.tokens }; + delete tokens[accountId]; + return { ...s, tokens }; + }); + await persist(state); + }, + + removeInstance: async (instanceId) => { + const { state, removedAccounts } = removeInstanceRecord(currentState(get), instanceId); + for (const account of removedAccounts) { + await tokenStore.remove(account.id); + set((s) => { + const tokens = { ...s.tokens }; + delete tokens[account.id]; + return { ...s, tokens }; + }); + } + await persist(state); + }, + + updateProfile: async (accountId, profile) => { + const { state } = updateAccountProfile(currentState(get), accountId, profile); + await persist(state); + }, + + setInstanceVersion: async (instanceId, version) => { + const current = currentState(get); + const instance = current.instances.find((i) => i.id === instanceId); + if (!instance || instance.version === version) return; + await persist({ + ...current, + instances: current.instances.map((i) => (i.id === instanceId ? { ...i, version } : i)), + }); + }, + + getTokenFor: (accountId) => get().tokens[accountId] ?? null, + }; +}); + +function currentState(get: () => AccountsStore): AccountState { + const { instances, accounts, activeAccountId } = get(); + return { instances, accounts, activeAccountId }; +} + +function instanceDefaultLabel(baseUrl: string): string { + try { + const url = new URL(baseUrl); + return url.host + (url.pathname && url.pathname !== '/' ? url.pathname : ''); + } catch { + return baseUrl; + } +} + +function provisionalAccountId(): string { + // Provisional id used only between token write and final registration; if the final + // id differs (brand-new account), the token is moved in registerAccount. + return `pending.${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; +} + +/** Convenience selector: active instance + account (null when not signed in). */ +export function selectActive(state: AccountState): { + instance: InstanceRecord; + account: AccountRecord; +} | null { + return getActive(state); +} diff --git a/src/core/accounts/registry.test.ts b/src/core/accounts/registry.test.ts new file mode 100644 index 0000000..02eb84b --- /dev/null +++ b/src/core/accounts/registry.test.ts @@ -0,0 +1,189 @@ +/** + * Account registry: pure state transitions. These invariants keep multi-account + * isolation honest — removing the active account always leaves a deterministic + * successor, and removing an instance removes every account it owns. + */ + +import { + addAccount, + getActive, + parseAccountState, + removeAccount, + removeInstance, + setActiveAccount, + updateAccountProfile, + upsertInstance, +} from './registry'; +import { EMPTY_ACCOUNT_STATE, type AccountState } from './types'; + +function state(partial: Partial): AccountState { + return { ...EMPTY_ACCOUNT_STATE, ...partial }; +} + +const instanceA = { id: 'inst-a', baseUrl: 'https://a.example', label: 'a.example', addedAt: 1 }; +const instanceB = { id: 'inst-b', baseUrl: 'https://b.example', label: 'b.example', addedAt: 2 }; + +const accountA1 = { + id: 'a1', + instanceId: 'inst-a', + login: 'alice', + addedAt: 10, + lastUsedAt: 100, +}; +const accountA2 = { + id: 'a2', + instanceId: 'inst-a', + login: 'anna', + addedAt: 20, + lastUsedAt: 200, +}; +const accountB1 = { + id: 'b1', + instanceId: 'inst-b', + login: 'bob', + addedAt: 30, + lastUsedAt: 300, +}; + +describe('parseAccountState', () => { + it('returns empty state for null / malformed storage', () => { + expect(parseAccountState(null)).toEqual(EMPTY_ACCOUNT_STATE); + expect(parseAccountState('not json')).toEqual(EMPTY_ACCOUNT_STATE); + expect(parseAccountState('42')).toEqual(EMPTY_ACCOUNT_STATE); + }); + + it('drops records that miss required fields', () => { + const raw = JSON.stringify({ + instances: [instanceA, { id: 'broken' }], + accounts: [accountA1, { login: 'no-id' }], + activeAccountId: 'a1', + }); + const parsed = parseAccountState(raw); + expect(parsed.instances).toHaveLength(1); + expect(parsed.accounts).toHaveLength(1); + expect(parsed.activeAccountId).toBe('a1'); + }); + + it('falls back to the first account when the active id is stale', () => { + const raw = JSON.stringify({ instances: [instanceA], accounts: [accountA2, accountA1], activeAccountId: 'ghost' }); + expect(parseAccountState(raw).activeAccountId).toBe('a2'); + }); +}); + +describe('upsertInstance', () => { + it('creates a new instance the first time', () => { + const { state: next, instance } = upsertInstance(EMPTY_ACCOUNT_STATE, { + baseUrl: instanceA.baseUrl, + label: instanceA.label, + }); + expect(next.instances).toHaveLength(1); + expect(instance.baseUrl).toBe(instanceA.baseUrl); + }); + + it('reuses the existing instance for the same base URL', () => { + const initial = state({ instances: [instanceA] }); + const { state: next, instance } = upsertInstance(initial, { + baseUrl: instanceA.baseUrl, + label: 'ignored', + version: '1.21.0', + }); + expect(next.instances).toHaveLength(1); + expect(instance.id).toBe('inst-a'); + expect(instance.version).toBe('1.21.0'); + }); +}); + +describe('addAccount', () => { + it('adds a new account and activates it', () => { + const { state: next, account } = addAccount(state({ instances: [instanceA] }), { + instanceId: 'inst-a', + login: 'alice', + userId: 1, + }); + expect(next.accounts).toHaveLength(1); + expect(next.activeAccountId).toBe(account.id); + }); + + it('refreshes an existing (instance, login) instead of duplicating it', () => { + const initial = state({ instances: [instanceA], accounts: [accountA1], activeAccountId: 'a2' }); + const { state: next, account } = addAccount(initial, { + instanceId: 'inst-a', + login: 'ALICE', + fullName: 'Alice', + }); + expect(next.accounts).toHaveLength(1); + expect(account.id).toBe('a1'); + expect(account.fullName).toBe('Alice'); + expect(next.activeAccountId).toBe('a1'); + }); +}); + +describe('removeAccount', () => { + it('reassigns the active account to the most recently used survivor', () => { + const initial = state({ + instances: [instanceA], + accounts: [accountA1, accountA2], + activeAccountId: 'a2', + }); + const { state: next, removed } = removeAccount(initial, 'a2'); + expect(removed?.id).toBe('a2'); + expect(next.accounts.map((a) => a.id)).toEqual(['a1']); + expect(next.activeAccountId).toBe('a1'); + }); + + it('clears the active account when the last one is removed', () => { + const initial = state({ instances: [instanceA], accounts: [accountA1], activeAccountId: 'a1' }); + expect(removeAccount(initial, 'a1').state.activeAccountId).toBeNull(); + }); + + it('leaves the active account alone when removing a different one', () => { + const initial = state({ + instances: [instanceA], + accounts: [accountA1, accountA2], + activeAccountId: 'a1', + }); + expect(removeAccount(initial, 'a2').state.activeAccountId).toBe('a1'); + }); +}); + +describe('removeInstance', () => { + it('removes the instance and all of its accounts', () => { + const initial = state({ + instances: [instanceA, instanceB], + accounts: [accountA1, accountA2, accountB1], + activeAccountId: 'a1', + }); + const { state: next, removedAccounts } = removeInstance(initial, 'inst-a'); + expect(removedAccounts.map((a) => a.id).sort()).toEqual(['a1', 'a2']); + expect(next.instances.map((i) => i.id)).toEqual(['inst-b']); + expect(next.accounts.map((a) => a.id)).toEqual(['b1']); + expect(next.activeAccountId).toBe('b1'); + }); +}); + +describe('setActiveAccount + getActive', () => { + it('activates a known account and resolves its instance', () => { + const initial = state({ instances: [instanceA], accounts: [accountA1, accountA2], activeAccountId: null }); + const { state: next } = setActiveAccount(initial, 'a2'); + expect(next.activeAccountId).toBe('a2'); + const active = getActive(next); + expect(active?.account.id).toBe('a2'); + expect(active?.instance.id).toBe('inst-a'); + }); + + it('ignores unknown account ids', () => { + const initial = state({ instances: [instanceA], accounts: [accountA1], activeAccountId: 'a1' }); + const { account } = setActiveAccount(initial, 'ghost'); + expect(account).toBeNull(); + }); +}); + +describe('updateAccountProfile', () => { + it('merges profile fields', () => { + const initial = state({ instances: [instanceA], accounts: [accountA1] }); + const { account } = updateAccountProfile(initial, 'a1', { fullName: 'Alice', avatarUrl: 'https://x/y.png' }); + expect(account?.fullName).toBe('Alice'); + expect(account?.avatarUrl).toBe('https://x/y.png'); + expect(account?.login).toBe('alice'); + }); +}); diff --git a/src/core/accounts/registry.ts b/src/core/accounts/registry.ts new file mode 100644 index 0000000..4530573 --- /dev/null +++ b/src/core/accounts/registry.ts @@ -0,0 +1,259 @@ +/** + * Account registry — pure state transitions plus AsyncStorage persistence. + * + * All mutation logic is pure and unit-testable; the Zustand store in + * `accounts-store.ts` wires these functions to async persistence and SecureStore. + * + * Invariants: + * - A (instanceId, login) pair exists at most once (one token per account entry). + * - Removing the active account always reassigns `activeAccountId` deterministically. + * - Removing an instance removes every account that belongs to it. + */ + +import AsyncStorage from '@react-native-async-storage/async-storage'; + +import { + EMPTY_ACCOUNT_STATE, + generateId, + type AccountRecord, + type AccountState, + type InstanceRecord, +} from './types'; + +export const ACCOUNTS_STORAGE_KEY = 'gitea-native:accounts:v1'; + +export interface AddInstanceInput { + baseUrl: string; + label: string; + version?: string; +} + +export interface AddAccountInput { + instanceId: string; + login: string; + userId?: number; + fullName?: string; + avatarUrl?: string; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +/** Defensive parser: malformed storage must never crash the app. */ +export function parseAccountState(raw: string | null): AccountState { + if (!raw) return EMPTY_ACCOUNT_STATE; + try { + const parsed: unknown = JSON.parse(raw); + if (!isRecord(parsed)) return EMPTY_ACCOUNT_STATE; + const instances = Array.isArray(parsed.instances) ? parsed.instances.filter(isInstance) : []; + const accounts = Array.isArray(parsed.accounts) ? parsed.accounts.filter(isAccount) : []; + const activeAccountId = + typeof parsed.activeAccountId === 'string' && + accounts.some((account) => account.id === parsed.activeAccountId) + ? parsed.activeAccountId + : (accounts[0]?.id ?? null); + return { instances, accounts, activeAccountId }; + } catch { + return EMPTY_ACCOUNT_STATE; + } +} + +function isInstance(value: unknown): value is InstanceRecord { + return ( + isRecord(value) && + typeof value.id === 'string' && + typeof value.baseUrl === 'string' && + typeof value.label === 'string' + ); +} + +function isAccount(value: unknown): value is AccountRecord { + return ( + isRecord(value) && + typeof value.id === 'string' && + typeof value.instanceId === 'string' && + typeof value.login === 'string' + ); +} + +export async function readAccountState(): Promise { + return parseAccountState(await AsyncStorage.getItem(ACCOUNTS_STORAGE_KEY)); +} + +export async function writeAccountState(state: AccountState): Promise { + await AsyncStorage.setItem(ACCOUNTS_STORAGE_KEY, JSON.stringify(state)); +} + +/** Reuses an existing instance for the base URL, or registers a new one. */ +export function upsertInstance( + state: AccountState, + input: AddInstanceInput, +): { state: AccountState; instance: InstanceRecord } { + const existing = state.instances.find((instance) => instance.baseUrl === input.baseUrl); + if (existing) { + const instance: InstanceRecord = { + ...existing, + label: input.label || existing.label, + version: input.version ?? existing.version, + }; + return { + state: { ...state, instances: state.instances.map((i) => (i.id === instance.id ? instance : i)) }, + instance, + }; + } + const instance: InstanceRecord = { + id: generateId(), + baseUrl: input.baseUrl, + label: input.label, + addedAt: Date.now(), + version: input.version, + }; + return { state: { ...state, instances: [...state.instances, instance] }, instance }; +} + +/** + * Registers an account, or refreshes the profile of an existing + * (instanceId, login) entry — re-adding the same user replaces its token + * instead of duplicating the account. + */ +export function addAccount( + state: AccountState, + input: AddAccountInput, +): { state: AccountState; account: AccountRecord } { + const existing = state.accounts.find( + (account) => + account.instanceId === input.instanceId && + account.login.toLowerCase() === input.login.toLowerCase(), + ); + + if (existing) { + const account: AccountRecord = { + ...existing, + userId: input.userId ?? existing.userId, + fullName: input.fullName ?? existing.fullName, + avatarUrl: input.avatarUrl ?? existing.avatarUrl, + lastUsedAt: Date.now(), + }; + return { + state: { + ...state, + accounts: state.accounts.map((a) => (a.id === account.id ? account : a)), + activeAccountId: account.id, + }, + account, + }; + } + + const account: AccountRecord = { + id: generateId(), + instanceId: input.instanceId, + login: input.login, + userId: input.userId, + fullName: input.fullName, + avatarUrl: input.avatarUrl, + addedAt: Date.now(), + lastUsedAt: Date.now(), + }; + return { + state: { + ...state, + accounts: [...state.accounts, account], + activeAccountId: account.id, + }, + account, + }; +} + +export function updateAccountProfile( + state: AccountState, + accountId: string, + profile: Partial>, +): { state: AccountState; account: AccountRecord | null } { + const account = state.accounts.find((a) => a.id === accountId); + if (!account) return { state, account: null }; + const updated: AccountRecord = { ...account, ...profile }; + return { + state: { ...state, accounts: state.accounts.map((a) => (a.id === accountId ? updated : a)) }, + account: updated, + }; +} + +function reassignActive(state: AccountState, removedAccountId: string): string | null { + if (state.activeAccountId !== removedAccountId) return state.activeAccountId; + const remaining = state.accounts.filter((a) => a.id !== removedAccountId); + if (remaining.length === 0) return null; + const mostRecent = [...remaining].sort((a, b) => (b.lastUsedAt ?? 0) - (a.lastUsedAt ?? 0))[0]; + return mostRecent.id; +} + +/** Removes one account. The caller is responsible for deleting its token and cache. */ +export function removeAccount( + state: AccountState, + accountId: string, +): { state: AccountState; removed: AccountRecord | null } { + const removed = state.accounts.find((a) => a.id === accountId) ?? null; + if (!removed) return { state, removed: null }; + const without: AccountState = { ...state, accounts: state.accounts.filter((a) => a.id !== accountId) }; + return { + state: { ...without, activeAccountId: reassignActive(without, accountId) }, + removed, + }; +} + +/** Disconnects an instance and removes all of its accounts. */ +export function removeInstance( + state: AccountState, + instanceId: string, +): { state: AccountState; removedAccounts: AccountRecord[] } { + const removedAccounts = state.accounts.filter((a) => a.instanceId === instanceId); + if (removedAccounts.length === 0 && !state.instances.some((i) => i.id === instanceId)) { + return { state, removedAccounts: [] }; + } + const without: AccountState = { + ...state, + instances: state.instances.filter((i) => i.id !== instanceId), + accounts: state.accounts.filter((a) => a.instanceId !== instanceId), + }; + const removedIds = new Set(removedAccounts.map((a) => a.id)); + let activeAccountId = state.activeAccountId; + if (activeAccountId && removedIds.has(activeAccountId)) { + activeAccountId = null; + const remaining = [...without.accounts].sort( + (a, b) => (b.lastUsedAt ?? 0) - (a.lastUsedAt ?? 0), + ); + activeAccountId = remaining[0]?.id ?? null; + } + return { state: { ...without, activeAccountId }, removedAccounts }; +} + +export function setActiveAccount( + state: AccountState, + accountId: string, +): { state: AccountState; account: AccountRecord | null } { + const account = state.accounts.find((a) => a.id === accountId); + if (!account) return { state, account: null }; + const touched: AccountRecord = { ...account, lastUsedAt: Date.now() }; + return { + state: { + ...state, + accounts: state.accounts.map((a) => (a.id === accountId ? touched : a)), + activeAccountId: accountId, + }, + account: touched, + }; +} + +export function getActive( + state: AccountState, +): { instance: InstanceRecord; account: AccountRecord } | null { + const account = state.accounts.find((a) => a.id === state.activeAccountId); + if (!account) return null; + const instance = state.instances.find((i) => i.id === account.instanceId); + if (!instance) return null; + return { instance, account }; +} + +export function getAccountsForInstance(state: AccountState, instanceId: string): AccountRecord[] { + return state.accounts.filter((a) => a.instanceId === instanceId); +} diff --git a/src/core/accounts/token-store.test.ts b/src/core/accounts/token-store.test.ts new file mode 100644 index 0000000..2ea85c5 --- /dev/null +++ b/src/core/accounts/token-store.test.ts @@ -0,0 +1,53 @@ +/** + * Token storage: the only place secrets are written. Verifies the SecureStore + * contract (key shape + keychain service) and that invalid ids never reach the + * native module. + */ + +import * as SecureStore from 'expo-secure-store'; + +import { tokenStore } from './token-store'; + +// jest.mock is hoisted above the imports by babel-jest at runtime. +jest.mock('expo-secure-store', () => ({ + getItemAsync: jest.fn(async () => null), + setItemAsync: jest.fn(async () => undefined), + deleteItemAsync: jest.fn(async () => undefined), +})); + +const OPTIONS = { keychainService: 'gitea-native.credentials' }; + +describe('tokenStore', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('writes the token under an account-scoped key and keychain service', async () => { + await tokenStore.set('acct-1', 'super-secret'); + expect(SecureStore.setItemAsync).toHaveBeenCalledWith('token.acct-1', 'super-secret', OPTIONS); + }); + + it('reads with the same key and service', async () => { + await tokenStore.get('acct-1'); + expect(SecureStore.getItemAsync).toHaveBeenCalledWith('token.acct-1', OPTIONS); + }); + + it('removes exactly one secret', async () => { + await tokenStore.remove('acct-1'); + expect(SecureStore.deleteItemAsync).toHaveBeenCalledWith('token.acct-1', OPTIONS); + }); + + it('rejects account ids that SecureStore would reject, before touching native code', async () => { + await expect(tokenStore.set('bad id', 'x')).rejects.toThrow('Invalid account id'); + expect(SecureStore.setItemAsync).not.toHaveBeenCalled(); + }); + + it('does not derive the key from the token value', async () => { + await tokenStore.set('acct-1', 'token.other'); + expect(SecureStore.setItemAsync).toHaveBeenCalledWith( + 'token.acct-1', + 'token.other', + OPTIONS, + ); + }); +}); diff --git a/src/core/accounts/token-store.ts b/src/core/accounts/token-store.ts new file mode 100644 index 0000000..422d34e --- /dev/null +++ b/src/core/accounts/token-store.ts @@ -0,0 +1,37 @@ +/** + * Token storage — the only place secrets are written. + * + * Backed by Expo SecureStore: + * - iOS: Keychain (kSecClassGenericPassword) + * - Android: EncryptedSharedPreferences backed by the Android Keystore + * + * Rules enforced by this module: + * - Tokens never touch AsyncStorage, logs, error messages, or the account registry. + * - Keys are strictly `[A-Za-z0-9._-]` (SecureStore requirement). + * - Writes/reads are scoped per account id so removal deletes exactly one secret. + */ + +import * as SecureStore from 'expo-secure-store'; + +const KEYCHAIN_SERVICE = 'gitea-native.credentials'; + +function tokenKey(accountId: string): string { + if (!/^[A-Za-z0-9._-]+$/.test(accountId)) { + throw new Error('Invalid account id for token storage.'); + } + return `token.${accountId}`; +} + +export const tokenStore = { + async get(accountId: string): Promise { + return SecureStore.getItemAsync(tokenKey(accountId), { keychainService: KEYCHAIN_SERVICE }); + }, + + async set(accountId: string, token: string): Promise { + await SecureStore.setItemAsync(tokenKey(accountId), token, { keychainService: KEYCHAIN_SERVICE }); + }, + + async remove(accountId: string): Promise { + await SecureStore.deleteItemAsync(tokenKey(accountId), { keychainService: KEYCHAIN_SERVICE }); + }, +}; diff --git a/src/core/accounts/types.ts b/src/core/accounts/types.ts new file mode 100644 index 0000000..8e99cb0 --- /dev/null +++ b/src/core/accounts/types.ts @@ -0,0 +1,49 @@ +/** + * Account & instance records. + * + * Instances and accounts are non-sensitive metadata persisted in AsyncStorage. + * Tokens are *never* part of these structures — they live exclusively in + * `token-store.ts` (Expo SecureStore → Keychain/Keystore). + */ + +export interface InstanceRecord { + id: string; + /** Normalized base URL, e.g. https://codeberg.org (sub-paths allowed). */ + baseUrl: string; + /** User-facing label; defaults to the host name. */ + label: string; + addedAt: number; + /** Last successfully negotiated server version (hint for capability detection). */ + version?: string; +} + +export interface AccountRecord { + id: string; + instanceId: string; + login: string; + userId?: number; + fullName?: string; + avatarUrl?: string; + addedAt: number; + /** Updated whenever the account is (re)activated. */ + lastUsedAt?: number; +} + +export interface AccountState { + instances: InstanceRecord[]; + accounts: AccountRecord[]; + activeAccountId: string | null; +} + +export const EMPTY_ACCOUNT_STATE: AccountState = { + instances: [], + accounts: [], + activeAccountId: null, +}; + +/** Deterministic-ish unique id without depending on crypto.randomUUID (Hermes-safe). */ +export function generateId(): string { + const time = Date.now().toString(36); + const random = Math.random().toString(36).slice(2, 10); + return `${time}${random}`; +} diff --git a/src/core/api/client.test.ts b/src/core/api/client.test.ts new file mode 100644 index 0000000..c3cd0b8 --- /dev/null +++ b/src/core/api/client.test.ts @@ -0,0 +1,152 @@ +/** + * HTTP client contract: credential handling, pagination metadata and error + * normalization. The token must appear only in the Authorization header and + * must never leak into an error message. + */ + +import { GiteaClient, buildQuery, type FetchLike } from './client'; +import { ApiError } from './errors'; + +/** Minimal fetch Response stub (avoids depending on a global Response). */ +function response( + body: string, + status = 200, + headers: Record = {}, +): Response { + return { + ok: status >= 200 && status < 300, + status, + headers: { + get: (key: string) => headers[key] ?? null, + }, + text: async () => body, + } as unknown as Response; +} + +const TOKEN = 'pat-super-secret'; + +function client(fetchImpl: FetchLike) { + return new GiteaClient({ baseUrl: 'https://codeberg.org', token: TOKEN, fetchImpl }); +} + +describe('buildQuery', () => { + it('omits null/undefined, joins arrays and encodes values', () => { + expect( + buildQuery({ page: 1, q: 'a b', empty: undefined, nullable: null, labels: ['x', 'y'] }), + ).toBe('?page=1&q=a+b&labels=x%2Cy'); + }); + + it('returns an empty string when there is nothing to send', () => { + expect(buildQuery({})).toBe(''); + }); +}); + +describe('GiteaClient authentication', () => { + it('sends the token only in the Authorization header', async () => { + const fetchImpl = jest.fn(async () => + response(JSON.stringify({ login: 'alice' })), + ) as unknown as jest.Mock; + + await client(fetchImpl).get('/user'); + + const [url, init] = fetchImpl.mock.calls[0]; + expect(url).toBe('https://codeberg.org/api/v1/user'); + expect(url).not.toContain(TOKEN); + expect(init.headers.Authorization).toBe(`token ${TOKEN}`); + expect(JSON.stringify(init)).not.toContain('?token='); + }); + + it('honours a sub-path instance', async () => { + const fetchImpl = jest.fn(async () => response('{}')) as unknown as jest.Mock; + const c = new GiteaClient({ baseUrl: 'https://example.com/git', fetchImpl }); + await c.get('/version'); + expect(fetchImpl.mock.calls[0][0]).toBe('https://example.com/git/api/v1/version'); + }); + + it('does not send an Authorization header for anonymous clients', async () => { + const fetchImpl = jest.fn(async () => response('{}')) as unknown as jest.Mock; + await new GiteaClient({ baseUrl: 'https://codeberg.org', fetchImpl }).get('/version'); + expect(fetchImpl.mock.calls[0][1].headers.Authorization).toBeUndefined(); + }); +}); + +describe('GiteaClient pagination', () => { + it('reads X-Total-Count and computes hasMore', async () => { + const fetchImpl = jest.fn(async () => + response(JSON.stringify([{ id: 1 }]), 200, { 'X-Total-Count': '42' }), + ) as unknown as jest.Mock; + + const raw = await client(fetchImpl).raw('/repos', { query: { page: 1, limit: 20 } }); + + expect(raw.total).toBe(42); + expect(raw.hasMore).toBe(true); + }); + + it('flags no more pages on the last page', async () => { + const fetchImpl = jest.fn(async () => + response(JSON.stringify([{ id: 1 }]), 200, { 'X-Total-Count': '20' }), + ) as unknown as jest.Mock; + + const raw = await client(fetchImpl).raw('/repos', { query: { page: 1, limit: 20 } }); + expect(raw.hasMore).toBe(false); + }); + + it('falls back to a length heuristic without a total', async () => { + const full = Array.from({ length: 20 }, (_, i) => ({ id: i })); + const fetchImpl = jest.fn(async () => response(JSON.stringify(full))) as unknown as jest.Mock; + const raw = await client(fetchImpl).raw('/repos', { query: { limit: 20 } }); + expect(raw.hasMore).toBe(true); + }); +}); + +describe('GiteaClient error mapping', () => { + it('maps 401 to an unauthorized ApiError', async () => { + const fetchImpl = jest.fn(async () => + response(JSON.stringify({ message: 'bad token' }), 401), + ) as unknown as jest.Mock; + + await expect(client(fetchImpl).get('/user')).rejects.toMatchObject({ + name: 'ApiError', + kind: 'unauthorized', + status: 401, + serverMessage: 'bad token', + }); + }); + + it('never includes the token in an error', async () => { + const fetchImpl = jest.fn(async () => response('', 403)) as unknown as jest.Mock; + const error = await client(fetchImpl) + .get('/user') + .then(() => null) + .catch((e: unknown) => e as ApiError); + + expect(error).toBeInstanceOf(ApiError); + expect(JSON.stringify({ message: error?.message, server: error?.serverMessage })).not.toContain( + TOKEN, + ); + }); + + it('maps transport failures to a network error', async () => { + const fetchImpl = jest.fn(async () => { + throw new TypeError('Network request failed'); + }) as unknown as jest.Mock; + + await expect(client(fetchImpl).get('/user')).rejects.toMatchObject({ kind: 'network' }); + }); + + it('maps unparseable 2xx bodies to invalid-response', async () => { + const fetchImpl = jest.fn(async () => response('nope')) as unknown as jest.Mock; + await expect(client(fetchImpl).get('/user')).rejects.toMatchObject({ kind: 'invalid-response' }); + }); + + it('maps 429 to rate-limit with Retry-After', async () => { + const fetchImpl = jest.fn(async () => + response('', 429, { 'Retry-After': '30' }), + ) as unknown as jest.Mock; + + await expect(client(fetchImpl).get('/user')).rejects.toMatchObject({ + kind: 'rate-limit', + retryAfterSeconds: 30, + }); + }); +}); diff --git a/src/core/api/client.ts b/src/core/api/client.ts new file mode 100644 index 0000000..018450c --- /dev/null +++ b/src/core/api/client.ts @@ -0,0 +1,253 @@ +/** + * Typed HTTP client for the Gitea REST API. + * + * Responsibilities: + * - Build URLs (base + path + query) without ever putting the token in a URL. + * - Attach `Authorization: token ` from an injected secret provider. + * - Normalize every failure into {@link ApiError} (status-based kinds, timeouts, + * aborts, rate limits) so callers never string-match error messages. + * - Support cancellation (AbortSignal) and per-request timeouts. + * - Parse pagination metadata (`X-Total-Count` + page/limit heuristic). + * + * The client is intentionally transport-only: endpoint knowledge lives in + * `endpoints.ts`, server-state caching in feature hooks. + */ + +import { ApiError, toApiError } from './errors'; +import { apiBaseUrl } from './instance-url'; + +export type QueryValue = + | string + | number + | boolean + | null + | undefined + | readonly (string | number)[]; +export type QueryParams = Record; + +export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; + +export interface RequestOptions { + method?: HttpMethod; + query?: QueryParams; + body?: unknown; + signal?: AbortSignal; + timeoutMs?: number; +} + +export interface PageMetaRaw { + total: number | null; +} + +export interface RawResponse { + data: T; + status: number; + total: number | null; + /** True when the server indicated more pages (total unknown uses a length heuristic). */ + hasMore: boolean; +} + +export type FetchLike = (input: string, init?: RequestInit) => Promise; + +export interface GiteaClientOptions { + /** Instance base URL (no `/api/v1` suffix). */ + baseUrl: string; + /** Personal access token. Omitted for unauthenticated probes (e.g. /version). */ + token?: string; + timeoutMs?: number; + fetchImpl?: FetchLike; +} + +export function buildQuery(params: QueryParams): string { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value === undefined || value === null) continue; + if (Array.isArray(value)) { + if (value.length > 0) search.append(key, value.join(',')); + continue; + } + search.append(key, String(value)); + } + const qs = search.toString(); + return qs ? `?${qs}` : ''; +} + +export class GiteaClient { + readonly baseUrl: string; + readonly apiRoot: string; + private readonly token: string | undefined; + private readonly timeoutMs: number; + private readonly fetchImpl: FetchLike; + + constructor(options: GiteaClientOptions) { + this.baseUrl = options.baseUrl; + this.apiRoot = apiBaseUrl(options.baseUrl); + this.token = options.token; + this.timeoutMs = options.timeoutMs ?? 15_000; + this.fetchImpl = options.fetchImpl ?? (fetch as FetchLike); + } + + /** True when this client carries credentials. */ + get isAuthenticated(): boolean { + return typeof this.token === 'string' && this.token.length > 0; + } + + async get(path: string, options: Omit = {}): Promise { + const raw = await this.raw(path, { ...options, method: 'GET' }); + return raw.data; + } + + async post(path: string, body?: unknown, options: RequestOptions = {}): Promise { + const raw = await this.raw(path, { ...options, method: 'POST', body }); + return raw.data; + } + + async put(path: string, body?: unknown, options: RequestOptions = {}): Promise { + const raw = await this.raw(path, { ...options, method: 'PUT', body }); + return raw.data; + } + + async patch(path: string, body?: unknown, options: RequestOptions = {}): Promise { + const raw = await this.raw(path, { ...options, method: 'PATCH', body }); + return raw.data; + } + + async delete(path: string, options: RequestOptions = {}): Promise { + const raw = await this.raw(path, { ...options, method: 'DELETE' }); + return raw.data; + } + + /** + * Performs a request and returns data plus pagination metadata. + * `hasMore` uses `X-Total-Count` when present, otherwise a length heuristic + * against the requested page size (Gitea does not consistently emit totals). + */ + async raw(path: string, options: RequestOptions = {}): Promise> { + const method = options.method ?? 'GET'; + const url = `${this.apiRoot}${path}${buildQuery(options.query ?? {})}`; + + const headers: Record = { Accept: 'application/json' }; + if (this.token) headers.Authorization = `token ${this.token}`; + let body: string | undefined; + if (options.body !== undefined) { + headers['Content-Type'] = 'application/json'; + body = JSON.stringify(options.body); + } + + const controller = new AbortController(); + let timedOut = false; + const timeoutMs = options.timeoutMs ?? this.timeoutMs; + const timer = setTimeout(() => { + timedOut = true; + controller.abort(); + }, timeoutMs); + const onCallerAbort = () => controller.abort(); + if (options.signal) { + if (options.signal.aborted) { + clearTimeout(timer); + throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); + } + options.signal.addEventListener('abort', onCallerAbort); + } + + let response: Response; + try { + response = await this.fetchImpl(url, { + method, + headers, + body, + signal: controller.signal, + }); + } catch (error) { + if (timedOut) { + throw new ApiError({ + kind: 'timeout', + status: 0, + message: 'The server took too long to respond.', + }); + } + if (options.signal?.aborted) { + throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); + } + // Transport-level failure (DNS, TLS, offline). toApiError never echoes the URL/token. + throw toApiError(error); + } finally { + clearTimeout(timer); + options.signal?.removeEventListener('abort', onCallerAbort); + } + + const totalRaw = response.headers.get('X-Total-Count'); + const total = totalRaw !== null && totalRaw !== '' && !Number.isNaN(Number(totalRaw)) + ? Number(totalRaw) + : null; + + const text = await response.text(); + let parsed: unknown = undefined; + if (text.length > 0) { + try { + parsed = JSON.parse(text); + } catch { + if (response.ok) { + throw new ApiError({ + kind: 'invalid-response', + status: response.status, + message: 'The server returned a response the app could not read.', + }); + } + } + } + + if (!response.ok) { + const serverMessage = + parsed && typeof parsed === 'object' && 'message' in parsed + ? String((parsed as { message: unknown }).message) + : text.length > 0 && text.length < 300 + ? text + : null; + const retryAfterHeader = response.headers.get('Retry-After'); + const retryAfterSeconds = + response.status === 429 && retryAfterHeader && !Number.isNaN(Number(retryAfterHeader)) + ? Number(retryAfterHeader) + : null; + const kind = ApiError.kindForStatus(response.status); + throw new ApiError({ + kind, + status: response.status, + serverMessage, + retryAfterSeconds, + message: messageForStatus(kind, response.status, serverMessage), + }); + } + + const requestedLimit = + typeof options.query?.limit === 'number' ? options.query.limit : null; + const requestedPage = typeof options.query?.page === 'number' ? options.query.page : 1; + const items = Array.isArray(parsed) ? (parsed as unknown[]).length : null; + const hasMore = + requestedLimit === null + ? false + : total !== null + ? requestedPage * requestedLimit < total + : items !== null && items >= requestedLimit; + + return { data: parsed as T, status: response.status, total, hasMore }; + } +} + +function messageForStatus(kind: ApiError['kind'], status: number, serverMessage: string | null): string { + if (serverMessage) return serverMessage; + switch (kind) { + case 'unauthorized': + return 'This Personal Access Token is no longer valid. It may have expired or been revoked.'; + case 'forbidden': + return 'You do not have permission to perform this action.'; + case 'not-found': + return 'Not found on this instance.'; + case 'rate-limit': + return 'The instance is rate limiting requests. Try again in a moment.'; + case 'server': + return `The instance returned an error (HTTP ${status}).`; + default: + return `Request failed (HTTP ${status}).`; + } +} diff --git a/src/core/api/endpoints.ts b/src/core/api/endpoints.ts new file mode 100644 index 0000000..c649b36 --- /dev/null +++ b/src/core/api/endpoints.ts @@ -0,0 +1,450 @@ +/** + * Typed Gitea REST v1 endpoint functions. + * + * Every function takes a {@link GiteaClient} and plain parameters — no React, + * no caching. Screens consume these through TanStack Query hooks so that + * caching, cancellation, and retries stay in one layer. + * + * Endpoint shapes were verified against the official OpenAPI spec shipped by + * Gitea instances at `/swagger.v1.json`. + */ + +import type { GiteaClient, RequestOptions } from './client'; +import type { + Activity, + Branch, + Commit, + ContentsEntry, + Issue, + Label, + NotificationCount, + NotificationThread, + PullRequest, + Repository, + ServerVersion, + Tag, + User, +} from './types'; + +export interface PageParams { + page?: number; + limit?: number; +} + +const enc = encodeURIComponent; + +/** Encodes a repository path ("src/a b.ts") segment by segment. */ +export function encodeRepoPath(path: string): string { + return path + .split('/') + .filter((segment) => segment.length > 0) + .map(enc) + .join('/'); +} + +export function repoPath(owner: string, repo: string): string { + return `/repos/${enc(owner)}/${enc(repo)}`; +} + +// --------------------------------------------------------------------------- +// Server & identity +// --------------------------------------------------------------------------- + +export function fetchVersion( + client: GiteaClient, + options?: RequestOptions, +): Promise { + return client.get('/version', options); +} + +export function fetchAuthenticatedUser( + client: GiteaClient, + options?: RequestOptions, +): Promise { + return client.get('/user', options); +} + +// --------------------------------------------------------------------------- +// Repositories +// --------------------------------------------------------------------------- + +export interface ListMyReposParams extends PageParams { + /** visibility: all | private | public (server default: all) */ + visibility?: 'all' | 'private' | 'public'; +} + +export async function listMyRepos( + client: GiteaClient, + params: ListMyReposParams = {}, + options?: RequestOptions, +) { + return client.raw('/user/repos', { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 20, visibility: params.visibility }, + }); +} + +export interface SearchReposParams extends PageParams { + q?: string; + sort?: 'alpha' | 'created' | 'updated' | 'size' | 'stars' | 'forks' | 'id'; + order?: 'asc' | 'desc'; + /** Restrict to repositories the authenticated user can access. */ + starredBy?: string; +} + +export async function searchRepositories( + client: GiteaClient, + params: SearchReposParams = {}, + options?: RequestOptions, +) { + return client.raw('/repos/search', { + ...options, + query: { + page: params.page ?? 1, + limit: params.limit ?? 20, + q: params.q?.trim() ? params.q.trim() : undefined, + sort: params.q?.trim() ? undefined : params.sort, + order: params.q?.trim() ? undefined : params.order, + starredBy: params.starredBy, + }, + }); +} + +export async function listStarredRepos( + client: GiteaClient, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw('/user/starred', { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 20 }, + }); +} + +export function fetchRepository( + client: GiteaClient, + owner: string, + repo: string, + options?: RequestOptions, +): Promise { + return client.get(repoPath(owner, repo), options); +} + +export function fetchRepositoryLanguages( + client: GiteaClient, + owner: string, + repo: string, + options?: RequestOptions, +): Promise> { + return client.get>(`${repoPath(owner, repo)}/languages`, options); +} + +// --------------------------------------------------------------------------- +// Contents, README, branches, tags +// --------------------------------------------------------------------------- + +export function listContents( + client: GiteaClient, + owner: string, + repo: string, + path = '', + params: { ref?: string } = {}, + options?: RequestOptions, +): Promise { + const suffix = path ? `/${encodeRepoPath(path)}` : ''; + return client.get(`${repoPath(owner, repo)}/contents${suffix}`, { + ...options, + query: { ref: params.ref }, + }); +} + +export function fetchFile( + client: GiteaClient, + owner: string, + repo: string, + path: string, + params: { ref?: string } = {}, + options?: RequestOptions, +): Promise { + return client.get(`${repoPath(owner, repo)}/contents/${encodeRepoPath(path)}`, { + ...options, + query: { ref: params.ref }, + }); +} + +/** + * Finds and loads the repository README. + * + * Gitea's API has no dedicated README endpoint, so we locate a `README*` entry in + * the repository root and fetch it through the contents API. + */ +export async function fetchReadme( + client: GiteaClient, + owner: string, + repo: string, + params: { ref?: string } = {}, + options?: RequestOptions, +): Promise { + const root = await listContents(client, owner, repo, '', params, options); + const readme = root.find( + (entry) => entry.type === 'file' && /^readme(\.[^.]+)?$/i.test(entry.name), + ); + if (!readme) return null; + return fetchFile(client, owner, repo, readme.path, params, options); +} + +export function listBranches( + client: GiteaClient, + owner: string, + repo: string, + params: PageParams & { q?: string } = {}, + options?: RequestOptions, +) { + return client.raw(`${repoPath(owner, repo)}/branches`, { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 30, q: params.q }, + }); +} + +export function fetchBranch( + client: GiteaClient, + owner: string, + repo: string, + branch: string, + options?: RequestOptions, +): Promise { + return client.get(`${repoPath(owner, repo)}/branches/${enc(branch)}`, options); +} + +export function listTags( + client: GiteaClient, + owner: string, + repo: string, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw(`${repoPath(owner, repo)}/tags`, { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 30 }, + }); +} + +// --------------------------------------------------------------------------- +// Commits +// --------------------------------------------------------------------------- + +export interface ListCommitsParams extends PageParams { + /** Branch, tag, or commit SHA. Defaults to the repository's default branch. */ + sha?: string; + /** Restrict to commits touching this path. */ + path?: string; +} + +export function listCommits( + client: GiteaClient, + owner: string, + repo: string, + params: ListCommitsParams = {}, + options?: RequestOptions, +) { + return client.raw(`${repoPath(owner, repo)}/commits`, { + ...options, + query: { + page: params.page ?? 1, + limit: params.limit ?? 20, + sha: params.sha, + path: params.path, + files: true, + stat: true, + }, + }); +} + +export function fetchCommit( + client: GiteaClient, + owner: string, + repo: string, + sha: string, + options?: RequestOptions, +): Promise { + return client.get(`${repoPath(owner, repo)}/commits/${enc(sha)}`, options); +} + +// --------------------------------------------------------------------------- +// Issues & pull requests +// --------------------------------------------------------------------------- + +export interface IssueSearchParams extends PageParams { + state?: 'open' | 'closed' | 'all'; + q?: string; + type?: 'issues' | 'pulls'; + assigned?: boolean; + created?: boolean; + reviewRequested?: boolean; +} + +/** Cross-repository issue search scoped to what the user can see. */ +export async function searchIssues( + client: GiteaClient, + params: IssueSearchParams = {}, + options?: RequestOptions, +) { + return client.raw('/repos/issues/search', { + ...options, + query: { + page: params.page ?? 1, + limit: params.limit ?? 20, + state: params.state ?? 'open', + q: params.q?.trim() || undefined, + type: params.type, + assigned: params.assigned ? true : undefined, + created: params.created ? true : undefined, + review_requested: params.reviewRequested ? true : undefined, + }, + }); +} + +export interface ListRepoIssuesParams extends PageParams { + state?: 'open' | 'closed' | 'all'; + q?: string; + labels?: string; +} + +export function listRepoIssues( + client: GiteaClient, + owner: string, + repo: string, + params: ListRepoIssuesParams = {}, + options?: RequestOptions, +) { + return client.raw(`${repoPath(owner, repo)}/issues`, { + ...options, + query: { + page: params.page ?? 1, + limit: params.limit ?? 20, + state: params.state ?? 'open', + q: params.q?.trim() || undefined, + labels: params.labels, + type: 'issues', + }, + }); +} + +export function fetchIssue( + client: GiteaClient, + owner: string, + repo: string, + index: number, + options?: RequestOptions, +): Promise { + return client.get(`${repoPath(owner, repo)}/issues/${index}`, options); +} + +export function listRepoLabels( + client: GiteaClient, + owner: string, + repo: string, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw(`${repoPath(owner, repo)}/labels`, { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 50 }, + }); +} + +export interface ListPullsParams extends PageParams { + state?: 'open' | 'closed' | 'all'; + sort?: 'oldest' | 'recentupdate' | 'recentclose' | 'leastupdate' | 'mostcomment' | 'leastcomment'; + baseBranch?: string; +} + +export function listPulls( + client: GiteaClient, + owner: string, + repo: string, + params: ListPullsParams = {}, + options?: RequestOptions, +) { + return client.raw(`${repoPath(owner, repo)}/pulls`, { + ...options, + query: { + page: params.page ?? 1, + limit: params.limit ?? 20, + state: params.state ?? 'open', + sort: params.sort, + base_branch: params.baseBranch, + }, + }); +} + +export function fetchPull( + client: GiteaClient, + owner: string, + repo: string, + index: number, + options?: RequestOptions, +): Promise { + return client.get(`${repoPath(owner, repo)}/pulls/${index}`, options); +} + +// --------------------------------------------------------------------------- +// Notifications +// --------------------------------------------------------------------------- + +export interface ListNotificationsParams extends PageParams { + all?: boolean; + /** ISO timestamp — only threads updated after this time. */ + since?: string; +} + +export function listNotifications( + client: GiteaClient, + params: ListNotificationsParams = {}, + options?: RequestOptions, +) { + return client.raw('/notifications', { + ...options, + query: { + page: params.page ?? 1, + limit: params.limit ?? 20, + all: params.all ? true : undefined, + since: params.since, + }, + }); +} + +export function fetchUnreadNotificationCount( + client: GiteaClient, + options?: RequestOptions, +): Promise { + return client.get('/notifications/new', options); +} + +export function markAllNotificationsRead(client: GiteaClient, options?: RequestOptions) { + return client.put('/notifications', { status: 'read' }, options); +} + +export function markNotificationThreadRead( + client: GiteaClient, + threadId: number, + options?: RequestOptions, +) { + return client.put(`/notifications/threads/${threadId}`, { status: 'read' }, options); +} + +// --------------------------------------------------------------------------- +// Activity feed (Home screen) +// --------------------------------------------------------------------------- + +export function listUserActivity( + client: GiteaClient, + username: string, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw(`/users/${enc(username)}/activities/feeds`, { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 20 }, + }); +} diff --git a/src/core/api/error-text.ts b/src/core/api/error-text.ts new file mode 100644 index 0000000..fa55d1d --- /dev/null +++ b/src/core/api/error-text.ts @@ -0,0 +1,38 @@ +/** + * Maps {@link ApiError} kinds to localized, user-facing messages. + * Kept out of the error model itself so the core layer stays i18n-free. + */ + +import type { TFunction } from 'i18next'; + +import { isApiError } from '@/core/api/errors'; + +export function apiErrorMessage(error: unknown, t: TFunction): string { + if (isApiError(error)) { + switch (error.kind) { + case 'network': + return t('errors.network'); + case 'timeout': + return t('errors.timeout'); + case 'unauthorized': + return t('errors.unauthorized'); + case 'forbidden': + return t('errors.forbidden'); + case 'not-found': + return t('errors.notFound'); + case 'conflict': + return t('errors.conflict'); + case 'rate-limit': + return t('errors.rateLimit'); + case 'server': + return t('errors.server'); + case 'invalid-response': + return t('errors.invalidResponse'); + case 'aborted': + case 'client': + default: + return t('errors.unknown'); + } + } + return t('errors.unknown'); +} diff --git a/src/core/api/errors.ts b/src/core/api/errors.ts new file mode 100644 index 0000000..1f34417 --- /dev/null +++ b/src/core/api/errors.ts @@ -0,0 +1,79 @@ +/** + * Centralized API error model. + * + * Every failure path in the app funnels through {@link ApiError} so screens can + * branch on `kind` instead of string matching. Messages are built exclusively from + * HTTP status information and server-provided bodies — request tokens are never + * part of an error, a message, or a log line. + */ + +export type ApiErrorKind = + | 'network' // DNS/TLS/connection failure + | 'timeout' // request exceeded the client timeout + | 'aborted' // cancelled by the caller (navigation, unmount) + | 'unauthorized' // 401 — token missing/expired/revoked + | 'forbidden' // 403 — authenticated but not allowed + | 'not-found' // 404 + | 'conflict' // 409 — e.g. stale file SHA when committing + | 'rate-limit' // 429 + | 'server' // 5xx + | 'client' // other 4xx (validation etc.) + | 'invalid-response'; // 2xx but body could not be understood + +export class ApiError extends Error { + readonly kind: ApiErrorKind; + /** HTTP status, or 0 for transport-level failures. */ + readonly status: number; + /** Seconds to wait before retrying (only for rate limits). */ + readonly retryAfterSeconds: number | null; + /** Server-provided message (already sanitized by the server). */ + readonly serverMessage: string | null; + + constructor(params: { + kind: ApiErrorKind; + status: number; + message: string; + serverMessage?: string | null; + retryAfterSeconds?: number | null; + }) { + super(params.message); + this.name = 'ApiError'; + this.kind = params.kind; + this.status = params.status; + this.serverMessage = params.serverMessage ?? null; + this.retryAfterSeconds = params.retryAfterSeconds ?? null; + } + + static kindForStatus(status: number): ApiErrorKind { + if (status === 401) return 'unauthorized'; + if (status === 403) return 'forbidden'; + if (status === 404) return 'not-found'; + if (status === 409) return 'conflict'; + if (status === 429) return 'rate-limit'; + if (status >= 500) return 'server'; + return 'client'; + } + + /** True when re-authentication is the only recovery (expired/invalid/revoked token). */ + get isAuthFailure(): boolean { + return this.kind === 'unauthorized'; + } +} + +/** Maps arbitrary thrown values into ApiError without ever leaking request details. */ +export function toApiError(error: unknown): ApiError { + if (error instanceof ApiError) return error; + if (error instanceof Error && error.name === 'AbortError') { + return new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); + } + // Transport failures (TypeError: Network request failed, TLS errors, ...). + return new ApiError({ + kind: 'network', + status: 0, + message: 'Could not reach the server. Check your connection and the instance URL.', + }); +} + +export function isApiError(error: unknown): error is ApiError { + return error instanceof ApiError; +} diff --git a/src/core/api/instance-url.test.ts b/src/core/api/instance-url.test.ts new file mode 100644 index 0000000..ad0b623 --- /dev/null +++ b/src/core/api/instance-url.test.ts @@ -0,0 +1,101 @@ +/** + * URL normalization & hardening. These rules protect the token: a token is only + * ever sent over HTTPS to a host the user explicitly entered. + */ + +import { + InstanceUrlError, + apiBaseUrl, + instanceHostLabel, + isLoopbackHost, + normalizeInstanceUrl, +} from './instance-url'; + +function kindOf(fn: () => unknown): string | undefined { + try { + fn(); + return undefined; + } catch (error) { + return error instanceof InstanceUrlError ? error.kind : undefined; + } +} + +describe('normalizeInstanceUrl', () => { + it.each([ + ['codeberg.org', 'https://codeberg.org'], + ['https://codeberg.org', 'https://codeberg.org'], + [' https://codeberg.org ', 'https://codeberg.org'], + ['https://codeberg.org/', 'https://codeberg.org'], + ['https://codeberg.org///', 'https://codeberg.org'], + ['https://example.com/git/', 'https://example.com/git'], + ['example.com/git', 'https://example.com/git'], + ])('normalizes %s → %s', (input, expected) => { + expect(normalizeInstanceUrl(input)).toBe(expected); + }); + + it('drops query strings and fragments from a base URL', () => { + expect(normalizeInstanceUrl('https://example.com/git?foo=1#bar')).toBe('https://example.com/git'); + }); + + it('rejects blank input', () => { + expect(kindOf(() => normalizeInstanceUrl(' '))).toBe('empty'); + }); + + it('rejects a non-http(s) scheme', () => { + expect(kindOf(() => normalizeInstanceUrl('ftp://example.com'))).toBe('unsupported-scheme'); + }); + + it('rejects embedded credentials used as a token smuggling vector', () => { + expect(kindOf(() => normalizeInstanceUrl('https://user:secret@example.com'))).toBe('credentials'); + }); + + it('rejects plain HTTP for non-loopback hosts', () => { + expect(kindOf(() => normalizeInstanceUrl('http://example.com'))).toBe('insecure'); + }); + + it.each(['localhost', '127.0.0.1', '0.0.0.0', '10.0.2.2'])( + 'allows plain HTTP on the loopback/dev host %s', + (host) => { + expect(normalizeInstanceUrl(`http://${host}:3000`)).toBe(`http://${host}:3000`); + }, + ); + + it('allows plain HTTP on the IPv6 loopback address', () => { + expect(normalizeInstanceUrl('http://[::1]:3000')).toBe('http://[::1]:3000'); + }); +}); + +describe('isLoopbackHost', () => { + it('accepts bracketed and bare IPv6 loopback', () => { + expect(isLoopbackHost('[::1]')).toBe(true); + expect(isLoopbackHost('::1')).toBe(true); + }); + + it('rejects public hosts', () => { + expect(isLoopbackHost('codeberg.org')).toBe(false); + }); +}); + +describe('apiBaseUrl', () => { + it('appends the REST root', () => { + expect(apiBaseUrl('https://codeberg.org')).toBe('https://codeberg.org/api/v1'); + }); + + it('preserves a sub-path installation', () => { + expect(apiBaseUrl('https://example.com/git')).toBe('https://example.com/git/api/v1'); + }); +}); + +describe('instanceHostLabel', () => { + it('returns the host for a bare instance', () => { + expect(instanceHostLabel('https://codeberg.org')).toBe('codeberg.org'); + }); + + it('includes a sub-path', () => { + expect(instanceHostLabel('https://example.com/git')).toBe('example.com/git'); + }); + + it('falls back to the raw value for unparseable input', () => { + expect(instanceHostLabel('not a url')).toBe('not a url'); + }); +}); diff --git a/src/core/api/instance-url.ts b/src/core/api/instance-url.ts new file mode 100644 index 0000000..8d369aa --- /dev/null +++ b/src/core/api/instance-url.ts @@ -0,0 +1,92 @@ +/** + * Instance URL parsing, normalization, and validation. + * + * Security rules enforced here: + * - Remote instances must use HTTPS (plain HTTP is only accepted for loopback + * development hosts such as localhost, 127.0.0.1 and the Android emulator). + * - Embedded credentials (user:pass@) are rejected — tokens belong in the token + * field, not the URL. + * - Only http/https schemes are accepted; the URL never reaches the network during + * normalization (no redirects are followed implicitly here). + * + * Gitea instances may be hosted under a sub-path (e.g. https://example.com/git), + * so the path component is preserved. + */ + +export type InstanceUrlErrorKind = + | 'empty' + | 'invalid' + | 'unsupported-scheme' + | 'insecure' + | 'credentials'; + +export class InstanceUrlError extends Error { + readonly kind: InstanceUrlErrorKind; + constructor(kind: InstanceUrlErrorKind, message: string) { + super(message); + this.name = 'InstanceUrlError'; + this.kind = kind; + } +} + +const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0', '10.0.2.2']); + +export function isLoopbackHost(hostname: string): boolean { + // URL.hostname wraps IPv6 addresses in brackets (`[::1]`). + const host = hostname.replace(/^\[|\]$/g, '').toLowerCase(); + return LOOPBACK_HOSTS.has(host); +} + +/** + * Normalizes user input into a canonical base URL (no trailing slash, no query/fragment). + * @throws {InstanceUrlError} when the input cannot be accepted. + */ +export function normalizeInstanceUrl(input: string): string { + const trimmed = input.trim(); + if (trimmed.length === 0) { + throw new InstanceUrlError('empty', 'Enter the address of your Gitea instance.'); + } + + const withScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`; + + let url: URL; + try { + url = new URL(withScheme); + } catch { + throw new InstanceUrlError('invalid', 'That does not look like a valid URL.'); + } + + if (url.protocol !== 'https:' && url.protocol !== 'http:') { + throw new InstanceUrlError('unsupported-scheme', 'Only http(s) addresses are supported.'); + } + if (url.username || url.password) { + throw new InstanceUrlError( + 'credentials', + 'Remove the username and password from the address — use the token field instead.', + ); + } + if (url.protocol === 'http:' && !isLoopbackHost(url.hostname)) { + throw new InstanceUrlError( + 'insecure', + 'Remote instances must use HTTPS. Plain HTTP is only allowed for localhost.', + ); + } + + const path = url.pathname.replace(/\/+$/, ''); + return `${url.origin}${path}`; +} + +/** REST API root for an instance base URL. */ +export function apiBaseUrl(instanceUrl: string): string { + return `${instanceUrl}/api/v1`; +} + +/** Human-friendly host label (used in account switcher when no custom label is set). */ +export function instanceHostLabel(instanceUrl: string): string { + try { + const url = new URL(instanceUrl); + return url.host + (url.pathname && url.pathname !== '/' ? url.pathname : ''); + } catch { + return instanceUrl; + } +} diff --git a/src/core/api/query-client.ts b/src/core/api/query-client.ts new file mode 100644 index 0000000..1edbeab --- /dev/null +++ b/src/core/api/query-client.ts @@ -0,0 +1,70 @@ +/** + * TanStack Query configuration. + * + * - Retries are status-aware: 4xx (except 429) and aborts never retry; + * transport/5xx failures retry twice with backoff; rate limits honor Retry-After. + * - A bounded AsyncStorage persister provides the offline read-only cache + * (successful queries only; account-scoped keys keep data isolated). + */ + +import AsyncStorage from '@react-native-async-storage/async-storage'; +import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'; +import { QueryClient } from '@tanstack/react-query'; + +import { ApiError } from './errors'; + +const NO_RETRY_KINDS = new Set([ + 'aborted', + 'unauthorized', + 'forbidden', + 'not-found', + 'conflict', + 'client', + 'rate-limit', + 'invalid-response', +]); + +export const OFFLINE_CACHE_MAX_AGE = 24 * 60 * 60 * 1000; // 24 hours + +export function createQueryClient(): QueryClient { + return new QueryClient({ + defaultOptions: { + queries: { + staleTime: 30_000, + gcTime: 10 * 60_000, + refetchOnReconnect: true, + retry: (failureCount, error) => { + if (error instanceof ApiError && NO_RETRY_KINDS.has(error.kind)) return false; + return failureCount < 2; + }, + retryDelay: (attempt, error) => { + if (error instanceof ApiError && error.retryAfterSeconds) { + return Math.min(error.retryAfterSeconds * 1000, 30_000); + } + return Math.min(1000 * 2 ** attempt, 8_000); + }, + }, + mutations: { + retry: false, + }, + }, + }); +} + +export function createQueryPersister() { + return createAsyncStoragePersister({ + storage: AsyncStorage, + key: 'gitea-native:query-cache:v1', + }); +} + +/** Only successful responses are dehydrated — errors and pending states stay ephemeral. */ +export function shouldDehydrateQuery(query: { state: { status: string } }): boolean { + return query.state.status === 'success'; +} + +/** App-wide singleton — the one QueryClient the provider, hooks and purges share. */ +export const queryClient: QueryClient = createQueryClient(); + +/** Bounded AsyncStorage persister for the offline read-only cache. */ +export const queryPersister = createQueryPersister(); diff --git a/src/core/api/query-keys.test.ts b/src/core/api/query-keys.test.ts new file mode 100644 index 0000000..26788dd --- /dev/null +++ b/src/core/api/query-keys.test.ts @@ -0,0 +1,53 @@ +/** + * Query-key factory: account isolation and one-call purge. If these break, + * switching accounts could leak one account's data into another's cache. + */ + +import { QueryClient } from '@tanstack/react-query'; + +import { purgeAccountCache, queryKeys } from './query-keys'; + +describe('queryKeys', () => { + it('scopes every key under its account', () => { + const key = queryKeys.repoDetail('acct-a', 'owner', 'repo'); + expect(key[0]).toBe('account'); + expect(key[1]).toBe('acct-a'); + expect(key).toEqual(['account', 'acct-a', 'repo', 'owner', 'repo', 'detail']); + }); + + it('produces different keys for different accounts', () => { + expect(queryKeys.me('acct-a')).not.toEqual(queryKeys.me('acct-b')); + }); + + it('keeps notifications under a shared root for prefix invalidation', () => { + const root = queryKeys.notificationsRoot('acct-a'); + const list = queryKeys.notifications('acct-a', { all: false }); + expect(list.slice(0, root.length)).toEqual(root); + }); +}); + +describe('purgeAccountCache', () => { + it('removes only the targeted account’s queries', () => { + const client = new QueryClient(); + const keyA = queryKeys.repoDetail('acct-a', 'o', 'n'); + const keyB = queryKeys.repoDetail('acct-b', 'o', 'n'); + client.setQueryData(keyA, { data: 'a' }); + client.setQueryData(keyB, { data: 'b' }); + + purgeAccountCache(client, 'acct-a'); + + expect(client.getQueryData(keyA)).toBeUndefined(); + expect(client.getQueryData(keyB)).toEqual({ data: 'b' }); + }); + + it('clears the unread-count and notifications caches for the account', () => { + const client = new QueryClient(); + client.setQueryData(queryKeys.unreadCount('acct-a'), { count: 3 }); + client.setQueryData(queryKeys.notifications('acct-a', { all: false }), { data: [] }); + + purgeAccountCache(client, 'acct-a'); + + expect(client.getQueryData(queryKeys.unreadCount('acct-a'))).toBeUndefined(); + expect(client.getQueryData(queryKeys.notifications('acct-a', { all: false }))).toBeUndefined(); + }); +}); diff --git a/src/core/api/query-keys.ts b/src/core/api/query-keys.ts new file mode 100644 index 0000000..eee1b4b --- /dev/null +++ b/src/core/api/query-keys.ts @@ -0,0 +1,108 @@ +/** + * Account-scoped query key factory. + * + * Every server-state key starts with `['account', accountId, ...]`, which gives us: + * - Automatic isolation between accounts (no shared cache entries). + * - One-call cache purge on account removal: + * `queryClient.removeQueries({ queryKey: queryKeys.account(id) })`. + * + * Never construct raw arrays in feature code — always go through this factory. + */ + +import type { QueryClient } from '@tanstack/react-query'; + +export const queryKeys = { + /** Root of everything this app writes into the query cache. */ + root: ['gitea-native'] as const, + + /** Top-level scope for one account. */ + account: (accountId: string) => ['account', accountId] as const, + + // --- instance/account level ----------------------------------------------- + version: (accountId: string) => [...queryKeys.account(accountId), 'version'] as const, + me: (accountId: string) => [...queryKeys.account(accountId), 'me'] as const, + unreadCount: (accountId: string) => [...queryKeys.account(accountId), 'unread-count'] as const, + activity: (accountId: string, username: string) => + [...queryKeys.account(accountId), 'activity', username] as const, + + // --- repositories ---------------------------------------------------------- + repos: { + mine: (accountId: string, params: Record) => + [...queryKeys.account(accountId), 'repos', 'mine', params] as const, + starred: (accountId: string, params: Record) => + [...queryKeys.account(accountId), 'repos', 'starred', params] as const, + search: (accountId: string, params: Record) => + [...queryKeys.account(accountId), 'repos', 'search', params] as const, + }, + + repo: (accountId: string, owner: string, name: string) => + [...queryKeys.account(accountId), 'repo', owner, name] as const, + + repoDetail: (accountId: string, owner: string, name: string) => + [...queryKeys.repo(accountId, owner, name), 'detail'] as const, + + repoLanguages: (accountId: string, owner: string, name: string) => + [...queryKeys.repo(accountId, owner, name), 'languages'] as const, + + contents: (accountId: string, owner: string, name: string, path: string, ref?: string) => + [...queryKeys.repo(accountId, owner, name), 'contents', { path, ref }] as const, + + file: (accountId: string, owner: string, name: string, path: string, ref?: string) => + [...queryKeys.repo(accountId, owner, name), 'file', { path, ref }] as const, + + readme: (accountId: string, owner: string, name: string, ref?: string) => + [...queryKeys.repo(accountId, owner, name), 'readme', { ref }] as const, + + branches: (accountId: string, owner: string, name: string, params: Record) => + [...queryKeys.repo(accountId, owner, name), 'branches', params] as const, + + branch: (accountId: string, owner: string, name: string, branch: string) => + [...queryKeys.repo(accountId, owner, name), 'branch', branch] as const, + + tags: (accountId: string, owner: string, name: string, params: Record) => + [...queryKeys.repo(accountId, owner, name), 'tags', params] as const, + + commits: (accountId: string, owner: string, name: string, params: Record) => + [...queryKeys.repo(accountId, owner, name), 'commits', params] as const, + + commit: (accountId: string, owner: string, name: string, sha: string) => + [...queryKeys.repo(accountId, owner, name), 'commit', sha] as const, + + // --- issues & pull requests ------------------------------------------------ + issueSearch: (accountId: string, params: Record) => + [...queryKeys.account(accountId), 'issues', 'search', params] as const, + + repoIssues: ( + accountId: string, + owner: string, + name: string, + params: Record, + ) => [...queryKeys.repo(accountId, owner, name), 'issues', params] as const, + + issue: (accountId: string, owner: string, name: string, index: number) => + [...queryKeys.repo(accountId, owner, name), 'issue', index] as const, + + repoLabels: (accountId: string, owner: string, name: string) => + [...queryKeys.repo(accountId, owner, name), 'labels'] as const, + + pulls: (accountId: string, owner: string, name: string, params: Record) => + [...queryKeys.repo(accountId, owner, name), 'pulls', params] as const, + + pull: (accountId: string, owner: string, name: string, index: number) => + [...queryKeys.repo(accountId, owner, name), 'pull', index] as const, + + // --- notifications --------------------------------------------------------- + notificationsRoot: (accountId: string) => + [...queryKeys.account(accountId), 'notifications'] as const, + + notifications: (accountId: string, params: Record) => + [...queryKeys.notificationsRoot(accountId), params] as const, +} as const; + +/** + * Removes every cached query belonging to an account. + * Called on account removal and when a token turns out to be invalid. + */ +export function purgeAccountCache(queryClient: QueryClient, accountId: string): void { + queryClient.removeQueries({ queryKey: queryKeys.account(accountId) }); +} diff --git a/src/core/api/types.ts b/src/core/api/types.ts new file mode 100644 index 0000000..bfba6d1 --- /dev/null +++ b/src/core/api/types.ts @@ -0,0 +1,389 @@ +/** + * Gitea REST API v1 model types. + * + * Curated from the official OpenAPI specification + * (https://dl.gitea.com/openapi/v1.json, served by Gitea instances at /swagger.v1.json). + * Only the fields the app actually consumes are declared; server responses may include + * additional fields, which is safe because the types describe a subset. + * + * All fields are optional unless Gitea guarantees them, because API surface varies + * across Gitea versions and instance configurations (see core/capabilities). + */ + +export type UserType = 'User' | 'Organization' | 'Bot'; +export type State = 'open' | 'closed'; +export type StateAll = 'open' | 'closed' | 'all'; +export type PullState = 'open' | 'closed'; +export type IssueOrPullState = 'open' | 'closed' | 'merged'; + +export interface User { + id?: number; + login: string; + login_name?: string; + full_name?: string; + email?: string; + avatar_url?: string; + html_url?: string; + description?: string; + is_admin?: boolean; + last_login?: string; + created?: string; + active?: boolean; + prohibit_login?: boolean; + language?: string; + restricted?: boolean; + visibility?: 'public' | 'limited' | 'private'; + followers_count?: number; + following_count?: number; + starred_repos_count?: number; + type?: UserType; +} + +export interface Permission { + admin?: boolean; + push?: boolean; + pull?: boolean; +} + +export interface Repository { + id: number; + name: string; + full_name: string; + owner?: User; + private?: boolean; + fork?: boolean; + template?: boolean; + html_url?: string; + description?: string; + empty?: boolean; + archived?: boolean; + mirror?: boolean; + default_branch?: string; + created_at?: string; + updated_at?: string; + pushed_at?: string; + clone_url?: string; + ssh_url?: string; + website?: string; + stars_count?: number; + forks_count?: number; + watchers_count?: number; + open_issues_count?: number; + open_pr_counter?: number; + release_counter?: number; + branch_count?: number; + size?: number; + language?: string; + languages_url?: string; + topics?: string[]; + has_issues?: boolean; + has_wiki?: boolean; + has_pull_requests?: boolean; + has_projects?: boolean; + has_releases?: boolean; + has_actions?: boolean; + has_packages?: boolean; + permissions?: Permission; + parent?: Repository; + avatar_url?: string; +} + +/** Repository metadata embedded in issue/PR responses. */ +export interface RepositoryMeta { + id?: number; + name?: string; + owner?: string; + full_name?: string; +} + +export interface Label { + id?: number; + name: string; + color?: string; + description?: string; + exclusive?: boolean; +} + +export interface Milestone { + id?: number; + title: string; + description?: string; + state?: State; + open_issues?: number; + closed_issues?: number; + due_on?: string; + created_at?: string; + closed_at?: string; +} + +export interface Attachment { + id?: number; + name: string; + size?: number; + uuid?: string; + download_count?: number; + created_at?: string; + browser_download_url?: string; +} + +export interface FileLinksResponse { + self?: string; + git?: string; + html?: string; +} + +export type ContentsType = 'file' | 'dir' | 'symlink' | 'submodule'; + +/** Response of GET /repos/{owner}/{repo}/contents/{filepath} — array for dirs, object for files. */ +export interface ContentsEntry { + name: string; + path: string; + sha: string; + type: ContentsType; + size: number; + encoding?: string; + /** Base64 content, present for files when the response is a single entry. */ + content?: string; + download_url?: string; + html_url?: string; + git_url?: string; + url?: string; + target?: string; + submodule_git_url?: string; + mode?: string; + last_commit_sha?: string; + last_commit_message?: string; + last_author_date?: string; +} + +export interface CommitUser { + name?: string; + email?: string; + date?: string; +} + +export interface CommitMeta { + sha: string; + url?: string; + created?: string; +} + +export interface CommitStats { + additions?: number; + deletions?: number; + total?: number; +} + +export interface CommitAffectedFile { + filename?: string; + status?: string; + additions?: number; + deletions?: number; + changes?: number; + patch?: string; +} + +export interface CommitVerification { + verified?: boolean; + reason?: string; + signature?: string; + payload?: string; +} + +export interface RepoCommit { + url?: string; + author?: CommitUser; + committer?: CommitUser; + message?: string; + tree?: CommitMeta; + verification?: CommitVerification; +} + +export interface PayloadCommitUser { + name?: string; + email?: string; + username?: string; +} + +export interface PayloadCommit { + id?: string; + message?: string; + url?: string; + author?: PayloadCommitUser; + committer?: PayloadCommitUser; + timestamp?: string; + added?: string[]; + removed?: string[]; + modified?: string[]; +} + +/** A single commit (list + detail share this shape in the Gitea API). */ +export interface Commit { + sha: string; + url?: string; + html_url?: string; + commit: RepoCommit; + author?: User; + committer?: User; + parents?: CommitMeta[]; + stats?: CommitStats; + files?: CommitAffectedFile[]; + created?: string; +} + +export interface Branch { + name: string; + commit?: PayloadCommit; + protected?: boolean; + effective_branch_protection_name?: string; + required_approvals?: number; + enable_status_check?: boolean; + status_check_contexts?: string[]; + user_can_push?: boolean; + user_can_merge?: boolean; +} + +export interface Tag { + name: string; + message?: string; + id?: string; + commit?: CommitMeta; + tarball_url?: string; + zipball_url?: string; +} + +export interface PullRequestMeta { + html_url?: string; + merged?: boolean; + merged_at?: string; + draft?: boolean; +} + +export interface Issue { + id: number; + number: number; + title: string; + body?: string; + user?: User; + labels?: Label[]; + milestone?: Milestone; + assignee?: User; + assignees?: User[]; + state?: State; + is_locked?: boolean; + created_at?: string; + updated_at?: string; + closed_at?: string; + comments?: number; + html_url?: string; + pull_request?: PullRequestMeta; + repository?: RepositoryMeta; +} + +export interface PRBranchInfo { + label?: string; + ref?: string; + sha?: string; + repo?: Repository; + repo_id?: number; +} + +export interface PullRequest { + id: number; + number: number; + title: string; + body?: string; + user?: User; + state?: State; + draft?: boolean; + labels?: Label[]; + milestone?: Milestone; + assignee?: User; + assignees?: User[]; + requested_reviewers?: User[]; + head?: PRBranchInfo; + base?: PRBranchInfo; + mergeable?: boolean; + merged?: boolean; + merged_at?: string; + merged_by?: User; + merge_commit_sha?: string; + merge_base?: string; + additions?: number; + deletions?: number; + changed_files?: number; + created_at?: string; + updated_at?: string; + closed_at?: string; + comments?: number; + review_comments?: number; + html_url?: string; +} + +export type NotificationSubjectType = 'Issue' | 'Pull' | 'Commit' | 'Repository'; + +export interface NotificationSubject { + title?: string; + type?: NotificationSubjectType; + url?: string; + html_url?: string; + latest_comment_html_url?: string; + state?: string; +} + +export interface NotificationThread { + id: number; + repository?: Repository; + subject?: NotificationSubject; + unread?: boolean; + pinned?: boolean; + updated_at?: string; + url?: string; +} + +export interface NotificationCount { + count: number; +} + +export interface ServerVersion { + version: string; +} + +export interface Activity { + id?: number; + user_id?: number; + act_user_id?: number; + act_user?: User; + repo_id?: number; + repo?: Repository; + ref_name?: string; + op_type?: string; + content?: string; + created?: string; + is_private?: boolean; +} + +export interface Comment { + id?: number; + html_url?: string; + pr_url?: string; + issue_url?: string; + user?: User; + original_author?: string; + body?: string; + created_at?: string; + updated_at?: string; +} + +/** Generic pagination metadata parsed from response headers. */ +export interface PageMeta { + page: number; + limit: number; + total: number | null; + hasNext: boolean; +} + +export interface Paged { + items: T[]; + page: PageMeta; +} diff --git a/src/core/capabilities/capabilities.ts b/src/core/capabilities/capabilities.ts new file mode 100644 index 0000000..fa2b58d --- /dev/null +++ b/src/core/capabilities/capabilities.ts @@ -0,0 +1,129 @@ +/** + * Instance capability detection. + * + * Rules (see docs/ARCHITECTURE.md): + * - Do not infer capabilities from version numbers alone. Version is a hint for + * display and for documented minimum-version checks only. + * - Endpoint availability is determined by probing real endpoints with the + * caller's credentials and reading the status code. + * - Repository-level features come from server-provided booleans on the + * Repository object (`has_issues`, `has_wiki`, …), not from guesses. + * + * Status vocabulary distinguishes: supported / unsupported / disabled / + * unauthorized / unknown. + */ + +import type { GiteaClient } from '@/core/api/client'; +import type { Repository } from '@/core/api/types'; + +export type CapabilityStatus = 'supported' | 'unsupported' | 'disabled' | 'unauthorized' | 'unknown'; + +export interface InstanceCapabilities { + baseUrl: string; + /** Server version from GET /version, or null when the endpoint failed. */ + version: string | null; + /** Notifications API (GET /notifications). */ + notifications: CapabilityStatus; + /** Cross-repo issue search (GET /repos/issues/search) — powers the Issues tab. */ + issueSearch: CapabilityStatus; + checkedAt: number; +} + +export interface RepoCapabilities { + issues: CapabilityStatus; + pullRequests: CapabilityStatus; + wiki: CapabilityStatus; + projects: CapabilityStatus; + actions: CapabilityStatus; + packages: CapabilityStatus; + releases: CapabilityStatus; +} + +const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour +const cache = new Map(); + +/** + * Probes optional endpoints once per hour per instance. + * A probe failure degrades to 'unknown' — never to a false 'supported'. + */ +export async function detectInstanceCapabilities( + client: GiteaClient, + options: { force?: boolean } = {}, +): Promise { + const cached = cache.get(client.baseUrl); + if (!options.force && cached && Date.now() - cached.checkedAt < CACHE_TTL_MS) { + return cached; + } + + let version: string | null = null; + try { + const response = await client.get<{ version: string }>('/version'); + version = response.version ?? null; + } catch { + version = cached?.version ?? null; + } + + const [notifications, issueSearch] = await Promise.all([ + probe(client, '/notifications?limit=1'), + probe(client, '/repos/issues/search?state=all&limit=1'), + ]); + + const result: InstanceCapabilities = { + baseUrl: client.baseUrl, + version, + notifications, + issueSearch, + checkedAt: Date.now(), + }; + cache.set(client.baseUrl, result); + return result; +} + +async function probe(client: GiteaClient, path: string): Promise { + try { + await client.get(path, { timeoutMs: 8_000 }); + return 'supported'; + } catch (error) { + if (error instanceof Error && 'kind' in error) { + const kind = (error as { kind: string }).kind; + if (kind === 'aborted' || kind === 'timeout' || kind === 'network') return 'unknown'; + if (kind === 'unauthorized' || kind === 'forbidden') return 'unauthorized'; + if (kind === 'not-found') return 'unsupported'; + if (kind === 'server') return 'unknown'; + return 'unknown'; + } + return 'unknown'; + } +} + +/** Clears the in-memory capability cache (used in tests). */ +export function clearCapabilityCache(): void { + cache.clear(); +} + +/** + * Repository feature flags as reported by the server itself. + * `false` means the feature is turned off for this repository ('disabled'), + * a missing flag on older servers means 'unknown'. + */ +export function deriveRepoCapabilities(repo: Repository): RepoCapabilities { + return { + issues: flag(repo.has_issues), + pullRequests: flag(repo.has_pull_requests), + wiki: flag(repo.has_wiki), + projects: flag(repo.has_projects), + actions: flag(repo.has_actions), + packages: flag(repo.has_packages), + releases: flag(repo.has_releases), + }; +} + +function flag(value: boolean | undefined): CapabilityStatus { + if (value === undefined) return 'unknown'; + return value ? 'supported' : 'disabled'; +} + +/** True when a feature should be surfaced in the UI. */ +export function isUsable(status: CapabilityStatus): boolean { + return status === 'supported' || status === 'unknown'; +} diff --git a/src/core/security/biometrics.ts b/src/core/security/biometrics.ts new file mode 100644 index 0000000..f35c859 --- /dev/null +++ b/src/core/security/biometrics.ts @@ -0,0 +1,67 @@ +/** + * Biometric authentication helpers (Face ID / Touch ID / Android biometrics). + * + * The app lock is strictly client-side: it gates UI access on this device and + * works independently of any server-side WebAuthn/passkey support. + */ + +import * as LocalAuthentication from 'expo-local-authentication'; + +export interface BiometricSupport { + /** Device has fingerprint/face/iris hardware. */ + hasHardware: boolean; + /** User has enrolled credentials. */ + isEnrolled: boolean; + /** Human-readable label of the preferred method, e.g. "Face ID". */ + label: string; + /** The lock can actually be used right now. */ + usable: boolean; +} + +const TYPE_LABELS: Record = { + [LocalAuthentication.AuthenticationType.FINGERPRINT]: 'fingerprint', + [LocalAuthentication.AuthenticationType.FACIAL_RECOGNITION]: 'face', + [LocalAuthentication.AuthenticationType.IRIS]: 'iris', +}; + +/** i18n-independent technical labels; screens map them to translated strings. */ +export async function getBiometricSupport(): Promise { + try { + const [hasHardware, isEnrolled, types] = await Promise.all([ + LocalAuthentication.hasHardwareAsync(), + LocalAuthentication.isEnrolledAsync(), + LocalAuthentication.supportedAuthenticationTypesAsync(), + ]); + const preferred = types[types.length - 1]; + return { + hasHardware, + isEnrolled, + label: preferred !== undefined ? (TYPE_LABELS[preferred] ?? 'biometrics') : 'biometrics', + usable: hasHardware && isEnrolled, + }; + } catch { + return { hasHardware: false, isEnrolled: false, label: 'biometrics', usable: false }; + } +} + +export type PromptOutcome = 'success' | 'failed' | 'cancelled' | 'unavailable'; + +/** + * Shows the system biometric prompt. + * Never throws — callers branch on the outcome. + */ +export async function promptBiometric(message: string): Promise { + try { + const result = await LocalAuthentication.authenticateAsync({ + promptMessage: message, + cancelLabel: 'Cancel', + disableDeviceFallback: false, + }); + if (result.success) return 'success'; + if (result.error === 'user_cancel' || result.error === 'system_cancel') return 'cancelled'; + if (result.error === 'not_enrolled' || result.error === 'not_available') return 'unavailable'; + return 'failed'; + } catch { + return 'failed'; + } +} diff --git a/src/core/utils/format.ts b/src/core/utils/format.ts new file mode 100644 index 0000000..b5e7f52 --- /dev/null +++ b/src/core/utils/format.ts @@ -0,0 +1,80 @@ +/** Formatting helpers shared across screens (i18n-aware where it matters). */ + +import type { TFunction } from 'i18next'; + +/** + * Relative timestamp: "just now" / "5m ago" / "3d ago" / absolute date past a week. + * Avoids Intl.DateTimeFormat (not guaranteed on Hermes) for the common cases. + */ +export function formatRelativeTime(iso: string | null | undefined, t: TFunction): string { + if (!iso) return t('common.never'); + const then = new Date(iso).getTime(); + if (Number.isNaN(then)) return t('common.unknown'); + + const diffMs = Date.now() - then; + if (diffMs < 60_000) return t('time.justNow'); + + const minutes = Math.floor(diffMs / 60_000); + if (minutes < 60) return t('time.minutesAgo', { count: minutes }); + + const hours = Math.floor(minutes / 60); + if (hours < 24) return t('time.hoursAgo', { count: hours }); + + const days = Math.floor(hours / 24); + if (days < 7) return t('time.daysAgo', { count: days }); + + const weeks = Math.floor(days / 7); + if (days < 30) return t('time.weeksAgo', { count: weeks }); + + return iso.slice(0, 10); +} + +/** Absolute date + time, ISO-based so it works without Intl. */ +export function formatDateTime(iso: string | null | undefined): string { + if (!iso) return '—'; + const date = new Date(iso); + if (Number.isNaN(date.getTime())) return '—'; + const pad = (n: number) => String(n).padStart(2, '0'); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad( + date.getHours(), + )}:${pad(date.getMinutes())}`; +} + +/** Human file size: 512 B, 4.2 KB, 13.1 MB … */ +export function formatBytes(bytes: number | null | undefined): string { + if (bytes === null || bytes === undefined || Number.isNaN(bytes)) return '—'; + if (bytes < 1024) return `${bytes} B`; + const units = ['KB', 'MB', 'GB', 'TB']; + let value = bytes; + let unitIndex = -1; + do { + value /= 1024; + unitIndex += 1; + } while (value >= 1024 && unitIndex < units.length - 1); + return `${value.toFixed(value >= 100 ? 0 : 1)} ${units[unitIndex]}`; +} + +/** Compact count for badges/meta: 999, 1.2k, 34k, 1.1m */ +export function formatCount(value: number | null | undefined): string { + if (value === null || value === undefined || Number.isNaN(value)) return '0'; + if (value < 1000) return String(value); + if (value < 1_000_000) { + const k = value / 1000; + return `${k >= 100 ? Math.round(k) : k.toFixed(1)}k`; + } + const m = value / 1_000_000; + return `${m >= 100 ? Math.round(m) : m.toFixed(1)}m`; +} + +/** Short commit SHA (7 chars when long enough). */ +export function shortSha(sha: string | undefined): string { + if (!sha) return ''; + return sha.length > 8 ? sha.slice(0, 7) : sha; +} + +/** First line of a commit message. */ +export function firstLine(message: string | undefined): string { + if (!message) return ''; + const line = message.split('\n', 1)[0]; + return line.trim(); +} diff --git a/src/core/utils/infinite.ts b/src/core/utils/infinite.ts new file mode 100644 index 0000000..a666243 --- /dev/null +++ b/src/core/utils/infinite.ts @@ -0,0 +1,25 @@ +/** Helpers for turning infinite query data into plain arrays. */ + +import type { InfiniteData } from '@tanstack/react-query'; + +import type { RawResponse } from '@/core/api/client'; + +export function flattenPages( + data: InfiniteData> | undefined, +): T[] { + if (!data) return []; + const items: T[] = []; + for (const page of data.pages) { + if (Array.isArray(page.data)) items.push(...page.data); + } + return items; +} + +/** True while any page is still loading (first load only). */ +export function isInitialLoading(query: { + isPending: boolean; + isFetching: boolean; + data?: unknown; +}): boolean { + return query.isPending && query.isFetching; +}