railyard/apps/ritgram/web/services/githubImportService.ts
caelum0x 6d221169e8 feat(ritgram): Move from GitHub — no-OAuth repo import via Gitea migrate API
GitHub OAuth app approval is blocked, so this ships the next-best onboarding
path: paste a GitHub username (public repos, no token) or an optional
fine-grained read token (private repos), tick repos, and Rithub mirrors each
one with Gitea's built-in /repos/migrate, streamed as live per-repo progress
over SSE, landing on the new Ritgram profile when done.

- GiteaForgeAdapter.migrateRepo(): calls the real Gitea migrate API, treats
  409 as "already there", and self-heals a false failure (proxy timeout or
  a post-clone step erroring after the repo already landed — both observed
  live against git.ereboslab.com) by re-checking existence with backoff
  before reporting a real failure.
- New public POST /api/v1/github-import/preview and auth'd
  POST /api/v1/github-import/start (requires an existing Rithub/Gitea
  connection); the GitHub token, when provided, is used once in-memory for
  that request and is never stored or logged. Both routes are rate limited.
- New /import-from-github page (public route) with username/token form,
  a tickable repo list, and a live per-repo progress list fed by SSE.

Verified end to end against the live git.ereboslab.com instance: created a
disposable Gitea test account, ran preview + start through the real HTTP
routes against real octocat.github.com repos, confirmed migrated repos
landing on Gitea, then deleted the test repos, the test Gitea account, and
the matching Ritgram test user + DB rows. Found and noted a real, unrelated
blocker: railyard-box is at 99% disk (for reference, this backend's dev/db
config lives in apps/ritgram/backend/.env, pointed at the project's Neon
dev DB; no change needed here).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-17 02:49:02 +03:00

103 lines
3.5 KiB
TypeScript

import api from './api'
// ---------------------------------------------------------------------------
// "Move from GitHub" — paste a username (public repos, no token) or an
// optional fine-grained read token (private repos), tick repos, Rithub
// mirrors them via Gitea's built-in migration API with live progress.
// Mirrors apps/ritgram/backend/src/controllers/githubImportController.ts.
// ---------------------------------------------------------------------------
export interface GithubImportRepo {
fullName: string
name: string
description: string | null
isPrivate: boolean
stars: number
language: string | null
updatedAt: string | null
}
export interface GithubImportPreview {
username: string
repos: GithubImportRepo[]
hasToken: boolean
}
export type GithubImportEvent =
| { type: 'start'; total: number }
| { type: 'migrating'; repo: string }
| { type: 'migrated'; repo: string; htmlUrl: string }
| { type: 'skipped'; repo: string; reason: string; htmlUrl: string }
| { type: 'failed'; repo: string; reason: string }
| { type: 'done'; migrated: number; skipped: number; failed: number; profileUrl: string }
function apiBase(): string {
const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api'
return `${base.replace(/\/+$/, '')}/v1`
}
export const githubImportService = {
/** Public — no Ritgram login required. Never stores the token server-side. */
preview: async (username: string, token?: string): Promise<GithubImportPreview> => {
const { data } = await api.post('/github-import/preview', { username, token })
return data.data
},
/**
* Requires Ritgram login + a connected Rithub (Gitea) account. Streams
* Server-Sent Events over a fetch() POST (EventSource has no POST body
* support) and invokes `onEvent` for each one as it arrives.
*/
start: async (
params: { username: string; token?: string; repos: string[] },
onEvent: (event: GithubImportEvent) => void,
signal?: AbortSignal
): Promise<void> => {
const response = await fetch(`${apiBase()}/github-import/start`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(params),
signal,
})
if (!response.ok || !response.body) {
let message = `Import failed (${response.status})`
try {
const body = await response.json()
message = body?.error?.message || body?.message || message
} catch {
// non-JSON error body; keep default message
}
throw new Error(message)
}
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
for (;;) {
const { value, done } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
// SSE frames are separated by a blank line; each frame may carry
// multiple "data: ..." lines, but this server only ever sends one.
let boundary = buffer.indexOf('\n\n')
while (boundary !== -1) {
const frame = buffer.slice(0, boundary)
buffer = buffer.slice(boundary + 2)
const line = frame.split('\n').find((l) => l.startsWith('data:'))
if (line) {
try {
onEvent(JSON.parse(line.slice(5).trim()) as GithubImportEvent)
} catch {
// ignore a malformed frame rather than aborting the whole import
}
}
boundary = buffer.indexOf('\n\n')
}
}
},
}