- web: Gitea OAuth2 login, signed session cookie, everything behind login; inbox with answers, project board (goals → tasks), task page with OpenSpec artifacts, questions and session controls; new project form; auto-refresh, light/dark, mobile - users + projects.owner_id; tokens AES-256-GCM encrypted; owner-only access - provisionProject (runner): new or existing Gitea repo, peppa-bot collaborator, template + openspec init, push, rollback; used by web and peppa project create (replaces scripts/bootstrap-project.sh) - peppa web login-link, peppa project owner; Gitea OAuth app script - bins/template resolved via PEPPA_ROOT (works inside the Next build) - testkit: mock-gitea + 10 tests (42 e2e total, all green) - OpenSpec: pep-1-web-platform archived into specs web-auth, project-provisioning, web-workspace Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
131 lines
4.8 KiB
TypeScript
131 lines
4.8 KiB
TypeScript
// Gitea API client: as a user (OAuth token) or as peppa-bot (GITEA_TOKEN).
|
|
import { PeppaError } from "./errors.ts";
|
|
|
|
export interface GiteaUser {
|
|
id: number;
|
|
login: string;
|
|
full_name?: string;
|
|
email?: string;
|
|
avatar_url?: string;
|
|
}
|
|
export interface GiteaOrg {
|
|
id: number;
|
|
username: string;
|
|
full_name?: string;
|
|
}
|
|
export interface GiteaRepo {
|
|
id: number;
|
|
name: string;
|
|
full_name: string;
|
|
owner: { login: string };
|
|
empty: boolean;
|
|
private: boolean;
|
|
default_branch: string;
|
|
clone_url: string;
|
|
html_url: string;
|
|
permissions?: { admin: boolean; push: boolean; pull: boolean };
|
|
}
|
|
export interface OAuthTokens {
|
|
access_token: string;
|
|
refresh_token?: string;
|
|
expires_in?: number;
|
|
}
|
|
|
|
export class GiteaError extends PeppaError {
|
|
constructor(
|
|
readonly status: number,
|
|
message: string,
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
export class GiteaClient {
|
|
constructor(
|
|
readonly baseUrl: string,
|
|
private readonly token: string,
|
|
) {}
|
|
|
|
async request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
|
const res = await fetch(`${this.baseUrl}/api/v1${path}`, {
|
|
method,
|
|
headers: { Authorization: `token ${this.token}`, "Content-Type": "application/json", Accept: "application/json" },
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
signal: AbortSignal.timeout(15_000),
|
|
});
|
|
if (res.status === 204) return undefined as T;
|
|
const text = await res.text();
|
|
if (!res.ok) {
|
|
let msg = text;
|
|
try {
|
|
msg = (JSON.parse(text) as { message?: string }).message ?? text;
|
|
} catch {}
|
|
throw new GiteaError(res.status, `Gitea ${method} ${path}: ${res.status} ${msg}`.slice(0, 400));
|
|
}
|
|
return (text ? JSON.parse(text) : undefined) as T;
|
|
}
|
|
|
|
me() {
|
|
return this.request<GiteaUser>("GET", "/user");
|
|
}
|
|
|
|
/** Orgs where the user may create repositories. */
|
|
async orgsWithRepoCreate(login: string): Promise<GiteaOrg[]> {
|
|
const orgs = await this.request<GiteaOrg[]>("GET", "/user/orgs?limit=50");
|
|
const out: GiteaOrg[] = [];
|
|
for (const o of orgs) {
|
|
const p = await this.request<{ can_create_repository: boolean }>("GET", `/users/${encodeURIComponent(login)}/orgs/${encodeURIComponent(o.username)}/permissions`).catch(() => null);
|
|
if (p?.can_create_repository) out.push(o);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
async getRepo(owner: string, name: string): Promise<GiteaRepo | null> {
|
|
try {
|
|
return await this.request<GiteaRepo>("GET", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`);
|
|
} catch (e) {
|
|
if (e instanceof GiteaError && e.status === 404) return null;
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
/** Creates a private repo; `asUser` = in the token owner's own namespace. */
|
|
createRepo(owner: string, asUser: boolean, name: string, description: string) {
|
|
const body = { name, description, private: true, default_branch: "main", auto_init: false };
|
|
return this.request<GiteaRepo>("POST", asUser ? "/user/repos" : `/orgs/${encodeURIComponent(owner)}/repos`, body);
|
|
}
|
|
|
|
addCollaborator(owner: string, repo: string, login: string, permission: "read" | "write" | "admin") {
|
|
return this.request<void>("PUT", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators/${encodeURIComponent(login)}`, { permission });
|
|
}
|
|
|
|
deleteRepo(owner: string, repo: string) {
|
|
return this.request<void>("DELETE", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`);
|
|
}
|
|
}
|
|
|
|
async function oauthToken(baseUrl: string, body: Record<string, string>): Promise<OAuthTokens> {
|
|
const res = await fetch(`${baseUrl}/login/oauth/access_token`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
body: JSON.stringify(body),
|
|
signal: AbortSignal.timeout(15_000),
|
|
});
|
|
const data = (await res.json().catch(() => ({}))) as OAuthTokens & { error?: string; error_description?: string };
|
|
if (!res.ok || !data.access_token) throw new GiteaError(res.status, `OAuth: ${data.error_description ?? data.error ?? res.status}`);
|
|
return data;
|
|
}
|
|
|
|
export function oauthAuthorizeUrl(baseUrl: string, clientId: string, redirectUri: string, state: string): string {
|
|
const q = new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri, response_type: "code", state });
|
|
return `${baseUrl}/login/oauth/authorize?${q}`;
|
|
}
|
|
|
|
export function exchangeOAuthCode(baseUrl: string, clientId: string, clientSecret: string, code: string, redirectUri: string) {
|
|
return oauthToken(baseUrl, { client_id: clientId, client_secret: clientSecret, code, grant_type: "authorization_code", redirect_uri: redirectUri });
|
|
}
|
|
|
|
export function refreshOAuthToken(baseUrl: string, clientId: string, clientSecret: string, refreshToken: string) {
|
|
return oauthToken(baseUrl, { client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken, grant_type: "refresh_token" });
|
|
}
|