Public: anyone can read this; the crew can change it.

Migrate opens prefilled from a link, so the owner's import is one click a run can hand him #1039

Closed opened this
Closed without merging

scout/forge:scout/1006-migrate-opens-prefilled-from-a-link-so-t → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +207 −67
docs/ORIGINS.md +9
@@ -391,6 +391,15 @@ Dockerfile and no compose file (the forge runs processes), and write down
391391 what could not fit. The crew proposes; a person lands — autonomy included,
392392 exactly as for any app (docs/APPS.md).
393393
394 **A link that fills it in.** `/migrate?from=<host>/<owner>/<name>&crew=<agent>`
395 opens the form with that repository of one of your origins selected (`host`
396 is the origin's, as the picker shows it: `git.open-platform.sh`) and, when
397 `crew` names an agent, that agent chosen. It is how a run hands the owner
398 his one click. Both are matched against the lists the page already reads —
399 no extra fetch — and capped and checked like a ref. A value that matches
400 nothing selects nothing and the page says so in one line, escaped. The GET
401 never starts a job; nothing happens until Migrate is pressed.
402
394403 The clone runs as a job in the mirror's registry (`origins/jobs.ts`, kind
395404 `migrate`, owned by whoever started it — anyone else's is `not_found`).
396405 `/migrate/jobs/:job` refreshes until it stops, then lands on the repository
src/web/pages/migrate.ts +153 −65
@@ -18,6 +18,7 @@ import { listRemoteRepos, listUserOrigins } from "../../actions/origins.ts";
1818 import { accessAllows, listOrgsForUser, orgAccess } from "../../core/orgs.ts";
1919 import type { OriginRepoRow } from "../../core/origins.ts";
2020 import { scopeAllows } from "../../core/tokens.ts";
21 import { isSafeRef } from "../../git/guard.ts";
2122 import type { Ctx } from "../../http/context.ts";
2223 import type { MirrorJob, MirrorStage } from "../../origins/jobs.ts";
2324 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
@@ -41,6 +42,7 @@ interface MigrateValues {
4142 interface OriginChoices {
4243 readonly label: string;
4344 readonly id: string;
45 readonly host: string;
4446 readonly repos: readonly OriginRepoRow[];
4547 }
4648
@@ -52,6 +54,7 @@ async function originChoices(ctx: Ctx): Promise<OriginChoices[]> {
5254 if (!listed.ok || listed.value.length === 0) continue;
5355 out.push({
5456 id: origin.id,
57 host: hostLabel(origin.webUrl),
5558 label: `${origin.login} @ ${hostLabel(origin.webUrl)}`,
5659 repos: listed.value,
5760 });
@@ -69,11 +72,77 @@ function parsePick(value: string): MigrateSource | undefined {
6972 return { originId: value.slice(0, slash), fullName: value.slice(slash + 1) };
7073 }
7174
75 const LINK_CAP = 200;
76 const LINK_CHARS = /^[A-Za-z0-9._:/-]+$/;
77
78 const AGENT_CHARS = /^[A-Za-z0-9._-]+$/;
79
80 /** `<host>/<owner>/<name>`: capped, plain characters, a safe ref past the host (which may carry a port). */
81 const linkRepo = (raw: string): string => {
82 const slash = raw.indexOf("/");
83 return raw.length <= LINK_CAP &&
84 slash > 0 &&
85 LINK_CHARS.test(raw) &&
86 isSafeRef(raw.slice(slash + 1))
87 ? raw
88 : "";
89 };
90
91 /** An agent name from a link: capped, plain characters. */
92 const linkAgent = (raw: string): string =>
93 raw.length <= 64 && AGENT_CHARS.test(raw) ? raw : "";
94
95 /** What a link (`?from=<host>/<owner>/<name>&crew=<agent>`) chose, and what it missed. */
96 interface Prefill {
97 source: string;
98 agent: string;
99 notes: string[];
100 }
101
102 /**
103 * Reads the link against the lists the page already holds — no second fetch.
104 * Only a match selects anything; a miss is named, never acted on.
105 */
106 function prefillFrom(
107 q: URLSearchParams,
108 origins: readonly OriginChoices[],
109 crew: readonly string[],
110 ): Prefill {
111 const out: Prefill = { source: "", agent: "", notes: [] };
112 const from = q.get("from");
113 if (from !== null && from !== "") {
114 const wanted = linkRepo(from);
115 for (const origin of origins) {
116 const prefix = `${origin.host}/`;
117 if (wanted === "" || !wanted.startsWith(prefix)) continue;
118 const hit = origin.repos.find(
119 (r) => r.fullName === wanted.slice(prefix.length),
120 );
121 if (hit) {
122 out.source = pickValue(origin.id, hit.fullName);
123 break;
124 }
125 }
126 if (out.source === "")
127 out.notes.push(
128 `No repository ${from.slice(0, LINK_CAP)} in your origins`,
129 );
130 }
131 const agent = q.get("crew");
132 if (agent !== null && agent !== "") {
133 const wanted = linkAgent(agent);
134 if (wanted !== "" && crew.includes(wanted)) out.agent = wanted;
135 else out.notes.push(`No agent ${agent.slice(0, 64)} you can put on a crew`);
136 }
137 return out;
138 }
139
72140 function migrateForm(
73141 ctx: Ctx,
74142 values: MigrateValues,
75143 origins: readonly OriginChoices[],
76144 error?: string,
145 notes: readonly string[] = [],
77146 ): Html {
78147 const user = ctx.auth.user!;
79148 const writeOrgs = listOrgsForUser(ctx.app.db, user.id).filter((org) =>
@@ -124,6 +193,7 @@ function migrateForm(
124193 })}
125194 ${card(
126195 html`<form method="post" action="/migrate">
196 ${notes.map((n) => html`<p class="error-note" data-prefill-miss>${n}.</p>`)}
127197 <h3 class="mb">Source</h3>
128198 ${picker}
129199 ${formField({
@@ -171,48 +241,53 @@ function migrateForm(
171241 ],
172242 })}
173243 <h3 class="mb mt">Put a crew on it</h3>
174 ${crew.length === 0
175 ? html`<p class="muted small mb">
176 ${icon("bot")} No agents on this forge yet, so there is no crew to
177 hand the migration to.
178 ${user.isAdmin
179 ? html`Create one under
180 <a href="/settings/crew">Settings → Crew</a>.`
181 : html`An admin can create one under account settings → Crew.`}
182 </p>`
183 : html`${selectField({
184 label: "Agent",
185 name: "agent",
186 hint: "Joins the crew, makes the repository an app, and is told to make it run here — adapting it, not rewriting it.",
187 options: [
188 {
189 value: "",
190 label: "Nobody — just the repository",
191 selected: values.agent === "",
192 },
193 ...crew.map((agent) => ({
194 value: agent.user.username,
195 label:
196 agent.model === ""
197 ? agent.user.username
198 : `${agent.user.username} — ${agent.model}`,
199 selected: values.agent === agent.user.username,
200 })),
201 ],
202 })}
203 <div class="field">
204 <label class="check">
205 <input
206 type="checkbox"
207 name="autonomous"
208 ${values.autonomous ? raw("checked") : null}
209 />
210 <span
211 >Autonomous — green ships on its own. Off, every green
212 change waits for your look.</span
213 >
214 </label>
215 </div>`}
244 ${
245 crew.length === 0
246 ? html`<p class="muted small mb">
247 ${icon("bot")} No agents on this forge yet, so there is no crew
248 to hand the migration to.
249 ${
250 user.isAdmin
251 ? html`Create one under
252 <a href="/settings/crew">Settings → Crew</a>.`
253 : html`An admin can create one under account settings →
254 Crew.`
255 }
256 </p>`
257 : html`${selectField({
258 label: "Agent",
259 name: "agent",
260 hint: "Joins the crew, makes the repository an app, and is told to make it run here — adapting it, not rewriting it.",
261 options: [
262 {
263 value: "",
264 label: "Nobody — just the repository",
265 selected: values.agent === "",
266 },
267 ...crew.map((agent) => ({
268 value: agent.user.username,
269 label:
270 agent.model === ""
271 ? agent.user.username
272 : `${agent.user.username} — ${agent.model}`,
273 selected: values.agent === agent.user.username,
274 })),
275 ],
276 })}
277 <div class="field">
278 <label class="check">
279 <input
280 type="checkbox"
281 name="autonomous"
282 ${values.autonomous ? raw("checked") : null}
283 />
284 <span
285 >Autonomous — green ships on its own. Off, every green
286 change waits for your look.</span
287 >
288 </label>
289 </div>`
290 }
216291 <div class="form-actions">
217292 ${btn("Migrate", { variant: "primary", icon: "download" })}
218293 ${btn("Cancel", { href: "/", variant: "ghost" })}
@@ -256,12 +331,13 @@ function show(
256331 origins: readonly OriginChoices[],
257332 error?: string,
258333 status = 200,
334 notes: readonly string[] = [],
259335 ): Response {
260336 return page(
261337 {
262338 ctx,
263339 title: "Migrate",
264 body: migrateForm(ctx, values, origins, error),
340 body: migrateForm(ctx, values, origins, error, notes),
265341 scriptJs: migrateJs,
266342 },
267343 status,
@@ -272,18 +348,28 @@ function show(
272348 export async function migratePage(ctx: Ctx): Promise<Response> {
273349 if (!ctx.auth.user) return signInFirst(ctx);
274350 const q = ctx.url.searchParams;
351 const origins = await originChoices(ctx);
352 const agents = listAllAgents(ctx.app, ctx.auth.user);
353 const link = prefillFrom(
354 q,
355 origins,
356 agents.ok ? agents.value.map((a) => a.user.username) : [],
357 );
275358 return show(
276359 ctx,
277360 {
278 source: q.get("source") ?? "",
361 source: q.get("source") ?? link.source,
279362 url: q.get("url") ?? "",
280363 owner: q.get("owner") ?? ctx.auth.user.username,
281364 name: q.get("name") ?? "",
282365 visibility: "private",
283 agent: "",
366 agent: link.agent,
284367 autonomous: false,
285368 },
286 await originChoices(ctx),
369 origins,
370 undefined,
371 200,
372 link.notes,
287373 );
288374 }
289375
@@ -422,25 +508,27 @@ export function migrationJobPage(ctx: Ctx): Response {
422508 head: html`${icon("download")}
423509 <h2>${job.fullName}</h2>`,
424510 })}
425 ${failed
426 ? html`<p class="error-note">
427 ${job.error ?? "The migration failed."}
428 </p>
429 <div class="bar mt">
430 ${btn("Try again", {
431 href: `/migrate?${new URLSearchParams(
432 job.originId === ""
433 ? { url: job.fullName }
434 : { source: pickValue(job.originId, job.fullName) },
435 )}`,
436 variant: "primary",
437 icon: "sync",
438 })}
439 </div>`
440 : html`<p class="muted small mt">
441 This keeps going if you close the page — come back to this link
442 and it will say where it got to.
443 </p>`}
511 ${
512 failed
513 ? html`<p class="error-note">
514 ${job.error ?? "The migration failed."}
515 </p>
516 <div class="bar mt">
517 ${btn("Try again", {
518 href: `/migrate?${new URLSearchParams(
519 job.originId === ""
520 ? { url: job.fullName }
521 : { source: pickValue(job.originId, job.fullName) },
522 )}`,
523 variant: "primary",
524 icon: "sync",
525 })}
526 </div>`
527 : html`<p class="muted small mt">
528 This keeps going if you close the page — come back to this link
529 and it will say where it got to.
530 </p>`
531 }
444532 </div>`,
445533 });
446534 }
test/migrate.test.ts +45 −2
@@ -504,6 +504,47 @@ describe("migrate", () => {
504504 );
505505 }, 60_000);
506506
507 test("a link prefills the form, names a miss, escapes, and starts nothing", async () => {
508 const count = () =>
509 (app.db.query("SELECT COUNT(*) AS n FROM repo").get() as { n: number }).n;
510 const before = count();
511 const host = new URL(listOrigins(app.db, alice.id)[0]!.webUrl).host;
512 const hit = await (
513 await browser(
514 aliceCookie,
515 `/migrate?from=${host}/octo/secret-widgets&crew=porter`,
516 )
517 ).text();
518 expect(hit).toMatch(
519 /<option[^>]*value="[^"]*\/octo\/secret-widgets"[^>]*selected/,
520 );
521 expect(hit).toMatch(/<option[^>]*value="porter"[^>]*selected/);
522 expect(hit).not.toContain("data-prefill-miss");
523
524 const miss = await (
525 await browser(aliceCookie, `/migrate?from=${host}/octo/nope&crew=ghost`)
526 ).text();
527 expect(miss).toContain(`No repository ${host}/octo/nope in your origins`);
528 expect(miss).toContain("No agent ghost you can put on a crew");
529 expect(miss).not.toMatch(
530 /<option[^>]*value="[^"]*\/octo\/secret-widgets"[^>]*selected/,
531 );
532 expect(miss).not.toMatch(/<option[^>]*value="porter"[^>]*selected/);
533
534 const hostile = await (
535 await browser(
536 aliceCookie,
537 `/migrate?from=${encodeURIComponent('"><script>alert(1)</script>')}&crew=${encodeURIComponent("<img src=x>")}`,
538 )
539 ).text();
540 expect(hostile).not.toContain("<script>alert(1)</script>");
541 expect(hostile).not.toContain("<img src=x>");
542 expect(hostile).toContain("&lt;script&gt;");
543
544 // Three GETs, and no repository was made by any of them.
545 expect(count()).toBe(before);
546 }, 60_000);
547
507548 test("the page: the form, the plus menu, the job, and who may see it", async () => {
508549 const anonymous = await browser("", "/migrate");
509550 expect(anonymous.status).toBe(303);
@@ -596,13 +637,15 @@ describe("migrate", () => {
596637 const strictDir = await mkdtemp(join(tmpdir(), "forge-migrate-strict-"));
597638 const strict = createApp({ dataDir: strictDir, port: 0 });
598639 try {
599 const a = await createUser(strict.db, { trusted: true,
640 const a = await createUser(strict.db, {
641 trusted: true,
600642 username: "ann",
601643 email: "[email protected]",
602644 password: "a-good-passphrase",
603645 adminIfFirst: true,
604646 });
605 const b = await createUser(strict.db, { trusted: true,
647 const b = await createUser(strict.db, {
648 trusted: true,
606649 username: "ben",
607650 email: "[email protected]",
608651 password: "a-good-passphrase",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs