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

Closed opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +196 −66
docs/ORIGINS.md +8
@@ -473,6 +473,14 @@ out) with the steps to make the dump. No connection string to the old
473473 database is ever committed or read at boot. The crew proposes; a person lands — autonomy included,
474474 exactly as for any app (docs/APPS.md).
475475
476 **A link that chooses.** `/migrate?from=<host>/<owner>/<name>&crew=<agent>`
477 opens the form with that repository (matched against the origins' lists the
478 page already reads, by the origin's host) and that agent selected, so a crew
479 run can leave the owner one link on an issue. Both are length-capped and
480 shape-checked; one that matches nothing is ignored and named in one escaped
481 line ("No repository host/o/n in your origins."). The GET never starts a job;
482 nothing happens until the owner presses Migrate.
483
476484 The clone runs as a job in the mirror's registry (`origins/jobs.ts`, kind
477485 `migrate`, owned by whoever started it — anyone else's is `not_found`).
478486 `/migrate/jobs/:job` refreshes until it stops, then lands on the repository
src/web/pages/migrate.ts +143 −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";
@@ -41,6 +42,8 @@ interface MigrateValues {
4142 interface OriginChoices {
4243 readonly label: string;
4344 readonly id: string;
45 /** The origin's web host, port included — what a link names it by. */
46 readonly host: string;
4447 readonly repos: readonly OriginRepoRow[];
4548 }
4649
@@ -52,6 +55,7 @@ async function originChoices(ctx: Ctx): Promise<OriginChoices[]> {
5255 if (!listed.ok || listed.value.length === 0) continue;
5356 out.push({
5457 id: origin.id,
58 host: URL.parse(origin.webUrl)?.host ?? "",
5559 label: `${origin.login} @ ${hostLabel(origin.webUrl)}`,
5660 repos: listed.value,
5761 });
@@ -74,6 +78,7 @@ function migrateForm(
7478 values: MigrateValues,
7579 origins: readonly OriginChoices[],
7680 error?: string,
81 notices: readonly string[] = [],
7782 ): Html {
7883 const user = ctx.auth.user!;
7984 const writeOrgs = listOrgsForUser(ctx.app.db, user.id).filter((org) =>
@@ -122,6 +127,7 @@ function migrateForm(
122127 ${pageHead("Migrate a repository", {
123128 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.",
124129 })}
130 ${notices.map((n) => html`<p class="muted small mb">${icon("globe")} ${n}</p>`)}
125131 ${card(
126132 html`<form method="post" action="/migrate">
127133 <h3 class="mb">Source</h3>
@@ -171,48 +177,53 @@ function migrateForm(
171177 ],
172178 })}
173179 <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>`}
180 ${
181 crew.length === 0
182 ? html`<p class="muted small mb">
183 ${icon("bot")} No agents on this forge yet, so there is no crew
184 to hand the migration to.
185 ${
186 user.isAdmin
187 ? html`Create one under
188 <a href="/settings/crew">Settings → Crew</a>.`
189 : html`An admin can create one under account settings →
190 Crew.`
191 }
192 </p>`
193 : html`${selectField({
194 label: "Agent",
195 name: "agent",
196 hint: "Joins the crew, makes the repository an app, and is told to make it run here — adapting it, not rewriting it.",
197 options: [
198 {
199 value: "",
200 label: "Nobody — just the repository",
201 selected: values.agent === "",
202 },
203 ...crew.map((agent) => ({
204 value: agent.user.username,
205 label:
206 agent.model === ""
207 ? agent.user.username
208 : `${agent.user.username} — ${agent.model}`,
209 selected: values.agent === agent.user.username,
210 })),
211 ],
212 })}
213 <div class="field">
214 <label class="check">
215 <input
216 type="checkbox"
217 name="autonomous"
218 ${values.autonomous ? raw("checked") : null}
219 />
220 <span
221 >Autonomous — green ships on its own. Off, every green
222 change waits for your look.</span
223 >
224 </label>
225 </div>`
226 }
216227 <div class="form-actions">
217228 ${btn("Migrate", { variant: "primary", icon: "download" })}
218229 ${btn("Cancel", { href: "/", variant: "ghost" })}
@@ -256,34 +267,98 @@ function show(
256267 origins: readonly OriginChoices[],
257268 error?: string,
258269 status = 200,
270 notices: readonly string[] = [],
259271 ): Response {
260272 return page(
261273 {
262274 ctx,
263275 title: "Migrate",
264 body: migrateForm(ctx, values, origins, error),
276 body: migrateForm(ctx, values, origins, error, notices),
265277 scriptJs: migrateJs,
266278 },
267279 status,
268280 );
269281 }
270282
271 // GET /migrate
283 /** Longest `from` or `crew` value read from a link. */
284 const LINK_MAX = 200;
285 const FROM_SHAPE =
286 /^[A-Za-z0-9.-]+(?::\d+)?\/[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
287 const CREW_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
288
289 /**
290 * `?from=<host>/<owner>/<name>&crew=<agent>`: what a link chooses, matched
291 * against the origins and agents the page already has — no second fetch.
292 * A value that matches nothing is named in a notice (escaped by the
293 * template) and otherwise ignored; a malformed one is not echoed at all.
294 */
295 function linkChoices(
296 ctx: Ctx,
297 origins: readonly OriginChoices[],
298 agents: readonly string[],
299 ): { source?: string; agent?: string; notices: string[] } {
300 const q = ctx.url.searchParams;
301 const out: { source?: string; agent?: string; notices: string[] } = {
302 notices: [],
303 };
304 const from = q.get("from");
305 if (from !== null && from !== "") {
306 if (from.length > LINK_MAX || !isSafeRef(from) || !FROM_SHAPE.test(from))
307 out.notices.push(
308 "The repository in this link is not in host/owner/name form.",
309 );
310 else {
311 const slash = from.indexOf("/");
312 const host = from.slice(0, slash).toLowerCase();
313 const full = from.slice(slash + 1);
314 for (const origin of origins) {
315 const hit = origin.repos.find((r) => r.fullName === full);
316 if (hit !== undefined && origin.host.toLowerCase() === host) {
317 out.source = pickValue(origin.id, hit.fullName);
318 break;
319 }
320 }
321 if (out.source === undefined)
322 out.notices.push(`No repository ${from} in your origins.`);
323 }
324 }
325 const crew = q.get("crew");
326 if (crew !== null && crew !== "") {
327 if (crew.length > LINK_MAX || !CREW_SHAPE.test(crew))
328 out.notices.push("The agent in this link is not a valid name.");
329 else if (!agents.includes(crew))
330 out.notices.push(`No agent ${crew} you can put on a crew.`);
331 else out.agent = crew;
332 }
333 return out;
334 }
335
336 // GET /migrate — never starts a job; a link only chooses.
272337 export async function migratePage(ctx: Ctx): Promise<Response> {
273338 if (!ctx.auth.user) return signInFirst(ctx);
274339 const q = ctx.url.searchParams;
340 const origins = await originChoices(ctx);
341 const listed = listAllAgents(ctx.app, ctx.auth.user);
342 const link = linkChoices(
343 ctx,
344 origins,
345 listed.ok ? listed.value.map((a) => a.user.username) : [],
346 );
275347 return show(
276348 ctx,
277349 {
278 source: q.get("source") ?? "",
350 source: q.get("source") ?? link.source ?? "",
279351 url: q.get("url") ?? "",
280352 owner: q.get("owner") ?? ctx.auth.user.username,
281353 name: q.get("name") ?? "",
282354 visibility: "private",
283 agent: "",
355 agent: link.agent ?? "",
284356 autonomous: false,
285357 },
286 await originChoices(ctx),
358 origins,
359 undefined,
360 200,
361 link.notices,
287362 );
288363 }
289364
@@ -422,25 +497,27 @@ export function migrationJobPage(ctx: Ctx): Response {
422497 head: html`${icon("download")}
423498 <h2>${job.fullName}</h2>`,
424499 })}
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>`}
500 ${
501 failed
502 ? html`<p class="error-note">
503 ${job.error ?? "The migration failed."}
504 </p>
505 <div class="bar mt">
506 ${btn("Try again", {
507 href: `/migrate?${new URLSearchParams(
508 job.originId === ""
509 ? { url: job.fullName }
510 : { source: pickValue(job.originId, job.fullName) },
511 )}`,
512 variant: "primary",
513 icon: "sync",
514 })}
515 </div>`
516 : html`<p class="muted small mt">
517 This keeps going if you close the page — come back to this link
518 and it will say where it got to.
519 </p>`
520 }
444521 </div>`,
445522 });
446523 }
test/migrate.test.ts +45
@@ -513,6 +513,51 @@ describe("migrate", () => {
513513 );
514514 });
515515
516 test("a link prefills the form and starts nothing", async () => {
517 const origin = listOrigins(app.db, alice.id)[0]!;
518 const host = new URL(origin.webUrl).host;
519 const count = () =>
520 (app.db.query("SELECT COUNT(*) AS n FROM repo").get() as { n: number }).n;
521 const before = count();
522 const hit = await (
523 await browser(
524 aliceCookie,
525 `/migrate?from=${host}/octo/secret-widgets&crew=porter`,
526 )
527 ).text();
528 expect(hit).toMatch(
529 new RegExp(
530 `<option\\s+value="${origin.id}/octo/secret-widgets"[^>]*selected`,
531 ),
532 );
533 expect(hit).toMatch(
534 /<option[^>]*value="porter"[^>]*selected|selected[^>]*value="porter"/,
535 );
536
537 const miss = await (
538 await browser(aliceCookie, `/migrate?from=${host}/octo/nope&crew=ghost`)
539 ).text();
540 expect(miss).toContain(`No repository ${host}/octo/nope in your origins.`);
541 expect(miss).toContain("No agent ghost");
542 expect(miss).not.toMatch(/value="[^"]*nope[^"]*"[^>]*selected/);
543
544 const hostile = await (
545 await browser(
546 aliceCookie,
547 `/migrate?from=${encodeURIComponent(`${host}/o/<script>alert(1)</script>`)}&crew=${encodeURIComponent('"><img src=x>')}`,
548 )
549 ).text();
550 expect(hostile).not.toContain("<script>alert(1)");
551 expect(hostile).not.toContain("<img src=x>");
552
553 const long = await browser(
554 aliceCookie,
555 `/migrate?from=${"a".repeat(5000)}`,
556 );
557 expect(long.status).toBe(200);
558 expect(count()).toBe(before);
559 });
560
516561 test("the page: the form, the plus menu, the job, and who may see it", async () => {
517562 const anonymous = await browser("", "/migrate");
518563 expect(anonymous.status).toBe(303);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs