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

An outsider with no account offers a patch to a public repository, held for a person to read #12442

opened this

Closed 18d 12h ago

mason/forge:mason/12402-an-outsider-with-no-account-offers-a-pat → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
26 files changed +758 −34
docs/MCP.md +1
@@ -239,6 +239,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
239239 | `whoami_can` | `role`, `passkeys` | What you can do: your role and its roles-table row, yes or no each | 231 |
240240 | `write_file` | — | No shell? Commit one file to a branch | 342 |
241241 | `report` | — | Report a problem in a public repository, no account needed | 468 |
242 | `offer` | — | Offer a patch (unified diff) to a public repository, no account needed; a person reads it first | 347 |
242243 | `start` | `contribute` | Start building with no account: an account, a repo, a live app and a token in one call | 387 |
243244 <!-- mcp-tools:end -->
244245
docs/features/offer.md added +42
@@ -0,0 +1,42 @@
1 # Offer a patch, with no account
2
3 On a public repository an outside person or agent can offer a change the way
4 they can report a problem: no account, no token, nothing to be taught.
5
6 - **API:** `POST /api/v1/repos/{owner}/{name}/offers` with
7 `{"title": "…", "body": "…", "patch": "<a unified diff>"}`
8 → `202 {"number", "state": "open", "url", "message"}`.
9 - **MCP:** the tool `offer` with `{repo, title, body?, patch}`; open without a
10 token, like `report`, and it says the same words. It is not in a fresh
11 connection's short list; `find_tool` or `tools/list` with `all: true` finds it.
12 - **Try it:** `git diff > fix.patch`, then
13 `curl -s -X POST "$FORGE/api/v1/repos/owner/name/offers" -H 'content-type: application/json' -d "$(jq -n --rawfile p fix.patch '{title:"Fix it", patch:$p}')"`.
14
15 ## What happens to it
16
17 It becomes a stranger's pull (`src/crew/stranger.ts`): committed to a
18 `contrib/offer/<segment>/…` branch under one shared account that writes
19 nothing, and opened the way an outside agent's pull is. A person who can write
20 the repository reads it and approves it; until then no preview and no
21 repository secret reaches its code, and it never merges without a person.
22 Paths a stranger may not change (secrets, `check` and `release` in
23 `forge.json`) stay guarded.
24
25 ## What is refused (422 naming why; nothing is stored)
26
27 | error | when |
28 |---|---|
29 | `empty_title`, `title_too_long`, `body_too_long`, `patch_missing` | the words are not 1-200 characters, at most 8,000, and a patch |
30 | `patch_too_large` | more than 200 KB |
31 | `patch_not_text`, `patch_unsupported` | a NUL byte; binary files, symlinks, submodules |
32 | `patch_touches_git` | any header names `.git` as a path part, in any case |
33 | `patch_bad_path` | a header path that is absolute, climbs with `..` or is quoted |
34 | `patch_does_not_apply` | it does not apply to the default branch's head |
35
36 A private, archived, sealed or mirrored repository answers `not_found`. Three
37 offers a minute from one source, ten a minute to one repository, thirty to the
38 forge (`429`); a repository holds at most 20 open offers (`429 queue_full`).
39
40 The patch is applied only to a scratch index (`src/git/patch_files.ts`: the
41 text goes on stdin, never in an argument), and its headers are read first
42 (`patchHeaderRefusal` in `src/actions/offer.ts`): on any doubt, refuse.
src/actions/here.ts +9 −1
@@ -320,6 +320,12 @@ function forgeActions(
320320 mcp: "report",
321321 ...tokenFree("report"),
322322 },
323 {
324 do: "offer a patch",
325 http: "POST /api/v1/repos/{owner}/{name}/offers",
326 mcp: "offer",
327 ...tokenFree("offer"),
328 },
323329 {
324330 // The HTTP route is open, but the MCP tool is not, so no claim is made.
325331 do: "see how to help build this forge",
@@ -382,13 +388,15 @@ function repoActions(
382388 const acts =
383389 viewer !== undefined && (scope === undefined || scopeAllows(scope, "rw"));
384390 const out: Action[] = [{ do: "read", http: `GET ${r}`, mcp: "repo" }];
385 if (canRead(db, repo, undefined))
391 if (canRead(db, repo, undefined)) {
386392 out.push({
387393 do: "report a problem",
388394 http: `POST ${r}/reports`,
389395 mcp: "report",
390396 ...tokenFree("report"),
391397 });
398 out.push({ do: "offer a patch", http: `POST ${r}/offers`, mcp: "offer", ...tokenFree("offer") });
399 }
392400 // What creates or costs waits for a proven email (`requireVerified`).
393401 const unproven =
394402 viewer !== undefined && !emailVerified(db, viewer.id) ? { verify: true } : {};
src/actions/offer.ts added +256
@@ -0,0 +1,256 @@
1 /**
2 * An offer from outside (#12402): anyone, with no account, sends a patch to
3 * a public repository and it becomes a stranger's pull (`crew/stranger.ts`)
4 * for a person to read. The riskiest door the forge has, so it refuses by
5 * default on any doubt:
6 *
7 * - **Public originals only.** A private, archived, sealed or mirrored
8 * repository answers `not_found`, exactly as a missing one.
9 * - **Limited three ways**, as reports are: per source, per repository and
10 * for the whole forge, each a sliding minute, and a repository holds at
11 * most `OFFERS_WAITING_MAX` open offers.
12 * - **The patch is text, read before it is run.** Its headers are scanned
13 * for `.git`, `..` and absolute or quoted paths; it is then applied only
14 * to a scratch index (`git/patch_files.ts`: the text goes on stdin, never
15 * in an argument; no work tree is touched) and read back as whole files
16 * that pass the ordinary safe-path rules. Nothing is stored unless every
17 * step passed.
18 * - **It is a stranger's pull.** Committed to a `contrib/offer/<segment>/…`
19 * branch (the shape only an outside hand has, `core/contribute_token.ts`)
20 * under one shared account that writes nothing, and opened with the
21 * outside agent's path: no preview or secret until a person approves it,
22 * no merge without one, and the forge.json and secret paths a stranger
23 * may not change stay guarded.
24 */
25 import { mkdir } from "node:fs/promises";
26 import { join } from "node:path";
27 import type { App } from "../app.ts";
28 import { commitIdentity } from "../core/commit_identity.ts";
29 import { isContributionFork } from "../core/contribute.ts";
30 import { type Pull } from "../core/pulls.ts";
31 import { plainText } from "../core/reports.ts";
32 import { RateLimiter } from "../core/ratelimit.ts";
33 import { canRead, type Repo } from "../core/repos.ts";
34 import { createUser, getUserById, type User } from "../core/users.ts";
35 import { runGit } from "../git/env.ts";
36 import { isSafeRef } from "../git/guard.ts";
37 import { resolveOid } from "../git/merge.ts";
38 import { patchToFiles } from "../git/patch_files.ts";
39 import { repoDir } from "../git/repos.ts";
40 import { commitFiles } from "../git/write.ts";
41 import { err, ok, type Result } from "../kernel/result.ts";
42 import { isMirror } from "../origins/write-through.ts";
43 import { noEmail } from "./users.ts";
44 import {
45 OFFER_BODY_MAX,
46 OFFER_PATCH_MAX,
47 OFFER_TITLE_MAX,
48 type OfferRefusal,
49 } from "./offer_words.ts";
50 import { openPull } from "./pulls.ts";
51
52 /** A few a minute from one source; the other two hold when a source lies. */
53 export const OFFERS_PER_SOURCE = 3;
54 const PER_REPO = 10;
55 const PER_FORGE = 30;
56 /** Open offers one repository holds before it takes no more. */
57 export const OFFERS_WAITING_MAX = 20;
58 /** The branch prefix every offer lives under; `core/contribute_token.ts` knows its shape. */
59 const BRANCH_PREFIX = "contrib/offer";
60
61 export type OfferError =
62 | { readonly error: "not_found" | "queue_full" | "unavailable" | OfferRefusal }
63 | { readonly error: "rate_limited"; readonly retryAfter: number };
64
65 export interface OfferInput {
66 readonly title: string;
67 readonly body: string;
68 readonly patch: string;
69 }
70
71 export interface Offered {
72 readonly number: number;
73 readonly pull: Pull;
74 }
75
76 interface Limits {
77 readonly source: RateLimiter;
78 readonly repo: RateLimiter;
79 readonly forge: RateLimiter;
80 }
81 const limiter = (perMinute: number) => new RateLimiter({ perMinute, adminPerMinute: perMinute, enabled: true });
82 /** One set per forge, so a test's forge never throttles another's. */
83 const limits = new WeakMap<App, Limits>();
84 function limitsOf(app: App): Limits {
85 let found = limits.get(app);
86 if (found === undefined) {
87 found = { source: limiter(OFFERS_PER_SOURCE), repo: limiter(PER_REPO), forge: limiter(PER_FORGE) };
88 limits.set(app, found);
89 }
90 return found;
91 }
92
93 /** Whether `repo` takes offers: a public, unsealed, unarchived original. */
94 export function takesOffers(app: App, repo: Repo): boolean {
95 return (
96 canRead(app.db, repo, undefined) &&
97 repo.visibility === "public" &&
98 repo.sealedFor === null &&
99 repo.archivedAt === null &&
100 !isMirror(app, repo) &&
101 !isContributionFork(app.db, repo.id)
102 );
103 }
104
105 /**
106 * The paths a patch's header lines name, as written (a name may hold spaces, so a line is split
107 * on slashes and spaces).
108 */
109 const HEADER = /^(?:diff --git |--- |\+\+\+ |rename (?:from|to) |copy (?:from|to) )(.*)$/;
110
111 /**
112 * Why a patch's headers are refused, or undefined. Every header line is read,
113 * and a content line that merely looks like one is refused too: on any doubt, no.
114 */
115 export function patchHeaderRefusal(patch: string): "patch_touches_git" | "patch_bad_path" | undefined {
116 for (const line of patch.split("\n")) {
117 const named = HEADER.exec(line.replace(/\r$/, ""));
118 if (named === null) continue;
119 const text = named[1] ?? "";
120 // A quoted name carries C escapes (`\056git`): refuse rather than decode.
121 if (text.includes('"') || text.includes("\\")) return "patch_bad_path";
122 for (const word of text.split(/[ \t]+/)) {
123 if (word === "" || word === "/dev/null") continue;
124 const path = word.replace(/^[ab]\//, "");
125 if (path.startsWith("/") || /[\x00-\x1f\x7f]/.test(word)) return "patch_bad_path";
126 for (const part of path.split("/")) {
127 if (part.toLowerCase() === ".git") return "patch_touches_git";
128 if (part === "..") return "patch_bad_path";
129 }
130 }
131 }
132 return undefined;
133 }
134
135 /** The words as they will be stored, or why they will not be. */
136 export function cleanOffer(input: { title: unknown; body: unknown; patch: unknown }): Result<OfferInput, OfferRefusal> {
137 const title = plainText(typeof input.title === "string" ? input.title : "").replace(/\s+/g, " ").trim();
138 if (title === "") return err("empty_title");
139 if (title.length > OFFER_TITLE_MAX) return err("title_too_long");
140 const body = plainText(typeof input.body === "string" ? input.body : "").trim();
141 if (body.length > OFFER_BODY_MAX) return err("body_too_long");
142 if (typeof input.patch !== "string" || input.patch.trim() === "") return err("patch_missing");
143 if (Buffer.byteLength(input.patch, "utf8") > OFFER_PATCH_MAX) return err("patch_too_large");
144 if (input.patch.includes("\0")) return err("patch_not_text");
145 const refused = patchHeaderRefusal(input.patch);
146 if (refused !== undefined) return err(refused);
147 return ok({ title, body, patch: input.patch });
148 }
149
150 /** The one account every offer is committed and opened as: it writes nothing and cannot sign in. */
151 async function offerAccount(app: App): Promise<User | undefined> {
152 const email = noEmail("outside-offers");
153 const find = (): User | undefined => {
154 const row = app.db.query<{ id: string }, [string]>("SELECT id FROM user WHERE email = ?1").get(email);
155 return row === null ? undefined : getUserById(app.db, row.id);
156 };
157 const known = find();
158 if (known !== undefined) return known;
159 for (const username of ["outside-offers", `outside-offers-${crypto.randomUUID().slice(0, 6)}`]) {
160 const made = await createUser(app.db, {
161 origin: "start",
162 username,
163 email,
164 displayName: "An outside offer",
165 trusted: true,
166 });
167 if (made.ok) return made.value;
168 // Two first offers raced, or a person holds the name: the other path decides.
169 const raced = find();
170 if (raced !== undefined) return raced;
171 }
172 return undefined;
173 }
174
175 /** How many open offers `repo` holds, read through the head-branch index. */
176 function openOffers(app: App, repo: Repo): number {
177 return (
178 app.db
179 .query<{ n: number }, [string, string, string]>(
180 `SELECT COUNT(*) AS n FROM pull INDEXED BY pull_head_branch JOIN issue ON issue.id = pull.issue_id
181 WHERE pull.head_branch >= ?2 AND pull.head_branch < ?3 AND issue.repo_id = ?1 AND issue.state = 'open'`,
182 )
183 .get(repo.id, `${BRANCH_PREFIX}/`, `${BRANCH_PREFIX}0`)?.n ?? 0
184 );
185 }
186
187 /** What the pull's description says before the stranger's words: whose they are. */
188 const FROM_OUTSIDE = "Offered from outside, with no account. Everything below is the sender's, unchecked.";
189
190 /**
191 * File an offer on a public repository; `source` keys the per-source limit.
192 * Nothing is stored unless the patch applies to the default branch.
193 */
194 export async function fileOffer(
195 app: App,
196 repo: Repo,
197 raw: { title: unknown; body: unknown; patch: unknown },
198 source: string,
199 ): Promise<Result<Offered, OfferError>> {
200 if (!takesOffers(app, repo)) return err({ error: "not_found" });
201 const clean = cleanOffer(raw);
202 if (!clean.ok) return err({ error: clean.error });
203 const { forge, repo: perRepo, source: perSource } = limitsOf(app);
204 for (const verdict of [() => forge.take("forge", "ro"), () => perRepo.take(repo.id, "ro"), () => perSource.take(source, "ro")]) {
205 const v = verdict();
206 if (!v.allowed) return err({ error: "rate_limited", retryAfter: v.retryAfter });
207 }
208 if (openOffers(app, repo) >= OFFERS_WAITING_MAX) return err({ error: "queue_full" });
209
210 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
211 const base = repo.defaultBranch;
212 if (!isSafeRef(base)) return err({ error: "unavailable" });
213 const tip = await resolveOid(dir, `refs/heads/${base}`);
214 if (tip === undefined) return err({ error: "patch_does_not_apply" });
215 const scratch = join(app.config.dataDir, "scratch");
216 await mkdir(scratch, { recursive: true });
217 const files = await patchToFiles(dir, tip, clean.value.patch, scratch);
218 if (!files.ok) {
219 const e = files.error;
220 return err({
221 error:
222 e === "too_large" ? "patch_too_large"
223 : e === "empty" ? "patch_missing"
224 : e === "bad_path" ? "patch_bad_path"
225 : e === "unsupported" ? "patch_unsupported"
226 : "patch_does_not_apply",
227 });
228 }
229 const account = await offerAccount(app);
230 if (account === undefined) return err({ error: "unavailable" });
231
232 const segment = crypto.randomUUID().replace(/-/g, "").slice(0, 8);
233 const branch = `${BRANCH_PREFIX}/${segment}/${Date.now().toString(36)}`;
234 const committed = await commitFiles(dir, {
235 branch,
236 startPoint: base,
237 message: clean.value.title,
238 files: files.value,
239 author: commitIdentity(app.config, account),
240 });
241 // `.git` as a path component is refused here too, by the writer itself.
242 if (!committed.ok) return err({ error: committed.error.kind === "invalid_path" ? "patch_touches_git" : "unavailable" });
243 const opened = await openPull(app, account, repo, {
244 title: clean.value.title,
245 body: `${FROM_OUTSIDE}\n\n${clean.value.body}`.trim(),
246 baseBranch: base,
247 headBranch: branch,
248 outsideAgent: true,
249 });
250 if (!opened.ok) {
251 // Nothing is kept of a refused offer: the branch goes with it.
252 await runGit(["update-ref", "-d", `refs/heads/${branch}`], { cwd: dir });
253 return err({ error: "unavailable" });
254 }
255 return ok({ number: opened.value.number, pull: opened.value });
256 }
src/actions/offer_words.ts added +51
@@ -0,0 +1,51 @@
1 /**
2 * The words a stranger is told about offering a patch, said once: the API's
3 * answers, the MCP `offer` tool, /llms.txt and the OpenAPI contract all read
4 * from here, so they are the same wherever they appear.
5 */
6
7 /** The most patch bytes one offer takes (200 KB). */
8 export const OFFER_PATCH_MAX = 200 * 1024;
9 /**
10 * JSON may spell each byte of a patch as six (`\u00XX`): a request is bounded past the patch,
11 * the patch itself exactly.
12 */
13 export const OFFER_REQUEST_MAX = OFFER_PATCH_MAX * 6 + 32 * 1024;
14 export const OFFER_TITLE_MAX = 200;
15 export const OFFER_BODY_MAX = 8_000;
16
17 /** The answer to an offer that was stored and now waits for a person. */
18 export const OFFER_RECEIVED =
19 "Received as a pull. A person who maintains this repository reads it; nothing runs with the repository's secrets and nothing lands before they approve it.";
20
21 /** What a refused offer is told: the shape that would have been taken. */
22 export const OFFER_HINT =
23 `send JSON {title, body?, patch}: plain text; a title of 1-${OFFER_TITLE_MAX} characters, ` +
24 `a body of at most ${OFFER_BODY_MAX}, a patch that is a unified diff of text files ` +
25 `(git diff output) of at most ${OFFER_PATCH_MAX / 1024} KB that applies to the default branch`;
26
27 export type OfferRefusal =
28 | "empty_title"
29 | "title_too_long"
30 | "body_too_long"
31 | "patch_missing"
32 | "patch_too_large"
33 | "patch_not_text"
34 | "patch_touches_git"
35 | "patch_bad_path"
36 | "patch_does_not_apply"
37 | "patch_unsupported";
38
39 /** Why each refusal is a 422, in words that say what to change. */
40 export const OFFER_WORDS: Readonly<Record<OfferRefusal, string>> = {
41 empty_title: "the title is empty: say in one line what the change does",
42 title_too_long: `the title is longer than ${OFFER_TITLE_MAX} characters`,
43 body_too_long: `the body is longer than ${OFFER_BODY_MAX} characters`,
44 patch_missing: "the patch is missing: send a unified diff as text",
45 patch_too_large: `the patch is larger than ${OFFER_PATCH_MAX / 1024} KB: offer a smaller change, or fork and send a pull`,
46 patch_not_text: "the patch is not plain text: send a unified diff of text files",
47 patch_touches_git: "the patch touches .git, which an offer may never change",
48 patch_bad_path: "the patch names a path that is absolute, climbs out with .., or is not a safe path",
49 patch_does_not_apply: "the patch does not apply to the repository's default branch: make it against its current head",
50 patch_unsupported: "the patch changes something an offer may not: binary files, symlinks and submodules are refused",
51 };
src/contract/openapi/routes/index.ts +1
@@ -361,6 +361,7 @@ export { route as postApiV1ReposOwnerNameJobsIdAction } from "./postApiV1ReposOw
361361 export { route as postApiV1ReposOwnerNameLabels } from "./postApiV1ReposOwnerNameLabels.ts";
362362 export { route as postApiV1ReposOwnerNameMakeItYours } from "./postApiV1ReposOwnerNameMakeItYours.ts";
363363 export { route as postApiV1ReposOwnerNameMilestonesNumberLimb } from "./postApiV1ReposOwnerNameMilestonesNumberLimb.ts";
364 export { route as postApiV1ReposOwnerNameOffers } from "./postApiV1ReposOwnerNameOffers.ts";
364365 export { route as postApiV1ReposOwnerNameOriginHook } from "./postApiV1ReposOwnerNameOriginHook.ts";
365366 export { route as postApiV1ReposOwnerNameOriginReconnect } from "./postApiV1ReposOwnerNameOriginReconnect.ts";
366367 export { route as postApiV1ReposOwnerNamePlan } from "./postApiV1ReposOwnerNamePlan.ts";
src/contract/openapi/routes/postApiV1ReposOwnerNameOffers.ts added +12
@@ -0,0 +1,12 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/offers`,
6 summary:
7 "Offer a change to a public repository as a unified diff (at most 200 KB), without an account; answers 202 { number, state, url, message }: a pull a person reads before anything runs or lands. A patch that does not apply, touches .git or is too large answers 422 naming why, and nothing is stored; a few a minute from one source",
8 auth: false,
9 role: "anonymous",
10 body: { title: "string", body: "string", patch: "string" },
11 status: 202,
12 };
src/contract/tags.ts +1
@@ -16,6 +16,7 @@ const ALIAS: Readonly<Record<string, string>> = {
1616 upstream: "forks",
1717 "make-it-yours": "forks",
1818 contribute: "forks",
19 offers: "forks",
1920 queue: "gates",
2021 growth: "issues",
2122 chapters: "issues",
src/core/mcp_card.ts +1 −1
@@ -58,7 +58,7 @@ export function apiCatalog(origin: string) {
5858 * `http/mcp.ts` answers these and refuses the rest with 401. The card and
5959 * `/api/v1/here` both read this list, so they cannot drift.
6060 */
61 export const TOKEN_FREE_TOOLS: readonly string[] = ["report", "start"];
61 export const TOKEN_FREE_TOOLS: readonly string[] = ["report", "offer", "start"];
6262
6363 /** A thin plugin the forge ships for a harness: where its source is and its one install line. */
6464 export interface HarnessPlugin {
src/crew/stranger.ts +3 −1
@@ -1,7 +1,9 @@
11 /**
22 * A stranger's pull (#9575): one whose author cannot write the repository
33 * and is not on its crew — a guest from another forge or from a fork here,
4 * or a reader's fork. A trusted source (#8937) is no stranger: a person
4 * or a reader's fork. An offer
5 * with no account (`actions/offer.ts`, #12402) is one: its author is the shared
6 * account that writes nothing. A trusted source (#8937) is no stranger: a person
57 * named it, and its walls wait for a person through `fold_walls.ts`.
68 *
79 * What happens to one:
src/http/api.ts +2
@@ -401,6 +401,7 @@ import { buildCartRoutes } from "./api/build_cart.ts";
401401 import { iterationRoutes } from "./api/iterations.ts";
402402 import { appNoteRoutes } from "./api/app_notes.ts";
403403 import { reportRoutes } from "./api/reports.ts";
404 import { offerRoutes } from "./offer_routes.ts";
404405 import { startRoutes } from "./api/start.ts";
405406 import { rollbackRoutes } from "./api/rollback.ts";
406407 import { takeBackRoutes } from "./api/take_back.ts";
@@ -2205,6 +2206,7 @@ export function apiRoutes(router: Router<Handler>): void {
22052206 chapterRoutes(router);
22062207
22072208 reportRoutes(router);
2209 offerRoutes(router);
22082210 startRoutes(router);
22092211 appNoteRoutes(router);
22102212 rollbackRoutes(router);
src/http/mcp.ts +10 −6
@@ -25,7 +25,7 @@ import type { User } from "../core/users.ts";
2525 import type { Ctx, Handler } from "./context.ts";
2626 import { running } from "../kernel/version.ts";
2727 import { bearerChallenge } from "./oauth.ts";
28 import { body, boundedBody, json } from "./respond.ts";
28 import { body, json } from "./respond.ts";
2929 import { page, signInHref } from "../web/layout.ts";
3030 import { html } from "../web/html.ts";
3131 import type { Router } from "./router.ts";
@@ -36,6 +36,8 @@ import { fileReport } from "../actions/reports.ts";
3636 import { START_HINT, START_WORDS, startBuilding } from "../actions/start.ts";
3737 import { CONTRIBUTE_TOKEN_HINT, CONTRIBUTE_TOKEN_WORDS, mintContributeToken } from "../actions/contribute_token.ts";
3838 import { REPORT_RECEIVED } from "../actions/report_words.ts";
39 import { OFFER_REQUEST_MAX } from "../actions/offer_words.ts";
40 import { OFFER_TOOL, offerAnswer, strangerMessage } from "./mcp_offer.ts";
3941 import { BODY_MAX, REQUEST_MAX, TITLE_MAX } from "../core/reports.ts";
4042 import { everydayOf } from "../core/everyday.ts";
4143 import { claimDone, completeWrite, dropWrite, recordWrite } from "../core/conversation_writes.ts";
@@ -59,7 +61,7 @@ export function toolEntries(tools: readonly (typeof TOOLS)[number][]) {
5961 ? {}
6062 : { _meta: { ui: { resourceUri: CARD_URI(CARD_OF_TOOL[t.name]!) }, "openai/outputTemplate": CARD_URI(CARD_OF_TOOL[t.name]!) } }),
6163 })),
62 ...[REPORT_TOOL, START_TOOL].map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
64 ...[REPORT_TOOL, OFFER_TOOL, START_TOOL].map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
6365 ];
6466 }
6567
@@ -327,7 +329,9 @@ export const START_TOOL = {
327329 type FreeHandler = (ctx: Ctx, id: unknown, args: Args) => unknown;
328330
329331 /** The gate picks its handler here, so a name listed in TOKEN_FREE_TOOLS without one is caught by a test. */
330 export const TOKEN_FREE_HANDLERS: Readonly<Record<string, FreeHandler>> = { report: reportAnswer, start: startAnswer };
332 export const TOKEN_FREE_HANDLERS: Readonly<Record<string, FreeHandler>> = { report: reportAnswer, offer: offerAnswer, start: startAnswer };
333
334 export { OFFER_TOOL };
331335
332336 /** The JSON-RPC answer to a token-free tool call, or undefined for any other message. */
333337 function reportCall(ctx: Ctx, message: unknown): unknown | undefined {
@@ -432,7 +436,7 @@ const NOT_HERE = (allow: string): Response =>
432436 new Response(null, { status: 405, headers: { allow } });
433437
434438 /** Every tool name the forge lists, admin-only ones included. */
435 export const toolNames = (): string[] => [...TOOLS.map((t) => t.name), REPORT_TOOL.name, START_TOOL.name];
439 export const toolNames = (): string[] => [...TOOLS.map((t) => t.name), REPORT_TOOL.name, OFFER_TOOL.name, START_TOOL.name];
436440
437441 /** What each tool declares about itself, for the test that walks them all. */
438442 export const toolRegistry = () =>
@@ -461,10 +465,10 @@ export function mcpRoutes(router: Router<Handler>): void {
461465 }
462466 // A stranger may call `report` and nothing else, so their body is read
463467 // to a hard byte limit and no further.
464 const message = await boundedBody(ctx.request, REQUEST_MAX);
468 const message = await strangerMessage(ctx.request);
465469 if (message === "too_large")
466470 return json(
467 { error: "too_large", message: `at most ${REQUEST_MAX} bytes without a token` },
471 { error: "too_large", message: `at most ${REQUEST_MAX} bytes without a token, ${OFFER_REQUEST_MAX} for an offer` },
468472 413,
469473 );
470474 const reported = reportCall(ctx, message);
src/http/mcp_offer.ts added +99
@@ -0,0 +1,99 @@
1 /**
2 * `offer`, a token-free MCP tool (#12402): a stranger's patch on a public
3 * repository, the same action and words as `POST …/offers`
4 * (`actions/offer.ts`). It becomes a pull a person reads before anything runs.
5 */
6 import { fileOffer } from "../actions/offer.ts";
7 import {
8 OFFER_BODY_MAX,
9 OFFER_HINT,
10 OFFER_REQUEST_MAX,
11 OFFER_RECEIVED,
12 OFFER_TITLE_MAX,
13 OFFER_WORDS,
14 } from "../actions/offer_words.ts";
15 import { getRepo } from "../core/repos.ts";
16 import type { Ctx } from "./context.ts";
17 import { type Args, str, REPO_ARG } from "./mcp/shared.ts";
18 import { readBounded } from "./limits.ts";
19 import { clientBucket } from "./peer.ts";
20 import { REQUEST_MAX } from "../core/reports.ts";
21
22 /**
23 * A stranger's MCP message: at most `REQUEST_MAX` bytes, except a call to
24 * `offer`, which carries a patch and may be `OFFER_REQUEST_MAX`. The stream
25 * itself is counted, so a chunked body declares nothing it can lie about.
26 * `{}` when it is not a JSON object.
27 */
28 export async function strangerMessage(request: Request): Promise<Record<string, unknown> | "too_large"> {
29 const bytes = await readBounded(request, OFFER_REQUEST_MAX);
30 if (bytes === "too_large") return "too_large";
31 let value: unknown;
32 try {
33 value = JSON.parse(new TextDecoder().decode(bytes));
34 } catch {
35 return {};
36 }
37 if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
38 const message = value as Record<string, unknown>;
39 const params = message["params"];
40 const name = typeof params === "object" && params !== null ? (params as Record<string, unknown>)["name"] : undefined;
41 return bytes.length > REQUEST_MAX && name !== OFFER_TOOL.name ? "too_large" : message;
42 }
43
44 export const OFFER_TOOL = {
45 name: "offer",
46 /** Its line in /llms.txt's `## MCP tools`; never sent to a client. */
47 doc: "`{ repo, title, body?, patch }`: offer a unified diff to a public repository; a person reads the pull first",
48 writes: true,
49 description: "Offer a patch (unified diff) to a public repository, no account needed; a person reads it first.",
50 inputSchema: {
51 type: "object",
52 properties: {
53 repo: REPO_ARG,
54 title: { type: "string", maxLength: OFFER_TITLE_MAX },
55 body: { type: "string", maxLength: OFFER_BODY_MAX },
56 patch: { type: "string" },
57 },
58 required: ["repo", "title", "patch"],
59 },
60 } as const;
61
62 export async function offerAnswer(ctx: Ctx, id: unknown, args: Args): Promise<unknown> {
63 const text = (t: string, isError = false) => ({
64 jsonrpc: "2.0",
65 id,
66 result: { content: [{ type: "text", text: t }], ...(isError ? { isError } : {}) },
67 });
68 const [owner, name, ...rest] = str(args["repo"]).split("/");
69 const repo = owner && name && rest.length === 0 ? getRepo(ctx.app.db, owner, name) : undefined;
70 if (repo === undefined) return text("not_found: no such public repository (owner/name)", true);
71 const filed = await fileOffer(
72 ctx.app,
73 repo,
74 { title: args["title"], body: args["body"], patch: args["patch"] },
75 clientBucket(ctx.request),
76 );
77 if (filed.ok)
78 return text(
79 JSON.stringify({
80 number: filed.value.number,
81 state: "open",
82 url: `${ctx.url.origin}/${repo.ownerName}/${repo.name}/pulls/${filed.value.number}`,
83 message: OFFER_RECEIVED,
84 }),
85 );
86 const e = filed.error;
87 switch (e.error) {
88 case "not_found":
89 return text("not_found: no such public repository (owner/name)", true);
90 case "rate_limited":
91 return text(`rate_limited: try again in ${e.retryAfter} seconds`, true);
92 case "queue_full":
93 return text("queue_full: this repository has many offers waiting; try again later", true);
94 case "unavailable":
95 return text("unavailable: offers cannot be taken just now; try again later", true);
96 default:
97 return text(`${e.error}: ${OFFER_WORDS[e.error]}; ${OFFER_HINT}`, true);
98 }
99 }
src/http/mcp_table.ts +2 −2
@@ -4,7 +4,7 @@
44 * description, and its bytes in `tools/list`. The doc holds it between two
55 * markers; test/mcp-table.test.ts fails, naming the tool, when they differ.
66 */
7 import { REPORT_TOOL, START_TOOL, toolEntries } from "./mcp.ts";
7 import { OFFER_TOOL, REPORT_TOOL, START_TOOL, toolEntries } from "./mcp.ts";
88 import { TOOLS } from "./mcp/tools.ts";
99
1010 export const TABLE_BEGIN = "<!-- mcp-tools:begin (generated by src/http/mcp_table.ts; edit the code, then run `bun scripts/mcp-table.ts`) -->";
@@ -70,7 +70,7 @@ export function firstSentence(text: string): string {
7070
7171 export function toolRows(): ToolRow[] {
7272 const entries = toolEntries(TOOLS);
73 const schemas = new Map<string, unknown>([...TOOLS.map((t) => [t.name, t.inputSchema] as const), [REPORT_TOOL.name, REPORT_TOOL.inputSchema], [START_TOOL.name, START_TOOL.inputSchema]]);
73 const schemas = new Map<string, unknown>([...TOOLS.map((t) => [t.name, t.inputSchema] as const), [REPORT_TOOL.name, REPORT_TOOL.inputSchema], [OFFER_TOOL.name, OFFER_TOOL.inputSchema], [START_TOOL.name, START_TOOL.inputSchema]]);
7474 return entries.map((entry) => ({
7575 name: entry.name,
7676 doors: doorsOf(schemas.get(entry.name)),
src/http/offer_routes.ts added +52
@@ -0,0 +1,52 @@
1 /**
2 * `POST /api/v1/repos/:owner/:name/offers` (#12402): a stranger's patch with
3 * no account, held as a pull for a person to read. The rules live in
4 * `actions/offer.ts`; the words in `actions/offer_words.ts`, shared with the
5 * MCP `offer` tool.
6 */
7 import { fileOffer } from "../actions/offer.ts";
8 import { OFFER_HINT, OFFER_RECEIVED, OFFER_REQUEST_MAX, OFFER_WORDS, type OfferRefusal } from "../actions/offer_words.ts";
9 import { loadRepo } from "./api.ts";
10 import type { Handler } from "./context.ts";
11 import { clientBucket } from "./peer.ts";
12 import { apiError, boundedBody, json, notFound, str, tryAgain } from "./respond.ts";
13 import type { Router } from "./router.ts";
14
15 /** A full queue drains as people read offers; no clock says when, so a minute. */
16 const QUEUE_RETRY = 60;
17
18 export function offerRoutes(router: Router<Handler>): void {
19 router.add("POST", "/api/v1/repos/:owner/:name/offers", async (ctx) => {
20 const repo = loadRepo(ctx);
21 if (!repo) return notFound();
22 const input = await boundedBody(ctx.request, OFFER_REQUEST_MAX);
23 if (input === "too_large") return apiError("patch_too_large", 422, OFFER_WORDS.patch_too_large);
24 const filed = await fileOffer(
25 ctx.app,
26 repo,
27 { title: str(input.title), body: str(input.body), patch: input.patch },
28 clientBucket(ctx.request),
29 );
30 if (!filed.ok) {
31 const refusal = filed.error;
32 if (refusal.error === "not_found") return notFound();
33 if (refusal.error === "rate_limited")
34 return tryAgain("rate_limited", 429, "too many offers; wait and send again", refusal.retryAfter);
35 if (refusal.error === "queue_full")
36 return tryAgain("queue_full", 429, "this repository has many offers waiting; try again later", QUEUE_RETRY);
37 if (refusal.error === "unavailable")
38 return tryAgain("unavailable", 503, "offers cannot be taken just now; try again later", QUEUE_RETRY);
39 const why: OfferRefusal = refusal.error;
40 return json({ error: why, message: `${OFFER_WORDS[why]}; ${OFFER_HINT}` }, 422);
41 }
42 return json(
43 {
44 number: filed.value.number,
45 state: "open",
46 url: `${ctx.url.origin}/${repo.ownerName}/${repo.name}/pulls/${filed.value.number}`,
47 message: OFFER_RECEIVED,
48 },
49 202,
50 );
51 });
52 }
src/http/server.ts +3 −3
@@ -529,7 +529,7 @@ import { viaGate } from "./via_gate.ts";
529529 import { checksRecheckRoutes } from "./checks_recheck.ts";
530530 import { feedRoutes } from "./feed.ts";
531531 import type { Database } from "bun:sqlite";
532 import { mcpRoutes, REPORT_TOOL, START_TOOL } from "./mcp.ts";
532 import { mcpRoutes, OFFER_TOOL, REPORT_TOOL, START_TOOL } from "./mcp.ts";
533533 import { TOOLS } from "./mcp/tools.ts";
534534 import { setCardTools } from "../core/mcp_card.ts";
535535 import { setMcpTools } from "../web/llms_tools.ts";
@@ -1280,8 +1280,8 @@ export function buildRouter(): Router<Handler> {
12801280 // reclaim a path under `/api/`.
12811281 // The forge as an MCP server: the studio's verbs for an assistant.
12821282 mcpRoutes(router);
1283 setMcpTools(TOOLS, [REPORT_TOOL, START_TOOL]);
1284 setCardTools([...TOOLS, REPORT_TOOL, START_TOOL]);
1283 setMcpTools(TOOLS, [REPORT_TOOL, OFFER_TOOL, START_TOOL]);
1284 setCardTools([...TOOLS, REPORT_TOOL, OFFER_TOOL, START_TOOL]);
12851285 // The public API as OpenAPI, for any client that reads it.
12861286 openapiRoute(router);
12871287 oauthRoutes(router);
src/web/standards.ts +3 −1
@@ -35,6 +35,7 @@ import { BODY_MAX, TITLE_MAX } from "../core/reports.ts";
3535 import { dayOf } from "../release/days.ts";
3636 import { readLandings } from "../release/landings.ts";
3737 import { REPORT_LINK_TITLE } from "../actions/report_words.ts";
38 import { OFFER_PATCH_MAX } from "../actions/offer_words.ts";
3839 import { sshTellCommand } from "../ssh/command.ts";
3940 import { llmsRepos, sitemapRepos, type LlmsListing } from "../core/listings.ts";
4041 import { canRead, getRepo, type Repo } from "../core/repos.ts";
@@ -489,7 +490,8 @@ function renderLlmsTxt(ctx: Ctx, o: string, tell: string | undefined, running: s
489490 "",
490491 "## Offer a change",
491492 "",
492 `- Account only. Fork (MCP fork); source: ${o}/{owner}/{name}/archive/{ref}.tar.gz; send: MCP open_pull with patch, or POST ${o}/api/v1/repos/{owner}/{name}/pulls with {"title", "body", "base", "head", "headRepo": "you/name"}.`,
493 `- No account: POST ${o}/api/v1/repos/{owner}/{name}/offers {"title", "body", "patch"} (a unified diff, ${OFFER_PATCH_MAX / 1024} KB at most) -> 202 {"number", "url"}, or MCP name "offer". A person reads it first; one that does not apply is a 422.`,
494 `- With an account: fork (MCP fork); source: ${o}/{owner}/{name}/archive/{ref}.tar.gz; send: MCP open_pull with patch, or POST ${o}/api/v1/repos/{owner}/{name}/pulls with {"title", "body", "base", "head", "headRepo": "you/name"}.`,
493495 "",
494496 "## Use it from your harness",
495497 "",
test/agent-card.test.ts +2 −2
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { createApp } from "../src/app.ts";
77 import { TOOLS } from "../src/http/mcp/tools.ts";
8 import { REPORT_TOOL, START_TOOL } from "../src/http/mcp.ts";
8 import { OFFER_TOOL, REPORT_TOOL, START_TOOL } from "../src/http/mcp.ts";
99 import { serve, type Servers } from "../src/http/server.ts";
1010
1111 describe("the agent card", () => {
@@ -47,7 +47,7 @@ describe("the agent card", () => {
4747 expect(mcp.tools.length).toBeGreaterThan(10);
4848 expect(agent.skills.map((s: any) => s.id).sort()).toEqual([...mcp.tools].sort());
4949 // The list tools/list serves, not the one both cards are built from.
50 const served = [...TOOLS, REPORT_TOOL, START_TOOL].map((t) => t.name);
50 const served = [...TOOLS, REPORT_TOOL, OFFER_TOOL, START_TOOL].map((t) => t.name);
5151 expect(agent.skills.map((s: any) => s.id).sort()).toEqual([...new Set(served)].sort());
5252 for (const s of agent.skills) expect(s.description.length).toBeGreaterThan(0);
5353 });
test/here-roles.test.ts +1 −1
@@ -99,7 +99,7 @@ test("each role gets its own list for one repository", async () => {
9999 });
100100
101101 test("every MCP tool a verb names is a real tool, and the verbs name it", async () => {
102 const real = new Set([...TOOLS.map((t) => t.name), "report"]);
102 const real = new Set([...TOOLS.map((t) => t.name), "report", "offer"]);
103103 for (const who of [undefined, "nina", "wes", "wren"])
104104 for (const a of await verbs(who)) {
105105 if (a.mcp !== undefined) expect(real.has(a.mcp)).toBe(true);
test/llms-anonymous.test.ts +12 −9
@@ -47,31 +47,34 @@ test("the anonymous text is small, varies by reader, and lists report and start
4747 const res = await fetch(`${servers.url}/llms.txt`);
4848 const body = await res.text();
4949 // 6.5 KiB until the three doors (#12015, about 440 bytes) opened the text;
50 // nothing else was cut to make room. 7.5 KiB since the check.txt door's line.
50 // nothing else was cut to make room. 7.5 KiB since the check.txt door's line, and the offer
51 // door (#12402: its line, and the section's no-account bullet) fits within it.
5152 expect(Buffer.byteLength(body)).toBeLessThan(7.5 * 1024);
5253 expect(res.headers.get("vary")).toContain("Cookie");
5354 expect(res.headers.get("vary")).toContain("Authorization");
5455 const listed = section(body);
55 expect(listed).toHaveLength(3);
56 expect(listed).toHaveLength(4);
5657 expect(listed[0]).toStartWith("- report: ");
57 expect(listed[1]).toStartWith("- start: ");
58 expect(listed[2]).toContain(`${TOOLS.length} more tools with an account`);
59 expect(listed[2]).toContain("tools/list");
60 expect(listed[2]).toContain("/contract/openapi.json");
58 expect(listed[1]).toStartWith("- offer: ");
59 expect(listed[2]).toStartWith("- start: ");
60 expect(listed[3]).toContain(`${TOOLS.length} more tools with an account`);
61 expect(listed[3]).toContain("tools/list");
62 expect(listed[3]).toContain("/contract/openapi.json");
6163 });
6264
6365 test("every tool the anonymous text names is one tools/list returns", async () => {
6466 const names = section(await fetch(`${servers.url}/llms.txt`).then((r) => r.text()))
6567 .map((l) => /^- ([a-z_]+): /.exec(l)?.[1])
6668 .filter((n): n is string => n !== undefined);
67 expect(names).toEqual(["report", "start"]);
69 expect(names).toEqual(["report", "offer", "start"]);
70 // `offer` is found with find_tool and in the whole list: the fresh list is held under 6000 bytes.
6871 const returned: string[] = [];
6972 let cursor: string | undefined;
7073 do {
7174 const list = await fetch(`${servers.url}/mcp`, {
7275 method: "POST",
7376 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
74 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", ...(cursor === undefined ? {} : { params: { cursor } }) }),
77 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: { all: true, ...(cursor === undefined ? {} : { cursor }) } }),
7578 }).then((r) => r.json() as Promise<any>);
7679 returned.push(...list.result.tools.map((t: { name: string }) => t.name));
7780 cursor = list.result.nextCursor;
@@ -83,7 +86,7 @@ test("a signed-in reader still gets every tool and report", async () => {
8386 const body = await fetch(`${servers.url}/llms.txt`, {
8487 headers: { authorization: `Bearer ${token}` },
8588 }).then((r) => r.text());
86 expect(section(body)).toHaveLength(TOOLS.length + 2);
89 expect(section(body)).toHaveLength(TOOLS.length + 3);
8790 });
8891
8992 test("the OpenAPI line names ?tag= and the tags", async () => {
test/llms-tools.test.ts +3 −3
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { createApp } from "../src/app.ts";
77 import { serve, type Servers } from "../src/http/server.ts";
8 import { REPORT_TOOL, START_TOOL } from "../src/http/mcp.ts";
8 import { OFFER_TOOL, REPORT_TOOL, START_TOOL } from "../src/http/mcp.ts";
99 import { TOOLS } from "../src/http/mcp/tools.ts";
1010 import { createToken } from "../src/core/tokens.ts";
1111 import { createUser } from "../src/core/users.ts";
@@ -45,9 +45,9 @@ describe("/llms.txt MCP tools", () => {
4545 expect(start).toBeGreaterThan(-1);
4646 const end = lines.findIndex((l, i) => i > start && l.startsWith("## "));
4747 const listed = lines.slice(start + 1, end).filter((l) => l.startsWith("- "));
48 const expected = [...TOOLS, REPORT_TOOL, START_TOOL].map((t: Listed) => {
48 const expected = [...TOOLS, REPORT_TOOL, OFFER_TOOL, START_TOOL].map((t: Listed) => {
4949 const admin = t.adminOnly === true || t.needsAdminScope === true ? " (admin)" : "";
50 return `- ${t.name}: ${(t.doc ?? t.description).replace(/\s+/g, " ").trim()}${admin}${t.writes ? " (writes)" : ""}${t.name === "report" || t.name === "start" ? " (no account)" : ""}`;
50 return `- ${t.name}: ${(t.doc ?? t.description).replace(/\s+/g, " ").trim()}${admin}${t.writes ? " (writes)" : ""}${t.name === "report" || t.name === "offer" || t.name === "start" ? " (no account)" : ""}`;
5151 });
5252 expect(listed).toEqual(expected);
5353 expect(TOOLS.some((t) => t.writes)).toBe(true);
test/mcp-card.test.ts +1 −1
@@ -42,7 +42,7 @@ describe("the MCP server card", () => {
4242 expect(card.version).toBe(running().version);
4343 expect(card.transport).toBe("streamable-http");
4444 expect(card.endpoint).toBe(`${base}/mcp`);
45 expect(card.tokenFreeTools).toEqual(["report", "start"]);
45 expect(card.tokenFreeTools).toEqual(["report", "offer", "start"]);
4646
4747 // Without a token the endpoint refuses everything but `report`.
4848 const report = await fetch(card.endpoint, {
test/mcp-table.test.ts +1 −1
@@ -89,5 +89,5 @@ test("the bytes are those of an admin's real tools/list response", async () => {
8989 }, 30_000);
9090
9191 test("the entry builder is the one tools/list uses", () => {
92 expect(toolEntries(TOOLS).length).toBe(TOOLS.length + 2);
92 expect(toolEntries(TOOLS).length).toBe(TOOLS.length + 3);
9393 });
test/mcp-tools.test.ts +1 −1
@@ -43,7 +43,7 @@ describe("the gathered tools", () => {
4343 test("are the files, sorted, one each, and `report` beside them", () => {
4444 expect(TOOLS.map((t) => t.name)).toEqual(files);
4545 expect(files).not.toContain("report");
46 expect(toolNames()).toEqual([...files, "report", "start"]);
46 expect(toolNames()).toEqual([...files, "report", "offer", "start"]);
4747 });
4848
4949 test("the index is current: run `bun scripts/mcp-tools.ts`", () => {
test/mcp.test.ts +2 −1
@@ -39,8 +39,9 @@ import { askForReviews } from "./helpers/reviews.ts";
3939
4040 /** tools/list's order: the tools by name, then `report`. */
4141 const sortedThenReport = (names: string[]): string[] => [
42 ...names.filter((n) => n !== "report" && n !== "start").sort((a, b) => a.localeCompare(b)),
42 ...names.filter((n) => n !== "report" && n !== "offer" && n !== "start").sort((a, b) => a.localeCompare(b)),
4343 "report",
44 "offer",
4445 "start",
4546 ];
4647
test/offer-stranger.test.ts added +187
@@ -0,0 +1,187 @@
1 /**
2 * An outsider with no account offers a patch to a public repository, held as a stranger's pull
3 * for a person (#12402).
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { editFiles } from "../src/actions/contents.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { OFFER_PATCH_MAX } from "../src/actions/offer_words.ts";
13 import { getPull } from "../src/core/pulls.ts";
14 import { getRepo, type Repo } from "../src/core/repos.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { isStrangerPull } from "../src/crew/stranger.ts";
17 import { runGit } from "../src/git/env.ts";
18 import { repoDir } from "../src/git/repos.ts";
19 import { guestWaits } from "../src/origins/guest.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { TOKEN_FREE_TOOLS } from "../src/core/mcp_card.ts";
22
23 const PATCH = `diff --git a/hello.txt b/hello.txt
24 --- a/hello.txt
25 +++ b/hello.txt
26 @@ -1,2 +1,2 @@
27 hello
28 -world
29 +there
30 `;
31
32 describe("offers from outside", () => {
33 let dataDir: string;
34 let app: App;
35 let servers: Servers;
36 let alice: User;
37 let game: Repo;
38 let n = 1;
39
40 /** Each call is its own source, so one test's limit never meets another's. */
41 const offer = (body: unknown, path = "/api/v1/repos/alice/game/offers", source = `10.1.0.${n++}`) =>
42 fetch(`${servers.url}${path}`, {
43 method: "POST",
44 headers: { "content-type": "application/json", "x-forwarded-for": source },
45 body: JSON.stringify(body),
46 });
47
48 const branches = async (): Promise<string[]> => {
49 const out = await runGit(["for-each-ref", "--format=%(refname:short)", "refs/heads"], {
50 cwd: repoDir(app.reposRoot, "alice", "game"),
51 });
52 return out.ok ? out.value.split("\n").filter(Boolean) : [];
53 };
54 const pullCount = (): number =>
55 app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM pull JOIN issue ON issue.id = pull.issue_id WHERE issue.repo_id = ?1").get(game.id)!.n;
56
57 beforeAll(async () => {
58 dataDir = await mkdtemp(join(tmpdir(), "forge-offer-"));
59 app = createApp({ dataDir, port: 0 });
60 servers = await serve(app);
61 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
62 if (!a.ok) throw new Error(a.error);
63 alice = a.value;
64 const made = await createRepo(app, alice, { name: "game", visibility: "public" });
65 if (!made.ok) throw new Error(String(made.error));
66 game = made.value;
67 const seeded = await editFiles(app, alice, game, { files: [{ path: "hello.txt", content: "hello\nworld\n" }], message: "first" });
68 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
69 const priv = await createRepo(app, alice, { name: "secret", visibility: "private" });
70 if (!priv.ok) throw new Error(String(priv.error));
71 const s = getRepo(app.db, "alice", "secret")!;
72 await editFiles(app, alice, s, { files: [{ path: "hello.txt", content: "hello\nworld\n" }], message: "first" });
73 }, 30_000);
74
75 afterAll(async () => {
76 servers.stop();
77 app.close();
78 await rm(dataDir, { recursive: true, force: true });
79 });
80
81 test("a patch with no token becomes a stranger's pull that waits for a person", async () => {
82 const res = await offer({ title: "Say there", body: "friendlier", patch: PATCH });
83 expect(res.status).toBe(202);
84 const done: any = await res.json();
85 expect(done.state).toBe("open");
86 expect(done.url).toBe(`${servers.url}/alice/game/pulls/${done.number}`);
87 const pull = getPull(app.db, game.id, done.number)!;
88 expect(pull.title).toBe("Say there");
89 expect(isStrangerPull(app.db, game, pull)).toBe(true);
90 // No secrets or preview and no crew until a person approves it.
91 expect(guestWaits(app.db, pull)).toBe(true);
92 const shown = await runGit(["show", `${pull.headBranch}:hello.txt`], { cwd: repoDir(app.reposRoot, "alice", "game") });
93 expect(shown.ok && shown.value).toBe("hello\nthere");
94 // The default branch is untouched.
95 const main = await runGit(["show", `${game.defaultBranch}:hello.txt`], { cwd: repoDir(app.reposRoot, "alice", "game") });
96 expect(main.ok && main.value).toBe("hello\nworld");
97 });
98
99 test("a patch that does not apply is a 422 naming why, and nothing is stored", async () => {
100 const before = { pulls: pullCount(), branches: await branches() };
101 const stale = PATCH.replace("-world", "-earth");
102 const res = await offer({ title: "Stale", patch: stale });
103 expect(res.status).toBe(422);
104 const refused: any = await res.json();
105 expect(refused.error).toBe("patch_does_not_apply");
106 expect(refused.message).toContain("does not apply");
107 expect(pullCount()).toBe(before.pulls);
108 expect(await branches()).toEqual(before.branches);
109 });
110
111 test("a patch that touches .git is a 422, in any spelling, and nothing is stored", async () => {
112 const before = { pulls: pullCount(), branches: await branches() };
113 const into = (path: string) => `diff --git a/${path} b/${path}\nnew file mode 100644\n--- /dev/null\n+++ b/${path}\n@@ -0,0 +1 @@\n+x\n`;
114 for (const path of [".git/hooks/pre-receive", ".GIT/config", "sub/.git/config", ".Git"]) {
115 const res = await offer({ title: "Hook", patch: into(path) });
116 expect({ path, status: res.status }).toEqual({ path, status: 422 });
117 expect(((await res.json()) as any).error).toBe("patch_touches_git");
118 }
119 expect(pullCount()).toBe(before.pulls);
120 expect(await branches()).toEqual(before.branches);
121 });
122
123 test("a path that climbs out, is absolute or is quoted is a 422", async () => {
124 const into = (path: string) => `diff --git a/${path} b/${path}\nnew file mode 100644\n--- /dev/null\n+++ b/${path}\n@@ -0,0 +1 @@\n+x\n`;
125 for (const path of ["../outside.txt", "a/../../b.txt", "//etc/passwd", '"\\056git/config"']) {
126 const res = await offer({ title: "Out", patch: into(path) });
127 expect({ path, status: res.status }).toEqual({ path, status: 422 });
128 expect(((await res.json()) as any).error).toBe("patch_bad_path");
129 }
130 });
131
132 test("a patch over 200 KB is a 422, however it arrives", async () => {
133 const big = `diff --git a/big.txt b/big.txt\nnew file mode 100644\n--- /dev/null\n+++ b/big.txt\n@@ -0,0 +1 @@\n+${"x".repeat(OFFER_PATCH_MAX)}\n`;
134 const res = await offer({ title: "Big", patch: big });
135 expect(res.status).toBe(422);
136 expect(((await res.json()) as any).error).toBe("patch_too_large");
137 });
138
139 test("a missing title or patch, or a binary patch, is a 422", async () => {
140 expect(((await (await offer({ title: " ", patch: PATCH })).json()) as any).error).toBe("empty_title");
141 expect(((await (await offer({ title: "x" })).json()) as any).error).toBe("patch_missing");
142 expect(((await (await offer({ title: "x", patch: 7 })).json()) as any).error).toBe("patch_missing");
143 const binary = "diff --git a/p.bin b/p.bin\nnew file mode 100644\nindex 0000000..e69de29\nBinary files /dev/null and b/p.bin differ\n";
144 const res = await offer({ title: "x", patch: binary });
145 expect(res.status).toBe(422);
146 });
147
148 test("a private or missing repository answers not_found, and a few a minute from one source", async () => {
149 expect((await offer({ title: "x", patch: PATCH }, "/api/v1/repos/alice/secret/offers")).status).toBe(404);
150 expect((await offer({ title: "x", patch: PATCH }, "/api/v1/repos/alice/none/offers")).status).toBe(404);
151 const source = "10.9.9.9";
152 const stale = PATCH.replace("-world", "-earth");
153 const seen: number[] = [];
154 for (let i = 0; i < 4; i++) seen.push((await offer({ title: "x", patch: stale }, undefined, source)).status);
155 expect(seen).toEqual([422, 422, 422, 429]);
156 });
157
158 test("the MCP offer tool needs no token and says the same words", async () => {
159 expect(TOKEN_FREE_TOOLS).toContain("offer");
160 const call = (args: unknown, source: string) =>
161 fetch(`${servers.url}/mcp`, {
162 method: "POST",
163 headers: { "content-type": "application/json", "x-forwarded-for": source },
164 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "offer", arguments: args } }),
165 });
166 const ok: any = await (await call({ repo: "alice/game", title: "Via MCP", patch: PATCH.replace("+there", "+hi") }, "10.2.0.1")).json();
167 expect(ok.result.isError).toBeUndefined();
168 const filed = JSON.parse(ok.result.content[0].text);
169 expect(getPull(app.db, game.id, filed.number)!.title).toBe("Via MCP");
170 const refused: any = await (await call({ repo: "alice/game", title: "Stale", patch: PATCH.replace("-world", "-earth") }, "10.2.0.2")).json();
171 expect(refused.result.isError).toBe(true);
172 expect(refused.result.content[0].text).toStartWith("patch_does_not_apply: ");
173 const hidden: any = await (await call({ repo: "alice/secret", title: "x", patch: PATCH }, "10.2.0.3")).json();
174 expect(hidden.result.content[0].text).toStartWith("not_found");
175 });
176
177 test("/llms.txt, the OpenAPI contract and the agent card list it", async () => {
178 const llms = await (await fetch(`${servers.url}/llms.txt`)).text();
179 expect(llms).toContain("/offers");
180 expect(llms).toContain('name "offer"');
181 expect(llms).toContain("- offer:");
182 const spec: any = await (await fetch(`${servers.url}/contract/openapi.json`)).json();
183 expect(Object.keys(spec.paths).some((p) => p.endsWith("/offers"))).toBe(true);
184 const card = await (await fetch(`${servers.url}/.well-known/agent-card.json`)).text();
185 expect(card).toContain("offer");
186 });
187 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs