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 #549

Closed opened this in answer to
Closed without merging

torque/forge:torque/488-repo-transfer-with-redirects-move-a-repo → main 6 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
19 files changed +1063 −19
README.md +7
@@ -461,6 +461,13 @@ work here.
461461 pull requests (fork → upstream) and detach-before-delete safety.
462462 - **Organizations & teams** — orgs own repos; teams grant read/write/admin
463463 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.
464471 - **Live updates** — a server-sent-event stream turns comment threads live and
465472 flags new activity, no refresh.
466473 - **Commit pages** — every commit's diff through the same viewer.
forge.json +1 −1
@@ -6,7 +6,7 @@
66 "ready": 90
77 },
88 "check": {
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits crew-parks 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 told-by",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits crew-parks 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 told-by transfer",
1010 "timeout": 1800
1111 }
1212 }
src/actions/repos.ts +47 −1
@@ -22,7 +22,11 @@ import {
2222 type Repo,
2323 type RepoSettings,
2424 } 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";
2630 import {
2731 createWebhook as insertWebhook,
2832 deleteWebhook as removeWebhook,
@@ -185,6 +189,48 @@ export async function deleteRepo(
185189 return ok();
186190 }
187191
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
188234 export function createLabel(
189235 app: App,
190236 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";
2020 import { createLog } from "../kernel/log.ts";
2121 import { err, ok, type Result } from "../kernel/result.ts";
2222 import { likeEscape, pageLimit } from "./issues.ts";
23 import { clearRedirect } from "./redirects.ts";
2324 import { REPO_VISIBLE, REPO_WRITABLE } from "./visibility.ts";
2425 import { accessAllows, orgAccess, type Access } from "./orgs.ts";
2526 import { getUserById, type User } from "./users.ts";
@@ -274,6 +275,7 @@ export async function createRepo(
274275 input.description ?? "",
275276 branch,
276277 );
278 clearRedirect(db, owner.username, input.name);
277279 return ok(getRepoById(db, repoId)!);
278280 }
279281
@@ -343,6 +345,7 @@ export async function forkRepo(
343345 parent.defaultBranch,
344346 parent.id,
345347 );
348 clearRedirect(db, owner.username, forkName);
346349 return ok(getRepoById(db, repoId)!);
347350 }
348351
src/core/schema.ts +38 −1
@@ -4,7 +4,10 @@
44 * truth that lives in git wherever possible — small on purpose.
55 */
66
7 export const migrations: readonly string[] = [
7 import type { Database } from "bun:sqlite";
8 import type { Migration } from "../kernel/db.ts";
9
10 export const migrations: readonly Migration[] = [
811 // 1 — foundation: users, sessions, tokens, repos, events, webhooks
912 `
1013 CREATE TABLE user (
@@ -1172,4 +1175,38 @@ export const migrations: readonly string[] = [
11721175 OR body LIKE '%without a pull: cancelled'
11731176 OR body LIKE '%interrupted by a restart%');
11741177 `,
1178 // 44 — where a repository used to live (`core/redirects.ts`). A transfer
1179 // leaves its old owner/name here so every old URL, API path and git
1180 // remote finds the repository by id, wherever it has gone since. A repo
1181 // created at that path takes it back: the row is deleted then.
1182 //
1183 // Written to survive two ordering accidents, like 37: for a while this
1184 // table was migration 42, then 43. A preview's database migrated then has
1185 // it and never ran what main put at that number. SQL cannot ask whether a
1186 // column or table exists, so this one is code: where the ledger has no
1187 // `kind`, 42 runs now, verbatim; where the table is already here, 43 runs
1188 // now, verbatim — its UPDATE matches nothing it already reworded. The
1189 // table is created only if missing.
1190 (db: Database) => {
1191 const ledger = db
1192 .query<{ name: string }, []>("SELECT name FROM pragma_table_info('usage')")
1193 .all();
1194 if (!ledger.some((c) => c.name === "kind")) db.exec(migrations[41] as string);
1195 const early = db
1196 .query<{ n: number }, []>(
1197 "SELECT COUNT(*) AS n FROM sqlite_master WHERE type = 'table' AND name = 'repo_redirect'",
1198 )
1199 .get();
1200 if (early?.n === 1) db.exec(migrations[42] as string);
1201 db.exec(`
1202 CREATE TABLE IF NOT EXISTS repo_redirect (
1203 owner_name TEXT NOT NULL COLLATE NOCASE,
1204 name TEXT NOT NULL COLLATE NOCASE,
1205 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
1206 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1207 PRIMARY KEY (owner_name, name)
1208 );
1209 CREATE INDEX IF NOT EXISTS repo_redirect_repo ON repo_redirect(repo_id);
1210 `);
1211 },
11751212 ];
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
@@ -1001,8 +1001,10 @@ async function work(
10011001 fork.value,
10021002 branch,
10031003 dir,
1004 forkBare,
1005 bare,
1004 // Read again by id: a transfer may have moved either repository
1005 // while the agent worked, and the paths from the start are stale.
1006 currentDir(app, fork.value),
1007 currentDir(app, repo),
10061008 { ...gitAuth, ...identity },
10071009 result.result,
10081010 stoppedAt === undefined
@@ -1056,6 +1058,12 @@ async function forkFor(
10561058 return ok(made.value);
10571059 }
10581060
1061 /** Where a repository's bare directory is now, read from its row by id. */
1062 function currentDir(app: App, repo: Repo): string {
1063 const now = getRepoById(app.db, repo.id) ?? repo;
1064 return repoDir(app.reposRoot, now.ownerName, now.name);
1065 }
1066
10591067 /**
10601068 * A clone on `branch`, matching what the forge holds. The clone is the
10611069 * 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> = {
108108 "pull.thread_resolved": "resolved a review thread",
109109 "repo.created": "created a repository",
110110 "repo.forked": "forked a repository",
111 "repo.transferred": "moved a repository",
111112 "repo.settings_updated": "changed repository settings",
112113 "repo.mirrored": "mirrored a repository",
113114 "repo.imported": "imported issues and pulls",
src/git/repos.ts +30 −1
@@ -5,7 +5,7 @@
55 */
66
77 import { join } from "node:path";
8 import { rm } from "node:fs/promises";
8 import { rename, rm } from "node:fs/promises";
99 import { defect } from "../kernel/error.ts";
1010 import { err, ok, type Result } from "../kernel/result.ts";
1111 import { runGit, type GitFailure } from "./env.ts";
@@ -131,3 +131,32 @@ export async function deleteRepoDir(
131131 await rm(dir, { recursive: true, force: true });
132132 return ok();
133133 }
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 {
7272 createWebhook,
7373 deleteLabel,
7474 deleteRepo,
75 transferRepo,
7576 deleteWebhook,
7677 forkRepo,
7778 updateRepoSettings,
@@ -139,7 +140,7 @@ import { isPinned } from "../core/pins.ts";
139140 import { listWebhooks } from "../core/webhooks.ts";
140141 import { diffCommit } from "../git/diff.ts";
141142 import { runGit } from "../git/env.ts";
142 import { isSafeRef, isSafeTreePath } from "../git/guard.ts";
143 import { isSafeName, isSafeRef, isSafeTreePath } from "../git/guard.ts";
143144 import { listBranches } from "../git/branches.ts";
144145 import {
145146 appView,
@@ -1162,6 +1163,24 @@ export function apiRoutes(router: Router<Handler>): void {
11621163 return json({}, 200);
11631164 });
11641165
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
11651184 router.add("GET", "/api/v1/repos/:owner/:name/events", (ctx) => {
11661185 const repo = loadRepo(ctx);
11671186 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
@@ -208,6 +208,7 @@ import {
208208 promptSourceRun,
209209 promptsSettingsPage,
210210 repoDelete,
211 repoTransfer,
211212 settingsPage,
212213 settingsUpdate,
213214 webhookCreate,
@@ -273,6 +274,7 @@ import {
273274 } from "../web/pages/origins.ts";
274275 import { pushThrough } from "../origins/push-through.ts";
275276 import { notFoundPage } from "../web/chrome.ts";
277 import { movedLocation, redirectResponse } from "./moved.ts";
276278 import { targetForShortCode } from "../origins/oauth.ts";
277279 import { apiRoutes } from "./api.ts";
278280 import { feedRoutes } from "./feed.ts";
@@ -891,6 +893,7 @@ export function buildRouter(): Router<Handler> {
891893 router.add("POST", "/:owner/:name/settings/hooks/:id/delete", webhookDelete);
892894 router.add("GET", "/:owner/:name/settings/danger", dangerPage);
893895 router.add("POST", "/:owner/:name/settings/delete", repoDelete);
896 router.add("POST", "/:owner/:name/settings/transfer", repoTransfer);
894897
895898 return router;
896899 }
@@ -1426,6 +1429,11 @@ async function answerGet(
14261429 return withRateHeaders(tooManyRequests(verdict), verdict);
14271430 }
14281431
1432 // A repository that moved answers its old address with its new one.
1433 const moved = movedLocation(app, url, matched.params, auth.user);
1434 if (moved !== undefined)
1435 return withRateHeaders(redirectResponse(moved, request.method), verdict);
1436
14291437 const themeCookie = cookieValue(request, "forge_theme") ?? "";
14301438 const modeCookieValue = cookieValue(request, "forge_mode") ?? "";
14311439 // `?mode=` on the URL is the escape hatch: a plain link a person is
src/kernel/db.ts +15 −5
@@ -32,7 +32,16 @@ const CACHE_KIB = 64 * 1024;
3232 */
3333 const MMAP_BYTES = 512 * 1024 * 1024;
3434
35 export function openDb(path: string, migrations: readonly string[]): Database {
35 /**
36 * One step of the schema: SQL, or — only where SQL cannot say it, such as
37 * "if this column is missing" — code run inside the same transaction.
38 */
39 export type Migration = string | ((db: Database) => void);
40
41 export function openDb(
42 path: string,
43 migrations: readonly Migration[],
44 ): Database {
3645 const db = new Database(path, { create: true, strict: true });
3746 applyPragmas(db);
3847 migrate(db, migrations);
@@ -120,7 +129,7 @@ export function isBusy(error: unknown): boolean {
120129 );
121130 }
122131
123 function migrate(db: Database, migrations: readonly string[]): void {
132 function migrate(db: Database, migrations: readonly Migration[]): void {
124133 const row = db
125134 .query<{ user_version: number }, []>("PRAGMA user_version")
126135 .get();
@@ -132,10 +141,11 @@ function migrate(db: Database, migrations: readonly string[]): void {
132141 );
133142 }
134143 for (let i = applied; i < migrations.length; i++) {
135 const sql = migrations[i];
136 if (!sql) defect("db.migration_missing", `migration ${i + 1} is empty`);
144 const step = migrations[i];
145 if (!step) defect("db.migration_missing", `migration ${i + 1} is empty`);
137146 db.transaction(() => {
138 db.exec(sql);
147 if (typeof step === "function") step(db);
148 else db.exec(step);
139149 // PRAGMA can't be parameterized; the value is a loop index, not input.
140150 db.exec(`PRAGMA user_version = ${i + 1}`);
141151 })();
src/tui/ssh.ts +31 −2
@@ -13,7 +13,9 @@
1313 import { join } from "node:path";
1414 import type { App as Forge } from "../app.ts";
1515 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";
1719 import { getUserById, type User } from "../core/users.ts";
1820 import { createRepo } from "../actions/repos.ts";
1921 import { hookEnv } from "../git/hooks.ts";
@@ -184,6 +186,30 @@ export function forgeSshSession(forge: Forge): (session: SshSession) => void {
184186 };
185187 }
186188
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
187213 /**
188214 * Git over an exec channel. The access matrix is exactly the HTTP one:
189215 * upload-pack → `canRead`; a guest may read a public repo.
@@ -207,7 +233,10 @@ async function serveGitCommand(
207233 }
208234
209235 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;
211240 if (!repo && write && user) {
212241 // Push-to-create, the same rule as smart HTTP: an authed owner (or org
213242 // writer) pushing to a repo that does not exist makes it.
src/web/pages/settings.ts +58 −1
@@ -52,11 +52,14 @@ import {
5252 setCrewRole,
5353 } from "../../core/agents.ts";
5454 import { isAutonomy } from "../../core/repos.ts";
55 import { isSafeName } from "../../git/guard.ts";
56 import { err } from "../../kernel/result.ts";
5557 import {
5658 createLabel,
5759 createWebhook,
5860 deleteLabel,
5961 deleteRepo,
62 transferRepo,
6063 deleteWebhook,
6164 updateLabel,
6265 updateRepoSettings,
@@ -1697,6 +1700,26 @@ export function dangerPage(ctx: Ctx): Response {
16971700 const base = repoBase(repo);
16981701 const full = `${repo.ownerName}/${repo.name}`;
16991702
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 );
17001723 const body = card(
17011724 html`<p>
17021725 Deleting <strong>${full}</strong> removes its issues, pull requests,
@@ -1719,7 +1742,41 @@ export function dangerPage(ctx: Ctx): Response {
17191742 <h2>Delete this repository</h2>`,
17201743 },
17211744 );
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 });
17231780 }
17241781
17251782 /**
test/crew-parks.test.ts +1 −1
@@ -258,7 +258,7 @@ describe("migration 43", () => {
258258 .query("INSERT INTO comment VALUES (?1, 'i', 'u', ?2)")
259259 .run(String(n), body),
260260 );
261 db.exec(migrations[42]!);
261 db.exec(migrations[42] as string);
262262 const after = db
263263 .query<{ body: string }, []>("SELECT body FROM comment ORDER BY id")
264264 .all()
test/transfer.test.ts added +554
@@ -0,0 +1,554 @@
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 type { Database } from "bun:sqlite";
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12 import { existsSync } from "node:fs";
13 import { mkdtemp, rm } from "node:fs/promises";
14 import { tmpdir } from "node:os";
15 import { join } from "node:path";
16 import { createApp, type App } from "../src/app.ts";
17 import { AppsRuntime } from "../src/apps/runtime.ts";
18 import { newApp } from "../src/actions/apps.ts";
19 import { createOrg } from "../src/actions/orgs.ts";
20 import { openPull } from "../src/actions/pulls.ts";
21 import {
22 commitToBranch,
23 createRepo,
24 forkRepo,
25 transferRepo,
26 } from "../src/actions/repos.ts";
27 import { listEvents } from "../src/core/events.ts";
28 import { migrations } from "../src/core/schema.ts";
29 import { getPull } from "../src/core/pulls.ts";
30 import { redirectsTo } from "../src/core/redirects.ts";
31 import { getRepo, getRepoById, type Repo } from "../src/core/repos.ts";
32 import { listRuns, type Run } from "../src/core/runs.ts";
33 import { createSession } from "../src/core/sessions.ts";
34 import { createToken } from "../src/core/tokens.ts";
35 import { createUser, type User } from "../src/core/users.ts";
36 import { runGit } from "../src/git/env.ts";
37 import { resolveOid } from "../src/git/merge.ts";
38 import { repoDir } from "../src/git/repos.ts";
39 import { serve, type Servers } from "../src/http/server.ts";
40 import { findGitRepo } from "../src/tui/ssh.ts";
41 import { openDb } from "../src/kernel/db.ts";
42 import { gitClientEnv } from "./helpers/git-client.ts";
43 import { quietLogs } from "./helpers/globals.ts";
44
45 quietLogs();
46
47 const DOMAIN = "apps.test";
48
49 async function git(args: string[], cwd: string) {
50 const proc = Bun.spawn(["git", ...args], {
51 cwd,
52 env: gitClientEnv(),
53 stdout: "pipe",
54 stderr: "pipe",
55 });
56 const [out, err, code] = await Promise.all([
57 new Response(proc.stdout).text(),
58 new Response(proc.stderr).text(),
59 proc.exited,
60 ]);
61 return { code, out: out.trim(), err: err.trim() };
62 }
63
64 describe("repo transfer with redirects", () => {
65 let dataDir: string;
66 let work: string;
67 let app: App;
68 let servers: Servers;
69 let runtime: AppsRuntime;
70 let alice: User;
71 let bob: User;
72 let carol: User;
73 let repo: Repo;
74 let fork: Repo;
75 let vault: Repo;
76 let pullNumber = 0;
77 let aliceToken = "";
78 let aliceRwToken = "";
79 let bobToken = "";
80
81 const call = (
82 path: string,
83 init: RequestInit & { token?: string; follow?: boolean } = {},
84 ): Promise<Response> => {
85 const headers = new Headers(init.headers);
86 if (typeof init.body === "string")
87 headers.set("content-type", "application/json");
88 if (init.token !== undefined)
89 headers.set("authorization", `Bearer ${init.token}`);
90 return fetch(`${servers.url}${path}`, {
91 ...init,
92 headers,
93 redirect: init.follow === true ? "follow" : "manual",
94 });
95 };
96
97 const transfer = (path: string, newOwner: unknown, token = aliceToken) =>
98 call(`/api/v1/repos/${path}/transfer`, {
99 method: "POST",
100 token,
101 body: JSON.stringify({ newOwner }),
102 });
103
104 const viaHost = (host: string) =>
105 fetch(`${servers.url}/`, { headers: { host }, redirect: "manual" });
106
107 async function settled(env: string, timeoutMs = 60_000): Promise<Run> {
108 const deadline = Date.now() + timeoutMs;
109 while (Date.now() < deadline) {
110 const run = listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).find(
111 (r) => r.env === env,
112 );
113 if (run && ["ok", "failed", "cancelled"].includes(run.state)) return run;
114 await Bun.sleep(100);
115 }
116 throw new Error(`${env} did not settle`);
117 }
118
119 const person = async (username: string): Promise<User> => {
120 const made = await createUser(app.db, {
121 username,
122 email: `${username}@forge.test`,
123 password: `${username}-long-passphrase`,
124 });
125 if (!made.ok) throw new Error(made.error);
126 return made.value;
127 };
128
129 beforeAll(async () => {
130 dataDir = await mkdtemp(join(tmpdir(), "forge-transfer-"));
131 work = await mkdtemp(join(tmpdir(), "forge-transfer-work-"));
132 app = createApp({ dataDir, port: 0 });
133 servers = await serve(app);
134 runtime = new AppsRuntime(app, {
135 domain: DOMAIN,
136 scheme: "http",
137 publicPort: servers.port,
138 forgeUrl: servers.url,
139 concurrency: 2,
140 });
141 await runtime.start();
142 alice = await person("alice");
143 bob = await person("bob");
144 carol = await person("carol");
145 aliceToken = createToken(app.db, alice.id, "t", "admin").token;
146 aliceRwToken = createToken(app.db, alice.id, "t", "rw").token;
147 bobToken = createToken(app.db, bob.id, "t", "admin").token;
148 if (!createOrg(app, alice, "forge").ok) throw new Error("org");
149 if (!createOrg(app, carol, "elsewhere").ok) throw new Error("org");
150
151 // A repository with an app, running in production…
152 const made = await newApp(app, alice, {
153 name: "hello",
154 description: "notes",
155 visibility: "public",
156 });
157 if (!made.ok) throw new Error(String(made.error));
158 repo = made.value.repo;
159 expect((await settled("production")).state).toBe("ok");
160
161 // …an open pull with a live preview…
162 const committed = await commitToBranch(app, alice, repo, {
163 branch: "greeting",
164 base: repo.defaultBranch,
165 message: "Say hello",
166 files: [{ path: "GREETING.md", content: "hi\n" }],
167 });
168 if (!committed.ok) throw new Error(String(committed.error));
169 const opened = await openPull(app, alice, repo, {
170 title: "Say hello",
171 baseBranch: repo.defaultBranch,
172 headBranch: "greeting",
173 });
174 if (!opened.ok) throw new Error(String(opened.error));
175 pullNumber = opened.value.number;
176 expect((await settled(`pull-${pullNumber}`)).state).toBe("ok");
177
178 // …and a fork that borrows its objects.
179 const forked = await forkRepo(app, bob, repo);
180 if (!forked.ok) throw new Error(String(forked.error));
181 fork = forked.value;
182
183 const shut = await createRepo(app, alice, { name: "vault" });
184 if (!shut.ok) throw new Error(String(shut.error));
185 vault = shut.value;
186 }, 180_000);
187
188 afterAll(async () => {
189 await runtime.stop();
190 servers.stop();
191 app.close();
192 await rm(dataDir, { recursive: true, force: true });
193 await rm(work, { recursive: true, force: true });
194 });
195
196 test("only an admin of the repository, into an owner they may fill", async () => {
197 // Bob can read it but does not administer it: it is not there for him.
198 expect((await transfer("alice/hello", "bob", bobToken)).status).toBe(404);
199 // An org alice does not administer.
200 const elsewhere = await transfer("alice/hello", "elsewhere");
201 expect(elsewhere.status).toBe(403);
202 expect(await elsewhere.json()).toEqual({ error: "forbidden_owner" });
203 // Another person's account is theirs to fill, not alice's.
204 expect((await transfer("alice/hello", "carol")).status).toBe(403);
205 expect(
206 ((await (await transfer("alice/hello", "nobody")).json()) as {
207 error: string;
208 }).error,
209 ).toBe("unknown_owner");
210 for (const bad of ["../x", "", 7, "a/b"]) {
211 const res = await transfer("alice/hello", bad);
212 expect(res.status).toBe(422);
213 expect(((await res.json()) as { error: string }).error).toBe(
214 "invalid_owner",
215 );
216 }
217 expect(
218 ((await (await transfer("alice/hello", "alice")).json()) as {
219 error: string;
220 }).error,
221 ).toBe("same_owner");
222 // An rw token is not enough for an admin act.
223 expect((await transfer("alice/hello", "forge", aliceRwToken)).status).toBe(
224 403,
225 );
226 // Nothing moved.
227 expect(getRepo(app.db, "alice", "hello")?.id).toBe(repo.id);
228 expect(redirectsTo(app.db, repo.id)).toEqual([]);
229 });
230
231 test("a name the destination already has is refused, and nothing moves", async () => {
232 const clash = await createRepo(app, carol, { name: "vault" });
233 expect(clash.ok).toBe(true);
234 const moved = await transferRepo(app, alice, vault, "carol");
235 // Alice cannot fill carol's account at all; as a site admin would:
236 expect(moved.ok).toBe(false);
237 const admin = { ...alice, isAdmin: true };
238 const taken = await transferRepo(app, admin, vault, "carol");
239 expect(taken.ok ? "moved" : taken.error).toBe("name_taken");
240 expect(getRepo(app.db, "alice", "vault")?.id).toBe(vault.id);
241 });
242
243 test("the move: same repository, new home, everything still attached", async () => {
244 const oldDir = repoDir(app.reposRoot, "alice", "hello");
245 const tip = await resolveOid(oldDir, "refs/heads/main");
246 const res = await transfer("alice/hello", "forge");
247 expect(res.status).toBe(200);
248 const body = (await res.json()) as Repo;
249 expect(body.id).toBe(repo.id);
250 expect(body.ownerName).toBe("forge");
251 repo = getRepoById(app.db, repo.id)!;
252
253 // On disk: the bare repo moved, whole.
254 expect(existsSync(oldDir)).toBe(false);
255 const newDir = repoDir(app.reposRoot, "forge", "hello");
256 expect(await resolveOid(newDir, "refs/heads/main")).toBe(tip!);
257 // The pull is the same pull, still open, on the same repository.
258 expect(getPull(app.db, repo.id, pullNumber)?.state).toBe("open");
259 // The fork still follows it, and can still read every borrowed object.
260 expect(getRepoById(app.db, fork.id)?.forkParentId).toBe(repo.id);
261 const forkDir = repoDir(app.reposRoot, "bob", "hello");
262 const fsck = await runGit(["fsck", "--connectivity-only", "--no-dangling"], {
263 cwd: forkDir,
264 });
265 expect(fsck.ok).toBe(true);
266 const following = await call("/api/v1/repos/bob/hello/following", {
267 token: bobToken,
268 });
269 expect(following.status).toBe(200);
270 expect(((await following.json()) as { parent: string }).parent).toBe(
271 "forge/hello",
272 );
273 // The app and its preview never stopped answering.
274 expect((await viaHost(`hello.${DOMAIN}`)).status).toBe(200);
275 expect((await viaHost(`hello--${pullNumber}.${DOMAIN}`)).status).toBe(200);
276 // Said once, in the outbox.
277 const said = listEvents(app.db, {
278 repoId: repo.id,
279 kind: "repo.transferred",
280 });
281 expect(said.map((e) => e.payload)).toEqual([
282 { from: "alice/hello", to: "forge/hello" },
283 ]);
284 });
285
286 test("every old page answers with the new one, path and query kept", async () => {
287 for (const [from, to] of [
288 ["/alice/hello", "/forge/hello"],
289 ["/alice/hello/pulls/1?tab=files", "/forge/hello/pulls/1?tab=files"],
290 ["/alice/hello/blob/main/GREETING.md", "/forge/hello/blob/main/GREETING.md"],
291 ["/ALICE/Hello/issues", "/forge/hello/issues"],
292 ] as const) {
293 const res = await call(from);
294 expect(res.status).toBe(301);
295 expect(res.headers.get("location")).toBe(`${servers.url}${to}`);
296 // The floor is on the redirect too.
297 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
298 }
299 // An old form post keeps its method and body.
300 const post = await call("/alice/hello/app/production/redeploy", {
301 method: "POST",
302 });
303 expect(post.status).toBe(308);
304 // The owner did not move: alice's profile is still alice's.
305 expect((await call("/alice")).status).toBe(200);
306 });
307
308 test("the API's old paths redirect, and a client that follows gets the answer", async () => {
309 const res = await call("/api/v1/repos/alice/hello", { token: aliceToken });
310 expect(res.status).toBe(301);
311 expect(res.headers.get("location")).toBe(
312 `${servers.url}/api/v1/repos/forge/hello`,
313 );
314 const pull = await call(`/api/v1/repos/alice/hello/pulls/${pullNumber}`, {
315 token: aliceToken,
316 follow: true,
317 });
318 expect(pull.status).toBe(200);
319 expect(((await pull.json()) as { number: number }).number).toBe(pullNumber);
320 const write = await call("/api/v1/repos/alice/hello/issues", {
321 method: "POST",
322 token: aliceToken,
323 body: JSON.stringify({ title: "x" }),
324 });
325 expect(write.status).toBe(308);
326 expect(write.headers.get("location")).toBe(
327 `${servers.url}/api/v1/repos/forge/hello/issues`,
328 );
329 // The same token works at the new path, unchanged.
330 const issue = await call("/api/v1/repos/forge/hello/issues", {
331 method: "POST",
332 token: aliceToken,
333 body: JSON.stringify({ title: "filed after the move" }),
334 });
335 expect(issue.status).toBe(201);
336 });
337
338 test("git over HTTP follows: clone and push through the old remote", async () => {
339 const dir = join(work, "clone");
340 const old = `http://alice:${aliceToken}@${new URL(servers.url).host}/alice/hello.git`;
341 const cloned = await git(["clone", "--quiet", old, dir], work);
342 expect(cloned.code).toBe(0);
343 expect(existsSync(join(dir, "forge.json"))).toBe(true);
344 await Bun.write(join(dir, "MOVED.md"), "still here\n");
345 expect((await git(["add", "MOVED.md"], dir)).code).toBe(0);
346 expect((await git(["commit", "-qm", "after the move"], dir)).code).toBe(0);
347 const pushed = await git(["push", "-q", old, "HEAD:refs/heads/moved"], dir);
348 expect(pushed.code).toBe(0);
349 const head = (await git(["rev-parse", "HEAD"], dir)).out;
350 expect(
351 await resolveOid(
352 repoDir(app.reposRoot, "forge", "hello"),
353 "refs/heads/moved",
354 ),
355 ).toBe(head);
356 // And nothing was push-created at the old path.
357 expect(getRepo(app.db, "alice", "hello")).toBeUndefined();
358 }, 60_000);
359
360 test("over SSH the old path serves the repository and says where it went", () => {
361 const found = findGitRepo(app.db, "alice", "hello", undefined);
362 expect(found.repo?.id).toBe(repo.id);
363 expect(found.moved).toBe(
364 "alice/hello has moved to forge/hello; point your remote at forge/hello.git",
365 );
366 expect(findGitRepo(app.db, "forge", "hello", undefined).moved).toBe(
367 undefined,
368 );
369 });
370
371 test("a private repository's old address tells a stranger nothing", async () => {
372 const moved = await transferRepo(app, alice, vault, "forge");
373 expect(moved.ok).toBe(true);
374 // Anonymous, and bob who cannot read it: the plain miss, never a 301.
375 expect((await call("/alice/vault")).status).toBe(404);
376 expect(
377 (await call("/api/v1/repos/alice/vault", { token: bobToken })).status,
378 ).toBe(404);
379 expect((await call("/alice/vault.git/info/refs?service=git-upload-pack")).status).toBe(401);
380 expect(findGitRepo(app.db, "alice", "vault", bob)).toEqual({
381 repo: undefined,
382 });
383 // Alice, who can, is sent on.
384 const her = await call("/api/v1/repos/alice/vault", { token: aliceToken });
385 expect(her.status).toBe(301);
386 expect(her.headers.get("location")).toEndWith("/api/v1/repos/forge/vault");
387 });
388
389 test("a repository made at the old path takes it back", async () => {
390 const again = await createRepo(app, alice, { name: "vault" });
391 expect(again.ok).toBe(true);
392 const res = await call("/api/v1/repos/alice/vault", { token: aliceToken });
393 expect(res.status).toBe(200);
394 expect(((await res.json()) as Repo).id).not.toBe(vault.id);
395 expect(redirectsTo(app.db, vault.id)).toEqual([]);
396 });
397
398 test("moving again: every old address follows the repository, not the path", async () => {
399 // Bob cannot fill an org he is not in; alice moves it home.
400 const back = await transfer("forge/hello", "alice");
401 expect(back.status).toBe(200);
402 // Where it lives now is live, not a redirect…
403 expect((await call("/alice/hello")).status).toBe(200);
404 // …and where it just was points here.
405 const from = await call("/forge/hello/pulls");
406 expect(from.status).toBe(301);
407 expect(from.headers.get("location")).toBe(
408 `${servers.url}/alice/hello/pulls`,
409 );
410 expect(redirectsTo(app.db, repo.id)).toEqual([
411 { owner: "forge", name: "hello" },
412 ]);
413 // The fork was told twice and can still read everything.
414 const fsck = await runGit(["fsck", "--connectivity-only", "--no-dangling"], {
415 cwd: repoDir(app.reposRoot, "bob", "hello"),
416 });
417 expect(fsck.ok).toBe(true);
418 expect((await viaHost(`hello--${pullNumber}.${DOMAIN}`)).status).toBe(200);
419 });
420
421 test("people move it from the danger zone, same rules, same-origin only", async () => {
422 const cookie = `forge_session=${createSession(app.db, alice.id).token}`;
423 const page = await call("/alice/hello/settings/danger", {
424 headers: { cookie },
425 });
426 expect(page.status).toBe(200);
427 expect(await page.text()).toContain("Move to another owner");
428 const post = (newOwner: string, headers: Record<string, string> = {}) =>
429 call("/alice/hello/settings/transfer", {
430 method: "POST",
431 headers: { cookie, ...headers },
432 body: new URLSearchParams({ newOwner }),
433 });
434 // Another site's page cannot ride alice's session into a move.
435 await post("forge", { origin: "http://evil.example" });
436 expect(getRepoById(app.db, repo.id)?.ownerName).toBe("alice");
437 // An org she does not administer: refused, said, nothing moved.
438 expect((await post("elsewhere")).status).toBe(303);
439 expect(getRepoById(app.db, repo.id)?.ownerName).toBe("alice");
440 const moved = await post("forge");
441 expect(moved.status).toBe(303);
442 expect(new URL(moved.headers.get("location")!, servers.url).pathname).toBe(
443 "/forge/hello",
444 );
445 expect(getRepoById(app.db, repo.id)?.ownerName).toBe("forge");
446 expect((await call("/alice/hello")).status).toBe(301);
447 });
448 });
449
450 describe("the redirect table's migration", () => {
451 const has = (db: Database, type: string, name: string): boolean =>
452 db
453 .query<{ n: number }, [string, string]>(
454 "SELECT COUNT(*) AS n FROM sqlite_master WHERE type = ?1 AND name = ?2",
455 )
456 .get(type, name)!.n === 1;
457 // The redirect table as this branch first wrote it, before any repair.
458 const early = `
459 CREATE TABLE repo_redirect (
460 owner_name TEXT NOT NULL COLLATE NOCASE,
461 name TEXT NOT NULL COLLATE NOCASE,
462 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
463 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
464 PRIMARY KEY (owner_name, name)
465 );
466 CREATE INDEX repo_redirect_repo ON repo_redirect(repo_id);`;
467 const ledgerHasKind = (db: Database): boolean =>
468 db
469 .query<{ name: string }, []>("SELECT name FROM pragma_table_info('usage')")
470 .all()
471 .some((c) => c.name === "kind");
472
473 test("repairs a database that took the redirect table as 42 and never ran the credential migration", async () => {
474 const dir = await mkdtemp(join(tmpdir(), "forge-redirect-mig-"));
475 try {
476 const path = join(dir, "forge.db");
477 // What pull #501's preview held: 1–41, then repo_redirect alone as 42.
478 const before = openDb(path, [...migrations.slice(0, 41), early]);
479 expect(has(before, "table", "repo_redirect")).toBe(true);
480 expect(ledgerHasKind(before)).toBe(false);
481 before.close();
482 // Today's list boots it: 42 is skipped as applied, 44 fills the gap.
483 const after = openDb(path, migrations);
484 expect(has(after, "table", "repo_redirect")).toBe(true);
485 expect(has(after, "index", "repo_redirect_repo")).toBe(true);
486 expect(ledgerHasKind(after)).toBe(true);
487 expect(
488 after
489 .query<{ id: string }, []>("SELECT id FROM subscription WHERE id = 'platform'")
490 .get(),
491 ).not.toBeNull();
492 after.close();
493 } finally {
494 await rm(dir, { recursive: true, force: true });
495 }
496 });
497
498 test("repairs a database that took the redirect table as 43 and never reworded interrupted parks", async () => {
499 const dir = await mkdtemp(join(tmpdir(), "forge-redirect-mig-"));
500 try {
501 const path = join(dir, "forge.db");
502 // What pull #549's preview held: 1–42, then repo_redirect as 43.
503 const before = openDb(path, [...migrations.slice(0, 42), early]);
504 before.exec("PRAGMA foreign_keys = OFF");
505 before.exec(
506 "INSERT INTO comment (id, issue_id, author_id, body) VALUES ('c1', 'i1', 'u1', 'Parked by the crew: the session hit a rate limit')",
507 );
508 before.close();
509 const after = openDb(path, migrations);
510 expect(has(after, "table", "repo_redirect")).toBe(true);
511 expect(
512 after
513 .query<{ body: string }, []>("SELECT body FROM comment WHERE id = 'c1'")
514 .get()!.body,
515 ).toBe("Interrupted, not parked: the session hit a rate limit");
516 after.close();
517 } finally {
518 await rm(dir, { recursive: true, force: true });
519 }
520 });
521
522 test("is only the new table on a database that ran 42 and 43 as main wrote them", async () => {
523 const dir = await mkdtemp(join(tmpdir(), "forge-redirect-mig-"));
524 try {
525 const path = join(dir, "forge.db");
526 const before = openDb(path, migrations.slice(0, 43));
527 // A park written after 43 is a real one: 44 must not reword it.
528 before.exec("PRAGMA foreign_keys = OFF");
529 before.exec(
530 "INSERT INTO comment (id, issue_id, author_id, body) VALUES ('c1', 'i1', 'u1', 'Parked by the crew: a rate limit test kept failing')",
531 );
532 before.exec(
533 "UPDATE subscription SET name = 'renamed by its operator' WHERE id = 'platform'",
534 );
535 before.close();
536 const after = openDb(path, migrations);
537 expect(has(after, "table", "repo_redirect")).toBe(true);
538 expect(
539 after
540 .query<{ body: string }, []>("SELECT body FROM comment WHERE id = 'c1'")
541 .get()!.body,
542 ).toBe("Parked by the crew: a rate limit test kept failing");
543 // 42 did not run twice: the operator's edit is still there.
544 expect(
545 after
546 .query<{ name: string }, []>("SELECT name FROM subscription WHERE id = 'platform'")
547 .get()!.name,
548 ).toBe("renamed by its operator");
549 after.close();
550 } finally {
551 await rm(dir, { recursive: true, force: true });
552 }
553 });
554 });
test/usage.test.ts +2 −3
@@ -65,9 +65,8 @@ describe("the ledger's migration", () => {
6565 const path = join(dir, "forge.db");
6666 // What a preview migrated before the renumbering holds: 1–35, then
6767 // the ledger alone as 36 — no share table.
68 const ledger = migrations[36]!.slice(
69 migrations[36]!.indexOf("CREATE TABLE IF NOT EXISTS usage"),
70 );
68 const m37 = migrations[36] as string;
69 const ledger = m37.slice(m37.indexOf("CREATE TABLE IF NOT EXISTS usage"));
7170 const before = openDb(path, [...migrations.slice(0, 35), ledger]);
7271 const has = (db: typeof before, name: string): boolean =>
7372 db

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs