railyard/apps/console/lib/ritProvision.ts
caelum0x 6801c08af9
Some checks failed
ci / cargo test (abacus) (push) Has been cancelled
ci / cargo test (agent-runtime) (push) Has been cancelled
ci / cargo test (context-passport) (push) Has been cancelled
ci / cargo test (game-economy) (push) Has been cancelled
ci / cargo test (ledgerline) (push) Has been cancelled
ci / cargo test (mint) (push) Has been cancelled
ci / cargo test (rago) (push) Has been cancelled
ci / cargo test (relay) (push) Has been cancelled
ci / node suites (push) Has been cancelled
ci / cargo test (toolgate) (push) Has been cancelled
ci / cargo test (turnstile) (push) Has been cancelled
ci / cargo test (vend) (push) Has been cancelled
feat(RIT-OPS,RIT-BRD): rename gitea -> rit everywhere we control, deployed + live-verified
apps/gitea -> apps/rithub-server; compose services/containers renamed
(rithub-server-app/postgres/act-runner) with explicit project name and
volume names pinned to the exact existing Docker volumes (no data loss);
our own GITEA_* compose/env var names -> RIT_*; new rit-admin CLI wrapper
on railyard-box; giteaSession.mjs/giteaOAuth.mjs/giteaInfo.mjs ->
ritSession/ritOAuth/ritInfo across 6 apps; GiteaForgeAdapter -> RitForgeAdapter
+ giteaSyncService/importGiteaRepos/syncGiteaRepos -> rit* in ritgram
(tsc clean); apps/console/lib/gitea.ts -> lib/ritProvision.ts; Go
internal/giteaclient -> internal/ritclient in rithub-async-import (go
build/test clean); new /auth/rit + /forges/rit/connect routes with
/gitea back-compat aliases; locale/swagger/footer/captcha template text
scrubbed of remaining "Gitea" strings.

Deployed to railyard-box: old containers stopped/removed, /srv/railyard-gitea
renamed to /srv/rithub-server with a symlink kept, docker compose up -d from
the new path, act_runner network-alias fix for its persisted instance URL.
Live-verified: docker compose config diff showed zero unintended value
changes, DB row counts unchanged (19 users, 635 repos), full route
regression 200/expected, 0 "gitea" in headers/bodies on every checked page,
real git clone+push over HTTPS and SSH with a disposable account (deleted
after). Deferred on purpose (documented in plans/railyard.md): the forge
discriminator / DB column names / Postgres role+volume names (data
migrations, not a naming change) and the upstream GITEA__ env-to-ini keys
and X-Gitea-* wire headers (hardcoded in the vendored engine binary).

See plans/railyard.md RIT-OPS/RIT-BRD entry for the full old->new map and
live evidence.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-12-01 16:34:39 +03:00

129 lines
5.7 KiB
TypeScript

// Rithub (apps/rithub-server) self-serve provisioning (backlog item 4): turns a
// signed-in Console session straight into a dedicated Rithub user, a private
// org and a first repo -- no separate native signup form. Server-only:
// the admin token never reaches a client component.
//
// Uses the underlying engine's documented `sudo=<username>` query parameter:
// a site-admin token can act "as" any user, so the org and repo end up
// correctly owned by the newly created user instead of the admin account.
// Verified live against a real engine container (create user -> create org
// as sudo -> create repo in org as sudo; duplicate calls answer 422/409 as
// expected). DB columns stay named gitea_username/gitea_org_slug/gitea_repo_url
// (migration 0014_org_gitea.sql, live data) -- renaming those is a separate,
// coordinated DB migration, deliberately out of scope for this naming pass.
export interface RitProvision {
username: string;
orgSlug: string;
repoName: string;
htmlUrl: string;
cloneUrl: string;
}
export interface RitClient {
/** Idempotent at the caller's level only: always provisions a *new* Rithub user. Callers must cache the result (see Org.gitea_username) and skip calling this again for an org that already has one. */
provision(input: { seed: string; email: string; repoName: string }): Promise<RitProvision>;
}
const MAX_SLUG_ATTEMPTS = 5;
/** Mirrors switchyard-server's signup.rs slugify (lower-case alnum, single dashes, no leading/trailing dash). */
export function slugify(raw: string): string {
let out = "";
let lastDash = true; // suppress a leading dash
for (const ch of raw.trim().toLowerCase()) {
if (ch >= "a" && ch <= "z" || ch >= "0" && ch <= "9") {
out += ch;
lastDash = false;
} else if (!lastDash) {
out += "-";
lastDash = true;
}
}
const base = out.replace(/-+$/, "").slice(0, 32);
return base || "org";
}
function randomSuffix(): string {
return Math.random().toString(36).slice(2, 8);
}
function randomPassword(): string {
// Rithub requires a password; the account signs in via OIDC SSO (backlog
// item 5) or an admin-reset, never this generated secret directly.
return `${crypto.randomUUID().replace(/-/g, "")}Aa1!`;
}
interface RitRepoBody {
html_url: string;
clone_url: string;
}
class HttpRitClient implements RitClient {
constructor(private base: string, private adminToken: string, private fetchImpl: typeof fetch = fetch) {}
private async req(path: string, init?: RequestInit): Promise<Response> {
return this.fetchImpl(`${this.base}${path}`, {
...init,
headers: { "content-type": "application/json", authorization: `token ${this.adminToken}`, ...(init?.headers ?? {}) },
});
}
private async createUser(base: string, email: string): Promise<string> {
for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt++) {
const username = `${base}-${randomSuffix()}`;
const res = await this.req("/admin/users", {
method: "POST",
body: JSON.stringify({ username, email, password: randomPassword(), must_change_password: false }),
});
if (res.status === 201) return username;
if (res.status !== 422) throw new Error(`rithub create user failed with ${res.status}`);
// 422: username or email already taken. A fresh random suffix clears a
// username collision; an email collision (the same person retrying) is
// rare under the caller's own idempotency check and surfaces here as
// repeated 422s, correctly failing closed rather than silently reusing
// someone else's account.
}
throw new Error("rithub: could not allocate a free username after several attempts");
}
private async createOrg(username: string, base: string): Promise<string> {
for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt++) {
const orgSlug = attempt === 0 ? base : `${base}-${randomSuffix()}`;
const res = await this.req(`/orgs?sudo=${encodeURIComponent(username)}`, {
method: "POST",
body: JSON.stringify({ username: orgSlug, visibility: "private" }),
});
if (res.status === 201) return orgSlug;
if (res.status !== 422) throw new Error(`rithub create org failed with ${res.status}`);
}
throw new Error("rithub: could not allocate a free org name after several attempts");
}
private async createRepo(username: string, orgSlug: string, repoName: string): Promise<RitRepoBody> {
const res = await this.req(`/orgs/${encodeURIComponent(orgSlug)}/repos?sudo=${encodeURIComponent(username)}`, {
method: "POST",
body: JSON.stringify({ name: repoName, auto_init: true, default_branch: "main" }),
});
if (res.status === 201) return (await res.json()) as RitRepoBody;
if (res.status === 409) {
const existing = await this.req(`/repos/${encodeURIComponent(orgSlug)}/${encodeURIComponent(repoName)}`);
if (!existing.ok) throw new Error(`rithub repo lookup failed with ${existing.status}`);
return (await existing.json()) as RitRepoBody;
}
throw new Error(`rithub create repo failed with ${res.status}`);
}
async provision(input: { seed: string; email: string; repoName: string }): Promise<RitProvision> {
const base = slugify(input.seed);
const username = await this.createUser(base, input.email);
const orgSlug = await this.createOrg(username, base);
const repo = await this.createRepo(username, orgSlug, input.repoName);
return { username, orgSlug, repoName: input.repoName, htmlUrl: repo.html_url, cloneUrl: repo.clone_url };
}
}
export function ritClient(opts: { apiUrl: string; adminToken: string; fetchImpl?: typeof fetch }): RitClient {
return new HttpRitClient(opts.apiUrl.replace(/\/$/, ""), opts.adminToken, opts.fetchImpl);
}