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

Each app a pack deploys shows a link back to its source on its page and in the terminal #16092

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16068-each-app-a-pack-deploys-shows-a-link-bac → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/16068-each-app-a-pack-deploys-shows-a-link-bac was merged into main as 92fee1a.

Review

Sign in to review this change.
18 files changed +296 −3
docs/features/packs.md +3 −1
@@ -18,7 +18,9 @@ A pack is a public forge repo with a `pack.json` at its root, named like the pac
1818 - Code: `src/packs/`, `src/web/pages/packs.ts`, `scripts/pack.ts`. Tests: `test/packs.test.ts`, `test/packs-up.test.ts` (the whole path against a fake source for both packs, `up()` itself with a real child forge on a free port, the owner reused on a second run, a stored credential, a partial deploy finished, a new upstream commit showing as drift), `test/packs-hands.test.ts` (the git credential is scoped to the forge and never sent to a pack's source; only 409 means "exists"; the terminal screen; an `owner/name` source is forked with lineage, kept on 409, a 422 or 429 refusal failing that step with the forge's message, an unreachable forge, and `absorb` absorbing the fork as its owner).
1919 - **A source on a forge (`owner/name`).** Deploying forks it with lineage (`POST /forks`) instead of pushing history: nothing is carried over the network and nothing is followed (no follow is set; the fork's lineage is the link). The fork keeps the app's name. `owner/name` is resolved on whichever forge the deploy targets, not on the pack author's forge. An existing fork (409 `already_forked`) counts as kept; a name already taken by something else fails that step. Non-admins are held to the fork limit (`FORKS_PER_DAY`, 5 a day), so a pack with more than five forge apps fails the rest with "at most 5 forks a day"; run it again the next day. Mirroring (below) is for https sources only: a forge-form source is reported as failed ("not an address a mirror may follow").
2020
21 Not done yet: a hosted "deploy this pack" press, a stable follow link from each app back to its source, the guest sign-up gate and the crew filtering guest pulls on automode (owner decisions on #9428).
21 Not done yet: a hosted "deploy this pack" press, the guest sign-up gate and the crew filtering guest pulls on automode (owner decisions on #9428).
22
23 - **Where an app came from (#16068).** `up` and `deploy` record each app's `source` (an https address, or `owner/name` of a forge repo) when the app is made, through `PUT /api/v1/repos/:owner/:name/source` (admin scope, the repository's admin). The app's page shows one muted line, "From <source>", linking to it (an address opens in the same tab and carries `rel="noopener noreferrer"`; `owner/name` links to that repo here), and the terminal's About screen has a `from` row. An app with no recorded source shows nothing. `sourceText` (`src/packs/source_guard.ts`) is the one validator: http(s) or `owner/name`, at most 300 characters, no whitespace or control character, no query or fragment, and an address carrying a user or password is refused, never stripped; an address is kept as parsed (`url.href`), so what is stored is what was checked, and the check runs again when the row is read. The source rides the repository row itself (a LEFT JOIN in `core/repos.ts`), so no repository page pays a statement for the line. A failure to record is its own failed step and never hides that the app is made. Code: `src/core/repo_source.ts` (table `repo_made_from`), `src/http/api/repo_source.ts`. Test: `test/packs-source-link.test.ts`.
outdated

Says an address 'opens in a new context'; the anchor does not set a target. Fix the sentence or the anchor.

2224
2325 ## The upstream mirrors (#10530)
2426
scripts/pack.ts +11
@@ -207,6 +207,17 @@ export function realHands(url: string, token: string, options: HandsOptions = {}
207207 if (r.status === 403) return { ok: false, why: "the forge refused (403): absorbing needs a site admin's token with admin scope, and this token is not one" };
208208 return { ok: false, why: `the forge answered ${r.status}` };
209209 },
210 async recordSource(owner, name, source) {
211 const r = await fetch(`${url}/api/v1/repos/${owner}/${name}/source`, {
212 method: "PUT",
213 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
214 body: JSON.stringify({ source }),
215 }).catch(() => null);
216 if (r === null) return { ok: false, why: `cannot reach ${url}` };
217 if (r.ok) return { ok: true };
218 const said = (await r.json().catch(() => null)) as { message?: unknown } | null;
219 return { ok: false, why: typeof said?.message === "string" ? said.message : `the forge answered ${r.status}` };
220 },
210221 async makeAgent(a) {
211222 const r = await fetch(`${url}/api/v1/agents`, {
212223 method: "POST",
src/contract/openapi/routes/index.ts +1
@@ -482,6 +482,7 @@ export { route as putApiV1ReposOwnerNamePullsNumberAssignee } from "./putApiV1Re
482482 export { route as putApiV1ReposOwnerNamePullsNumberHold } from "./putApiV1ReposOwnerNamePullsNumberHold.ts";
483483 export { route as putApiV1ReposOwnerNamePullsNumberLabels } from "./putApiV1ReposOwnerNamePullsNumberLabels.ts";
484484 export { route as putApiV1ReposOwnerNamePullsNumberReview } from "./putApiV1ReposOwnerNamePullsNumberReview.ts";
485 export { route as putApiV1ReposOwnerNameSource } from "./putApiV1ReposOwnerNameSource.ts";
485486 export { route as putApiV1ReposOwnerNameUpstream } from "./putApiV1ReposOwnerNameUpstream.ts";
486487 export { route as putApiV1SecretsScopeName } from "./putApiV1SecretsScopeName.ts";
487488 export { route as putApiV1UserNotify } from "./putApiV1UserNotify.ts";
src/contract/openapi/routes/putApiV1ReposOwnerNameSource.ts added +13
@@ -0,0 +1,13 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: `${REPO}/source`,
6 summary: "Record where a pack's app came from",
7 detail: "Record where a pack's app came from (admin scope): an owner/name on a forge or an http(s) address with no credential, shown as the From line on its page and in the terminal; answers the source kept",
8 auth: true,
9 role: "admin",
10 body: { source: "string" },
11 refusals: { bad_source: "`source` is not an owner/name or a plain http(s) address" },
12 refuses: [401, 404],
13 };
src/contract/tags.ts +1
@@ -35,6 +35,7 @@ const ALIAS: Readonly<Record<string, string>> = {
3535 branches: "repos",
3636 commits: "repos",
3737 contents: "repos",
38 source: "repos",
3839 statement: "plan",
3940 vision: "plan",
4041 roadmap: "plan",
src/core/migration-pins/20261123130000-repo-made-from.pin added +1
@@ -0,0 +1,1 @@
1 3b3bc0616f309e9d760a14322a07f403f1a8673dde55912024a20a6cddad86e6
src/core/migrations/20261123130000-repo-made-from.ts added +9
@@ -0,0 +1,9 @@
1 // Where a pack's app came from (#16068): the address it was made from, or `owner/name` on a forge.
2 // One row per app; none means nothing is said. Additive: the release before never reads it.
3 export default `
4 CREATE TABLE IF NOT EXISTS repo_made_from (
5 repo_id TEXT PRIMARY KEY REFERENCES repo(id) ON DELETE CASCADE,
6 source TEXT NOT NULL,
7 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
8 );
9 `;
src/core/repo_fields.ts +1
@@ -74,6 +74,7 @@ const CREW_FIELDS = {
7474 directionIssueId: "string|null",
7575 sealedFor: "string|null",
7676 severedAt: "string|null",
77 madeFrom: "string|null",
7778 } as const satisfies Readonly<Record<string, string>>;
7879
7980 /** A list item as a writer gets it: the stored row whole, `detached` included. */
src/core/repo_source.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * Where a pack's app came from (#16068): one address kept per repository, read
3 * back as the muted "From …" line on its page and in the terminal. Pure data,
4 * no authz; the address is judged by `packs/source_guard.ts` before it is kept
5 * and again when it is read, so a stale row is never drawn.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { sourceText } from "../packs/source_guard.ts";
10 import type { Repo } from "./repos.ts";
11
12 export interface RepoSource {
13 /** `owner/name` of a repository on a forge, or an http(s) address with no credential. */
14 readonly source: string;
15 /** Where the words link: this forge's page for `owner/name`, else the address. */
16 readonly href: string;
17 }
18
19 const linked = (source: string): RepoSource => ({ source, href: source.includes("://") ? source : `/${source}` });
20
21 /**
22 * The source kept for a repository, or undefined when none or no longer fit to show. Read off
23 * the repository row (`Repo.madeFrom`, joined in `core/repos.ts`), so it costs no statement.
24 */
25 export function repoSource(repo: Pick<Repo, "madeFrom">): RepoSource | undefined {
26 if (repo.madeFrom === null) return undefined;
27 const checked = sourceText(repo.madeFrom);
28 return checked.ok ? linked(checked.value) : undefined;
29 }
30
31 /** Keep the source, replacing an earlier one; the refusal's words when it is not fit to keep. */
32 export function setRepoSource(db: Database, repoId: string, raw: string): { ok: true; source: string } | { ok: false; error: string } {
33 const checked = sourceText(raw);
34 if (!checked.ok) return { ok: false, error: checked.error };
35 db.query(
36 "INSERT INTO repo_made_from (repo_id, source) VALUES (?1, ?2) ON CONFLICT (repo_id) DO UPDATE SET source = excluded.source",
37 ).run(repoId, checked.value);
38 return { ok: true, source: checked.value };
39 }
src/core/repos.ts +11 −2
@@ -196,6 +196,12 @@ export interface Repo {
196196 readonly detached: RepoDetached | null;
197197 /** When a fork's owner cut it loose from its parent; null when it never was (#14855). */
198198 readonly severedAt: string | null;
199 /**
200 * Where a pack's app came from, as kept (#16068), or null. Read on the same row as the rest
201 * (a LEFT JOIN on its primary key) so the header's "From …" line costs no statement of its
202 * own; `core/repo_source.ts` judges it again before anything draws it.
203 */
204 readonly madeFrom: string | null;
199205 /**
200206 * Open issue and pull counts. Absent from a bare `getRepo` — a single
201207 * fetch on a hot path should not pay for a count nobody asked for — and
@@ -239,15 +245,17 @@ interface RepoRow {
239245 last_fetch_at: string | null;
240246 fetch_error: string;
241247 origin_detached_at: string | null;
248 made_from: string | null;
242249 }
243250
244251 // LEFT JOIN, because the origin may have been disconnected out from under a
245252 // mirror — the repo survives, the link does not.
246253 const SELECT = `
247 SELECT repo.*, user.username AS owner_name, origin.kind AS origin_kind,
254 SELECT repo.*, user.username AS owner_name, origin.kind AS origin_kind, made.source AS made_from,
248255 origin.software AS origin_software
249256 FROM repo JOIN user ON user.id = repo.owner_id
250 LEFT JOIN origin ON origin.id = repo.origin_id`;
257 LEFT JOIN origin ON origin.id = repo.origin_id
258 LEFT JOIN repo_made_from made ON made.repo_id = repo.id`;
251259
252260 /** The by-name match `getRepo` and `repoVisibility` share, so the two cannot drift. */
253261 const BY_NAME = "user.username = ?1 COLLATE NOCASE AND repo.name = ?2 COLLATE NOCASE";
@@ -293,6 +301,7 @@ function toRepo(row: RepoRow): Repo {
293301 }
294302 : null,
295303 severedAt: row.origin_id === null && row.origin_full_name === null ? row.origin_detached_at : null,
304 madeFrom: row.made_from,
296305 detached:
297306 row.origin_id === null &&
298307 row.origin_full_name !== null &&
src/http/api.ts +2
@@ -373,6 +373,7 @@ import { secretRoutes } from "./api/secrets.ts";
373373 import { drillRoutes } from "./api/drills.ts";
374374 import { featureRoutes } from "./api/features.ts";
375375 import { upstreamRoutes } from "./api/upstream.ts";
376 import { repoSourceRoutes } from "./api/repo_source.ts";
376377 import { pullRoutes } from "./api/pulls.ts";
377378 import type { Router } from "./router.ts";
378379 import { clientAddress } from "./peer.ts";
@@ -1654,6 +1655,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
16541655 });
16551656
16561657 upstreamRoutes(router);
1658 repoSourceRoutes(router);
16571659
16581660 router.add("PATCH", "/api/v1/repos/:owner/:name", async (ctx) => {
16591661 const denied = requireScope(ctx, "admin");
src/http/api/repo_source.ts added +25
@@ -0,0 +1,25 @@
1 /**
2 * `PUT /api/v1/repos/:owner/:name/source` with `{source}` (#16068): a pack's
3 * deploy records where an app came from. The repository's admin only; the
4 * address is judged by `sourceText` before anything is kept.
5 */
6
7 import { canAdmin } from "../../core/repos.ts";
8 import { setRepoSource } from "../../core/repo_source.ts";
9 import { loadRepo } from "../api.ts";
10 import type { Handler } from "../context.ts";
11 import { apiError, body, json, notFound, requireScope, str } from "../respond.ts";
12 import type { Router } from "../router.ts";
13
14 export function repoSourceRoutes(router: Router<Handler>): void {
15 router.add("PUT", "/api/v1/repos/:owner/:name/source", async (ctx) => {
16 const denied = requireScope(ctx, "admin");
17 if (denied) return denied;
18 const repo = loadRepo(ctx);
19 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return notFound();
20 const input = await body(ctx.request);
21 const saved = setRepoSource(ctx.app.db, repo.id, str(input.source));
22 if (!saved.ok) return apiError("bad_source", 422, saved.error);
23 return json({ source: saved.source });
24 });
25 }
src/packs/deploy.ts +18
@@ -24,6 +24,11 @@ export interface Hands {
2424 follow(owner: string, name: string, source: string, branch: string | undefined): Promise<{ ok: true } | { ok: false; why: string }>;
2525 /** Absorb the app as a feature, as the deploying admin. Refused when the app declares no feature: a repository cannot promote itself. */
2626 absorb(owner: string, name: string): Promise<{ ok: true } | { ok: false; why: string }>;
27 /**
28 * Keep where the app came from, so its page and the terminal say so. Optional: a hand that cannot
29 * is left out, not failed.
30 */
31 recordSource?(owner: string, name: string, source: string): Promise<{ ok: true } | { ok: false; why: string }>;
2732 makeAgent(a: Pack["crew"][number]): Promise<{ ok: true } | { ok: false; exists: boolean; why: string }>;
2833 }
2934
@@ -39,6 +44,16 @@ async function absorbStep(hands: Hands, owner: string, name: string): Promise<St
3944 return r.ok ? { what: `absorb ${name}`, state: "done", note: "a feature in the menu" } : { what: `absorb ${name}`, state: "failed", note: r.why };
4045 }
4146
47 /**
48 * The source is recorded after the app is made; only a refusal is a step, so it is reported and
49 * never hides that the app is made.
50 */
51 async function sourceStep(hands: Hands, owner: string, name: string, source: string): Promise<Step[]> {
52 if (hands.recordSource === undefined) return [];
53 const r = await hands.recordSource(owner, name, source);
54 return r.ok ? [] : [{ what: `source ${name}`, state: "failed", note: r.why }];
55 }
56
4257 /** A forge-repo source is forked, not copied: the fork's lineage is the follow, so nothing is carried or followed over the network. */
4358 async function forkStep(hands: Hands, app: Pack["apps"][number]): Promise<Step[]> {
4459 const forked = await hands.forkFrom(app.source, app.name);
@@ -47,6 +62,7 @@ async function forkStep(hands: Hands, app: Pack["apps"][number]): Promise<Step[]
4762 return [{ what: `app ${app.name}`, state: "kept", note: "already here" }];
4863 }
4964 const steps: Step[] = [{ what: `app ${app.name}`, state: "done", note: `forked from ${app.source}` }];
65 steps.push(...(await sourceStep(hands, forked.owner, app.name, app.source)));
5066 if (app.absorb === true) steps.push(await absorbStep(hands, forked.owner, app.name));
5167 return steps;
5268 }
@@ -78,6 +94,7 @@ export async function deployPack(pack: Pack, hands: Hands): Promise<readonly Ste
7894 ? { what: `app ${app.name}`, state: "kept", note: "already here" }
7995 : { what: `app ${app.name}`, state: "failed", note: `already here, not followed: ${followed.why}` },
8096 );
97 steps.push(...(await sourceStep(hands, owner, app.name, app.source)));
8198 if (followed.ok && app.absorb === true) steps.push(await absorbStep(hands, owner, app.name));
8299 continue;
83100 }
@@ -92,6 +109,7 @@ export async function deployPack(pack: Pack, hands: Hands): Promise<readonly Ste
92109 ? { what: `app ${app.name}`, state: "done", note: `history from ${app.source}, following it` }
93110 : { what: `app ${app.name}`, state: "failed", note: `history carried, not followed: ${followed.why}` },
94111 );
112 steps.push(...(await sourceStep(hands, made.owner, app.name, app.source)));
95113 if (followed.ok && app.absorb === true) steps.push(await absorbStep(hands, made.owner, app.name));
96114 }
97115 for (const member of pack.crew) {
src/packs/source_guard.ts +25
@@ -47,3 +47,28 @@ export async function guardSource(
4747 return err(refusal(bare, vetted.error === "refused" ? "is, or resolves to, an internal address" : "could not be resolved"));
4848 return ok(remoteGitEnv(base, pinFor(address, vetted.value)));
4949 }
50
51 const SOURCE_FORGE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
52
53 /**
54 * A source fit to keep and show (#16068): `owner/name` on a forge, or an http
55 * or https address with a host and no credential, query or fragment. An
56 * address carrying a user or password is refused, never stripped, so a secret
57 * is not kept in a field that is drawn on a page. Whitespace or a control
58 * character inside is refused (`URL.parse` would silently drop a tab or a
59 * newline), and an address is kept as parsed, `url.href`, so what is stored is
60 * exactly what was checked.
61 */
62 export function sourceText(raw: string): Result<string, string> {
63 const text = raw.trim();
64 if (text === "" || text.length > 300) return err("the source is an address or owner/name, at most 300 characters.");
65 if (/[\s\p{Cc}]/u.test(text)) return err("the source is one address or owner/name, without spaces or control characters.");
66 if (SOURCE_FORGE.test(text) && !text.split("/").some((s) => /^\.+$/.test(s))) return ok(text);
67 const url = URL.parse(text);
68 if (url === null || (url.protocol !== "https:" && url.protocol !== "http:") || url.hostname === "")
outdated

Medium. Return url.href rather than the raw text, or refuse control characters. URL.parse ignores tabs and newlines inside an address, so the stored value can differ from what was checked.

69 return err("the source is an http(s) address or owner/name.");
70 if (url.username !== "" || url.password !== "") return err("the source carries a credential, so the forge will not keep it.");
71 if (url.search !== "" || url.hash !== "" || url.href.includes("?") || url.href.includes("#"))
72 return err("the source is an address without a query or fragment.");
73 return ok(url.href);
74 }
src/tui/screens/about.ts +10
@@ -61,6 +61,7 @@ import {
6161 upstreamLabel,
6262 } from "../../actions/upstream_follow.ts";
6363 import { getFollow, listChecks } from "../../core/upstream_follow.ts";
64 import { repoSource } from "../../core/repo_source.ts";
6465 import {
6566 getProvenance,
6667 shownTrail,
@@ -155,6 +156,7 @@ export function aboutScreen(
155156 ...aboutFacts(f, src, facts, ref, repo),
156157 ...paceRows(f, repo),
157158 ...trailRows(f, repo),
159 ...sourceRows(f, repo),
158160 ...upstreamRows(f, repo),
159161 ...behindRows(f, repo),
160162 ...offerRows(offered),
@@ -747,6 +749,14 @@ export function trailRows(
747749 ];
748750 }
749751
752 /**
753 * "From <source>" for an app a pack made (#16068), the web header's words; nothing for any other.
754 */
755 export function sourceRows(f: Pick<Session, "db">, repo: Repo | undefined): [string, string][] {
756 const kept = repo === undefined ? undefined : repoSource(repo);
757 return kept === undefined ? [] : [["from", kept.source]];
758 }
759
750760 /**
751761 * How long an app's golden path took, in the apps page's words (#7488):
752762 * nothing on a repository that is not an app, or before either figure exists.
src/web/chrome.ts +14
@@ -20,6 +20,7 @@ import {
2020 } from "../core/repos.ts";
2121 import { nearRepos as nearTo } from "../core/near_repos.ts";
2222 import { type Repo, visibleForks } from "../core/repos.ts";
23 import { repoSource } from "../core/repo_source.ts";
2324 import { parentUrl, shownTrail, sourceLabel } from "../core/provenance.ts";
2425 import type { App } from "../app.ts";
2526 import type { Ctx } from "../http/context.ts";
@@ -333,6 +334,7 @@ export function scopeHeader(
333334 () => html`<p class="muted small">${facts.description}</p>`,
334335 )}
335336 ${repo === undefined ? null : lineageLine(ctx.app, repo, parent, family, parent !== undefined && canAdmin(ctx.app.db, repo, ctx.auth.user) ? `${base}/settings#follow-choice` : undefined)}
337 ${repo === undefined ? null : sourceLine(repo)}
336338 ${when(
337339 scope.upstream !== undefined && upstreamHref(scope) === undefined,
338340 // The where strip carries "fork of octo/widgets" and links it, which
@@ -417,6 +419,18 @@ export function lineageLine(
417419 </p>`;
418420 }
419421
422 /**
423 * The one muted "From <source>" line of an app a pack made (#16068); nothing for any other.
424 * Read off the repository row already in hand, so no repository page pays a statement for it.
outdated

Medium. This reads the database on every repo header, which is why two query budgets had to rise. Fold it into an existing read or skip it unless the repo is an app. Principle 8 / the direction's speed bar.

425 */
426 function sourceLine(repo: Repo): Html | null {
427 const kept = repoSource(repo);
outdated

Principle 8 and the docs: the link has rel but no target, yet packs.md says it opens in a new context. Make them agree. Also this adds one read on every repo header (see body, item 2).

428 if (kept === undefined) return null;
429 const external = kept.href.includes("://");
430 return html`<p class="muted small break" data-pack-source>From
431 <a href="${kept.href}"${external ? html` rel="noopener noreferrer"` : html``}>${kept.source}</a></p>`;
432 }
433
420434 /**
421435 * How a fork follows its parent, in the one plain sentence every door says (`followLineWords`,
422436 * #15767), linked to the setting for whoever may change it, then how far behind it is when the
test/packs-hands.test.ts +1
@@ -354,6 +354,7 @@ describe("forge-repo sources", () => {
354354 ]);
355355 expect(posts).toEqual([
356356 'POST /api/v1/repos/trevato/radar/forks {"name":"radar"}',
357 'PUT /api/v1/repos/me/radar/source {"source":"trevato/radar"}',
357358 'POST /api/v1/repos/trevato/notes/forks {"name":"notes"}',
358359 "GET /api/v1/user ",
359360 ]);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs