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

On a public app, the toolbar's 'make it yours' forks it into the visitor's forge in one step with a receipt, and says why when it cannot #15669

Merged opened this

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

Merged

torque/forge:torque/15645-on-a-public-app-the-toolbar-s-make-it-yo → main 0 commits fork 5 threads · 5 unresolved

  • Merged. torque/15645-on-a-public-app-the-toolbar-s-make-it-yo was merged into main as 7e5ef6c.

Review

Sign in to review this change.
13 files changed +383 −55
docs/features/make-it-yours.md +21
@@ -14,6 +14,24 @@ An app's own page offers the same one button (`src/web/studio/yours_button.ts`):
1414 sign-in and back; once you have a copy it reads **Open your copy**; a private app shows none, and it is never the page's primary button (**Open the app** is).
1515 There is no separate fork action on the repository tool: the existing `make_it_yours` tool below is that action.
1616
17 ## The toolbar's line
18
19 On a public app you do not write to, the forge toolbar's pill says **Make it yours** (`yoursLink`,
20 `src/apps/crew.ts`). Signed in, that one tap is the whole ask: the crew door (`/__forge/crew`) mints a `go`
21 token for the viewer the app's grant names and this repository (`signYoursGo`, `src/apps/yours_go.ts`: an HMAC
22 under a key derived from the forge's own, good for ten minutes), and the forge's plan page submits its own form to
23 `POST make-it-yours` only when that token verifies for the signed-in person and the repository. A link anyone else
24 writes (`go=1`, another person's or another app's token, an expired one) opens the same page, which waits for the
25 button: a third-party page cannot make a copy, and spend someone's copies and storage, by linking to it. The page's
26 one small script is served by the forge; without script the button is the same ask. Signed out, the link carries
27 no token: it goes through sign-in and back to the page, which waits for the button.
28
29 When it cannot be done, the pill says why in one line in place of the link (`yoursWhy`, from the same plan the
30 page and the MCP use): a guest ("This account is a guest..."), the day's copies made (`limitWords`), the
31 repositories limit or the storage limit ("Not made: 10 of 10 repositories."). A private app shows nothing, and so
32 does a repository you write to. The reason is a status line (`role="status"`), read aloud, never a link. The check
33 is a few indexed reads and the cached storage figure; nothing is made.
34
1735 ## Undo
1836
1937 `undoMakeItYours` removes the copy this tap made, only while it has no commits of its own and no pull was sent from
@@ -25,6 +43,9 @@ no Undo. The original is never touched.
2543 On a repository you can see but not write, open the palette and choose **Make it yours** (or press `Y` on the
2644 repository screen): a name, a visibility, the plan, then a confirm. Once you have a copy, **Undo make it yours**
2745 appears in the same palette and asks to confirm. A copy with changes or a sent pull is kept, and the toast says why.
46 A refusal is said on the screen and as a toast, from the same plan the toolbar reads (`refusalText`,
47 `src/tui/screens/yours.ts`): the repositories limit and the storage limit name the same figure the pill does
48 ("1 of 1 repositories"), and the day's copies say when another can be made (`test/tui-make-it-yours.test.ts`).
2849
2950 ## MCP
3051
src/actions/make_it_yours.ts +52 −2
@@ -23,7 +23,7 @@
2323 * already made does not count.
2424 */
2525
26 import { storageLimitMessage } from "../core/storage.ts";
26 import { storageLimitMessage, storageRefusal } from "../core/storage.ts";
2727 import type { App } from "../app.ts";
2828 import {
2929 getAppByRepo,
@@ -39,13 +39,14 @@ import {
3939 getRepoById,
4040 type Repo,
4141 } from "../core/repos.ts";
42 import { NOT_A_MEMBER } from "../core/roles.ts";
4243 import { isActive, type User } from "../core/users.ts";
4344 import { err, ok, type Result } from "../kernel/result.ts";
4445 import { requireVerified } from "./verify.ts";
4546 import { requireAbility } from "./roles.ts";
4647 import { requireAppRoom, appLimitWords } from "./app_limit.ts";
4748 import { disableApp, enableApp } from "./apps.ts";
48 import { deleteRepo, forkRepo, repositoryLimitMessage } from "./repos.ts";
49 import { deleteRepo, forkRepo, repositoryLimitMessage, repositoryLimitRefusal } from "./repos.ts";
4950 import { FORKS_PER_DAY } from "./fork_limit.ts";
5051 import { refsContaining } from "../git/builds.ts";
5152 import { listRefs } from "../git/read.ts";
@@ -213,6 +214,11 @@ export async function makeItYours(
213214 // so no repository is left behind), in the plan as in the making.
214215 if (!requireAppRoom(app, actor, actor.id).ok)
215216 return err({ kind: "invalid", message: appLimitWords(app, actor.id) });
217 // The forge's limits, in the plan as in the making, so a person is told before they tap.
218 if (repositoryLimitRefusal(app, actor) !== undefined)
219 return err({ kind: "repository_limit", message: repositoryLimitMessage(app, actor) });
220 if ((await storageRefusal(app, actor, actor.id)) !== undefined)
221 return err({ kind: "storage_limit", message: storageLimitMessage(app, actor.id) });
216222 const slug = freeSlug(app, { name }, actor.username);
217223 const plan = {
218224 dryRun,
@@ -274,6 +280,50 @@ export const receiptWords = (plan: Pick<MakeItYoursPlan, "repo" | "from" | "exis
274280 ? `${plan.repo} was already yours, a copy of ${plan.from}.`
275281 : `${plan.repo} is yours: a copy of ${plan.from}, following it. Its first deploy is under way. Undo removes it while it has nothing of your own.`;
276282
283 /** The limit's refusal, in the words the page, the toolbar and the MCP all say. */
284 export const limitWords = (resetsAtIso: string): string =>
285 `That is today's copies made (${COPIES_PER_DAY} a day). Another can be made after ${resetsAtIso.slice(11, 16)} UTC.`;
286
287 /**
288 * A refusal, in one line; undefined where there is nothing to say (not there, or already theirs).
289 */
290 export function refusalWords(error: MakeItYoursError): string | undefined {
291 switch (error.kind) {
292 case "not_found":
293 case "own":
294 return undefined;
295 case "invalid":
296 return error.message;
297 case "repository_limit":
298 case "storage_limit":
299 return `Not made: ${error.message}.`;
300 case "not_member":
301 return `Not made: ${NOT_A_MEMBER}.`;
302 case "unverified":
303 return "Prove your email first: the link is in your inbox.";
304 case "limit":
305 return limitWords(error.resetsAt);
306 default:
307 return "That could not be made yours.";
308 }
309 }
310
311 /**
outdated

yoursWhyNot misses repository_limit/storage_limit (child limit) which the issue names; check them in the plan so the toolbar says them in one line.

312 * Why a signed-in person cannot make this app theirs right now, in one line
313 * (the toolbar says it in place of the action), or undefined when they can.
314 * It plans; nothing is made.
315 */
316 export async function yoursWhyNot(app: App, actor: User, source: Repo): Promise<string | undefined> {
317 const plan = await makeItYours(app, actor, source, { dryRun: true });
318 if (!plan.ok)
319 return plan.error.kind === "not_member"
320 ? "This account is a guest, so it cannot copy apps; it can help build by sending changes."
321 : refusalWords(plan.error);
322 if (!plan.value.existing && plan.value.copiesLeft === 0)
323 return limitWords(resetsAt(app, actor.id, Date.now()));
324 return undefined;
325 }
326
277327 export const undoWords = (repo: string): string => `${repo} is removed. The original was not touched.`;
278328
279329 /** What an undo that only plans says: what it would remove, and how to do it. */
src/apps/crew.ts +29 −1
@@ -7,6 +7,8 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import type { App } from "../app.ts";
11 import { yoursWhyNot } from "../actions/make_it_yours.ts";
1012 import type { AppRecord } from "../core/apps.ts";
1113 import { mayDirectCrew } from "../crew/direct.ts";
1214 import { timePhase } from "../core/route_timing.ts";
@@ -157,6 +159,14 @@ export function yoursLink(
157159 app: AppRecord,
158160 viewerId: string | undefined,
159161 ): string | undefined {
162 const shown = yoursShown(db, app, viewerId);
163 return shown === undefined
164 ? undefined
165 : new URL(`/${shown.ownerName}/${shown.name}/make-it-yours`, forgeUrl).href;
166 }
167
168 /** The repository `yoursLink` points at, or undefined where it shows nothing. */
169 function yoursShown(db: Database, app: AppRecord, viewerId: string | undefined) {
160170 if (app.access !== "public") return undefined;
161171 const repo = getRepoById(db, app.repoId);
162172 if (repo === undefined || repo.visibility !== "public") return undefined;
@@ -165,5 +175,23 @@ export function yoursLink(
165175 if (viewer === undefined || !isActive(viewer)) return undefined;
166176 if (canWrite(db, repo, viewer)) return undefined;
167177 }
168 return new URL(`/${repo.ownerName}/${repo.name}/make-it-yours`, forgeUrl).href;
178 return repo;
179 }
180
181 /**
182 * Why the signed-in reader cannot make this public app theirs just now, in
183 * the one line the page and the MCP say (`yoursWhyNot`); undefined when they
184 * can, or when `yoursLink` shows nothing. Signed out, the page asks them to
185 * sign in, so there is nothing to refuse yet.
186 */
187 export async function yoursWhy(
188 app: App,
189 record: AppRecord,
190 viewerId: string | undefined,
191 ): Promise<string | undefined> {
192 if (viewerId === undefined) return undefined;
193 const repo = yoursShown(app.db, record, viewerId);
194 const viewer = getUserById(app.db, viewerId);
195 if (repo === undefined || viewer === undefined) return undefined;
196 return yoursWhyNot(app, viewer, repo);
169197 }
src/apps/proxy.ts +18 −2
@@ -54,7 +54,7 @@ import {
5454 type EnvName,
5555 } from "./data.ts";
5656 import type { AppsRuntime, EnvStatus } from "./runtime.ts";
57 import { crewLine, crewNow, tellLink, yoursLink } from "./crew.ts";
57 import { crewLine, crewNow, tellLink, yoursLink, yoursWhy } from "./crew.ts";
5858 import { sideOf, type Side } from "./side.ts";
5959 import { feedback, mintProof } from "./feedback.ts";
6060 import { carryPeer, clientBucket, nameClient } from "../http/peer.ts";
@@ -79,6 +79,7 @@ import { behindDefault } from "./pill_behind.ts";
7979 import { repoDir } from "../git/repos.ts";
8080 import { cspNonce, HIDE_COOKIE, HIDE_PATH, HIDE_SECONDS, htmlAnswer, readPage, rewritable, TOOLBAR_ASSET_PATH, TOOLBAR_ASSET_PREFIX, toolbarResponse, withToolbar, type PillWhere } from "./toolbar.ts";
8181 import { COMMENT_ASSET_PATH, commentResponse } from "./toolbar_comment.ts";
82 import { signYoursGo } from "./yours_go.ts";
8283 import { IDENTITY_HEADERS, identityHeaders, plainProof, readGrant, signGrant, verifyGrant, type Grant, type GrantWho } from "./grants.ts";
8384 // The grants moved to grants.ts (#15623); the tests still reach them here.
8485 export { grantUrl, identityKey, IDENTITY_HEADERS, plainProof, readGrant, signGrant, verifyGrant, type Grant, type GrantWho } from "./grants.ts";
@@ -1057,6 +1058,10 @@ export async function proxyApp(
10571058 sealedPull(runtime, target) !== undefined
10581059 ? undefined
10591060 : yoursLink(runtime.app.db, runtime.options.forgeUrl, target.app, signed?.who?.id);
outdated

A dry-run plan on every crew fetch is heavy for the common request; compute cheaply or cache per viewer/app for a short time.

1061 const why =
1062 yours === undefined || sealedPull(runtime, target) !== undefined
1063 ? undefined
1064 : await yoursWhy(runtime.app, target.app, signed?.who?.id);
10601065 const side =
10611066 signed?.who === undefined
10621067 ? null
@@ -1065,7 +1070,18 @@ export async function proxyApp(
10651070 JSON.stringify({
10661071 ...crew,
10671072 ...(tell === undefined ? {} : { tell }),
outdated

The link carries a fixed go=1 that anyone can write. Mint the token here from the grant viewer (never from the client) and append it, so only the toolbar can produce a link that submits itself.

1068 ...(yours === undefined ? {} : { yours }),
1073 // The tap submits itself only for the viewer the grant names, on this repository: the
1074 // token is minted here, never taken from the client (`yours_go.ts`). Signed out, the
1075 // page waits for the button after sign-in.
1076 ...(yours === undefined
1077 ? {}
1078 : {
1079 yours:
1080 signed?.who === undefined
1081 ? `${yours}?receipt=1`
1082 : `${yours}?receipt=1&go=${signYoursGo(runtime.app.config.dataDir, signed.who.id, target.app.repoId)}`,
1083 }),
1084 ...(why === undefined ? {} : { yoursWhy: why }),
10691085 ...(side === null ? {} : { side }),
10701086 }),
10711087 );
src/apps/toolbar.ts +6 −11
@@ -481,17 +481,12 @@ const toolbarSource = `(function () {
481481 crew.appendChild(ta);
482482 }
483483 }
484 // Make it yours: the forge's own fork page, on its origin; it asks a
485 // signed-out reader to sign in and returns to itself.
486 if (typeof c.yours === "string") {
487 var y = new URL(c.yours);
488 if (y.origin === forge) {
489 var ya = document.createElement("a");
490 ya.textContent = "Make it yours";
491 ya.href = y.href;
492 ya.style.cssText = LS;
493 crew.appendChild(ya);
494 }
484 if (typeof c.yours === "string" && new URL(c.yours).origin === forge) {
outdated

Principle 8/accessibility: the refusal is a bare span; give it role="status" so a screen reader hears why the action is gone. Also keep the string-type check on c.yours.

485 var yw = c.yoursWhy, ya = document.createElement(yw ? "span" : "a");
486 ya.textContent = yw || "Make it yours";
487 if (yw) ya.setAttribute("role", "status"); else ya.href = c.yours;
488 ya.style.cssText = LS;
489 crew.appendChild(ya);
495490 }
496491 // The other side: origin plus this path as text, so "//" cannot leave it.
497492 var sd = c.side;
src/apps/yours_go.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * The toolbar's "make it yours" tap, as a signed ask (#15645). The plan page
3 * submits its own form only when its link carries one of these: minted by the
4 * crew door (`/__forge/crew`) for the viewer its grant names and the app's
5 * repository, under a key derived from the forge's own, for a few minutes. A
6 * link anyone else writes (a third-party page, a message) carries none that
7 * verifies, so the page waits for the person's own tap on its button.
8 *
9 * Token: `<expiry ms>.<HMAC-SHA256 of "yours-go.<viewer>.<repo>.<expiry>">`,
10 * base64url.
11 */
12
13 import { createHmac, timingSafeEqual } from "node:crypto";
14 import { loadKey } from "../kernel/secret.ts";
15
16 /** How long a minted tap stays good: the crew door is read as the pill opens. */
17 export const YOURS_GO_TTL_MS = 10 * 60_000;
18
19 const SHAPE = /^(\d{1,15})\.([A-Za-z0-9_-]{43})$/;
20
21 function mac(dataDir: string, viewerId: string, repoId: string, expires: string): string {
22 return createHmac("sha256", loadKey(dataDir))
23 .update(`yours-go.${viewerId}.${repoId}.${expires}`)
24 .digest("base64url");
25 }
26
27 /** A tap token for this viewer and this repository, good until `now + ttlMs`. */
28 export function signYoursGo(
29 dataDir: string,
30 viewerId: string,
31 repoId: string,
32 now = Date.now(),
33 ttlMs = YOURS_GO_TTL_MS,
34 ): string {
35 const expires = String(now + ttlMs);
36 return `${expires}.${mac(dataDir, viewerId, repoId, expires)}`;
37 }
38
39 /** Whether `token` was minted for this viewer and repository and has not run out. */
40 export function verifyYoursGo(
41 dataDir: string,
42 token: string | null | undefined,
43 viewerId: string,
44 repoId: string,
45 now = Date.now(),
46 ): boolean {
47 if (typeof token !== "string") return false;
48 const m = SHAPE.exec(token);
49 if (m === null) return false;
50 const [, expires, signature] = m as unknown as [string, string, string];
51 if (Number(expires) <= now) return false;
52 const a = Buffer.from(signature);
53 const b = Buffer.from(mac(dataDir, viewerId, repoId, expires));
54 return a.length === b.length && timingSafeEqual(a, b);
55 }
src/web/studio/make_it_yours.ts +20 −20
@@ -7,7 +7,8 @@
77
88 import { blockedWay } from "../blocked.ts";
99 import { notMemberBlocked } from "../../actions/blocked_words.ts";
10 import { COPIES_PER_DAY, makeItYours, receiptWords, undoMakeItYours } from "../../actions/make_it_yours.ts";
10 import { verifyYoursGo } from "../../apps/yours_go.ts";
11 import { makeItYours, refusalWords, receiptWords, undoMakeItYours } from "../../actions/make_it_yours.ts";
1112 import type { Ctx } from "../../http/context.ts";
1213 import {
1314 loadRepo,
@@ -20,10 +21,9 @@ import { field, readForm } from "../form.ts";
2021 import { html, when } from "../html.ts";
2122 import { flashTo, page, redirect } from "../layout.ts";
2223 import { btn, card, row } from "../ui.ts";
23 import { BECOME_A_MEMBER, LINK_IS_NOT_MEMBERSHIP } from "../../core/roles.ts";
24 import { BECOME_A_MEMBER, LINK_IS_NOT_MEMBERSHIP, NOT_A_MEMBER } from "../../core/roles.ts";
2425 import { HELP_BUILD, HELP_BUILD_NEXT } from "../../core/contribute.ts";
2526 import type { Repo } from "../../core/repos.ts";
26 import { NOT_A_MEMBER } from "../../core/roles.ts";
2727 import {
2828 notePhase,
2929 takeSessionTime,
@@ -31,6 +31,8 @@ import {
3131 timePhase,
3232 } from "../../core/route_timing.ts";
3333
34 const AUTO_SUBMIT_JS = `document.getElementById("yours").requestSubmit();`;

High: auto-submitting on a bare go=1 makes a GET navigation perform the fork. A cross-site link triggers it for any signed-in visitor (forced fork, quota and storage burn). Submit only when a viewer-and-repo-bound, short-lived signed token minted by the crew endpoint verifies; otherwise wait for the button.

35
3436 type Refusal = Extract<Awaited<ReturnType<typeof makeItYours>>, { ok: false }>["error"];
3537
3638 /** Where a refused plan lands: back on the repository, saying why. */
@@ -98,6 +100,7 @@ export async function makeItYoursPage(ctx: Ctx): Promise<Response> {
98100 method="post"
99101 action="${repoBase(repo)}/make-it-yours"
100102 class="stack"
103 id="yours"
101104 >
102105 ${when(
103106 ctx.url.searchParams.get("receipt") === "1",
@@ -155,7 +158,17 @@ export async function makeItYoursPage(ctx: Ctx): Promise<Response> {
155158 </form>`,
156159 )}
157160 </div>`;
158 const response = page({ ctx, title: `Make ${p.from} yours`, body });
161 const response = page({
162 ctx,
163 title: `Make ${p.from} yours`,
164 body,
165 // The toolbar's tap is the whole ask only when its `go` token verifies for this viewer and
166 // repository (minted by the crew door, `apps/yours_go.ts`): then the page confirms itself,
167 // from its own origin. Any other link waits for the button below, which is the same ask.
168 ...(verifyYoursGo(ctx.app.config.dataDir, ctx.url.searchParams.get("go"), user.id, repo.id)
169 ? { scriptJs: AUTO_SUBMIT_JS }
170 : {}),
171 });
159172 notePhase(ctx.request, "render", performance.now() - rendering);
160173 return response;
161174 }
@@ -174,22 +187,9 @@ export async function makeItYoursSubmit(ctx: Ctx): Promise<Response> {
174187 ...(name === "" ? {} : { name }),
175188 });
176189 if (!made.ok || made.value.made === undefined) {
177 const message = !made.ok
178 ? made.error.kind === "invalid"
179 ? made.error.message
180 : made.error.kind === "repository_limit" || made.error.kind === "storage_limit"
181 ? `Not made: ${made.error.message}.`
182 : made.error.kind === "not_member"
183 ? `Not made: ${NOT_A_MEMBER}.`
184 : made.error.kind === "own"
185 ? "This app is already yours."
186 : made.error.kind === "unverified"
187 ? "Prove your email first: the link is in your inbox."
188 : made.error.kind === "limit"
189 ? `That is today's copies made (${COPIES_PER_DAY} a day). ` +
190 `Another can be made after ${made.error.resetsAt.slice(11, 16)} UTC.`
191 : "That could not be made yours."
192 : "That could not be made yours.";
190 const message =
191 (!made.ok && (made.error.kind === "own" ? "This app is already yours." : refusalWords(made.error))) ||
192 "That could not be made yours.";
193193 return flashTo(ctx, repoBase(repo), { tone: "danger", message });
194194 }
195195 if (field(form, "receipt") === "1")
test/apps-crew-pill.test.ts +3 −2
@@ -236,8 +236,9 @@ describe("the crew line", () => {
236236 url: `${servers.url}/alice/notes/runs/${run.id}`,
237237 tell: `${servers.url}/alice/notes/tell`,
238238 });
239 // A public app's signed-out reader is offered only the fork page.
240 const yours = { yours: `${servers.url}/alice/notes/make-it-yours` };
239 // A public app's signed-out reader is offered only the fork page, with no tap token (the page
240 // waits for its button).
241 const yours = { yours: `${servers.url}/alice/notes/make-it-yours?receipt=1` };
241242 expect(await (await ask()).json()).toEqual(yours);
242243 expect(await (await ask(`${grant}x`)).json()).toEqual(yours);
243244 // A grant that names nobody is a guest: nothing.
test/apps-toolbar-state.test.ts +4 −1
@@ -35,9 +35,12 @@ const DISMISSAL_ALLOWANCE = 1150;
3535 const CHECK_SLOT_ALLOWANCE = 230;
3636 // The pull title beside the number (#15169), allowed by name: 160 bytes.
3737 const TITLE_ALLOWANCE = 170;
38 // The toolbar's Make it yours saying why it cannot (a status, not a link), allowed by name: 40
39 // bytes.
40 const YOURS_WHY_ALLOWANCE = 50;
3841
3942 test("the addition stays under 300 bytes", () => {
40 expect(Buffer.byteLength(toolbarJs) - BASE_SCRIPT_BYTES).toBeLessThan(300 + DISMISSAL_ALLOWANCE + CHECK_SLOT_ALLOWANCE + TITLE_ALLOWANCE);
43 expect(Buffer.byteLength(toolbarJs) - BASE_SCRIPT_BYTES).toBeLessThan(300 + DISMISSAL_ALLOWANCE + CHECK_SLOT_ALLOWANCE + TITLE_ALLOWANCE + YOURS_WHY_ALLOWANCE);
4144 const tag = toolbarTag("https://forge.test", where("x".repeat(CHANGE_MAX)), "p", "n");
4245 const bare = toolbarTag("https://forge.test", where(), "p", "n");
4346 expect(Buffer.byteLength(tag) - Buffer.byteLength(bare)).toBeLessThan(300);
test/apps-toolbar-yours.test.ts +149 −14
@@ -1,4 +1,7 @@
1 /** The pill's "Make it yours": a public app's stranger gets the fork page; the owner and a private app get nothing. */
1 /**
2 * The pill's "Make it yours": a public app's stranger gets the fork page (and a reason when it
3 * cannot); the owner and a private app get nothing.
4 */
25
36 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
47 import { mkdtemp, rm } from "node:fs/promises";
@@ -6,15 +9,21 @@ import { tmpdir } from "node:os";
69 import { join } from "node:path";
710 import { createApp, type App } from "../src/app.ts";
811 import { newApp } from "../src/actions/apps.ts";
9 import { yoursLink } from "../src/apps/crew.ts";
12 import { COPIES_PER_DAY, limitWords, makeItYours } from "../src/actions/make_it_yours.ts";
13 import { yoursLink, yoursWhy } from "../src/apps/crew.ts";
1014 import { signGrant, type AppTarget, type GrantWho } from "../src/apps/proxy.ts";
1115 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
1216 import { toolbarJs } from "../src/apps/toolbar.ts";
17 import { signYoursGo, verifyYoursGo } from "../src/apps/yours_go.ts";
1318 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
1419 import { createIssue } from "../src/core/issues.ts";
1520 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
1621 import { setSealed } from "../src/core/sealed.ts";
17 import { createUser } from "../src/core/users.ts";
22 import { createSession } from "../src/core/sessions.ts";
23 import { getRepoById } from "../src/core/repos.ts";
24 import { setMember } from "../src/core/roles.ts";
25 import { setQuota } from "../src/settings/quotas.ts";
26 import { createUser, type User } from "../src/core/users.ts";
1827 import { serve, type Servers } from "../src/http/server.ts";
1928 import { quietLogs } from "./helpers/globals.ts";
2029
@@ -26,6 +35,7 @@ let app: App;
2635 let servers: Servers;
2736 let runtime: AppsRuntime;
2837 let alice = "";
38 let aliceUser: User;
2939 let bob = "";
3040 let pub: AppRecord;
3141 let priv: AppRecord;
@@ -43,12 +53,8 @@ beforeAll(async () => {
4353 servers = await serve(app);
4454 runtime = new AppsRuntime(app, { domain: DOMAIN, scheme: "http", publicPort: servers.port, forgeUrl: servers.url, concurrency: 1 });
4555 await runtime.start();
46 const person = async (username: string, adminIfFirst?: boolean) => {
47 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", ...(adminIfFirst ? { adminIfFirst } : {}) });
48 if (!u.ok) throw new Error(u.error);
49 return u.value;
50 };
5156 const a = await person("alice", true);
57 aliceUser = a;
5258 alice = a.id;
5359 bob = (await person("bob")).id;
5460 const make = async (name: string, visibility: "public" | "private") => {
@@ -99,6 +105,24 @@ afterAll(async () => {
99105 await rm(dataDir, { recursive: true, force: true });
100106 });
101107
108 async function person(username: string, adminIfFirst?: boolean): Promise<User> {
109 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", ...(adminIfFirst ? { adminIfFirst } : {}) });
110 if (!u.ok) throw new Error(u.error);
111 return u.value;
112 }
113 /** A public app of alice's of its own, so a test's copies touch no other's. */
114 async function freshApp(name: string): Promise<AppRecord> {
115 const made = await newApp(app, aliceUser, { name, description: "x", visibility: "public" });
116 if (!made.ok) throw new Error(String(made.error));
117 return getAppByRepo(app.db, made.value.repo.id)!;
118 }
119 /** A member (so not a guest), by name. */
120 async function member(username: string): Promise<User> {
121 const u = await person(username);
122 setMember(app.db, u.id, true, alice, new Date());
123 return u;
124 }
125
102126 const link = (a: AppRecord, who?: string) => yoursLink(app.db, servers.url, a, who);
103127
104128 test("a signed-out reader and a signed-in stranger of a public app are offered the fork page", () => {
@@ -124,7 +148,12 @@ test("the endpoint takes who the reader is from the grant, never the client", as
124148 (await fetch(`${servers.url}/__forge/crew`, {
125149 headers: { host: `pubapp.${DOMAIN}`, cookie: `${cookie}=${signGrant(dataDir, target, 60_000, Date.now(), who)}` },
126150 })).json() as Promise<{ yours?: string }>;
127 expect((await ask({ id: bob, name: "bob", role: "user" })).yours).toBe(`${servers.url}/alice/pubapp/make-it-yours`);
151 const bobs = new URL((await ask({ id: bob, name: "bob", role: "user" })).yours!);
152 expect(`${bobs.origin}${bobs.pathname}`).toBe(`${servers.url}/alice/pubapp/make-it-yours`);
153 expect(bobs.searchParams.get("receipt")).toBe("1");
154 // The tap token is minted for the viewer the grant names and this app's repository.
155 expect(verifyYoursGo(dataDir, bobs.searchParams.get("go"), bob, pub.repoId)).toBe(true);
156 expect(verifyYoursGo(dataDir, bobs.searchParams.get("go"), alice, pub.repoId)).toBe(false);
128157 expect((await ask({ id: alice, name: "alice", role: "admin" })).yours).toBeUndefined();
129158 });
130159
@@ -145,7 +174,7 @@ const crewAt = async (host: string, who?: string, env = "production") => {
145174 };
146175
147176 test("through the proxy, a preview of a sealed pull offers no link; an open pull's does", async () => {
148 expect((await crewAt(`pubapp--${openPull}.${DOMAIN}`, bob, `pull-${openPull}`)).yours).toBe(`${servers.url}/alice/pubapp/make-it-yours`);
177 expect((await crewAt(`pubapp--${openPull}.${DOMAIN}`, bob, `pull-${openPull}`)).yours).toStartWith(`${servers.url}/alice/pubapp/make-it-yours?receipt=1&go=`);
149178 // Someone who may not see the sealed pull, signed in or not, is not answered by its preview's
150179 // crew door at all (#15200).
151180 const sealedTarget = { app: pub, env: `pull-${sealedPullNo}` } as AppTarget;
@@ -176,6 +205,7 @@ test("through the proxy, the link is in no JSON or asset answer; a page carries
176205 async function runPill(crew: unknown) {
177206 const forge = "http://forge.test";
178207 const anchors: Record<string, any>[] = [];
208 const spans: Record<string, any>[] = [];
179209 const el = (): Record<string, any> => ({
180210 style: {}, dataset: {}, children: [] as any[],
181211 appendChild(c: any) { this.children.push(c); return c; },
@@ -183,7 +213,7 @@ async function runPill(crew: unknown) {
183213 attachShadow() { shadow = el(); return shadow; },
184214 });
185215 let shadow: Record<string, any> | undefined;
186 const make = (tag: string) => { const e = el(); e.tag = tag; if (tag === "a") anchors.push(e); return e; };
216 const make = (tag: string) => { const e = el(); e.tag = tag; e.attrs = {}; e.setAttribute = (k: string, v: string) => { e.attrs[k] = v; }; if (tag === "a") anchors.push(e); if (tag === "span") spans.push(e); return e; };
187217 const inShadow = (node: any, hit: any): boolean => node === hit || (node.children ?? []).some((c: any) => inShadow(c, hit));
188218 const doc = { currentScript: { src: "/__forge/toolbar-x.js", dataset: { forge, app: "pubapp", env: "production" } }, createElement: make, addEventListener() {}, body: el() };
189219 const fn = new Function("window", "document", "fetch", "location", "URL", toolbarJs);
@@ -196,14 +226,119 @@ async function runPill(crew: unknown) {
196226 }), { href: "https://pubapp.apps.test/" }, URL);
197227 });
198228 const yours = anchors.find((a) => a.textContent === "Make it yours");
199 return { yours, inShadow: yours !== undefined && shadow !== undefined && inShadow(shadow, yours) };
229 return { spans, yours, inShadow: yours !== undefined && shadow !== undefined && inShadow(shadow, yours) };
200230 }
201231
202232 test("the pill makes the anchor in its shadow root, same tab, with the forge's href; a foreign origin makes none", async () => {
203 const good = await runPill({ yours: "http://forge.test/alice/pubapp/make-it-yours" });
204 expect(good.yours?.href).toBe("http://forge.test/alice/pubapp/make-it-yours");
233 const good = await runPill({ yours: "http://forge.test/alice/pubapp/make-it-yours?receipt=1&go=1" });
234 expect(good.yours?.href).toBe("http://forge.test/alice/pubapp/make-it-yours?receipt=1&go=1");
205235 expect(good.inShadow).toBe(true);
206236 expect(good.yours?.target).toBeUndefined();
207237 expect((await runPill({ yours: "https://evil.test/alice/pubapp/make-it-yours" })).yours).toBeUndefined();
208238 expect((await runPill({})).yours).toBeUndefined();
209239 });
240
241 test("a guest is told in one line, and the crew answer carries the reason end to end", async () => {
242 const guest = await person("guestly");
243 const target = { app: pub, env: "production" } as AppTarget;
244 const cookie = `forge_grant_${pub.id.slice(-8)}`;
245 const crew = (await (await fetch(`${servers.url}/__forge/crew`, {
246 headers: { host: `pubapp.${DOMAIN}`, cookie: `${cookie}=${signGrant(dataDir, target, 60_000, Date.now(), { id: guest.id, name: "guestly", role: "user" })}` },
247 })).json()) as { yours?: string; yoursWhy?: string };
248 expect(crew.yoursWhy).toBe("This account is a guest, so it cannot copy apps; it can help build by sending changes.");
249 expect(crew.yours).toContain("make-it-yours");
250 });
251
252 test("no reason against a member stranger; none for the owner, a signed-out reader or a private app", async () => {
253 const bobby = await member("bobby");
254 expect(await yoursWhy(app, pub, bobby.id)).toBeUndefined();
255 expect(await yoursWhy(app, pub, undefined)).toBeUndefined();
256 expect(await yoursWhy(app, pub, alice)).toBeUndefined();
257 expect(await yoursWhy(app, priv, bobby.id)).toBeUndefined();
258 });
259
260 test("once the day's copies are made the reason is the page's own limit words; a copy already made is not refused", async () => {
261 const carol = await member("carol");
262 const apps: AppRecord[] = [];
263 for (let i = 0; i <= COPIES_PER_DAY; i++) apps.push(await freshApp(`limited${i}`));
264 for (let i = 0; i < COPIES_PER_DAY; i++) {
265 const made = await makeItYours(app, carol, getRepoById(app.db, apps[i]!.repoId)!, { dryRun: false });
266 expect(made.ok).toBe(true);
267 }
268 const why = await yoursWhy(app, apps[COPIES_PER_DAY]!, carol.id);
269 const hhmm = /after (\d\d:\d\d) UTC/.exec(why ?? "")?.[1];
270 expect(hhmm).toBeDefined();
271 // Exactly the sentence `limitWords` makes, for the time it names.
272 expect(why).toBe(limitWords(`2000-01-01T${hhmm}:00.000Z`));
273 expect(await yoursWhy(app, apps[0]!, carol.id)).toBeUndefined();
274 });
275
276 test("the repositories limit is said up front, in the words the fork would be refused in", async () => {
277 const dan = await member("dan");
278 const target = await freshApp("limitedrepo");
279 setQuota(app.db, "repositories", 0 + 1, alice);
280 try {
281 const own = await newApp(app, dan, { name: "mine", description: "x", visibility: "private" });
282 expect(own.ok).toBe(true);
283 const why = await yoursWhy(app, target, dan.id);
284 expect(why).toBe("Not made: 1 of 1 repositories.");
285 const real = await makeItYours(app, dan, getRepoById(app.db, target.repoId)!, { dryRun: false });
286 expect(real.ok).toBe(false);
287 expect(real.ok ? "" : real.error.kind).toBe("repository_limit");
288 } finally {
289 setQuota(app.db, "repositories", null, alice);
290 }
291 });
292
293 test("the pill says a reason as a status line, never as a link; and still checks the string", async () => {
294 const refused = await runPill({ yours: "http://forge.test/alice/pubapp/make-it-yours?receipt=1&go=1", yoursWhy: "Not made: 1 of 1 repositories." });
295 expect(refused.yours).toBeUndefined();
296 const span = refused.spans.find((e) => e.textContent === "Not made: 1 of 1 repositories.");
297 expect(span?.attrs.role).toBe("status");
298 expect(span?.href).toBeUndefined();
299 expect((await runPill({ yours: 5, yoursWhy: "x" })).spans.some((e) => e.textContent === "x")).toBe(false);
300 });
301
302 const autoSubmits = (h: string) => (h.match(/<script[^>]*\ssrc="[^"]+"/g) ?? []).length;
303
304 test("the toolbar's tap lands on a page that submits itself, to the forge's own POST; the plain page loads no script", async () => {
305 const eve = await member("eve");
306 const cookie = `forge_session=${createSession(app.db, eve.id).token}`;
307 const get = (q: string) => fetch(`${servers.url}/alice/pubapp/make-it-yours${q}`, { headers: { cookie } });
308 const tapped = await get(`?receipt=1&go=${signYoursGo(dataDir, eve.id, pub.repoId)}`);
309 expect(tapped.status).toBe(200);
310 const html = await tapped.text();
311 expect(html).toContain('id="yours"');
312 expect(html).toContain('action="/alice/pubapp/make-it-yours"');
313 expect(html).toContain("Make it yours");
314 const csp = tapped.headers.get("content-security-policy") ?? "";
315 expect(csp).toContain("script-src");
316 const plain = await (await get("?receipt=1")).text();
317 expect(autoSubmits(html)).toBeGreaterThan(autoSubmits(plain));
318 });
319
320 test("a link anyone can write never submits itself: go=1, a forged, expired, or another viewer's or repository's token waits for the button", async () => {
321 const fay = await member("fay");
322 const cookie = `forge_session=${createSession(app.db, fay.id).token}`;
323 const get = async (go: string) =>
324 (await fetch(`${servers.url}/alice/pubapp/make-it-yours?receipt=1&go=${encodeURIComponent(go)}`, { headers: { cookie } })).text();
325 const plain = await (await fetch(`${servers.url}/alice/pubapp/make-it-yours?receipt=1`, { headers: { cookie } })).text();
326 const good = await get(signYoursGo(dataDir, fay.id, pub.repoId));
327 expect(autoSubmits(good)).toBeGreaterThan(autoSubmits(plain));
328 const refused = [
329 "1",
330 signYoursGo(dataDir, bob, pub.repoId), // another viewer's
331 signYoursGo(dataDir, fay.id, orgApp.repoId), // another repository's
332 signYoursGo(dataDir, fay.id, pub.repoId, Date.now() - 60 * 60_000), // run out
333 `${Date.now() + 60_000}.${"A".repeat(43)}`, // not signed by this forge
334 ];
335 for (const go of refused) {
336 const page = await get(go);
337 expect(page).toContain('id="yours"'); // the button is still the ask
338 expect(autoSubmits(page)).toBe(autoSubmits(plain));
339 }
340 });
341
342 test("a signed-out reader's link carries no tap token", async () => {
343 expect((await crewAt(`pubapp.${DOMAIN}`)).yours).toBe(`${servers.url}/alice/pubapp/make-it-yours?receipt=1`);
344 });
test/never-lost.test.ts +1 −1
@@ -155,7 +155,7 @@ describe("never lost: the pill from production and from a preview", () => {
155155 if (place.preview) expect(html).toContain(` data-pull="${pull}"`);
156156 // A public app offers a stranger Make it yours, never the tell page.
157157 expect(await (await ask(host(), "/__forge/crew")).json()).toEqual({
158 yours: `${servers.url}/alice/notes/make-it-yours`,
158 yours: `${servers.url}/alice/notes/make-it-yours?receipt=1`,
159159 });
160160 const door = await (await ask(host(), "/__forge/")).text();
161161 expect(door).toContain("/__forge/signin");
test/repo-pages-timing.test.ts +1 −1
@@ -62,7 +62,7 @@ const MAX_STATEMENTS: Record<string, number> = {
6262 "/alice/forge/issues/new": 38,
6363 "/alice/forge/report": 37, // +1: reports closed, read from the row (#15053)
6464 "/alice/forge/toolbar": 22,
65 "/alice/forge/make-it-yours": 27,
65 "/alice/forge/make-it-yours": 32, // +4: the plan reads the repository and storage limits (the toolbar says them up front)
6666 };
6767
6868 /** Path, who is signed in, the phases it names (bar `app` and `total`), in order. */
test/tui-make-it-yours.test.ts +24
@@ -16,6 +16,7 @@ import { quietLogs } from "./helpers/globals.ts";
1616 import { promote } from "./helpers/members.ts";
1717 import { settleApp, settleUntil } from "./helpers/tui.ts";
1818 import { proveAll } from "./helpers/verified.ts";
19 import { setQuota } from "../src/settings/quotas.ts";
1920
2021 quietLogs();
2122
@@ -129,6 +130,29 @@ test("a sixth copy in a day is refused in MCP's words, and nothing is made", asy
129130 h.app.stop();
130131 });
131132
133 test("the repositories limit is refused in the words the toolbar says, and nothing is made", async () => {
134 const dave = await mkUser("dave");
135 promote(forge.db);
136 proveAll(forge);
137 const repo = await original();
138 const own = await newApp(forge, dave, { name: "mine", visibility: "private" });
139 if (!own.ok) throw new Error(String(own.error));
140 setQuota(forge.db, "repositories", 1, alice.id);
141 try {
142 const h = await open(dave, repo);
143 await h.press("Y");
144 await h.press("enter");
145 const text = await h.press("enter");
146 // The toolbar's line is "Not made: 1 of 1 repositories." (`refusalWords`); the terminal says
147 // the same figure.
148 expect(text).toContain("1 of 1 repositories");
149 expect(getRepo(forge.db, "dave", repo.name)).toBeUndefined();
150 h.app.stop();
151 } finally {
152 setQuota(forge.db, "repositories", null, alice.id);
153 }
154 });
155
132156 test("your own repository is refused as 'already yours'", async () => {
133157 const repo = await original();
134158 const h = await open(alice, repo);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs