Public: anyone can read this; the crew can change it.
An outsider's offered pull on a public repository returns a receipt and a status link they can poll without an account #13179
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/13162-an-outsider-s-offered-pull-on-a-public-r → main 9 commits fork
15 files
changed +264
−21
docs/MCP.md +1 −1
| @@ -254,7 +254,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`; | ||
| 254 | 254 | |
| 255 | 255 | Five tools need no token, for the same reach as their HTTP doors: `report`, |
| 256 | 256 | `offer`, `start`, `explore` and `search` (`TOKEN_FREE_TOOLS` in `src/core/mcp_card.ts`). |
| 257 | `offer` (`{ repo, title, body?, patch }`) calls `fileOffer`, the action behind | |
| 257 | `offer` (`{ repo, title, body?, patch }`, or `{ receipt }` to read an offer's state) calls `fileOffer`, the action behind | |
| 258 | 258 | `POST /api/v1/repos/{owner}/{name}/offers`, with the same refusal words (the 422 |
| 259 | 259 | reasons, `rate_limited`, `queue_full`; a private repository answers `not_found`); |
| 260 | 260 | it is the one open call whose body may be larger than 64 KB (a patch, up to |
docs/features/offer.md +9
| @@ -42,3 +42,12 @@ forge (`429`); a repository holds at most 20 open offers (`429 queue_full`). | ||
| 42 | 42 | The patch is applied only to a scratch index (`src/git/patch_files.ts`: the |
| 43 | 43 | text goes on stdin, never in an argument), and its headers are read first |
| 44 | 44 | (`patchHeaderRefusal` in `src/actions/offer.ts`): on any doubt, refuse. |
| 45 | ||
| 46 | ## The receipt | |
| 47 | ||
| 48 | The 202 answer carries `receipt` (128 random bits, hex) and `status`, the URL | |
| 49 | `GET /api/v1/offers/{receipt}`. It answers `{ receipt, state, reason }` and | |
| 50 | nothing else: `state` is `received`, `under review` (a review exists), | |
| 51 | `landed` or `declined`, and `reason` is one fixed sentence for it | |
| 52 | (`src/core/offer_receipt.ts`). An id never given is `404`. The MCP `offer` | |
| 53 | tool returns the same fields, and `offer` with `{ receipt }` reads the state. |
src/actions/offer.ts +4 −1
| @@ -27,6 +27,7 @@ import { join } from "node:path"; | ||
| 27 | 27 | import type { App } from "../app.ts"; |
| 28 | 28 | import { commitIdentity } from "../core/commit_identity.ts"; |
| 29 | 29 | import { isContributionFork } from "../core/contribute.ts"; |
| 30 | import { issueReceipt } from "../core/offer_receipt.ts"; | |
| 30 | 31 | import { type Pull } from "../core/pulls.ts"; |
| 31 | 32 | import { plainText } from "../core/reports.ts"; |
| 32 | 33 | import { RateLimiter } from "../core/ratelimit.ts"; |
| @@ -114,6 +115,8 @@ export interface OfferInput { | ||
| 114 | 115 | export interface Offered { |
| 115 | 116 | readonly number: number; |
| 116 | 117 | readonly pull: Pull; |
| 118 | /** The random id the sender reads the offer's state by. */ | |
| 119 | readonly receipt: string; | |
| 117 | 120 | } |
| 118 | 121 | |
| 119 | 122 | interface Limits { |
| @@ -295,5 +298,5 @@ export async function fileOffer( | ||
| 295 | 298 | await runGit(["update-ref", "-d", `refs/heads/${branch}`], { cwd: dir }); |
| 296 | 299 | return err({ error: "unavailable" }); |
| 297 | 300 | } |
| 298 | return ok({ number: opened.value.number, pull: opened.value }); | |
| 301 | return ok({ number: opened.value.number, pull: opened.value, receipt: issueReceipt(app.db, opened.value.id) }); | |
| 299 | 302 | } |
src/contract/openapi/routes/getApiV1OffersReceipt.ts added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | import { type Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/offers/{receipt}", | |
| 6 | summary: | |
| 7 | "Read the state of one offered patch by the random receipt its offer returned, without an account; answers only that offer's own state, and an unknown receipt is a 404", | |
| 8 | auth: false, | |
| 9 | role: "anonymous", | |
| 10 | refusals: { not_found: "404: no offer has this receipt" }, | |
| 11 | }; |
src/contract/openapi/routes/index.ts +1
| @@ -114,6 +114,7 @@ export { route as getApiV1MaintenanceRuns } from "./getApiV1MaintenanceRuns.ts"; | ||
| 114 | 114 | export { route as getApiV1Map } from "./getApiV1Map.ts"; |
| 115 | 115 | export { route as getApiV1MigrateJob } from "./getApiV1MigrateJob.ts"; |
| 116 | 116 | export { route as getApiV1MigrateJobStream } from "./getApiV1MigrateJobStream.ts"; |
| 117 | export { route as getApiV1OffersReceipt } from "./getApiV1OffersReceipt.ts"; | |
| 117 | 118 | export { route as getApiV1OpenapiJson } from "./getApiV1OpenapiJson.ts"; |
| 118 | 119 | export { route as getApiV1OrgsOrg } from "./getApiV1OrgsOrg.ts"; |
| 119 | 120 | export { route as getApiV1OrgsOrgTeams } from "./getApiV1OrgsOrgTeams.ts"; |
src/core/migration-pins/20261115110000-offer-receipt.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 38fff801ab1719d3425da08d2c2ea0eff0d6ed0b6e96f9d2155262c12cdd897a |
src/core/migrations/20261115110000-offer-receipt.ts added +9
| @@ -0,0 +1,9 @@ | ||
| 1 | // An outsider's offer is given a random receipt (#13162) they read its state by, with no account. | |
| 2 | // The id is the only key to the row; the pull it names is the repository's own. New table only. | |
| 3 | export default ` | |
| 4 | CREATE TABLE offer_receipt ( | |
| 5 | id TEXT PRIMARY KEY, | |
| 6 | issue_id TEXT NOT NULL REFERENCES issue(id) ON DELETE CASCADE, | |
| 7 | created_at TEXT NOT NULL | |
| 8 | ); | |
| 9 | `; |
src/core/offer_receipt.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | /** | |
| 2 | * The receipt of an offer from outside (#13162): a random id, a state read from the pull it | |
| 3 | * names, and one sentence of why. It shows that offer's state and nothing else. | |
| 4 | */ | |
| 5 | import type { Database } from "bun:sqlite"; | |
| 6 | import { getIssueById } from "./issues.ts"; | |
| 7 | import { getPull } from "./pulls.ts"; | |
| 8 | import { listReviews } from "./reviews.ts"; | |
| 9 | ||
| 10 | export type OfferState = "received" | "under review" | "landed" | "declined"; | |
| 11 | ||
| 12 | export interface Receipt { | |
| 13 | readonly receipt: string; | |
| 14 | readonly state: OfferState; | |
| 15 | readonly reason: string; | |
| 16 | } | |
| 17 | ||
| 18 | /** The words said once for each state. */ | |
| 19 | export const OFFER_STATE_WORDS: Readonly<Record<OfferState, string>> = { | |
| 20 | received: "A person who maintains this repository has not read it yet.", | |
| 21 | "under review": "A person who maintains this repository is reading it and has left a review.", | |
| 22 | landed: "A maintainer approved it and it is now part of the repository.", | |
| 23 | declined: "A maintainer closed it without landing it.", | |
| 24 | }; | |
| 25 | ||
| 26 | /** 128 random bits, hex: never derived from a pull number or a clock. */ | |
| 27 | const newId = (): string => crypto.randomUUID().replace(/-/g, ""); | |
| 28 | ||
| 29 | /** Keep a receipt for the pull `issueId`; returns its id. */ | |
| 30 | export function issueReceipt(db: Database, issueId: string): string { | |
| 31 | const id = newId(); | |
| 32 | db.query("INSERT INTO offer_receipt (id, issue_id, created_at) VALUES (?1, ?2, ?3)").run(id, issueId, new Date().toISOString()); | |
| 33 | return id; | |
| 34 | } | |
| 35 | ||
| 36 | /** The receipt's state now, or undefined for an id that was never given. */ | |
| 37 | export function readReceipt(db: Database, id: string): Receipt | undefined { | |
| 38 | if (!/^[0-9a-f]{32}$/.test(id)) return undefined; | |
| 39 | const row = db.query<{ issue_id: string }, [string]>("SELECT issue_id FROM offer_receipt WHERE id = ?1").get(id); | |
| 40 | if (row === null) return undefined; | |
| 41 | const issue = getIssueById(db, row.issue_id); | |
| 42 | const pull = issue === undefined ? undefined : getPull(db, issue.repoId, issue.number); | |
| 43 | const state: OfferState = | |
| 44 | pull === undefined || pull.mergedAt !== null ? (pull === undefined ? "declined" : "landed") | |
| 45 | : pull.state === "closed" ? "declined" | |
| 46 | : listReviews(db, pull.id).length > 0 ? "under review" | |
| 47 | : "received"; | |
| 48 | return { receipt: id, state, reason: OFFER_STATE_WORDS[state] }; | |
| 49 | } |
src/http/api.ts +19 −12
| @@ -407,7 +407,7 @@ import { buildCartRoutes } from "./api/build_cart.ts"; | ||
| 407 | 407 | import { iterationRoutes } from "./api/iterations.ts"; |
| 408 | 408 | import { appNoteRoutes } from "./api/app_notes.ts"; |
| 409 | 409 | import { reportRoutes } from "./api/reports.ts"; |
| 410 | import { offerHandler } from "./offer_routes.ts"; | |
| 410 | import { offerHandler, offerStatusHandler } from "./offer_routes.ts"; | |
| 411 | 411 | import { startRoutes } from "./api/start.ts"; |
| 412 | 412 | import { rollbackRoutes } from "./api/rollback.ts"; |
| 413 | 413 | import { takeBackRoutes } from "./api/take_back.ts"; |
| @@ -810,7 +810,9 @@ function editFailure(error: { kind: string } & Record<string, unknown>) { | ||
| 810 | 810 | const ANCHOR_FORMAT = |
| 811 | 811 | 'An anchor is {"path": a file in the pull\'s diff, "line": its line number, "side": "new" (the head\'s numbering, for added or kept lines) or "old" (the base\'s, for removed lines)}; the line must be inside one of the diff\'s hunks: in `@@ -a,b +c,d @@` the hunk\'s first line is c on the new side and a on the old. GET …/pulls/N returns the diff.'; |
| 812 | 812 | |
| 813 | /** A review's line comments as the API was sent them; undefined when they are not a list of objects. */ | |
| 813 | /** | |
| 814 | * A review's line comments as the API was sent them; undefined when they are not a list of objects. | |
| 815 | */ | |
| 814 | 816 | function reviewLines(raw: unknown): ReviewInput[] | undefined { |
| 815 | 817 | if (raw === undefined || raw === null) return []; |
| 816 | 818 | // The cap is `submitReview`'s to refuse, by name (`too_many_lines`). |
| @@ -1969,7 +1971,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1969 | 1971 | const from = at + 1; |
| 1970 | 1972 | const items = all.slice(from, from + limit); |
| 1971 | 1973 | const more = from + limit < all.length; |
| 1972 | // The tag is of the exact bytes sent: a pushed, moved or deleted tag changes them, and so does the page. | |
| 1974 | // The tag is of the exact bytes sent: a pushed, moved or deleted tag changes them, and so | |
| 1975 | // does the page. | |
| 1973 | 1976 | const text = JSON.stringify({ items, next_cursor: more ? items[items.length - 1]!.name : null }); |
| 1974 | 1977 | const etag = weakEtag(text); |
| 1975 | 1978 | const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" }; |
| @@ -2232,6 +2235,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2232 | 2235 | |
| 2233 | 2236 | reportRoutes(router); |
| 2234 | 2237 | router.add("POST", "/api/v1/repos/:owner/:name/offers", offerHandler); |
| 2238 | router.add("GET", "/api/v1/offers/:receipt", offerStatusHandler); | |
| 2235 | 2239 | startRoutes(router); |
| 2236 | 2240 | appNoteRoutes(router); |
| 2237 | 2241 | rollbackRoutes(router); |
| @@ -2419,8 +2423,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2419 | 2423 | }, |
| 2420 | 2424 | ); |
| 2421 | 2425 | // One action on a whole limb (#733): defer, resume, or close as not |
| 2422 | // doing, or raise or lower it among its siblings (#1064). A fleet operation in every respect — a dry run by default with a | |
| 2423 | // read credential, an admin token to apply, the receipt in | |
| 2426 | // doing, or raise or lower it among its siblings (#1064). A fleet operation in every respect — a | |
| 2427 | // dry run by default with a read credential, an admin token to apply, the receipt in | |
| 2424 | 2428 | // /api/v1/fleet/ops/:id and its undo at …/undo. |
| 2425 | 2429 | router.add( |
| 2426 | 2430 | "POST", |
| @@ -2500,7 +2504,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2500 | 2504 | const since = parseSince(ctx.url.searchParams.get("since")); |
| 2501 | 2505 | if (since === undefined) return apiError("invalid_since", 422, "since is day, week or month"); |
| 2502 | 2506 | const scope = sealedScope(ctx.app.db, repo, ctx.auth.user); |
| 2503 | // Built by the map's worker, so the thread serves everything else meanwhile; a snapshot of this write clock answers at once. | |
| 2507 | // Built by the map's worker, so the thread serves everything else meanwhile; a snapshot of this | |
| 2508 | // write clock answers at once. | |
| 2504 | 2509 | const got = await snapshotMap(ctx.app, { repoId: repo.id, scope, now: new Date() }); |
| 2505 | 2510 | if (got === undefined) return notFound(); |
| 2506 | 2511 | // The growth line is read here, not in the snapshot: it moves with the clock, not with writes. |
| @@ -2539,7 +2544,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2539 | 2544 | }); |
| 2540 | 2545 | }); |
| 2541 | 2546 | // What people asked of the crew in the repositories the caller can write — |
| 2542 | // by default what has nothing merged yet, oldest first — and what became of each (core/asked.ts, the /asked page). | |
| 2547 | // by default what has nothing merged yet, oldest first — and what became of each (core/asked.ts, | |
| 2548 | // the /asked page). | |
| 2543 | 2549 | router.add("GET", "/api/v1/asked", (ctx) => { |
| 2544 | 2550 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 2545 | 2551 | const denied = requireScope(ctx, "ro"); |
| @@ -2658,8 +2664,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2658 | 2664 | ...(states[i] ?? {}), |
| 2659 | 2665 | })); |
| 2660 | 2666 | }); |
| 2661 | // The tag is of the exact bytes sent, so a new verdict, head or state is never hidden behind a 304; | |
| 2662 | // the page, state, limit, cursor and fields are in the body or the query that chose it. | |
| 2667 | // The tag is of the exact bytes sent, so a new verdict, head or state is never hidden behind a | |
| 2668 | // 304; the page, state, limit, cursor and fields are in the body or the query that chose it. | |
| 2663 | 2669 | return timePhase(ctx.request, "render", () => { |
| 2664 | 2670 | const text = JSON.stringify(paged(items, query.limit, (p) => p.number)); |
| 2665 | 2671 | const etag = weakEtag(text); |
| @@ -2851,7 +2857,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2851 | 2857 | ...(diff === undefined ? {} : { diff }), |
| 2852 | 2858 | hold: hold === undefined ? null : holdJson(hold), |
| 2853 | 2859 | }); |
| 2854 | // Tagged by the exact bytes sent, after access was checked: a new head, verdict, review or merge is never hidden behind a 304. | |
| 2860 | // Tagged by the exact bytes sent, after access was checked: a new head, verdict, review or | |
| 2861 | // merge is never hidden behind a 304. | |
| 2855 | 2862 | const etag = weakEtag(text); |
| 2856 | 2863 | const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" }; |
| 2857 | 2864 | if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers }); |
| @@ -3712,8 +3719,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 3712 | 3719 | return kept ? json(await beatAnswer(ctx.app, raw)) : apiError("not_found", 404, "no such door"); |
| 3713 | 3720 | }); |
| 3714 | 3721 | |
| 3715 | // A child asking its parent to broker an origin sign-in (`spawn/origin_broker.ts`): signed with the | |
| 3716 | // heartbeat key; every refusal is the same 404, so nothing says who is a child. | |
| 3722 | // A child asking its parent to broker an origin sign-in (`spawn/origin_broker.ts`): signed with | |
| 3723 | // the heartbeat key; every refusal is the same 404, so nothing says who is a child. | |
| 3717 | 3724 | router.add("POST", "/api/v1/broker/origins", async (ctx) => { |
| 3718 | 3725 | const bytes = await readBounded(ctx.request, CALL_BODY_MAX); |
| 3719 | 3726 | if (bytes === "too_large") return apiError("not_found", 404, "no such door"); |
src/http/mcp/offer.ts +2
| @@ -68,6 +68,8 @@ export async function offerAnswer(ctx: Ctx, id: unknown, args: Args): Promise<un | ||
| 68 | 68 | JSON.stringify({ |
| 69 | 69 | number: filed.value.number, |
| 70 | 70 | state: "open", |
| 71 | receipt: filed.value.receipt, | |
| 72 | status: `${ctx.url.origin}/api/v1/offers/${filed.value.receipt}`, | |
| 71 | 73 | url: `${ctx.url.origin}/${repo.ownerName}/${repo.name}/pulls/${filed.value.number}`, |
| 72 | 74 | message: OFFER_RECEIVED, |
| 73 | 75 | }), |
src/http/offer_routes.ts +12
| @@ -12,6 +12,7 @@ import { | ||
| 12 | 12 | OFFER_WORDS, |
| 13 | 13 | type OfferRefusal, |
| 14 | 14 | } from "../actions/offer.ts"; |
| 15 | import { readReceipt } from "../core/offer_receipt.ts"; | |
| 15 | 16 | import { canRead, getRepo } from "../core/repos.ts"; |
| 16 | 17 | import type { Handler } from "./context.ts"; |
| 17 | 18 | import { clientBucket } from "./peer.ts"; |
| @@ -49,9 +50,20 @@ export const offerHandler: Handler = async (ctx) => { | ||
| 49 | 50 | { |
| 50 | 51 | number: filed.value.number, |
| 51 | 52 | state: "open", |
| 53 | receipt: filed.value.receipt, | |
| 54 | status: `${ctx.url.origin}/api/v1/offers/${filed.value.receipt}`, | |
| 52 | 55 | url: `${ctx.url.origin}/${repo.ownerName}/${repo.name}/pulls/${filed.value.number}`, |
| 53 | 56 | message: OFFER_RECEIVED, |
| 54 | 57 | }, |
| 55 | 58 | 202, |
| 56 | 59 | ); |
| 57 | 60 | }; |
| 61 | ||
| 62 | /** | |
| 63 | * `GET /api/v1/offers/:receipt`: that offer's own state and nothing else; an unknown id is a | |
| 64 | * 404. Its state changes and is polled, so no cache keeps one. | |
| 65 | */ | |
| 66 | export const offerStatusHandler: Handler = (ctx) => { | |
| 67 | const found = readReceipt(ctx.app.db, ctx.params.receipt!); | |
| 68 | return found === undefined ? notFound() : json(found, 200, { "cache-control": "no-store" }); | |
| 69 | }; |
src/http/route_marks.ts +13 −3
| @@ -16,7 +16,10 @@ import { Router } from "./router.ts"; | ||
| 16 | 16 | |
| 17 | 17 | export type Mark = "admin" | "open"; |
| 18 | 18 | |
| 19 | /** Every head of a registered route: one mark for all of it, or `mixed` when each route is listed below. */ | |
| 19 | /** | |
| 20 | * Every head of a registered route: one mark for all of it, or `mixed` when each route is listed | |
| 21 | * below. | |
| 22 | */ | |
| 20 | 23 | export const HEADS: Readonly<Record<string, Mark | "mixed">> = { |
| 21 | 24 | "/": "open", |
| 22 | 25 | "/-": "open", |
| @@ -71,6 +74,7 @@ export const HEADS: Readonly<Record<string, Mark | "mixed">> = { | ||
| 71 | 74 | "/api/v1/maintenance": "open", |
| 72 | 75 | "/api/v1/map": "open", |
| 73 | 76 | "/api/v1/migrate": "open", |
| 77 | "/api/v1/offers": "open", | |
| 74 | 78 | "/api/v1/openapi.json": "open", |
| 75 | 79 | "/api/v1/orgs": "open", |
| 76 | 80 | "/api/v1/packs": "open", |
| @@ -422,7 +426,10 @@ export function markOf(pattern: string): Mark | undefined { | ||
| 422 | 426 | } |
| 423 | 427 | |
| 424 | 428 | let listed: Router<Mark> | undefined; |
| 425 | /** ROUTES as a matcher, literal segments before parameters so `/packs/new` is not read as `/packs/:name`. */ | |
| 429 | /** | |
| 430 | * ROUTES as a matcher, literal segments before parameters so `/packs/new` is not read as | |
| 431 | * `/packs/:name`. | |
| 432 | */ | |
| 426 | 433 | function listedRoutes(): Router<Mark> { |
| 427 | 434 | if (listed !== undefined) return listed; |
| 428 | 435 | const params = (p: string) => p.split("/").filter((s) => s.startsWith(":") || s.startsWith("*")).length; |
| @@ -432,7 +439,10 @@ function listedRoutes(): Router<Mark> { | ||
| 432 | 439 | return (listed = matcher); |
| 433 | 440 | } |
| 434 | 441 | |
| 435 | /** Whether a request path falls on a route marked `admin`; unlisted under a `mixed` head counts as `admin`. */ | |
| 442 | /** | |
| 443 | * Whether a request path falls on a route marked `admin`; unlisted under a `mixed` head counts as | |
| 444 | * `admin`. | |
| 445 | */ | |
| 436 | 446 | export function isAdminRoute(path: string): boolean { |
| 437 | 447 | const own = listedRoutes().match("*", path); |
| 438 | 448 | if (own !== undefined) return own.handler === "admin"; |
test/offer-receipt.test.ts added +121
| @@ -0,0 +1,121 @@ | ||
| 1 | /** An outsider's offer returns a receipt they read its state by, with no account (#13162). */ | |
| 2 | import { OFFER_TOOL } from "../src/http/mcp/offer.ts"; | |
| 3 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 4 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 5 | import { tmpdir } from "node:os"; | |
| 6 | import { join } from "node:path"; | |
| 7 | import { createApp, type App } from "../src/app.ts"; | |
| 8 | import { editFiles } from "../src/actions/contents.ts"; | |
| 9 | import { createRepo } from "../src/actions/repos.ts"; | |
| 10 | import { OFFER_STATE_WORDS } from "../src/core/offer_receipt.ts"; | |
| 11 | import { setIssueState } from "../src/core/issues.ts"; | |
| 12 | import { submitReview } from "../src/core/reviews.ts"; | |
| 13 | import { getRepo } from "../src/core/repos.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | ||
| 17 | const PATCH = `diff --git a/hello.txt b/hello.txt | |
| 18 | --- a/hello.txt | |
| 19 | +++ b/hello.txt | |
| 20 | @@ -1,2 +1,2 @@ | |
| 21 | hello | |
| 22 | -world | |
| 23 | +there | |
| 24 | `; | |
| 25 | ||
| 26 | describe("offer receipt", () => { | |
| 27 | let dataDir: string; | |
| 28 | let app: App; | |
| 29 | let servers: Servers; | |
| 30 | let alice: User; | |
| 31 | let n = 1; | |
| 32 | ||
| 33 | const offer = async () => { | |
| 34 | const res = await fetch(`${servers.url}/api/v1/repos/alice/game/offers`, { | |
| 35 | method: "POST", | |
| 36 | headers: { "content-type": "application/json", "x-forwarded-for": `10.3.0.${n++}` }, | |
| 37 | body: JSON.stringify({ title: "Say there", patch: PATCH }), | |
| 38 | }); | |
| 39 | return { status: res.status, headers: res.headers, body: (await res.json()) as any }; | |
| 40 | }; | |
| 41 | const status = async (id: string) => { | |
| 42 | const res = await fetch(`${servers.url}/api/v1/offers/${id}`); | |
| 43 | return { status: res.status, headers: res.headers, body: (await res.json()) as any }; | |
| 44 | }; | |
| 45 | const issueOf = (number: number): string => | |
| 46 | app.db.query<{ id: string }, [number]>("SELECT id FROM issue WHERE number = ?1").get(number)!.id; | |
| 47 | ||
| 48 | beforeAll(async () => { | |
| 49 | dataDir = await mkdtemp(join(tmpdir(), "forge-offer-receipt-")); | |
| 50 | app = createApp({ dataDir, port: 0 }); | |
| 51 | servers = await serve(app); | |
| 52 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 53 | if (!a.ok) throw new Error(a.error); | |
| 54 | alice = a.value; | |
| 55 | const made = await createRepo(app, alice, { name: "game", visibility: "public" }); | |
| 56 | if (!made.ok) throw new Error(String(made.error)); | |
| 57 | const seeded = await editFiles(app, alice, getRepo(app.db, "alice", "game")!, { files: [{ path: "hello.txt", content: "hello\nworld\n" }], message: "first" }); | |
| 58 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 59 | }, 30_000); | |
| 60 | ||
| 61 | afterAll(async () => { | |
| 62 | servers.stop(); | |
| 63 | app.close(); | |
| 64 | await rm(dataDir, { recursive: true, force: true }); | |
| 65 | }); | |
| 66 | ||
| 67 | test("the offer carries a random receipt and a status URL that answers its state", async () => { | |
| 68 | const a = await offer(); | |
| 69 | const b = await offer(); | |
| 70 | expect(a.status).toBe(202); | |
| 71 | expect(a.body.receipt).toMatch(/^[0-9a-f]{32}$/); | |
| 72 | expect(a.body.receipt).not.toBe(b.body.receipt); | |
| 73 | expect(a.body.status).toBe(`${servers.url}/api/v1/offers/${a.body.receipt}`); | |
| 74 | const got = await status(a.body.receipt); | |
| 75 | expect(got.status).toBe(200); | |
| 76 | expect(got.headers.get("cache-control")).toBe("no-store"); | |
| 77 | expect(got.body).toEqual({ receipt: a.body.receipt, state: "received", reason: OFFER_STATE_WORDS.received }); | |
| 78 | }); | |
| 79 | ||
| 80 | test("the state follows review, landing and declining", async () => { | |
| 81 | const reviewed = await offer(); | |
| 82 | const pull = app.db.query<{ head_oid: string }, [string]>("SELECT head_oid FROM pull WHERE issue_id = ?1").get(issueOf(reviewed.body.number))!; | |
| 83 | submitReview(app.db, { issueId: issueOf(reviewed.body.number), authorId: alice.id, state: "commented", commitOid: pull.head_oid }); | |
| 84 | expect((await status(reviewed.body.receipt)).body.state).toBe("under review"); | |
| 85 | ||
| 86 | const landed = await offer(); | |
| 87 | app.db.query("UPDATE pull SET merged_at = ?2 WHERE issue_id = ?1").run(issueOf(landed.body.number), new Date().toISOString()); | |
| 88 | setIssueState(app.db, issueOf(landed.body.number), "closed"); | |
| 89 | const l = await status(landed.body.receipt); | |
| 90 | expect(l.body.state).toBe("landed"); | |
| 91 | expect(l.body.reason).toBe(OFFER_STATE_WORDS.landed); | |
| 92 | ||
| 93 | const declined = await offer(); | |
| 94 | setIssueState(app.db, issueOf(declined.body.number), "closed", "dropped"); | |
| 95 | expect((await status(declined.body.receipt)).body.state).toBe("declined"); | |
| 96 | }); | |
| 97 | ||
| 98 | test("a wrong id, a pull number and a malformed id are all 404", async () => { | |
| 99 | const a = await offer(); | |
| 100 | expect((await status("0".repeat(32))).status).toBe(404); | |
| 101 | expect((await status(String(a.body.number))).status).toBe(404); | |
| 102 | expect((await status("' OR 1=1 --")).status).toBe(404); | |
| 103 | }); | |
| 104 | ||
| 105 | test("the MCP offer tool gives the receipt and keeps its schema", async () => { | |
| 106 | const call = async (args: unknown) => { | |
| 107 | const res = await fetch(`${servers.url}/mcp`, { | |
| 108 | method: "POST", | |
| 109 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "x-forwarded-for": `10.3.0.${n++}` }, | |
| 110 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "offer", arguments: args } }), | |
| 111 | }); | |
| 112 | return ((await res.json()) as any).result; | |
| 113 | }; | |
| 114 | const made = JSON.parse((await call({ repo: "alice/game", title: "Say there", patch: PATCH })).content[0].text); | |
| 115 | expect(made.receipt).toMatch(/^[0-9a-f]{32}$/); | |
| 116 | expect(made.status).toContain(`/api/v1/offers/${made.receipt}`); | |
| 117 | const tool = OFFER_TOOL; | |
| 118 | expect(tool.inputSchema.required).toEqual(["repo", "title", "patch"]); | |
| 119 | expect("receipt" in tool.inputSchema.properties).toBe(false); | |
| 120 | }); | |
| 121 | }); |
test/pages-budget.test.ts +9 −3
| @@ -26,6 +26,7 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 26 | 26 | import { createApp as createAppRecord } from "../src/core/apps.ts"; |
| 27 | 27 | import { startChatBuild } from "../src/core/chat_build.ts"; |
| 28 | 28 | import { createConversation } from "../src/core/conversations.ts"; |
| 29 | import { issueReceipt } from "../src/core/offer_receipt.ts"; | |
| 29 | 30 | import { createIssue } from "../src/core/issues.ts"; |
| 30 | 31 | import { pin } from "../src/core/pins.ts"; |
| 31 | 32 | import { getRepo } from "../src/core/repos.ts"; |
| @@ -151,6 +152,8 @@ beforeAll(async () => { | ||
| 151 | 152 | const pull = createIssue(app.db, { repoId: forge.id, authorId: bob.id, title: "A pull", body: "body", kind: "pull" }); |
| 152 | 153 | if (!pull.ok) throw new Error(pull.error); |
| 153 | 154 | app.db.run("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?1, 'main', 'topic', '', 'h')", [pull.value.id]); |
| 155 | // An offer's receipt, for `/api/v1/offers/:receipt`: random, so the fixture reads it back. | |
| 156 | FIXTURE["/api/v1/offers/:receipt"] = `/api/v1/offers/${issueReceipt(app.db, pull.value.id)}`; | |
| 154 | 157 | // A conversation that builds, with a version on its branch, for the two build reads. |
| 155 | 158 | const talk = createConversation(app.db, alice.id); |
| 156 | 159 | if (!talk.ok) throw new Error(talk.error); |
| @@ -159,7 +162,8 @@ beforeAll(async () => { | ||
| 159 | 162 | if (!version.ok) throw new Error(JSON.stringify(version.error)); |
| 160 | 163 | FIXTURE["/api/v1/conversations/:id/build"] = `/api/v1/conversations/${talk.value.id}/build`; |
| 161 | 164 | FIXTURE["/api/v1/conversations/:id/build/versions/:n/diff"] = `/api/v1/conversations/${talk.value.id}/build/versions/1/diff`; |
| 162 | // An agent's start the claim page can show (`/claim/start/:token`): bob's, so no extra account joins the walk. | |
| 165 | // An agent's start the claim page can show (`/claim/start/:token`): bob's, so no extra account | |
| 166 | // joins the walk. | |
| 163 | 167 | recordStart(app.db, bob.id, "claim_fixture", "127.0.0.1"); |
| 164 | 168 | servers = await serve(app); |
| 165 | 169 | const signin = await fetch(`${servers.url}/signin`, { |
| @@ -171,7 +175,8 @@ beforeAll(async () => { | ||
| 171 | 175 | cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!; |
| 172 | 176 | }, 60_000); |
| 173 | 177 | afterAll(() => { |
| 174 | // The walk fills the shared recorder to its pattern cap; leave it empty for the next file in this process. | |
| 178 | // The walk fills the shared recorder to its pattern cap; leave it empty for the next file in this | |
| 179 | // process. | |
| 175 | 180 | liveOf(app).perfRecord.clear(); |
| 176 | 181 | servers.stop(); |
| 177 | 182 | app.close(); |
| @@ -186,7 +191,8 @@ test("every GET page is within its counted work, warm, naming its slowest phase" | ||
| 186 | 191 | const init = { headers: { cookie }, redirect: "manual" as const }; |
| 187 | 192 | for (const [pattern, path] of walked) { |
| 188 | 193 | let w = await pageWork(app.db, `${servers.url}${path}`, init); |
| 189 | // A page over budget is measured twice more: stray background work raises a count once, an N+1 every time. | |
| 194 | // A page over budget is measured twice more: stray background work raises a count once, an N+1 | |
| 195 | // every time. | |
| 190 | 196 | for (let again = 0; again < 2 && judge(pattern, w).length > 0; again++) { |
| 191 | 197 | const next = await pageWork(app.db, `${servers.url}${path}`, init); |
| 192 | 198 | if (next.statements + next.git < w.statements + w.git) w = next; |
test/security-floor-routes.test.ts +3 −1
| @@ -27,6 +27,7 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 27 | 27 | import { commitToBranch } from "../src/actions/repos.ts"; |
| 28 | 28 | import { createApp as insertApp } from "../src/core/apps.ts"; |
| 29 | 29 | import { createIssue } from "../src/core/issues.ts"; |
| 30 | import { issueReceipt } from "../src/core/offer_receipt.ts"; | |
| 30 | 31 | import { createPull } from "../src/core/pulls.ts"; |
| 31 | 32 | import { createRepo } from "../src/core/repos.ts"; |
| 32 | 33 | import { createRun } from "../src/core/runs.ts"; |
| @@ -44,7 +45,7 @@ import { pool } from "./helpers/sweep-clock.ts"; | ||
| 44 | 45 | quietLogs(); |
| 45 | 46 | |
| 46 | 47 | /** Parameters the seed supplies; any other parameter makes a pattern unseeded. */ |
| 47 | const SEEDED = new Set(["owner", "name", "username", "number", "ref", "oid", "path", "env", "slug", "spec", "machine", "n"]); | |
| 48 | const SEEDED = new Set(["owner", "name", "username", "number", "ref", "oid", "path", "env", "slug", "spec", "machine", "n", "receipt"]); | |
| 48 | 49 | |
| 49 | 50 | const ORIGIN = "needs a connected origin account and a mirror job; the seed connects none"; |
| 50 | 51 | const MIGRATE = "needs a migration job, which only an import creates"; |
| @@ -188,6 +189,7 @@ beforeAll(async () => { | ||
| 188 | 189 | Object.assign(fill, { |
| 189 | 190 | owner: "ada", name: "notes", username: "ada", ref: "main", oid: pull.value.headOid, |
| 190 | 191 | path: "a.txt", env: "prod", slug: "notes", spec: "192", machine: "standard", |
| 192 | receipt: issueReceipt(app.db, pull.value.id), | |
| 191 | 193 | issue: String(issue.value.number), pull: String(pull.value.number), run: run.id, |
| 192 | 194 | }); |
| 193 | 195 | // A conversation that builds, with the version its branch holds, for the build reads. |
new above
offline