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

Closed opened this
Closed without merging

scout/forge:scout/1078-migrate-opens-prefilled-from-a-link-so-t → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +198 −68
docs/ORIGINS.md +8
@@ -469,6 +469,14 @@ Dockerfile and no compose file (the forge runs processes), and write down
469469 what could not fit. The crew proposes; a person lands — autonomy included,
470470 exactly as for any app (docs/APPS.md).
471471
472 **A link that chooses.** `/migrate?from=<host>/<owner>/<name>&crew=<agent>`
473 opens the form with that repository (matched against the origins' lists the
474 page already reads, by the origin's host) and that agent selected, so a crew
475 run can leave the owner one link on an issue. Both are length-capped and
476 shape-checked; one that matches nothing is ignored and named in one escaped
477 line ("No repository host/o/n in your origins."). The GET never starts a job;
478 nothing happens until the owner presses Migrate.
479
472480 The clone runs as a job in the mirror's registry (`origins/jobs.ts`, kind
473481 `migrate`, owned by whoever started it — anyone else's is `not_found`).
474482 `/migrate/jobs/:job` refreshes until it stops, then lands on the repository
src/web/pages/migrate.ts +141 −66
@@ -20,6 +20,7 @@ import type { OriginRepoRow } from "../../core/origins.ts";
2020 import { scopeAllows } from "../../core/tokens.ts";
2121 import type { Ctx } from "../../http/context.ts";
2222 import type { MirrorJob, MirrorStage } from "../../origins/jobs.ts";
23 import { isSafeRef } from "../../git/guard.ts";
2324 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
2425 import { field, readForm } from "../form.ts";
2526 import { html, raw, type Html } from "../html.ts";
@@ -74,6 +75,7 @@ function migrateForm(
7475 values: MigrateValues,
7576 origins: readonly OriginChoices[],
7677 error?: string,
78 notices: readonly string[] = [],
7779 ): Html {
7880 const user = ctx.auth.user!;
7981 const writeOrgs = listOrgsForUser(ctx.app.db, user.id).filter((org) =>
@@ -122,6 +124,7 @@ function migrateForm(
122124 ${pageHead("Migrate a repository", {
123125 sub: "A one-time clone of the whole history — every branch, every tag — into a repository that lives here from now on. Nothing is written back to where it came from.",
124126 })}
127 ${notices.map((n) => html`<p class="muted small mb">${icon("globe")} ${n}</p>`)}
125128 ${card(
126129 html`<form method="post" action="/migrate">
127130 <h3 class="mb">Source</h3>
@@ -171,48 +174,53 @@ function migrateForm(
171174 ],
172175 })}
173176 <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>`}
177 ${
178 crew.length === 0
179 ? html`<p class="muted small mb">
180 ${icon("bot")} No agents on this forge yet, so there is no crew
181 to hand the migration to.
182 ${
183 user.isAdmin
184 ? html`Create one under
185 <a href="/settings/crew">Settings → Crew</a>.`
186 : html`An admin can create one under account settings →
187 Crew.`
188 }
189 </p>`
190 : html`${selectField({
191 label: "Agent",
192 name: "agent",
193 hint: "Joins the crew, makes the repository an app, and is told to make it run here — adapting it, not rewriting it.",
194 options: [
195 {
196 value: "",
197 label: "Nobody — just the repository",
198 selected: values.agent === "",
199 },
200 ...crew.map((agent) => ({
201 value: agent.user.username,
202 label:
203 agent.model === ""
204 ? agent.user.username
205 : `${agent.user.username} — ${agent.model}`,
206 selected: values.agent === agent.user.username,
207 })),
208 ],
209 })}
210 <div class="field">
211 <label class="check">
212 <input
213 type="checkbox"
214 name="autonomous"
215 ${values.autonomous ? raw("checked") : null}
216 />
217 <span
218 >Autonomous — green ships on its own. Off, every green
219 change waits for your look.</span
220 >
221 </label>
222 </div>`
223 }
216224 <div class="form-actions">
217225 ${btn("Migrate", { variant: "primary", icon: "download" })}
218226 ${btn("Cancel", { href: "/", variant: "ghost" })}
@@ -256,34 +264,99 @@ function show(
256264 origins: readonly OriginChoices[],
257265 error?: string,
258266 status = 200,
267 notices: readonly string[] = [],
259268 ): Response {
260269 return page(
261270 {
262271 ctx,
263272 title: "Migrate",
264 body: migrateForm(ctx, values, origins, error),
273 body: migrateForm(ctx, values, origins, error, notices),
265274 scriptJs: migrateJs,
266275 },
267276 status,
268277 );
269278 }
270279
271 // GET /migrate
280 /** Longest `from` or `crew` value read from a link. */
281 const LINK_MAX = 200;
282 const FROM_SHAPE =
283 /^[A-Za-z0-9.-]+(?::\d+)?\/[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
284 const CREW_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
285
286 /**
287 * `?from=<host>/<owner>/<name>&crew=<agent>`: what a link chooses, matched
288 * against the origins and agents the page already has — no second fetch.
289 * A value that matches nothing is named in a notice (escaped by the
290 * template) and otherwise ignored; a malformed one is not echoed at all.
291 */
292 function linkChoices(
293 ctx: Ctx,
294 origins: readonly OriginChoices[],
295 agents: readonly string[],
296 ): { source?: string; agent?: string; notices: string[] } {
297 const q = ctx.url.searchParams;
298 const out: { source?: string; agent?: string; notices: string[] } = {
299 notices: [],
300 };
301 const from = q.get("from");
302 if (from !== null && from !== "") {
303 if (from.length > LINK_MAX || !isSafeRef(from) || !FROM_SHAPE.test(from))
304 out.notices.push(
305 "The repository in this link is not in host/owner/name form.",
306 );
307 else {
308 const slash = from.indexOf("/");
309 const host = from.slice(0, slash).toLowerCase();
310 const full = from.slice(slash + 1);
311 for (const origin of origins) {
312 const label = origin.label.slice(origin.label.lastIndexOf(" @ ") + 3);
313 const hit = origin.repos.find((r) => r.fullName === full);
314 if (hit !== undefined && label.toLowerCase() === host) {
315 out.source = pickValue(origin.id, hit.fullName);
316 break;
317 }
318 }
319 if (out.source === undefined)
320 out.notices.push(`No repository ${from} in your origins.`);
321 }
322 }
323 const crew = q.get("crew");
324 if (crew !== null && crew !== "") {
325 if (crew.length > LINK_MAX || !CREW_SHAPE.test(crew))
326 out.notices.push("The agent in this link is not a valid name.");
327 else if (!agents.includes(crew))
328 out.notices.push(`No agent ${crew} you can put on a crew.`);
329 else out.agent = crew;
330 }
331 return out;
332 }
333
334 // GET /migrate — never starts a job; a link only chooses.
272335 export async function migratePage(ctx: Ctx): Promise<Response> {
273336 if (!ctx.auth.user) return signInFirst(ctx);
274337 const q = ctx.url.searchParams;
338 const origins = await originChoices(ctx);
339 const listed = listAllAgents(ctx.app, ctx.auth.user);
340 const link = linkChoices(
341 ctx,
342 origins,
343 listed.ok ? listed.value.map((a) => a.user.username) : [],
344 );
275345 return show(
276346 ctx,
277347 {
278 source: q.get("source") ?? "",
348 source: q.get("source") ?? link.source ?? "",
279349 url: q.get("url") ?? "",
280350 owner: q.get("owner") ?? ctx.auth.user.username,
281351 name: q.get("name") ?? "",
282352 visibility: "private",
283 agent: "",
353 agent: link.agent ?? "",
284354 autonomous: false,
285355 },
286 await originChoices(ctx),
356 origins,
357 undefined,
358 200,
359 link.notices,
287360 );
288361 }
289362
@@ -422,25 +495,27 @@ export function migrationJobPage(ctx: Ctx): Response {
422495 head: html`${icon("download")}
423496 <h2>${job.fullName}</h2>`,
424497 })}
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>`}
498 ${
499 failed
500 ? html`<p class="error-note">
501 ${job.error ?? "The migration failed."}
502 </p>
503 <div class="bar mt">
504 ${btn("Try again", {
505 href: `/migrate?${new URLSearchParams(
506 job.originId === ""
507 ? { url: job.fullName }
508 : { source: pickValue(job.originId, job.fullName) },
509 )}`,
510 variant: "primary",
511 icon: "sync",
512 })}
513 </div>`
514 : html`<p class="muted small mt">
515 This keeps going if you close the page — come back to this link
516 and it will say where it got to.
517 </p>`
518 }
444519 </div>`,
445520 });
446521 }
test/migrate.test.ts +49 −2
@@ -504,6 +504,51 @@ describe("migrate", () => {
504504 );
505505 }, 60_000);
506506
507 test("a link prefills the form and starts nothing", async () => {
508 const origin = listOrigins(app.db, alice.id)[0]!;
509 const host = new URL(origin.webUrl).host;
510 const count = () =>
511 (app.db.query("SELECT COUNT(*) AS n FROM repo").get() as { n: number }).n;
512 const before = count();
513 const hit = await (
514 await browser(
515 aliceCookie,
516 `/migrate?from=${host}/octo/secret-widgets&crew=porter`,
517 )
518 ).text();
519 expect(hit).toMatch(
520 new RegExp(
521 `<option\\s+value="${origin.id}/octo/secret-widgets"[^>]*selected`,
522 ),
523 );
524 expect(hit).toMatch(
525 /<option[^>]*value="porter"[^>]*selected|selected[^>]*value="porter"/,
526 );
527
528 const miss = await (
529 await browser(aliceCookie, `/migrate?from=${host}/octo/nope&crew=ghost`)
530 ).text();
531 expect(miss).toContain(`No repository ${host}/octo/nope in your origins.`);
532 expect(miss).toContain("No agent ghost");
533 expect(miss).not.toMatch(/value="[^"]*nope[^"]*"[^>]*selected/);
534
535 const hostile = await (
536 await browser(
537 aliceCookie,
538 `/migrate?from=${encodeURIComponent(`${host}/o/<script>alert(1)</script>`)}&crew=${encodeURIComponent('"><img src=x>')}`,
539 )
540 ).text();
541 expect(hostile).not.toContain("<script>alert(1)");
542 expect(hostile).not.toContain("<img src=x>");
543
544 const long = await browser(
545 aliceCookie,
546 `/migrate?from=${"a".repeat(5000)}`,
547 );
548 expect(long.status).toBe(200);
549 expect(count()).toBe(before);
550 });
551
507552 test("the page: the form, the plus menu, the job, and who may see it", async () => {
508553 const anonymous = await browser("", "/migrate");
509554 expect(anonymous.status).toBe(303);
@@ -596,13 +641,15 @@ describe("migrate", () => {
596641 const strictDir = await mkdtemp(join(tmpdir(), "forge-migrate-strict-"));
597642 const strict = createApp({ dataDir: strictDir, port: 0 });
598643 try {
599 const a = await createUser(strict.db, { trusted: true,
644 const a = await createUser(strict.db, {
645 trusted: true,
600646 username: "ann",
601647 email: "[email protected]",
602648 password: "a-good-passphrase",
603649 adminIfFirst: true,
604650 });
605 const b = await createUser(strict.db, { trusted: true,
651 const b = await createUser(strict.db, {
652 trusted: true,
606653 username: "ben",
607654 email: "[email protected]",
608655 password: "a-good-passphrase",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs