Public: anyone can read this; the crew can change it.
Repo transfer with redirects: move a repository to another owner (e.g. an org) without breaking URLs, git remotes or the crew #501
torque/forge:torque/488-repo-transfer-with-redirects-move-a-repo → main 3 commits fork
16 files
changed +912
−9
README.md +7
| @@ -461,6 +461,13 @@ work here. | ||
| 461 | 461 | pull requests (fork → upstream) and detach-before-delete safety. |
| 462 | 462 | - **Organizations & teams** — orgs own repos; teams grant read/write/admin |
| 463 | 463 | resolved through membership. |
| 464 | - **Moving a repository** — `POST /api/v1/repos/:owner/:name/transfer | |
| 465 | {"newOwner"}` (or Settings → Danger zone) hands a repository to yourself | |
| 466 | or an org you administer. Its pulls, app and previews, crew, secrets, runs | |
| 467 | and forks go with it; its old pages and API paths answer 301 (308 for | |
| 468 | writes), git over HTTPS follows, and SSH serves it with a line naming the | |
| 469 | new path — to anyone who may read it, and to nobody else. A repository | |
| 470 | later made at the old path takes the address back. | |
| 464 | 471 | - **Live updates** — a server-sent-event stream turns comment threads live and |
| 465 | 472 | flags new activity, no refresh. |
| 466 | 473 | - **Commit pages** — every commit's diff through the same viewer. |
forge.json +1 −1
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | "ready": 90 |
| 7 | 7 | }, |
| 8 | 8 | "check": { |
| 9 | "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits crew-sandbox steer session-settle landing decide ledger checks dependencies autonomy studio studio-words forks fork-flow cross-repo-pull pulls apps apps-adversarial apps-busy apps-token web git-trust helpers shards migrate vitals guard asks feed feed-page offline share cloud run-secrets forge-cloudflare usage credentials standing board-windows spawn-plan spawn web-apps fleet-ops meter", | |
| 9 | "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits crew-sandbox steer session-settle landing decide ledger checks dependencies autonomy studio studio-words forks fork-flow cross-repo-pull pulls apps apps-adversarial apps-busy apps-token web git-trust helpers shards migrate vitals guard asks feed feed-page offline share cloud run-secrets forge-cloudflare usage credentials standing board-windows spawn-plan spawn web-apps fleet-ops meter transfer", | |
| 10 | 10 | "timeout": 1800 |
| 11 | 11 | } |
| 12 | 12 | } |
src/actions/repos.ts +47 −1
| @@ -22,7 +22,11 @@ import { | ||
| 22 | 22 | type Repo, |
| 23 | 23 | type RepoSettings, |
| 24 | 24 | } from "../core/repos.ts"; |
| 25 | import type { User } from "../core/users.ts"; | |
| 25 | import { | |
| 26 | transferRepo as moveRepo, | |
| 27 | type TransferError, | |
| 28 | } from "../core/transfer.ts"; | |
| 29 | import { getUserByName, type User } from "../core/users.ts"; | |
| 26 | 30 | import { |
| 27 | 31 | createWebhook as insertWebhook, |
| 28 | 32 | deleteWebhook as removeWebhook, |
| @@ -185,6 +189,48 @@ export async function deleteRepo( | ||
| 185 | 189 | return ok(); |
| 186 | 190 | } |
| 187 | 191 | |
| 192 | export type TransferRepoActionError = | |
| 193 | | TransferError | |
| 194 | | "not_found" | |
| 195 | | "unknown_owner" | |
| 196 | | "forbidden_owner"; | |
| 197 | ||
| 198 | /** | |
| 199 | * Move a repository to another owner (`core/transfer.ts`). The actor must | |
| 200 | * administer the repository and be able to put a repository where it is | |
| 201 | * going: their own account, or an org they administer. A site admin may | |
| 202 | * hand it to any person or org. An agent owns nothing, so it is never a | |
| 203 | * destination — and never an actor here, since it never administers. | |
| 204 | */ | |
| 205 | export async function transferRepo( | |
| 206 | app: App, | |
| 207 | actor: User | undefined, | |
| 208 | repo: Repo, | |
| 209 | newOwner: string, | |
| 210 | ): Promise<Result<Repo, TransferRepoActionError>> { | |
| 211 | const admin = requireRepoAdmin(app, actor, repo); | |
| 212 | if (!admin.ok) return admin; | |
| 213 | const target = getUserByName(app.db, newOwner); | |
| 214 | if (target === undefined) return err("unknown_owner"); | |
| 215 | const receives = | |
| 216 | target.kind !== "agent" && | |
| 217 | (target.id === admin.value.id || | |
| 218 | admin.value.isAdmin || | |
| 219 | (target.kind === "org" && | |
| 220 | accessAllows(orgAccess(app.db, target.id, admin.value), "admin"))); | |
| 221 | if (!receives) return err("forbidden_owner"); | |
| 222 | const from = `${repo.ownerName}/${repo.name}`; | |
| 223 | const moved = await moveRepo(app.db, app.reposRoot, repo, target); | |
| 224 | if (!moved.ok) return moved; | |
| 225 | app.bus.append({ | |
| 226 | kind: "repo.transferred", | |
| 227 | repoId: repo.id, | |
| 228 | actorId: admin.value.id, | |
| 229 | payload: { from, to: `${moved.value.ownerName}/${moved.value.name}` }, | |
| 230 | }); | |
| 231 | return moved; | |
| 232 | } | |
| 233 | ||
| 188 | 234 | export function createLabel( |
| 189 | 235 | app: App, |
| 190 | 236 | actor: User | undefined, |
src/core/redirects.ts added +63
| @@ -0,0 +1,63 @@ | ||
| 1 | /** | |
| 2 | * Where a repository used to live. A transfer (`core/transfer.ts`) leaves | |
| 3 | * its old `owner/name` behind as a row pointing at the repository's id, so | |
| 4 | * an old link, API path or git remote still finds it — and keeps finding it | |
| 5 | * through any number of later moves, because the row names the repository, | |
| 6 | * not its address. A repository created at that path takes the path back. | |
| 7 | * | |
| 8 | * Pure data: whether the asker may see where it went is the caller's | |
| 9 | * question (`canRead`), never answered here. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { Database } from "bun:sqlite"; | |
| 13 | import { getRepoById, type Repo } from "./repos.ts"; | |
| 14 | ||
| 15 | /** The repository that used to live at `owner/name`, if one did. */ | |
| 16 | export function movedRepo( | |
| 17 | db: Database, | |
| 18 | owner: string, | |
| 19 | name: string, | |
| 20 | ): Repo | undefined { | |
| 21 | const row = db | |
| 22 | .query< | |
| 23 | { repo_id: string }, | |
| 24 | [string, string] | |
| 25 | >("SELECT repo_id FROM repo_redirect WHERE owner_name = ?1 AND name = ?2") | |
| 26 | .get(owner, name); | |
| 27 | return row ? getRepoById(db, row.repo_id) : undefined; | |
| 28 | } | |
| 29 | ||
| 30 | /** Leave `owner/name` pointing at `repoId`, replacing any older pointer. */ | |
| 31 | export function recordRedirect( | |
| 32 | db: Database, | |
| 33 | owner: string, | |
| 34 | name: string, | |
| 35 | repoId: string, | |
| 36 | ): void { | |
| 37 | db.query( | |
| 38 | `INSERT INTO repo_redirect (owner_name, name, repo_id) VALUES (?1, ?2, ?3) | |
| 39 | ON CONFLICT (owner_name, name) DO UPDATE SET repo_id = excluded.repo_id, | |
| 40 | created_at = excluded.created_at`, | |
| 41 | ).run(owner, name, repoId); | |
| 42 | } | |
| 43 | ||
| 44 | /** A repository lives at `owner/name` now; nothing redirects away from it. */ | |
| 45 | export function clearRedirect(db: Database, owner: string, name: string): void { | |
| 46 | db.query( | |
| 47 | "DELETE FROM repo_redirect WHERE owner_name = ?1 AND name = ?2", | |
| 48 | ).run(owner, name); | |
| 49 | } | |
| 50 | ||
| 51 | /** The old addresses of one repository, oldest first. */ | |
| 52 | export function redirectsTo( | |
| 53 | db: Database, | |
| 54 | repoId: string, | |
| 55 | ): { owner: string; name: string }[] { | |
| 56 | return db | |
| 57 | .query< | |
| 58 | { owner_name: string; name: string }, | |
| 59 | [string] | |
| 60 | >("SELECT owner_name, name FROM repo_redirect WHERE repo_id = ?1 ORDER BY created_at") | |
| 61 | .all(repoId) | |
| 62 | .map((r) => ({ owner: r.owner_name, name: r.name })); | |
| 63 | } |
src/core/repos.ts +3
| @@ -20,6 +20,7 @@ import { id } from "../kernel/id.ts"; | ||
| 20 | 20 | import { createLog } from "../kernel/log.ts"; |
| 21 | 21 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 22 | 22 | import { likeEscape, pageLimit } from "./issues.ts"; |
| 23 | import { clearRedirect } from "./redirects.ts"; | |
| 23 | 24 | import { REPO_VISIBLE, REPO_WRITABLE } from "./visibility.ts"; |
| 24 | 25 | import { accessAllows, orgAccess, type Access } from "./orgs.ts"; |
| 25 | 26 | import { getUserById, type User } from "./users.ts"; |
| @@ -274,6 +275,7 @@ export async function createRepo( | ||
| 274 | 275 | input.description ?? "", |
| 275 | 276 | branch, |
| 276 | 277 | ); |
| 278 | clearRedirect(db, owner.username, input.name); | |
| 277 | 279 | return ok(getRepoById(db, repoId)!); |
| 278 | 280 | } |
| 279 | 281 | |
| @@ -343,6 +345,7 @@ export async function forkRepo( | ||
| 343 | 345 | parent.defaultBranch, |
| 344 | 346 | parent.id, |
| 345 | 347 | ); |
| 348 | clearRedirect(db, owner.username, forkName); | |
| 346 | 349 | return ok(getRepoById(db, repoId)!); |
| 347 | 350 | } |
| 348 | 351 |
src/core/schema.ts +14
| @@ -1151,4 +1151,18 @@ export const migrations: readonly string[] = [ | ||
| 1151 | 1151 | UPDATE run SET subscription_id = 'platform' |
| 1152 | 1152 | WHERE kind = 'agent' AND subscription_id IS NULL; |
| 1153 | 1153 | `, |
| 1154 | // 43 — where a repository used to live (`core/redirects.ts`). A transfer | |
| 1155 | // leaves its old owner/name here so every old URL, API path and git | |
| 1156 | // remote finds the repository by id, wherever it has gone since. A repo | |
| 1157 | // created at that path takes it back: the row is deleted then. | |
| 1158 | ` | |
| 1159 | CREATE TABLE repo_redirect ( | |
| 1160 | owner_name TEXT NOT NULL COLLATE NOCASE, | |
| 1161 | name TEXT NOT NULL COLLATE NOCASE, | |
| 1162 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 1163 | created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 1164 | PRIMARY KEY (owner_name, name) | |
| 1165 | ); | |
| 1166 | CREATE INDEX repo_redirect_repo ON repo_redirect(repo_id); | |
| 1167 | `, | |
| 1154 | 1168 | ]; |
src/core/transfer.ts added +101
| @@ -0,0 +1,101 @@ | ||
| 1 | /** | |
| 2 | * Moving a repository to another owner. Everything the forge keeps about a | |
| 3 | * repository — its crew, autonomy and direction, secrets, app and previews, | |
| 4 | * pulls, runs, forks — is keyed by the repository's id, so a move changes | |
| 5 | * exactly two things: where the bare repo sits on disk, and the owner on | |
| 6 | * its row. The old address is left behind as a redirect (`redirects.ts`). | |
| 7 | * | |
| 8 | * Same ordering rule as creation: the directory is in its new place before | |
| 9 | * the row says so. Forks borrow the parent's objects by absolute path, so | |
| 10 | * every direct fork is repointed before the row moves too; a failure on the | |
| 11 | * way puts the directory and the forks back. | |
| 12 | */ | |
| 13 | ||
| 14 | import type { Database } from "bun:sqlite"; | |
| 15 | import { existsSync, mkdirSync, realpathSync } from "node:fs"; | |
| 16 | import { rename } from "node:fs/promises"; | |
| 17 | import { dirname, join } from "node:path"; | |
| 18 | import { closeReader } from "../git/read.ts"; | |
| 19 | import { repoDir, repointAlternates } from "../git/repos.ts"; | |
| 20 | import { createLog } from "../kernel/log.ts"; | |
| 21 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 22 | import { clearRedirect, recordRedirect } from "./redirects.ts"; | |
| 23 | import { getRepoById, listForks, type Repo } from "./repos.ts"; | |
| 24 | ||
| 25 | const log = createLog("transfer"); | |
| 26 | ||
| 27 | export type TransferError = "same_owner" | "name_taken" | "transfer_failed"; | |
| 28 | ||
| 29 | /** Every spelling of `<dir>/objects` a fork's alternates file may hold. */ | |
| 30 | function objectPaths(dir: string): string[] { | |
| 31 | const plain = join(dir, "objects"); | |
| 32 | const real = existsSync(plain) ? realpathSync(plain) : plain; | |
| 33 | return real === plain ? [plain] : [plain, real]; | |
| 34 | } | |
| 35 | ||
| 36 | export async function transferRepo( | |
| 37 | db: Database, | |
| 38 | reposRoot: string, | |
| 39 | repo: Repo, | |
| 40 | newOwner: { readonly id: string; readonly username: string }, | |
| 41 | ): Promise<Result<Repo, TransferError>> { | |
| 42 | if (newOwner.id === repo.ownerId) return err("same_owner"); | |
| 43 | if ( | |
| 44 | db | |
| 45 | .query( | |
| 46 | "SELECT 1 FROM repo WHERE owner_id = ?1 AND name = ?2 COLLATE NOCASE", | |
| 47 | ) | |
| 48 | .get(newOwner.id, repo.name) | |
| 49 | ) | |
| 50 | return err("name_taken"); | |
| 51 | ||
| 52 | const from = repoDir(reposRoot, repo.ownerName, repo.name); | |
| 53 | const to = repoDir(reposRoot, newOwner.username, repo.name); | |
| 54 | // A directory with no row is debris from something that failed; it is | |
| 55 | // still somebody's bytes, and a move never lands on top of them. | |
| 56 | if (existsSync(to)) return err("name_taken"); | |
| 57 | const fromObjects = objectPaths(from); | |
| 58 | ||
| 59 | const forks = listForks(db, repo.id).map((fork) => | |
| 60 | repoDir(reposRoot, fork.ownerName, fork.name), | |
| 61 | ); | |
| 62 | // Pooled `cat-file`s hold the old directory, and a fork's hold the old | |
| 63 | // alternates they read at start; all of them reopen on next use. | |
| 64 | closeReader(from); | |
| 65 | for (const dir of forks) closeReader(dir); | |
| 66 | ||
| 67 | try { | |
| 68 | mkdirSync(dirname(to), { recursive: true }); | |
| 69 | await rename(from, to); | |
| 70 | } catch (error) { | |
| 71 | log.error("cannot move repository", { from, to, error: String(error) }); | |
| 72 | return err("transfer_failed"); | |
| 73 | } | |
| 74 | const repointed: string[] = []; | |
| 75 | try { | |
| 76 | for (const dir of forks) | |
| 77 | if (await repointAlternates(dir, fromObjects, join(to, "objects"))) | |
| 78 | repointed.push(dir); | |
| 79 | db.transaction(() => { | |
| 80 | db.query("UPDATE repo SET owner_id = ?1 WHERE id = ?2").run( | |
| 81 | newOwner.id, | |
| 82 | repo.id, | |
| 83 | ); | |
| 84 | clearRedirect(db, newOwner.username, repo.name); | |
| 85 | recordRedirect(db, repo.ownerName, repo.name, repo.id); | |
| 86 | })(); | |
| 87 | } catch (error) { | |
| 88 | log.error("transfer failed; putting the repository back", { | |
| 89 | from, | |
| 90 | to, | |
| 91 | error: String(error), | |
| 92 | }); | |
| 93 | for (const dir of repointed) | |
| 94 | await repointAlternates(dir, objectPaths(to), fromObjects[0]!); | |
| 95 | for (const dir of forks) closeReader(dir); | |
| 96 | closeReader(to); | |
| 97 | await rename(to, from); | |
| 98 | return err("transfer_failed"); | |
| 99 | } | |
| 100 | return ok(getRepoById(db, repo.id)!); | |
| 101 | } |
src/crew/runner.ts +10 −2
| @@ -991,8 +991,10 @@ async function work( | ||
| 991 | 991 | fork.value, |
| 992 | 992 | branch, |
| 993 | 993 | dir, |
| 994 | forkBare, | |
| 995 | bare, | |
| 994 | // Read again by id: a transfer may have moved either repository | |
| 995 | // while the agent worked, and the paths from the start are stale. | |
| 996 | currentDir(app, fork.value), | |
| 997 | currentDir(app, repo), | |
| 996 | 998 | { ...gitAuth, ...identity }, |
| 997 | 999 | result.result, |
| 998 | 1000 | stoppedAt === undefined |
| @@ -1045,6 +1047,12 @@ async function forkFor( | ||
| 1045 | 1047 | return ok(made.value); |
| 1046 | 1048 | } |
| 1047 | 1049 | |
| 1050 | /** Where a repository's bare directory is now, read from its row by id. */ | |
| 1051 | function currentDir(app: App, repo: Repo): string { | |
| 1052 | const now = getRepoById(app.db, repo.id) ?? repo; | |
| 1053 | return repoDir(app.reposRoot, now.ownerName, now.name); | |
| 1054 | } | |
| 1055 | ||
| 1048 | 1056 | /** |
| 1049 | 1057 | * A clone on `branch`, matching what the forge holds. The clone is the |
| 1050 | 1058 | * triangle git was built for: it fetches from the repository and pushes to |
src/design/activity.ts +1
| @@ -108,6 +108,7 @@ const WORDS: Record<string, string> = { | ||
| 108 | 108 | "pull.thread_resolved": "resolved a review thread", |
| 109 | 109 | "repo.created": "created a repository", |
| 110 | 110 | "repo.forked": "forked a repository", |
| 111 | "repo.transferred": "moved a repository", | |
| 111 | 112 | "repo.settings_updated": "changed repository settings", |
| 112 | 113 | "repo.mirrored": "mirrored a repository", |
| 113 | 114 | "repo.imported": "imported issues and pulls", |
src/git/repos.ts +30 −1
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import { join } from "node:path"; |
| 8 | import { rm } from "node:fs/promises"; | |
| 8 | import { rename, rm } from "node:fs/promises"; | |
| 9 | 9 | import { defect } from "../kernel/error.ts"; |
| 10 | 10 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 11 | 11 | import { runGit, type GitFailure } from "./env.ts"; |
| @@ -131,3 +131,32 @@ export async function deleteRepoDir( | ||
| 131 | 131 | await rm(dir, { recursive: true, force: true }); |
| 132 | 132 | return ok(); |
| 133 | 133 | } |
| 134 | ||
| 135 | /** | |
| 136 | * Point a fork's borrowed objects at its parent's new home. `clone --shared` | |
| 137 | * records the parent's object directory as an absolute path, so a parent | |
| 138 | * that moves takes every fork's history with it unless each fork is told. | |
| 139 | * Lines naming anything else are kept as they were. Returns whether the | |
| 140 | * file changed. | |
| 141 | */ | |
| 142 | export async function repointAlternates( | |
| 143 | forkDir: string, | |
| 144 | fromObjects: readonly string[], | |
| 145 | toObjects: string, | |
| 146 | ): Promise<boolean> { | |
| 147 | const path = join(forkDir, "objects", "info", "alternates"); | |
| 148 | const file = Bun.file(path); | |
| 149 | if (!(await file.exists())) return false; | |
| 150 | const before = await file.text(); | |
| 151 | const after = before | |
| 152 | .split("\n") | |
| 153 | .map((line) => | |
| 154 | fromObjects.includes(line.trim().replace(/\/+$/, "")) ? toObjects : line, | |
| 155 | ) | |
| 156 | .join("\n"); | |
| 157 | if (after === before) return false; | |
| 158 | // Whole or not at all: a reader never sees half a list of object stores. | |
| 159 | await Bun.write(`${path}.moving`, after); | |
| 160 | await rename(`${path}.moving`, path); | |
| 161 | return true; | |
| 162 | } |
src/http/api.ts +20 −1
| @@ -72,6 +72,7 @@ import { | ||
| 72 | 72 | createWebhook, |
| 73 | 73 | deleteLabel, |
| 74 | 74 | deleteRepo, |
| 75 | transferRepo, | |
| 75 | 76 | deleteWebhook, |
| 76 | 77 | forkRepo, |
| 77 | 78 | updateRepoSettings, |
| @@ -139,7 +140,7 @@ import { isPinned } from "../core/pins.ts"; | ||
| 139 | 140 | import { listWebhooks } from "../core/webhooks.ts"; |
| 140 | 141 | import { diffCommit } from "../git/diff.ts"; |
| 141 | 142 | import { runGit } from "../git/env.ts"; |
| 142 | import { isSafeRef, isSafeTreePath } from "../git/guard.ts"; | |
| 143 | import { isSafeName, isSafeRef, isSafeTreePath } from "../git/guard.ts"; | |
| 143 | 144 | import { listBranches } from "../git/branches.ts"; |
| 144 | 145 | import { |
| 145 | 146 | appView, |
| @@ -1162,6 +1163,24 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1162 | 1163 | return json({}, 200); |
| 1163 | 1164 | }); |
| 1164 | 1165 | |
| 1166 | // Move to another owner. The old path keeps answering with the new one | |
| 1167 | // (`core/redirects.ts`, followed in `server.ts`). | |
| 1168 | router.add("POST", "/api/v1/repos/:owner/:name/transfer", async (ctx) => { | |
| 1169 | const denied = requireScope(ctx, "admin"); | |
| 1170 | if (denied) return denied; | |
| 1171 | const repo = loadRepo(ctx); | |
| 1172 | if (!repo) return notFound(); | |
| 1173 | const newOwner = str((await body(ctx.request)).newOwner).trim(); | |
| 1174 | if (!isSafeName(newOwner)) | |
| 1175 | return apiError("invalid_owner", 422, "newOwner must be an account name"); | |
| 1176 | const moved = await transferRepo(ctx.app, ctx.auth.user, repo, newOwner); | |
| 1177 | if (!moved.ok) | |
| 1178 | return moved.error === "forbidden_owner" | |
| 1179 | ? json({ error: "forbidden_owner" }, 403) | |
| 1180 | : respondAccess(moved.error, moved.error === "transfer_failed" ? 500 : 422); | |
| 1181 | return json(repoJson(ctx, moved.value), 200); | |
| 1182 | }); | |
| 1183 | ||
| 1165 | 1184 | router.add("GET", "/api/v1/repos/:owner/:name/events", (ctx) => { |
| 1166 | 1185 | const repo = loadRepo(ctx); |
| 1167 | 1186 | if (!repo) return notFound(); |
src/http/moved.ts added +73
| @@ -0,0 +1,73 @@ | ||
| 1 | /** | |
| 2 | * The old address of a moved repository answers with the new one. One | |
| 3 | * check, before any handler: a path whose repository segments name a | |
| 4 | * redirect (`core/redirects.ts`) — a page `/:owner/:name/…`, the API's | |
| 5 | * `/api/v1/repos/:owner/:name/…`, or git's `/:owner/:name.git/…` — is | |
| 6 | * rewritten in place and the rest of the path and the query are kept. | |
| 7 | * | |
| 8 | * Only a viewer who may read the repository learns where it went; anyone | |
| 9 | * else falls through to the handler, which answers exactly as for a path | |
| 10 | * that never existed (`not_found` stays ambiguous). GET and HEAD get 301; | |
| 11 | * anything else 308, which keeps the method and the body. Git's smart HTTP | |
| 12 | * follows the redirect on its first request and talks to the new path from | |
| 13 | * then on. | |
| 14 | */ | |
| 15 | ||
| 16 | import type { App } from "../app.ts"; | |
| 17 | import { movedRepo } from "../core/redirects.ts"; | |
| 18 | import { canRead, getRepo } from "../core/repos.ts"; | |
| 19 | import type { User } from "../core/users.ts"; | |
| 20 | ||
| 21 | /** Where the repository segments of a path sit: pages and git, or the API. */ | |
| 22 | function repoSegments(segments: readonly string[]): number | undefined { | |
| 23 | if (segments[1] === "api") | |
| 24 | return segments[2] === "v1" && segments[3] === "repos" ? 4 : undefined; | |
| 25 | return 1; | |
| 26 | } | |
| 27 | ||
| 28 | function decoded(raw: string | undefined): string | undefined { | |
| 29 | if (raw === undefined) return undefined; | |
| 30 | try { | |
| 31 | return decodeURIComponent(raw); | |
| 32 | } catch { | |
| 33 | return undefined; | |
| 34 | } | |
| 35 | } | |
| 36 | ||
| 37 | /** The URL this request should be sent to instead, if its repository moved. */ | |
| 38 | export function movedLocation( | |
| 39 | app: App, | |
| 40 | url: URL, | |
| 41 | params: Readonly<Record<string, string>>, | |
| 42 | viewer: User | undefined, | |
| 43 | ): URL | undefined { | |
| 44 | const owner = params["owner"]; | |
| 45 | const name = params["name"]; | |
| 46 | if (owner === undefined || name === undefined) return undefined; | |
| 47 | const segments = url.pathname.split("/"); | |
| 48 | const at = repoSegments(segments); | |
| 49 | if (at === undefined) return undefined; | |
| 50 | // The route's own `:owner/:name`, not some other pair deeper in the path. | |
| 51 | const rawName = decoded(segments[at + 1]); | |
| 52 | const git = rawName === `${name}.git`; | |
| 53 | if (decoded(segments[at]) !== owner || (rawName !== name && !git)) | |
| 54 | return undefined; | |
| 55 | const repo = movedRepo(app.db, owner, name); | |
| 56 | if (repo === undefined || !canRead(app.db, repo, viewer)) return undefined; | |
| 57 | // A repository living at the path always wins over one that left it. | |
| 58 | if (getRepo(app.db, owner, name) !== undefined) return undefined; | |
| 59 | const next = [...segments]; | |
| 60 | next[at] = encodeURIComponent(repo.ownerName); | |
| 61 | next[at + 1] = encodeURIComponent(repo.name) + (git ? ".git" : ""); | |
| 62 | const to = new URL(url); | |
| 63 | to.pathname = next.join("/"); | |
| 64 | return to; | |
| 65 | } | |
| 66 | ||
| 67 | export function redirectResponse(to: URL, method: string): Response { | |
| 68 | const status = method === "GET" || method === "HEAD" ? 301 : 308; | |
| 69 | return new Response(null, { | |
| 70 | status, | |
| 71 | headers: { location: to.toString(), "cache-control": "no-store" }, | |
| 72 | }); | |
| 73 | } |
src/http/server.ts +8
| @@ -203,6 +203,7 @@ import { | ||
| 203 | 203 | promptSourceRun, |
| 204 | 204 | promptsSettingsPage, |
| 205 | 205 | repoDelete, |
| 206 | repoTransfer, | |
| 206 | 207 | settingsPage, |
| 207 | 208 | settingsUpdate, |
| 208 | 209 | webhookCreate, |
| @@ -268,6 +269,7 @@ import { | ||
| 268 | 269 | } from "../web/pages/origins.ts"; |
| 269 | 270 | import { pushThrough } from "../origins/push-through.ts"; |
| 270 | 271 | import { notFoundPage } from "../web/chrome.ts"; |
| 272 | import { movedLocation, redirectResponse } from "./moved.ts"; | |
| 271 | 273 | import { targetForShortCode } from "../origins/oauth.ts"; |
| 272 | 274 | import { apiRoutes } from "./api.ts"; |
| 273 | 275 | import { feedRoutes } from "./feed.ts"; |
| @@ -893,6 +895,7 @@ export function buildRouter(): Router<Handler> { | ||
| 893 | 895 | router.add("POST", "/:owner/:name/settings/hooks/:id/delete", webhookDelete); |
| 894 | 896 | router.add("GET", "/:owner/:name/settings/danger", dangerPage); |
| 895 | 897 | router.add("POST", "/:owner/:name/settings/delete", repoDelete); |
| 898 | router.add("POST", "/:owner/:name/settings/transfer", repoTransfer); | |
| 896 | 899 | |
| 897 | 900 | return router; |
| 898 | 901 | } |
| @@ -1428,6 +1431,11 @@ async function answerGet( | ||
| 1428 | 1431 | return withRateHeaders(tooManyRequests(verdict), verdict); |
| 1429 | 1432 | } |
| 1430 | 1433 | |
| 1434 | // A repository that moved answers its old address with its new one. | |
| 1435 | const moved = movedLocation(app, url, matched.params, auth.user); | |
| 1436 | if (moved !== undefined) | |
| 1437 | return withRateHeaders(redirectResponse(moved, request.method), verdict); | |
| 1438 | ||
| 1431 | 1439 | const themeCookie = cookieValue(request, "forge_theme") ?? ""; |
| 1432 | 1440 | const modeCookieValue = cookieValue(request, "forge_mode") ?? ""; |
| 1433 | 1441 | // `?mode=` on the URL is the escape hatch: a plain link a person is |
src/tui/ssh.ts +31 −2
| @@ -13,7 +13,9 @@ | ||
| 13 | 13 | import { join } from "node:path"; |
| 14 | 14 | import type { App as Forge } from "../app.ts"; |
| 15 | 15 | import { findKeyByFingerprint, touchKey } from "../core/keys.ts"; |
| 16 | import { canRead, canWrite, getRepo } from "../core/repos.ts"; | |
| 16 | import type { Database } from "bun:sqlite"; | |
| 17 | import { canRead, canWrite, getRepo, type Repo } from "../core/repos.ts"; | |
| 18 | import { movedRepo } from "../core/redirects.ts"; | |
| 17 | 19 | import { getUserById, type User } from "../core/users.ts"; |
| 18 | 20 | import { createRepo } from "../actions/repos.ts"; |
| 19 | 21 | import { hookEnv } from "../git/hooks.ts"; |
| @@ -184,6 +186,30 @@ export function forgeSshSession(forge: Forge): (session: SshSession) => void { | ||
| 184 | 186 | }; |
| 185 | 187 | } |
| 186 | 188 | |
| 189 | /** | |
| 190 | * The repository a git command names: the one living at the path, or the | |
| 191 | * one that moved away from it (`core/redirects.ts`) with a line saying where | |
| 192 | * it went — but only for someone who may read it; anyone else is told what | |
| 193 | * a path that never existed is told. | |
| 194 | */ | |
| 195 | export function findGitRepo( | |
| 196 | db: Database, | |
| 197 | owner: string, | |
| 198 | name: string, | |
| 199 | user: User | undefined, | |
| 200 | ): { repo: Repo | undefined; moved?: string } { | |
| 201 | const repo = getRepo(db, owner, name); | |
| 202 | if (repo !== undefined) return { repo }; | |
| 203 | const moved = movedRepo(db, owner, name); | |
| 204 | if (moved === undefined || !canRead(db, moved, user)) | |
| 205 | return { repo: undefined }; | |
| 206 | const to = `${moved.ownerName}/${moved.name}`; | |
| 207 | return { | |
| 208 | repo: moved, | |
| 209 | moved: `${owner}/${name} has moved to ${to}; point your remote at ${to}.git`, | |
| 210 | }; | |
| 211 | } | |
| 212 | ||
| 187 | 213 | /** |
| 188 | 214 | * Git over an exec channel. The access matrix is exactly the HTTP one: |
| 189 | 215 | * upload-pack → `canRead`; a guest may read a public repo. |
| @@ -207,7 +233,10 @@ async function serveGitCommand( | ||
| 207 | 233 | } |
| 208 | 234 | |
| 209 | 235 | const write = parsed.service === "git-receive-pack"; |
| 210 | let repo = getRepo(forge.db, parsed.owner, parsed.name); | |
| 236 | const found = findGitRepo(forge.db, parsed.owner, parsed.name, user); | |
| 237 | if (found.moved !== undefined) | |
| 238 | session.writeStderr(`forge: ${found.moved}${CRLF}`); | |
| 239 | let repo = found.repo; | |
| 211 | 240 | if (!repo && write && user) { |
| 212 | 241 | // Push-to-create, the same rule as smart HTTP: an authed owner (or org |
| 213 | 242 | // writer) pushing to a repo that does not exist makes it. |
src/web/pages/settings.ts +58 −1
| @@ -52,11 +52,14 @@ import { | ||
| 52 | 52 | setCrewRole, |
| 53 | 53 | } from "../../core/agents.ts"; |
| 54 | 54 | import { isAutonomy } from "../../core/repos.ts"; |
| 55 | import { isSafeName } from "../../git/guard.ts"; | |
| 56 | import { err } from "../../kernel/result.ts"; | |
| 55 | 57 | import { |
| 56 | 58 | createLabel, |
| 57 | 59 | createWebhook, |
| 58 | 60 | deleteLabel, |
| 59 | 61 | deleteRepo, |
| 62 | transferRepo, | |
| 60 | 63 | deleteWebhook, |
| 61 | 64 | updateLabel, |
| 62 | 65 | updateRepoSettings, |
| @@ -1697,6 +1700,26 @@ export function dangerPage(ctx: Ctx): Response { | ||
| 1697 | 1700 | const base = repoBase(repo); |
| 1698 | 1701 | const full = `${repo.ownerName}/${repo.name}`; |
| 1699 | 1702 | |
| 1703 | const move = card( | |
| 1704 | html`<form method="post" action="${base}/settings/transfer"> | |
| 1705 | <p> | |
| 1706 | Moving <strong>${full}</strong> to another owner keeps everything that | |
| 1707 | hangs off it — pulls, issues, the app and its previews, the crew, | |
| 1708 | secrets, runs and forks. Its old address, API paths and git remotes go | |
| 1709 | on answering with the new one until a repository is made there. | |
| 1710 | </p> | |
| 1711 | ${formField({ | |
| 1712 | label: "New owner", | |
| 1713 | name: "newOwner", | |
| 1714 | value: "", | |
| 1715 | mono: true, | |
| 1716 | required: true, | |
| 1717 | hint: "Your own account, or an org you administer.", | |
| 1718 | })} | |
| 1719 | <div class="form-actions">${btn("Move this repository")}</div> | |
| 1720 | </form>`, | |
| 1721 | { head: html`<h2>Move to another owner</h2>` }, | |
| 1722 | ); | |
| 1700 | 1723 | const body = card( |
| 1701 | 1724 | html`<p> |
| 1702 | 1725 | Deleting <strong>${full}</strong> removes its issues, pull requests, |
| @@ -1719,7 +1742,41 @@ export function dangerPage(ctx: Ctx): Response { | ||
| 1719 | 1742 | <h2>Delete this repository</h2>`, |
| 1720 | 1743 | }, |
| 1721 | 1744 | ); |
| 1722 | return settingsPageResponse(ctx, repo, "danger", "Danger zone", body); | |
| 1745 | return settingsPageResponse( | |
| 1746 | ctx, | |
| 1747 | repo, | |
| 1748 | "danger", | |
| 1749 | "Danger zone", | |
| 1750 | html`${move}${body}`, | |
| 1751 | ); | |
| 1752 | } | |
| 1753 | ||
| 1754 | const TRANSFER_WORDS: Record<string, string> = { | |
| 1755 | invalid_owner: "That is not an account name.", | |
| 1756 | unknown_owner: "There is no account by that name.", | |
| 1757 | forbidden_owner: "You can move it only to yourself or an org you administer.", | |
| 1758 | same_owner: "It already lives there.", | |
| 1759 | name_taken: "That owner already has a repository by this name.", | |
| 1760 | }; | |
| 1761 | ||
| 1762 | // POST /:owner/:name/settings/transfer | |
| 1763 | export async function repoTransfer(ctx: Ctx): Promise<Response> { | |
| 1764 | const gate = await adminForm(ctx); | |
| 1765 | if (gate instanceof Response) return gate; | |
| 1766 | const { repo, form } = gate; | |
| 1767 | const newOwner = field(form, "newOwner").trim(); | |
| 1768 | const moved = isSafeName(newOwner) | |
| 1769 | ? await transferRepo(ctx.app, ctx.auth.user, repo, newOwner) | |
| 1770 | : err("invalid_owner" as const); | |
| 1771 | if (!moved.ok) | |
| 1772 | return flashTo(ctx, `${repoBase(repo)}/settings/danger`, { | |
| 1773 | tone: "danger", | |
| 1774 | message: `${TRANSFER_WORDS[moved.error] ?? "The repository could not be moved."} Nothing moved.`, | |
| 1775 | }); | |
| 1776 | const to = `${moved.value.ownerName}/${moved.value.name}`; | |
| 1777 | return flashTo(ctx, repoBase(moved.value), { | |
| 1778 | message: `Moved to ${to}. The old address forwards here.`, | |
| 1779 | }); | |
| 1723 | 1780 | } |
| 1724 | 1781 | |
| 1725 | 1782 | /** |
test/transfer.test.ts added +445
| @@ -0,0 +1,445 @@ | ||
| 1 | /** | |
| 2 | * Moving a repository to another owner (issue #488): a repository with a | |
| 3 | * running app, a fork, a live preview and an open pull moves into an org, | |
| 4 | * and then every old address is tried — pages, the API, git over HTTP and | |
| 5 | * the SSH lookup — and everything that hung off the repository is still | |
| 6 | * hanging off it. Plus who may move what, where, and what a stranger learns | |
| 7 | * from an old address of a private repository (nothing). | |
| 8 | */ | |
| 9 | ||
| 10 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 11 | import { existsSync } from "node:fs"; | |
| 12 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 13 | import { tmpdir } from "node:os"; | |
| 14 | import { join } from "node:path"; | |
| 15 | import { createApp, type App } from "../src/app.ts"; | |
| 16 | import { AppsRuntime } from "../src/apps/runtime.ts"; | |
| 17 | import { newApp } from "../src/actions/apps.ts"; | |
| 18 | import { createOrg } from "../src/actions/orgs.ts"; | |
| 19 | import { openPull } from "../src/actions/pulls.ts"; | |
| 20 | import { | |
| 21 | commitToBranch, | |
| 22 | createRepo, | |
| 23 | forkRepo, | |
| 24 | transferRepo, | |
| 25 | } from "../src/actions/repos.ts"; | |
| 26 | import { listEvents } from "../src/core/events.ts"; | |
| 27 | import { getPull } from "../src/core/pulls.ts"; | |
| 28 | import { redirectsTo } from "../src/core/redirects.ts"; | |
| 29 | import { getRepo, getRepoById, type Repo } from "../src/core/repos.ts"; | |
| 30 | import { listRuns, type Run } from "../src/core/runs.ts"; | |
| 31 | import { createSession } from "../src/core/sessions.ts"; | |
| 32 | import { createToken } from "../src/core/tokens.ts"; | |
| 33 | import { createUser, type User } from "../src/core/users.ts"; | |
| 34 | import { runGit } from "../src/git/env.ts"; | |
| 35 | import { resolveOid } from "../src/git/merge.ts"; | |
| 36 | import { repoDir } from "../src/git/repos.ts"; | |
| 37 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 38 | import { findGitRepo } from "../src/tui/ssh.ts"; | |
| 39 | import { gitClientEnv } from "./helpers/git-client.ts"; | |
| 40 | import { quietLogs } from "./helpers/globals.ts"; | |
| 41 | ||
| 42 | quietLogs(); | |
| 43 | ||
| 44 | const DOMAIN = "apps.test"; | |
| 45 | ||
| 46 | async function git(args: string[], cwd: string) { | |
| 47 | const proc = Bun.spawn(["git", ...args], { | |
| 48 | cwd, | |
| 49 | env: gitClientEnv(), | |
| 50 | stdout: "pipe", | |
| 51 | stderr: "pipe", | |
| 52 | }); | |
| 53 | const [out, err, code] = await Promise.all([ | |
| 54 | new Response(proc.stdout).text(), | |
| 55 | new Response(proc.stderr).text(), | |
| 56 | proc.exited, | |
| 57 | ]); | |
| 58 | return { code, out: out.trim(), err: err.trim() }; | |
| 59 | } | |
| 60 | ||
| 61 | describe("repo transfer with redirects", () => { | |
| 62 | let dataDir: string; | |
| 63 | let work: string; | |
| 64 | let app: App; | |
| 65 | let servers: Servers; | |
| 66 | let runtime: AppsRuntime; | |
| 67 | let alice: User; | |
| 68 | let bob: User; | |
| 69 | let carol: User; | |
| 70 | let repo: Repo; | |
| 71 | let fork: Repo; | |
| 72 | let vault: Repo; | |
| 73 | let pullNumber = 0; | |
| 74 | let aliceToken = ""; | |
| 75 | let aliceRwToken = ""; | |
| 76 | let bobToken = ""; | |
| 77 | ||
| 78 | const call = ( | |
| 79 | path: string, | |
| 80 | init: RequestInit & { token?: string; follow?: boolean } = {}, | |
| 81 | ): Promise<Response> => { | |
| 82 | const headers = new Headers(init.headers); | |
| 83 | if (typeof init.body === "string") | |
| 84 | headers.set("content-type", "application/json"); | |
| 85 | if (init.token !== undefined) | |
| 86 | headers.set("authorization", `Bearer ${init.token}`); | |
| 87 | return fetch(`${servers.url}${path}`, { | |
| 88 | ...init, | |
| 89 | headers, | |
| 90 | redirect: init.follow === true ? "follow" : "manual", | |
| 91 | }); | |
| 92 | }; | |
| 93 | ||
| 94 | const transfer = (path: string, newOwner: unknown, token = aliceToken) => | |
| 95 | call(`/api/v1/repos/${path}/transfer`, { | |
| 96 | method: "POST", | |
| 97 | token, | |
| 98 | body: JSON.stringify({ newOwner }), | |
| 99 | }); | |
| 100 | ||
| 101 | const viaHost = (host: string) => | |
| 102 | fetch(`${servers.url}/`, { headers: { host }, redirect: "manual" }); | |
| 103 | ||
| 104 | async function settled(env: string, timeoutMs = 60_000): Promise<Run> { | |
| 105 | const deadline = Date.now() + timeoutMs; | |
| 106 | while (Date.now() < deadline) { | |
| 107 | const run = listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).find( | |
| 108 | (r) => r.env === env, | |
| 109 | ); | |
| 110 | if (run && ["ok", "failed", "cancelled"].includes(run.state)) return run; | |
| 111 | await Bun.sleep(100); | |
| 112 | } | |
| 113 | throw new Error(`${env} did not settle`); | |
| 114 | } | |
| 115 | ||
| 116 | const person = async (username: string): Promise<User> => { | |
| 117 | const made = await createUser(app.db, { | |
| 118 | username, | |
| 119 | email: `${username}@forge.test`, | |
| 120 | password: `${username}-long-passphrase`, | |
| 121 | }); | |
| 122 | if (!made.ok) throw new Error(made.error); | |
| 123 | return made.value; | |
| 124 | }; | |
| 125 | ||
| 126 | beforeAll(async () => { | |
| 127 | dataDir = await mkdtemp(join(tmpdir(), "forge-transfer-")); | |
| 128 | work = await mkdtemp(join(tmpdir(), "forge-transfer-work-")); | |
| 129 | app = createApp({ dataDir, port: 0 }); | |
| 130 | servers = await serve(app); | |
| 131 | runtime = new AppsRuntime(app, { | |
| 132 | domain: DOMAIN, | |
| 133 | scheme: "http", | |
| 134 | publicPort: servers.port, | |
| 135 | forgeUrl: servers.url, | |
| 136 | concurrency: 2, | |
| 137 | }); | |
| 138 | await runtime.start(); | |
| 139 | alice = await person("alice"); | |
| 140 | bob = await person("bob"); | |
| 141 | carol = await person("carol"); | |
| 142 | aliceToken = createToken(app.db, alice.id, "t", "admin").token; | |
| 143 | aliceRwToken = createToken(app.db, alice.id, "t", "rw").token; | |
| 144 | bobToken = createToken(app.db, bob.id, "t", "admin").token; | |
| 145 | if (!createOrg(app, alice, "forge").ok) throw new Error("org"); | |
| 146 | if (!createOrg(app, carol, "elsewhere").ok) throw new Error("org"); | |
| 147 | ||
| 148 | // A repository with an app, running in production… | |
| 149 | const made = await newApp(app, alice, { | |
| 150 | name: "hello", | |
| 151 | description: "notes", | |
| 152 | visibility: "public", | |
| 153 | }); | |
| 154 | if (!made.ok) throw new Error(String(made.error)); | |
| 155 | repo = made.value.repo; | |
| 156 | expect((await settled("production")).state).toBe("ok"); | |
| 157 | ||
| 158 | // …an open pull with a live preview… | |
| 159 | const committed = await commitToBranch(app, alice, repo, { | |
| 160 | branch: "greeting", | |
| 161 | base: repo.defaultBranch, | |
| 162 | message: "Say hello", | |
| 163 | files: [{ path: "GREETING.md", content: "hi\n" }], | |
| 164 | }); | |
| 165 | if (!committed.ok) throw new Error(String(committed.error)); | |
| 166 | const opened = await openPull(app, alice, repo, { | |
| 167 | title: "Say hello", | |
| 168 | baseBranch: repo.defaultBranch, | |
| 169 | headBranch: "greeting", | |
| 170 | }); | |
| 171 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 172 | pullNumber = opened.value.number; | |
| 173 | expect((await settled(`pull-${pullNumber}`)).state).toBe("ok"); | |
| 174 | ||
| 175 | // …and a fork that borrows its objects. | |
| 176 | const forked = await forkRepo(app, bob, repo); | |
| 177 | if (!forked.ok) throw new Error(String(forked.error)); | |
| 178 | fork = forked.value; | |
| 179 | ||
| 180 | const shut = await createRepo(app, alice, { name: "vault" }); | |
| 181 | if (!shut.ok) throw new Error(String(shut.error)); | |
| 182 | vault = shut.value; | |
| 183 | }, 180_000); | |
| 184 | ||
| 185 | afterAll(async () => { | |
| 186 | await runtime.stop(); | |
| 187 | servers.stop(); | |
| 188 | app.close(); | |
| 189 | await rm(dataDir, { recursive: true, force: true }); | |
| 190 | await rm(work, { recursive: true, force: true }); | |
| 191 | }); | |
| 192 | ||
| 193 | test("only an admin of the repository, into an owner they may fill", async () => { | |
| 194 | // Bob can read it but does not administer it: it is not there for him. | |
| 195 | expect((await transfer("alice/hello", "bob", bobToken)).status).toBe(404); | |
| 196 | // An org alice does not administer. | |
| 197 | const elsewhere = await transfer("alice/hello", "elsewhere"); | |
| 198 | expect(elsewhere.status).toBe(403); | |
| 199 | expect(await elsewhere.json()).toEqual({ error: "forbidden_owner" }); | |
| 200 | // Another person's account is theirs to fill, not alice's. | |
| 201 | expect((await transfer("alice/hello", "carol")).status).toBe(403); | |
| 202 | expect( | |
| 203 | ((await (await transfer("alice/hello", "nobody")).json()) as { | |
| 204 | error: string; | |
| 205 | }).error, | |
| 206 | ).toBe("unknown_owner"); | |
| 207 | for (const bad of ["../x", "", 7, "a/b"]) { | |
| 208 | const res = await transfer("alice/hello", bad); | |
| 209 | expect(res.status).toBe(422); | |
| 210 | expect(((await res.json()) as { error: string }).error).toBe( | |
| 211 | "invalid_owner", | |
| 212 | ); | |
| 213 | } | |
| 214 | expect( | |
| 215 | ((await (await transfer("alice/hello", "alice")).json()) as { | |
| 216 | error: string; | |
| 217 | }).error, | |
| 218 | ).toBe("same_owner"); | |
| 219 | // An rw token is not enough for an admin act. | |
| 220 | expect((await transfer("alice/hello", "forge", aliceRwToken)).status).toBe( | |
| 221 | 403, | |
| 222 | ); | |
| 223 | // Nothing moved. | |
| 224 | expect(getRepo(app.db, "alice", "hello")?.id).toBe(repo.id); | |
| 225 | expect(redirectsTo(app.db, repo.id)).toEqual([]); | |
| 226 | }); | |
| 227 | ||
| 228 | test("a name the destination already has is refused, and nothing moves", async () => { | |
| 229 | const clash = await createRepo(app, carol, { name: "vault" }); | |
| 230 | expect(clash.ok).toBe(true); | |
| 231 | const moved = await transferRepo(app, alice, vault, "carol"); | |
| 232 | // Alice cannot fill carol's account at all; as a site admin would: | |
| 233 | expect(moved.ok).toBe(false); | |
| 234 | const admin = { ...alice, isAdmin: true }; | |
| 235 | const taken = await transferRepo(app, admin, vault, "carol"); | |
| 236 | expect(taken.ok ? "moved" : taken.error).toBe("name_taken"); | |
| 237 | expect(getRepo(app.db, "alice", "vault")?.id).toBe(vault.id); | |
| 238 | }); | |
| 239 | ||
| 240 | test("the move: same repository, new home, everything still attached", async () => { | |
| 241 | const oldDir = repoDir(app.reposRoot, "alice", "hello"); | |
| 242 | const tip = await resolveOid(oldDir, "refs/heads/main"); | |
| 243 | const res = await transfer("alice/hello", "forge"); | |
| 244 | expect(res.status).toBe(200); | |
| 245 | const body = (await res.json()) as Repo; | |
| 246 | expect(body.id).toBe(repo.id); | |
| 247 | expect(body.ownerName).toBe("forge"); | |
| 248 | repo = getRepoById(app.db, repo.id)!; | |
| 249 | ||
| 250 | // On disk: the bare repo moved, whole. | |
| 251 | expect(existsSync(oldDir)).toBe(false); | |
| 252 | const newDir = repoDir(app.reposRoot, "forge", "hello"); | |
| 253 | expect(await resolveOid(newDir, "refs/heads/main")).toBe(tip!); | |
| 254 | // The pull is the same pull, still open, on the same repository. | |
| 255 | expect(getPull(app.db, repo.id, pullNumber)?.state).toBe("open"); | |
| 256 | // The fork still follows it, and can still read every borrowed object. | |
| 257 | expect(getRepoById(app.db, fork.id)?.forkParentId).toBe(repo.id); | |
| 258 | const forkDir = repoDir(app.reposRoot, "bob", "hello"); | |
| 259 | const fsck = await runGit(["fsck", "--connectivity-only", "--no-dangling"], { | |
| 260 | cwd: forkDir, | |
| 261 | }); | |
| 262 | expect(fsck.ok).toBe(true); | |
| 263 | const following = await call("/api/v1/repos/bob/hello/following", { | |
| 264 | token: bobToken, | |
| 265 | }); | |
| 266 | expect(following.status).toBe(200); | |
| 267 | expect(((await following.json()) as { parent: string }).parent).toBe( | |
| 268 | "forge/hello", | |
| 269 | ); | |
| 270 | // The app and its preview never stopped answering. | |
| 271 | expect((await viaHost(`hello.${DOMAIN}`)).status).toBe(200); | |
| 272 | expect((await viaHost(`hello--${pullNumber}.${DOMAIN}`)).status).toBe(200); | |
| 273 | // Said once, in the outbox. | |
| 274 | const said = listEvents(app.db, { | |
| 275 | repoId: repo.id, | |
| 276 | kind: "repo.transferred", | |
| 277 | }); | |
| 278 | expect(said.map((e) => e.payload)).toEqual([ | |
| 279 | { from: "alice/hello", to: "forge/hello" }, | |
| 280 | ]); | |
| 281 | }); | |
| 282 | ||
| 283 | test("every old page answers with the new one, path and query kept", async () => { | |
| 284 | for (const [from, to] of [ | |
| 285 | ["/alice/hello", "/forge/hello"], | |
| 286 | ["/alice/hello/pulls/1?tab=files", "/forge/hello/pulls/1?tab=files"], | |
| 287 | ["/alice/hello/blob/main/GREETING.md", "/forge/hello/blob/main/GREETING.md"], | |
| 288 | ["/ALICE/Hello/issues", "/forge/hello/issues"], | |
| 289 | ] as const) { | |
| 290 | const res = await call(from); | |
| 291 | expect(res.status).toBe(301); | |
| 292 | expect(res.headers.get("location")).toBe(`${servers.url}${to}`); | |
| 293 | // The floor is on the redirect too. | |
| 294 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 295 | } | |
| 296 | // An old form post keeps its method and body. | |
| 297 | const post = await call("/alice/hello/app/production/redeploy", { | |
| 298 | method: "POST", | |
| 299 | }); | |
| 300 | expect(post.status).toBe(308); | |
| 301 | // The owner did not move: alice's profile is still alice's. | |
| 302 | expect((await call("/alice")).status).toBe(200); | |
| 303 | }); | |
| 304 | ||
| 305 | test("the API's old paths redirect, and a client that follows gets the answer", async () => { | |
| 306 | const res = await call("/api/v1/repos/alice/hello", { token: aliceToken }); | |
| 307 | expect(res.status).toBe(301); | |
| 308 | expect(res.headers.get("location")).toBe( | |
| 309 | `${servers.url}/api/v1/repos/forge/hello`, | |
| 310 | ); | |
| 311 | const pull = await call(`/api/v1/repos/alice/hello/pulls/${pullNumber}`, { | |
| 312 | token: aliceToken, | |
| 313 | follow: true, | |
| 314 | }); | |
| 315 | expect(pull.status).toBe(200); | |
| 316 | expect(((await pull.json()) as { number: number }).number).toBe(pullNumber); | |
| 317 | const write = await call("/api/v1/repos/alice/hello/issues", { | |
| 318 | method: "POST", | |
| 319 | token: aliceToken, | |
| 320 | body: JSON.stringify({ title: "x" }), | |
| 321 | }); | |
| 322 | expect(write.status).toBe(308); | |
| 323 | expect(write.headers.get("location")).toBe( | |
| 324 | `${servers.url}/api/v1/repos/forge/hello/issues`, | |
| 325 | ); | |
| 326 | // The same token works at the new path, unchanged. | |
| 327 | const issue = await call("/api/v1/repos/forge/hello/issues", { | |
| 328 | method: "POST", | |
| 329 | token: aliceToken, | |
| 330 | body: JSON.stringify({ title: "filed after the move" }), | |
| 331 | }); | |
| 332 | expect(issue.status).toBe(201); | |
| 333 | }); | |
| 334 | ||
| 335 | test("git over HTTP follows: clone and push through the old remote", async () => { | |
| 336 | const dir = join(work, "clone"); | |
| 337 | const old = `http://alice:${aliceToken}@${new URL(servers.url).host}/alice/hello.git`; | |
| 338 | const cloned = await git(["clone", "--quiet", old, dir], work); | |
| 339 | expect(cloned.code).toBe(0); | |
| 340 | expect(existsSync(join(dir, "forge.json"))).toBe(true); | |
| 341 | await Bun.write(join(dir, "MOVED.md"), "still here\n"); | |
| 342 | expect((await git(["add", "MOVED.md"], dir)).code).toBe(0); | |
| 343 | expect((await git(["commit", "-qm", "after the move"], dir)).code).toBe(0); | |
| 344 | const pushed = await git(["push", "-q", old, "HEAD:refs/heads/moved"], dir); | |
| 345 | expect(pushed.code).toBe(0); | |
| 346 | const head = (await git(["rev-parse", "HEAD"], dir)).out; | |
| 347 | expect( | |
| 348 | await resolveOid( | |
| 349 | repoDir(app.reposRoot, "forge", "hello"), | |
| 350 | "refs/heads/moved", | |
| 351 | ), | |
| 352 | ).toBe(head); | |
| 353 | // And nothing was push-created at the old path. | |
| 354 | expect(getRepo(app.db, "alice", "hello")).toBeUndefined(); | |
| 355 | }, 60_000); | |
| 356 | ||
| 357 | test("over SSH the old path serves the repository and says where it went", () => { | |
| 358 | const found = findGitRepo(app.db, "alice", "hello", undefined); | |
| 359 | expect(found.repo?.id).toBe(repo.id); | |
| 360 | expect(found.moved).toBe( | |
| 361 | "alice/hello has moved to forge/hello; point your remote at forge/hello.git", | |
| 362 | ); | |
| 363 | expect(findGitRepo(app.db, "forge", "hello", undefined).moved).toBe( | |
| 364 | undefined, | |
| 365 | ); | |
| 366 | }); | |
| 367 | ||
| 368 | test("a private repository's old address tells a stranger nothing", async () => { | |
| 369 | const moved = await transferRepo(app, alice, vault, "forge"); | |
| 370 | expect(moved.ok).toBe(true); | |
| 371 | // Anonymous, and bob who cannot read it: the plain miss, never a 301. | |
| 372 | expect((await call("/alice/vault")).status).toBe(404); | |
| 373 | expect( | |
| 374 | (await call("/api/v1/repos/alice/vault", { token: bobToken })).status, | |
| 375 | ).toBe(404); | |
| 376 | expect((await call("/alice/vault.git/info/refs?service=git-upload-pack")).status).toBe(401); | |
| 377 | expect(findGitRepo(app.db, "alice", "vault", bob)).toEqual({ | |
| 378 | repo: undefined, | |
| 379 | }); | |
| 380 | // Alice, who can, is sent on. | |
| 381 | const her = await call("/api/v1/repos/alice/vault", { token: aliceToken }); | |
| 382 | expect(her.status).toBe(301); | |
| 383 | expect(her.headers.get("location")).toEndWith("/api/v1/repos/forge/vault"); | |
| 384 | }); | |
| 385 | ||
| 386 | test("a repository made at the old path takes it back", async () => { | |
| 387 | const again = await createRepo(app, alice, { name: "vault" }); | |
| 388 | expect(again.ok).toBe(true); | |
| 389 | const res = await call("/api/v1/repos/alice/vault", { token: aliceToken }); | |
| 390 | expect(res.status).toBe(200); | |
| 391 | expect(((await res.json()) as Repo).id).not.toBe(vault.id); | |
| 392 | expect(redirectsTo(app.db, vault.id)).toEqual([]); | |
| 393 | }); | |
| 394 | ||
| 395 | test("moving again: every old address follows the repository, not the path", async () => { | |
| 396 | // Bob cannot fill an org he is not in; alice moves it home. | |
| 397 | const back = await transfer("forge/hello", "alice"); | |
| 398 | expect(back.status).toBe(200); | |
| 399 | // Where it lives now is live, not a redirect… | |
| 400 | expect((await call("/alice/hello")).status).toBe(200); | |
| 401 | // …and where it just was points here. | |
| 402 | const from = await call("/forge/hello/pulls"); | |
| 403 | expect(from.status).toBe(301); | |
| 404 | expect(from.headers.get("location")).toBe( | |
| 405 | `${servers.url}/alice/hello/pulls`, | |
| 406 | ); | |
| 407 | expect(redirectsTo(app.db, repo.id)).toEqual([ | |
| 408 | { owner: "forge", name: "hello" }, | |
| 409 | ]); | |
| 410 | // The fork was told twice and can still read everything. | |
| 411 | const fsck = await runGit(["fsck", "--connectivity-only", "--no-dangling"], { | |
| 412 | cwd: repoDir(app.reposRoot, "bob", "hello"), | |
| 413 | }); | |
| 414 | expect(fsck.ok).toBe(true); | |
| 415 | expect((await viaHost(`hello--${pullNumber}.${DOMAIN}`)).status).toBe(200); | |
| 416 | }); | |
| 417 | ||
| 418 | test("people move it from the danger zone, same rules, same-origin only", async () => { | |
| 419 | const cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 420 | const page = await call("/alice/hello/settings/danger", { | |
| 421 | headers: { cookie }, | |
| 422 | }); | |
| 423 | expect(page.status).toBe(200); | |
| 424 | expect(await page.text()).toContain("Move to another owner"); | |
| 425 | const post = (newOwner: string, headers: Record<string, string> = {}) => | |
| 426 | call("/alice/hello/settings/transfer", { | |
| 427 | method: "POST", | |
| 428 | headers: { cookie, ...headers }, | |
| 429 | body: new URLSearchParams({ newOwner }), | |
| 430 | }); | |
| 431 | // Another site's page cannot ride alice's session into a move. | |
| 432 | await post("forge", { origin: "http://evil.example" }); | |
| 433 | expect(getRepoById(app.db, repo.id)?.ownerName).toBe("alice"); | |
| 434 | // An org she does not administer: refused, said, nothing moved. | |
| 435 | expect((await post("elsewhere")).status).toBe(303); | |
| 436 | expect(getRepoById(app.db, repo.id)?.ownerName).toBe("alice"); | |
| 437 | const moved = await post("forge"); | |
| 438 | expect(moved.status).toBe(303); | |
| 439 | expect(new URL(moved.headers.get("location")!, servers.url).pathname).toBe( | |
| 440 | "/forge/hello", | |
| 441 | ); | |
| 442 | expect(getRepoById(app.db, repo.id)?.ownerName).toBe("forge"); | |
| 443 | expect((await call("/alice/hello")).status).toBe(301); | |
| 444 | }); | |
| 445 | }); |
new above
offline