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

Closed opened this
Closed without merging

scout/forge:scout/1006-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 +202 −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 +148 −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,72 @@ 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 /**
79 * A link parameter that may be looked up: capped, plain characters, and —
80 * past the host, which may carry a port — a safe ref.
81 */
82 const linkValue = (raw: string | null, pattern = LINK_CHARS): string => {
83 if (raw === null || raw.length > LINK_CAP || !pattern.test(raw)) return "";
84 const path = pattern === LINK_CHARS ? raw.slice(raw.indexOf("/") + 1) : raw;
85 return raw.includes("/") === (pattern === LINK_CHARS) && isSafeRef(path)
86 ? raw
87 : "";
88 };
89
90 /** What a link (`?from=<host>/<owner>/<name>&crew=<agent>`) chose, and what it missed. */
91 interface Prefill {
92 source: string;
93 agent: string;
94 notes: string[];
95 }
96
97 /**
98 * Reads the link against the lists the page already holds — no second fetch.
99 * Only a match selects anything; a miss is named, never acted on.
100 */
101 function prefillFrom(
102 q: URLSearchParams,
103 origins: readonly OriginChoices[],
104 crew: readonly string[],
105 ): Prefill {
106 const out: Prefill = { source: "", agent: "", notes: [] };
107 const from = q.get("from");
108 if (from !== null && from !== "") {
109 const wanted = linkValue(from);
110 for (const origin of origins) {
111 const prefix = `${origin.host}/`;
112 if (wanted === "" || !wanted.startsWith(prefix)) continue;
113 const hit = origin.repos.find(
114 (r) => r.fullName === wanted.slice(prefix.length),
115 );
116 if (hit) {
117 out.source = pickValue(origin.id, hit.fullName);
118 break;
119 }
120 }
121 if (out.source === "")
122 out.notes.push(
123 `No repository ${from.slice(0, LINK_CAP)} in your origins`,
124 );
125 }
126 const agent = q.get("crew");
127 if (agent !== null && agent !== "") {
128 const wanted = linkValue(agent, /^[A-Za-z0-9._-]+$/);
129 if (wanted !== "" && crew.includes(wanted)) out.agent = wanted;
130 else out.notes.push(`No agent ${agent.slice(0, 64)} you can put on a crew`);
131 }
132 return out;
133 }
134
72135 function migrateForm(
73136 ctx: Ctx,
74137 values: MigrateValues,
75138 origins: readonly OriginChoices[],
76139 error?: string,
140 notes: readonly string[] = [],
77141 ): Html {
78142 const user = ctx.auth.user!;
79143 const writeOrgs = listOrgsForUser(ctx.app.db, user.id).filter((org) =>
@@ -124,6 +188,7 @@ function migrateForm(
124188 })}
125189 ${card(
126190 html`<form method="post" action="/migrate">
191 ${notes.map((n) => html`<p class="error-note" data-prefill-miss>${n}.</p>`)}
127192 <h3 class="mb">Source</h3>
128193 ${picker}
129194 ${formField({
@@ -171,48 +236,53 @@ function migrateForm(
171236 ],
172237 })}
173238 <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>`}
239 ${
240 crew.length === 0
241 ? html`<p class="muted small mb">
242 ${icon("bot")} No agents on this forge yet, so there is no crew
243 to hand the migration to.
244 ${
245 user.isAdmin
246 ? html`Create one under
247 <a href="/settings/crew">Settings → Crew</a>.`
248 : html`An admin can create one under account settings →
249 Crew.`
250 }
251 </p>`
252 : html`${selectField({
253 label: "Agent",
254 name: "agent",
255 hint: "Joins the crew, makes the repository an app, and is told to make it run here — adapting it, not rewriting it.",
256 options: [
257 {
258 value: "",
259 label: "Nobody — just the repository",
260 selected: values.agent === "",
261 },
262 ...crew.map((agent) => ({
263 value: agent.user.username,
264 label:
265 agent.model === ""
266 ? agent.user.username
267 : `${agent.user.username} — ${agent.model}`,
268 selected: values.agent === agent.user.username,
269 })),
270 ],
271 })}
272 <div class="field">
273 <label class="check">
274 <input
275 type="checkbox"
276 name="autonomous"
277 ${values.autonomous ? raw("checked") : null}
278 />
279 <span
280 >Autonomous — green ships on its own. Off, every green
281 change waits for your look.</span
282 >
283 </label>
284 </div>`
285 }
216286 <div class="form-actions">
217287 ${btn("Migrate", { variant: "primary", icon: "download" })}
218288 ${btn("Cancel", { href: "/", variant: "ghost" })}
@@ -256,12 +326,13 @@ function show(
256326 origins: readonly OriginChoices[],
257327 error?: string,
258328 status = 200,
329 notes: readonly string[] = [],
259330 ): Response {
260331 return page(
261332 {
262333 ctx,
263334 title: "Migrate",
264 body: migrateForm(ctx, values, origins, error),
335 body: migrateForm(ctx, values, origins, error, notes),
265336 scriptJs: migrateJs,
266337 },
267338 status,
@@ -272,18 +343,28 @@ function show(
272343 export async function migratePage(ctx: Ctx): Promise<Response> {
273344 if (!ctx.auth.user) return signInFirst(ctx);
274345 const q = ctx.url.searchParams;
346 const origins = await originChoices(ctx);
347 const agents = listAllAgents(ctx.app, ctx.auth.user);
348 const link = prefillFrom(
349 q,
350 origins,
351 agents.ok ? agents.value.map((a) => a.user.username) : [],
352 );
275353 return show(
276354 ctx,
277355 {
278 source: q.get("source") ?? "",
356 source: q.get("source") ?? link.source,
279357 url: q.get("url") ?? "",
280358 owner: q.get("owner") ?? ctx.auth.user.username,
281359 name: q.get("name") ?? "",
282360 visibility: "private",
283 agent: "",
361 agent: link.agent,
284362 autonomous: false,
285363 },
286 await originChoices(ctx),
364 origins,
365 undefined,
366 200,
367 link.notes,
287368 );
288369 }
289370
@@ -422,25 +503,27 @@ export function migrationJobPage(ctx: Ctx): Response {
422503 head: html`${icon("download")}
423504 <h2>${job.fullName}</h2>`,
424505 })}
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>`}
506 ${
507 failed
508 ? html`<p class="error-note">
509 ${job.error ?? "The migration failed."}
510 </p>
511 <div class="bar mt">
512 ${btn("Try again", {
513 href: `/migrate?${new URLSearchParams(
514 job.originId === ""
515 ? { url: job.fullName }
516 : { source: pickValue(job.originId, job.fullName) },
517 )}`,
518 variant: "primary",
519 icon: "sync",
520 })}
521 </div>`
522 : html`<p class="muted small mt">
523 This keeps going if you close the page — come back to this link
524 and it will say where it got to.
525 </p>`
526 }
444527 </div>`,
445528 });
446529 }
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