import { createHash } from 'node:crypto'; import { createReadStream, openAsBlob } from 'node:fs'; import { stat } from 'node:fs/promises'; import { basename } from 'node:path'; interface Attachment { readonly name: string; readonly size: number; readonly uuid: string; readonly digest?: string; } export interface GiteaRelease { readonly id: number; readonly tag_name: string; readonly draft: boolean; readonly prerelease: boolean; readonly assets: readonly Attachment[] | null; } interface DraftRelease { readonly tag_name: string; readonly target_commitish: string; readonly name: string; readonly body: string; readonly prerelease: boolean; } interface GitRef { readonly ref: string; readonly object: { readonly sha: string }; } const REQUEST_TIMEOUT_MS = 30_000; const TRANSFER_TIMEOUT_MS = 15 * 60_000; export class GiteaReleaseClient { readonly #base: URL; readonly #api: URL; readonly #token: string; constructor(base: string, repository: string, token: string) { const url = new URL(base); const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname); if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || url.username || url.password || url.search || url.hash) { throw new Error('GITEA_URL must be a clean HTTPS or loopback HTTP URL.'); } if (!/^[\w-][\w.-]*\/[\w-][\w.-]*$/.test(repository)) { throw new Error('GITEA_REPOSITORY must be in owner/repository form.'); } url.pathname = `${url.pathname.replace(/\/+$/, '')}/`; this.#base = url; this.#api = new URL(`api/v1/repos/${repository}/`, url); this.#token = token; } async verifyTag(tag: string, objectId: string): Promise { const url = new URL(`git/refs/tags/${encodeURIComponent(tag)}`, this.#api); const response = await this.#request(url); const result = await response.json() as GitRef | GitRef[]; const refs = Array.isArray(result) ? result : [result]; if (!refs.some(({ ref, object }) => ref === `refs/tags/${tag}` && object.sha === objectId)) { throw new Error(`The local tag ${tag} differs from the tag on Gitea.`); } } async findRelease(tag: string): Promise { // The list includes drafts when the token has repository write access. for (let page = 1; ; page += 1) { const url = new URL(`releases?limit=50&page=${page}`, this.#api); const response = await this.#request(url); const releases = await response.json() as GiteaRelease[]; const release = releases.find((entry) => entry.tag_name === tag); if (release || !/;\s*rel="next"/i.test(response.headers.get('link') ?? '')) { return release; } } } async createDraft(draft: DraftRelease): Promise { return this.#writeRelease('POST', 'releases', { ...draft, draft: true }); } async publish(id: number): Promise { const release = await this.#writeRelease('PATCH', `releases/${id}`, { draft: false }); if (release.draft) throw new Error('Gitea kept the release as a draft.'); } async syncAttachments(release: GiteaRelease, paths: readonly string[]): Promise { const missing: string[] = []; for (const path of paths) { const name = basename(path); const matches = (release.assets ?? []).filter((attachment) => attachment.name === name); if (matches.length > 1) throw new Error(`Gitea has duplicate attachments named ${name}.`); const existing = matches[0]; if (existing) await this.#verifyAttachment(existing, path); else missing.push(path); } if (missing.length && !release.draft) { throw new Error(`Published Gitea release ${release.tag_name} is missing expected attachments.`); } for (const path of missing) { const name = basename(path); const file = await openAsBlob(path, { type: 'application/octet-stream' }); const form = new FormData(); form.set('attachment', file, name); const url = new URL(`releases/${release.id}/assets`, this.#api); console.info(`Uploading ${name} to Gitea...`); const response = await this.#request(url, { method: 'POST', body: form }, TRANSFER_TIMEOUT_MS); const uploaded = await response.json() as Attachment; if (uploaded.name !== name || uploaded.size !== file.size) { throw new Error(`Gitea returned unexpected attachment metadata for ${name}.`); } } } async #verifyAttachment(attachment: Attachment, path: string): Promise { if ((await stat(path)).size !== attachment.size) { throw new Error(`Gitea already has different bytes for ${attachment.name}.`); } const localDigest = await digest(createReadStream(path)); let remoteDigest = attachment.digest; if (!remoteDigest) { // Older Gitea versions omit the digest. Read back through this same server. const url = new URL(`attachments/${encodeURIComponent(attachment.uuid)}`, this.#base); const response = await this.#request(url, {}, TRANSFER_TIMEOUT_MS); if (!response.body) throw new Error(`Gitea returned no bytes for ${attachment.name}.`); remoteDigest = await digest(response.body); } if (localDigest !== remoteDigest) throw new Error(`Gitea already has different bytes for ${attachment.name}.`); console.info(`Verified existing Gitea attachment ${attachment.name}.`); } async #writeRelease(method: 'POST' | 'PATCH', path: string, payload: object): Promise { const response = await this.#request(new URL(path, this.#api), { method, body: JSON.stringify(payload), headers: { 'content-type': 'application/json' }, }); return await response.json() as GiteaRelease; } async #request(url: URL, init: RequestInit = {}, timeout = REQUEST_TIMEOUT_MS): Promise { const headers = new Headers(init.headers); headers.set('authorization', `Bearer ${this.#token}`); const response = await fetch(url, { ...init, headers, redirect: 'error', signal: AbortSignal.timeout(timeout) }); if (!response.ok) { const error = await response.json().catch(() => null) as { message?: string } | null; const detail = error?.message ? `: ${error.message}` : ''; throw new Error(`Gitea ${init.method ?? 'GET'} ${url.pathname} failed with HTTP ${response.status}${detail}`); } return response; } } async function digest(chunks: AsyncIterable): Promise { const hash = createHash('sha256'); for await (const chunk of chunks) hash.update(chunk); return `sha256:${hash.digest('hex')}`; }