feat(core): API client, account registry, secure token store, security

- typed transport-only Gitea client (auth header, timeouts, pagination, ApiError)
- instance URL normalization/validation: HTTPS enforced, creds rejected
- pure account registry with deterministic active-account reassignment
- SecureStore token store (token.<id> under gitea-native.credentials)
- account-scoped TanStack query keys + purgeAccountCache
- Zustand accounts store, biometric helper, error/format utils
This commit is contained in:
JustZoe101 committed 2026-10-09 16:41:10 +02:00
1 parent 7b89c594ea
commit e0ca502cc9
21 files changed
+2874

No files matched your search

+253
View File
@@ -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 <PAT>` 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<string, QueryValue>;
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<T> {
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<Response>;
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<T>(path: string, options: Omit<RequestOptions, 'method' | 'body'> = {}): Promise<T> {
const raw = await this.raw<T>(path, { ...options, method: 'GET' });
return raw.data;
}
async post<T>(path: string, body?: unknown, options: RequestOptions = {}): Promise<T> {
const raw = await this.raw<T>(path, { ...options, method: 'POST', body });
return raw.data;
}
async put<T>(path: string, body?: unknown, options: RequestOptions = {}): Promise<T> {
const raw = await this.raw<T>(path, { ...options, method: 'PUT', body });
return raw.data;
}
async patch<T>(path: string, body?: unknown, options: RequestOptions = {}): Promise<T> {
const raw = await this.raw<T>(path, { ...options, method: 'PATCH', body });
return raw.data;
}
async delete<T>(path: string, options: RequestOptions = {}): Promise<T> {
const raw = await this.raw<T>(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<T>(path: string, options: RequestOptions = {}): Promise<RawResponse<T>> {
const method = options.method ?? 'GET';
const url = `${this.apiRoot}${path}${buildQuery(options.query ?? {})}`;
const headers: Record<string, string> = { 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}).`;
}
}