Public: anyone can read this; the crew can change it.
Propose upstream says why the origin held it; an invited contributor may fork that repository (#16416) #16417
Check · Review · Land · Live done — Landed and live in production.
talk/cells-upstream → main 0 commits 1 thread · 1 unresolved
11 files
changed +390
−14
docs/features/contributors.md +1
| @@ -9,6 +9,7 @@ The repository's admin invites a person as a **contributor**. A contributor read | ||
| 9 | 9 | - **Talk and MCP**: `invite { repo, who }`, one confirm, makes a person with an account a contributor at once; they hear it on their notice path (`crew/notify.ts`), with a link to their Talk on the app. `invite { repo, who, remove: true }` takes them off; `invite { repo }` lists who works on it (a read, never held). The repository's admin only: a contributor is told it is the admin's, anyone else gets not found. |
| 10 | 10 | - **The terminal**: on an app's deploys screen, `W` lists who works on it; `a` invites a person by username and `d` takes the one under the cursor off, each after a confirm. |
| 11 | 11 | - **Exports**: the owner's account export names who contributes to each repository, by username only; a contributor's names the repositories they contribute to. |
| 12 | - **Proposing from another forge**: a contributor may fork the repository even while the forge holds new accounts (`guard_new_accounts`), since a fork is how a reader proposes; nothing else they make skips that wait. Someone not invited who is held hears it from `propose_upstream` in one sentence: the forge holds forks by new accounts, ask the owner to invite you. | |
| 12 | 13 | - **Taking someone off** is at once: every read, app entry and crew direction asks the row on its request. |
| 13 | 14 | |
| 14 | 15 | Someone without an account cannot be invited yet: a one-use link for them is the next step. |
src/actions/bring.ts +35 −3
| @@ -27,7 +27,8 @@ import { repoDir } from "../git/repos.ts"; | ||
| 27 | 27 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 28 | 28 | import { startMirror } from "../origins/mirror.ts"; |
| 29 | 29 | import { settled, type MirrorJob } from "../origins/jobs.ts"; |
| 30 | import type { Origin } from "../origins/types.ts"; | |
| 30 | import type { Origin, OriginSaid } from "../origins/types.ts"; | |
| 31 | import { NEW_ACCOUNT_GUARD_MESSAGE } from "../core/capacity.ts"; | |
| 31 | 32 | import { needsOf, originOnHost, parseBringLink } from "../origins/bring.ts"; |
| 32 | 33 | import { requireVerified } from "./verify.ts"; |
| 33 | 34 | import { appLimitWords } from "./app_limit.ts"; |
| @@ -395,10 +396,39 @@ export async function planUpstream( | ||
| 395 | 396 | return refuse("invalid", `${branch.slice(0, 60)} is not a branch name to propose: letters, digits, dashes, dots and slashes, at most ${String(UPSTREAM_BRANCH_MAX)} characters.`); |
| 396 | 397 | const as = branch === mirror.defaultBranch ? `${copy.ownerName}/${branch}` : branch; |
| 397 | 398 | const route = await proposalRoute(app, through.value); |
| 398 | const fork = route === "fork" ? ((await existingFork(app, origin, provider, fullName))?.fullName ?? `${origin.login}/${fullName.split("/")[1] ?? copy.name}`) : null; | |
| 399 | const found = route === "fork" ? await existingFork(app, origin, provider, fullName) : undefined; | |
| 400 | // A fork to be made that the origin says it would refuse is refused here, before the yes: a | |
| 401 | // person is never asked to confirm a step that will fail. | |
| 402 | if (route === "fork" && found === undefined) { | |
| 403 | const live = await provider.getRepo(fullName); | |
| 404 | if (live.ok && live.value.permissions.fork === false) return refuse("fork_held", forkHeldWords(fullName)); | |
| 405 | } | |
| 406 | const fork = route === "fork" ? (found?.fullName ?? `${origin.login}/${fullName.split("/")[1] ?? copy.name}`) : null; | |
| 399 | 407 | return ok({ copy, mirror, at: fullName, on: originWords(origin), branch, into: route === "direct" ? "branch" : "fork", fork, as }); |
| 400 | 408 | } |
| 401 | 409 | |
| 410 | /** | |
| 411 | * The origin holds the account's fork of `at` (`owner/name`): the hold, and the invite that lifts | |
| 412 | * it. How new is too new is the origin's to say: named only when its own refusal (`said`) names it. | |
| 413 | */ | |
| 414 | function forkHeldWords(at: string, said?: string): string { | |
| 415 | const [owner = "", name = ""] = at.split("/"); | |
| 416 | const days = /\b(\d{1,3})\s*days?\b/i.exec(said ?? "")?.[1]; | |
| 417 | const who = days === undefined ? "new accounts" : `accounts newer than ${days} days`; | |
| 418 | return `${at}'s forge holds forks by ${who}; ask ${owner} to invite you to ${name}, then propose again.`; | |
| 419 | } | |
| 420 | ||
| 421 | /** | |
| 422 | * Why the origin did not open a proposal, in one sentence with the way through: its own words when | |
| 423 | * it gave some. A forge that holds a new account's fork (`guard_new_accounts`) is named for that, | |
| 424 | * with the invite that lifts it for this repository (`forkRepo`'s contributor exemption). | |
| 425 | */ | |
| 426 | function upstreamRefused(plan: UpstreamPlan, error: string, said: OriginSaid | undefined): string { | |
| 427 | if (said?.code === "refused" && said.message === NEW_ACCOUNT_GUARD_MESSAGE) return forkHeldWords(plan.at, said.message); | |
| 428 | if (said !== undefined) return `${plan.on} refused it, in its words: "${said.message}". Nothing was opened there.`; | |
| 429 | return `${plan.on} did not open it (${error}).`; | |
| 430 | } | |
| 431 | ||
| 402 | 432 | /** |
| 403 | 433 | * Propose a copy's branch upstream, as planned: refused when the plan the person said yes to is |
| 404 | 434 | * no longer what would happen. Answers the pull request's address at the origin. |
| @@ -419,7 +449,9 @@ export async function proposeUpstream( | ||
| 419 | 449 | // It is sent to another forge's API as the pull request's title: one line, bounded. |
| 420 | 450 | if (title.length > UPSTREAM_TITLE_MAX || /[\p{Cc}\p{Cf}\u2028\u2029]/u.test(title)) |
| 421 | 451 | return refuse("invalid", `The title is one line of at most ${String(UPSTREAM_TITLE_MAX)} characters.`); |
| 452 | const heard: OriginSaid[] = []; | |
| 422 | 453 | const opened = await openPull(app, actor, plan.mirror, { |
| 454 | heard: (said) => heard.push(said), | |
| 423 | 455 | title, |
| 424 | 456 | ...(input.body === undefined ? {} : { body: input.body }), |
| 425 | 457 | baseBranch: plan.mirror.defaultBranch, |
| @@ -427,6 +459,6 @@ export async function proposeUpstream( | ||
| 427 | 459 | headRepo: plan.copy, |
| 428 | 460 | route: plan.into === "branch" ? "direct" : "fork", |
| 429 | 461 | }); |
| 430 | if (!opened.ok) return refuse(String(opened.error), `${plan.on} did not open it (${String(opened.error)}).`); | |
| 462 | if (!opened.ok) return refuse(String(opened.error), upstreamRefused(plan, String(opened.error), heard[0])); | |
| 431 | 463 | return ok({ url: opened.value.originUrl ?? `${plan.mirror.ownerName}/${plan.mirror.name}/pulls/${opened.value.number}`, plan }); |
| 432 | 464 | } |
src/actions/pulls.ts +9 −1
| @@ -110,6 +110,7 @@ import { watchPullsSoon } from "../origins/hook.ts"; | ||
| 110 | 110 | import { adoptResolution, ownHost, pullSourceOf, sourceTrailers } from "../core/trusted_sources.ts"; |
| 111 | 111 | import { carryBranchThrough } from "../origins/push-through.ts"; |
| 112 | 112 | import { ensureFork, forkHead, pushToFork } from "../origins/fork-route.ts"; |
| 113 | import type { OriginSaid } from "../origins/types.ts"; | |
| 113 | 114 | import { denied } from "../origins/operator.ts"; |
| 114 | 115 | import type { WriteThrough } from "../origins/write-through.ts"; |
| 115 | 116 | import { requestSyncNow } from "../origins/sync.ts"; |
| @@ -149,6 +150,8 @@ export interface OpenPullInput { | ||
| 149 | 150 | headBranch: string; |
| 150 | 151 | /** For a fork proposing upstream: the fork the head branch lives in. */ |
| 151 | 152 | headRepo?: Repo; |
| 153 | /** On a mirror: told the origin's own words when it refuses the fork or the pull. */ | |
| 154 | heard?: (said: OriginSaid) => void; | |
| 152 | 155 | /** The issue id of the pull this one reverts ("Take it back"). Native |
| 153 | 156 | * repos only — a mirror's pull is the origin's, which has no such field. */ |
| 154 | 157 | revertsIssueId?: string; |
| @@ -285,6 +288,8 @@ async function createThePull( | ||
| 285 | 288 | through.value.origin, |
| 286 | 289 | through.value.provider, |
| 287 | 290 | through.value.fullName, |
| 291 | undefined, | |
| 292 | input.heard, | |
| 288 | 293 | ); |
| 289 | 294 | if (!forked.ok) |
| 290 | 295 | return err( |
| @@ -315,7 +320,10 @@ async function createThePull( | ||
| 315 | 320 | head: pullHead, |
| 316 | 321 | }, |
| 317 | 322 | ); |
| 318 | if (!created.ok) return err(refusal(created.error.error)); | |
| 323 | if (!created.ok) { | |
| 324 | if (created.error.said !== undefined) input.heard?.(created.error.said); | |
| 325 | return err(refusal(created.error.error)); | |
| 326 | } | |
| 319 | 327 | const imported = importIssue( |
| 320 | 328 | { db: app.db, repoId: baseRepo.id, actorId: user.id }, |
| 321 | 329 | created.value, |
src/actions/repos.ts +15 −1
| @@ -42,6 +42,7 @@ import { | ||
| 42 | 42 | type DecisionsBy, |
| 43 | 43 | type ForkRepoError, |
| 44 | 44 | canAdmin, |
| 45 | contributes, | |
| 45 | 46 | type Repo, |
| 46 | 47 | type RepoSettings, |
| 47 | 48 | } from "../core/repos.ts"; |
| @@ -132,17 +133,30 @@ export function repositoryLimitMessage(app: App, user: User, ownerId = user.id): | ||
| 132 | 133 | * younger than a week may not create repositories or forks. Agents run the |
| 133 | 134 | * crew's work and admins run the forge, so the guard is for untrusted |
| 134 | 135 | * newcomers, not them. Refuses in the legacy trigger's own words. |
| 136 | * A contributor (`core/invites.ts`) was vouched for by the repository's | |
| 137 | * admin: forking that repository (`vouchedBy`) is how they propose to it, | |
| 138 | * so the wait does not hold for it. Nothing else they make skips it. | |
| 135 | 139 | */ |
| 136 | 140 | function requireNewAccountGuard( |
| 137 | 141 | app: App, |
| 138 | 142 | user: User, |
| 143 | vouchedBy?: Repo, | |
| 139 | 144 | ): Result<User, "refused"> { |
| 140 | 145 | if (capacityValue(app.db, "guard_new_accounts") !== "on") return ok(user); |
| 141 | 146 | if (user.kind === "agent" || user.isAdmin) return ok(user); |
| 147 | if (vouchedBy !== undefined && contributes(app.db, vouchedBy, user)) return ok(user); | |
| 142 | 148 | const ageMs = Date.now() - new Date(user.createdAt).getTime(); |
| 143 | 149 | return ageMs >= NEW_FOR_MS ? ok(user) : err("refused"); |
| 144 | 150 | } |
| 145 | 151 | |
| 152 | /** | |
| 153 | * Whether the new-account guard holds `user`'s fork of `parent` (`forkRepo` would refuse it | |
| 154 | * `refused`), said on the repository GET so another forge plans around it before asking a yes. | |
| 155 | */ | |
| 156 | export function forkHeld(app: App, user: User, parent: Repo): boolean { | |
| 157 | return !requireNewAccountGuard(app, user, parent).ok; | |
| 158 | } | |
| 159 | ||
| 146 | 160 | /** Resolve the owner id for a new repo: the actor, or an org they can write to. */ |
| 147 | 161 | export function resolveOwner( |
| 148 | 162 | app: App, |
| @@ -229,7 +243,7 @@ export async function forkRepo( | ||
| 229 | 243 | if (!user.ok) return user; |
| 230 | 244 | const proven = requireContributor(app, user.value); |
| 231 | 245 | if (!proven.ok) return proven; |
| 232 | const guarded = requireNewAccountGuard(app, user.value); | |
| 246 | const guarded = requireNewAccountGuard(app, user.value, parent); | |
| 233 | 247 | if (!guarded.ok) return guarded; |
| 234 | 248 | // A guest forks to contribute: public parents only, always public, marked in |
| 235 | 249 | // the row's own write so the fork is never an ordinary one for a moment. |
src/http/api.ts +8 −1
| @@ -106,6 +106,7 @@ import { | ||
| 106 | 106 | repositoryLimitMessage, |
| 107 | 107 | resolveOwner, |
| 108 | 108 | updateRepoSettings, |
| 109 | forkHeld, | |
| 109 | 110 | } from "../actions/repos.ts"; |
| 110 | 111 | import { TRANSFER_SAID, TRANSFER_STATUS, renameRepository, transferRepository } from "../actions/transfer.ts"; |
| 111 | 112 | import { |
| @@ -1676,7 +1677,13 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1676 | 1677 | // viewer may do here, as a Gitea client reads it: another forge connected to this one as an |
| 1677 | 1678 | // origin asks it before proposing, to push a branch here or to its own fork (#10262). |
| 1678 | 1679 | const viewer = ctx.auth.user; |
| 1679 | const permissions = { push: viewer !== undefined && canWrite(ctx.app.db, repo, viewer), admin: viewer !== undefined && canAdmin(ctx.app.db, repo, viewer) }; | |
| 1680 | // `fork`: whether this forge would take the viewer's fork, so a proposal is never planned | |
| 1681 | // through a fork the new-account guard refuses. | |
| 1682 | const permissions = { | |
| 1683 | push: viewer !== undefined && canWrite(ctx.app.db, repo, viewer), | |
| 1684 | admin: viewer !== undefined && canAdmin(ctx.app.db, repo, viewer), | |
| 1685 | fork: viewer !== undefined && !forkHeld(ctx.app, viewer, repo), | |
| 1686 | }; | |
| 1680 | 1687 | const res = json({ ...facts, audience, upstream, credit, permissions }); |
| 1681 | 1688 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 1682 | 1689 | return res; |
src/origins/fork-route.ts +4 −1
| @@ -36,7 +36,7 @@ import { err, ok, type Result } from "../kernel/result.ts"; | ||
| 36 | 36 | import { READ_ONLY, writesPaused } from "./credential.ts"; |
| 37 | 37 | import { redact, secretsIn } from "./credentials.ts"; |
| 38 | 38 | import { pushToOrigin } from "./git-mirror.ts"; |
| 39 | import type { Provider, RemoteRepo } from "./types.ts"; | |
| 39 | import type { OriginSaid, Provider, RemoteRepo } from "./types.ts"; | |
| 40 | 40 | |
| 41 | 41 | /** |
| 42 | 42 | * How long to wait for a fork to exist. GitHub's docs say most forks are |
| @@ -155,6 +155,8 @@ export async function ensureFork( | ||
| 155 | 155 | provider: Provider, |
| 156 | 156 | upstream: string, |
| 157 | 157 | waitMs: number = forkDeadline.ms, |
| 158 | /** Told the origin's own words when it refuses the fork (`OriginSaid`). */ | |
| 159 | heard?: (said: OriginSaid) => void, | |
| 158 | 160 | ): Promise<Result<{ remote: RemoteRepo; existed: boolean }, EnsureForkError>> { |
| 159 | 161 | const found = await existingFork(app, origin, provider, upstream); |
| 160 | 162 | if (found !== undefined) { |
| @@ -175,6 +177,7 @@ export async function ensureFork( | ||
| 175 | 177 | if (taken.ok && !sameRepo(taken.value.parent, upstream)) |
| 176 | 178 | asked = await provider.forkRepo(upstream, secondName(upstream)); |
| 177 | 179 | } |
| 180 | if (!asked.ok && asked.error.said !== undefined) heard?.(asked.error.said); | |
| 178 | 181 | let remote: RemoteRepo; |
| 179 | 182 | if (asked.ok) { |
| 180 | 183 | const ready = await awaitFork(provider, asked.value.fullName, waitMs); |
src/origins/providers/forge.ts +3 −1
| @@ -169,7 +169,7 @@ export class ForgeProvider extends ForgejoProvider { | ||
| 169 | 169 | const owner = asString(field(raw, "ownerName")) || named?.owner || ""; |
| 170 | 170 | const name = asString(field(raw, "name")) || named?.name || ""; |
| 171 | 171 | const web = `${this.webUrl}/${owner}/${name}`; |
| 172 | return ( | |
| 172 | const repo = ( | |
| 173 | 173 | toRepo({ |
| 174 | 174 | id: field(raw, "id"), |
| 175 | 175 | full_name: `${owner}/${name}`, |
| @@ -187,6 +187,8 @@ export class ForgeProvider extends ForgejoProvider { | ||
| 187 | 187 | permissions: { push: dig(raw, "permissions", "push") !== false, admin: dig(raw, "permissions", "admin") === true }, |
| 188 | 188 | }) |
| 189 | 189 | ); |
| 190 | // A forge that holds this account's forks says so; one that does not say leaves it unknown. | |
| 191 | return dig(raw, "permissions", "fork") === false ? { ...repo, permissions: { ...repo.permissions, fork: false } } : repo; | |
| 190 | 192 | } |
| 191 | 193 | |
| 192 | 194 | /** |
src/origins/providers/http.ts +21 −1
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | import { redact } from "../credentials.ts"; |
| 13 | 13 | import { originFetch } from "../origin_fetch.ts"; |
| 14 | 14 | import type { |
| 15 | OriginSaid, | |
| 15 | 16 | ProviderCredential, |
| 16 | 17 | ProviderFailure, |
| 17 | 18 | ProviderResult, |
| @@ -320,8 +321,11 @@ export class ApiClient { | ||
| 320 | 321 | new Date(Date.now() + 60_000).toISOString(), |
| 321 | 322 | ); |
| 322 | 323 | const missing = missingScopes(said); |
| 324 | // A forge says why in its own words (a new account's fork held, say): kept, so the person | |
| 325 | // hears the origin's reason and not "may not" alone. | |
| 326 | const words = refusalSaid(said); | |
| 323 | 327 | return missing.length === 0 |
| 324 | ? fail("forbidden", "the token may not do that on the origin") | |
| 328 | ? { ok: false, error: { error: "forbidden", message: "the token may not do that on the origin", ...(words === undefined ? {} : { said: words }) } } | |
| 325 | 329 | : { |
| 326 | 330 | ok: false, |
| 327 | 331 | error: { |
| @@ -370,6 +374,22 @@ export class ApiClient { | ||
| 370 | 374 | } |
| 371 | 375 | } |
| 372 | 376 | |
| 377 | /** A 403's `{ error, message }` as `OriginSaid`, or undefined when it carries none. */ | |
| 378 | function refusalSaid(text: string): OriginSaid | undefined { | |
| 379 | let body: unknown; | |
| 380 | try { | |
| 381 | body = JSON.parse(text); | |
| 382 | } catch { | |
| 383 | return undefined; | |
| 384 | } | |
| 385 | if (typeof body !== "object" || body === null) return undefined; | |
| 386 | const r = body as Record<string, unknown>; | |
| 387 | const line = (v: unknown, max: number): string => | |
| 388 | typeof v === "string" ? v.replace(/[\p{Cc}\p{Cf}\u2028\u2029]+/gu, " ").trim().slice(0, max) : ""; | |
| 389 | const message = line(r["message"], 300); | |
| 390 | return message === "" ? undefined : { code: line(r["error"], 64), message }; | |
| 391 | } | |
| 392 | ||
| 373 | 393 | /** |
| 374 | 394 | * Exhaustion, in the two dialects that exist. GitHub speaks `X-RateLimit-*` |
| 375 | 395 | * and signals a spent budget with a 403 whose remaining is zero, not a 429. |
src/origins/types.ts +20 −1
| @@ -88,7 +88,15 @@ export interface RemoteRepo { | ||
| 88 | 88 | readonly htmlUrl: string; |
| 89 | 89 | /** Last push on the origin, ISO 8601, or null when empty. */ |
| 90 | 90 | readonly pushedAt: string | null; |
| 91 | readonly permissions: { readonly push: boolean; readonly admin: boolean }; | |
| 91 | readonly permissions: { | |
| 92 | readonly push: boolean; | |
| 93 | readonly admin: boolean; | |
| 94 | /** | |
| 95 | * `false` when the origin holds this account's forks (a forge's new-account guard), so a | |
| 96 | * proposal through a fork would be refused; absent when the origin does not say. | |
| 97 | */ | |
| 98 | readonly fork?: boolean; | |
| 99 | }; | |
| 92 | 100 | /** |
| 93 | 101 | * Open conversations, as the origin counts them. GitHub's |
| 94 | 102 | * `open_issues_count` is issues *and* pull requests in one number and it |
| @@ -308,6 +316,17 @@ export interface ProviderFailure { | ||
| 308 | 316 | * origin's own words (`read:user`), when it said (Forgejo, Gitea). |
| 309 | 317 | */ |
| 310 | 318 | readonly missingScopes?: readonly string[]; |
| 319 | /** For `forbidden`: the origin's own refusal, when it said one in its JSON. */ | |
| 320 | readonly said?: OriginSaid; | |
| 321 | } | |
| 322 | ||
| 323 | /** | |
| 324 | * A refusal in the origin's own JSON (`{ error, message }`, as a forge answers one): each one line, | |
| 325 | * bounded, control characters out. The origin's words, to show a person, never instructions. | |
| 326 | */ | |
| 327 | export interface OriginSaid { | |
| 328 | readonly code: string; | |
| 329 | readonly message: string; | |
| 311 | 330 | } |
| 312 | 331 | |
| 313 | 332 | /** |
test/talk-bring.test.ts +4 −4
| @@ -406,10 +406,10 @@ describe("propose upstream: the copy's branch as a pull request at the origin", | ||
| 406 | 406 | describe("propose upstream: the rest of what it promises", () => { |
| 407 | 407 | test("the repository GET says the caller's own rights: owner push and admin, a reader and a stranger neither", async () => { |
| 408 | 408 | const get = async (token?: string) => |
| 409 | ((await (await fetch(`${friendServers.url}/api/v1/repos/bob/widgets`, { headers: token === undefined ? {} : { authorization: `Bearer ${token}` } })).json()) as { permissions: { push: boolean; admin: boolean } }).permissions; | |
| 410 | expect(await get(bobToken)).toEqual({ push: true, admin: true }); | |
| 411 | expect(await get(carolToken)).toEqual({ push: false, admin: false }); | |
| 412 | expect(await get()).toEqual({ push: false, admin: false }); | |
| 409 | ((await (await fetch(`${friendServers.url}/api/v1/repos/bob/widgets`, { headers: token === undefined ? {} : { authorization: `Bearer ${token}` } })).json()) as { permissions: { push: boolean; admin: boolean; fork: boolean } }).permissions; | |
| 410 | expect(await get(bobToken)).toEqual({ push: true, admin: true, fork: true }); | |
| 411 | expect(await get(carolToken)).toEqual({ push: false, admin: false, fork: true }); | |
| 412 | expect(await get()).toEqual({ push: false, admin: false, fork: false }); | |
| 413 | 413 | }); |
| 414 | 414 | |
| 415 | 415 | test("a forge's answers, canned: rights read when sent and unknown (push) when not; branches by cursor and as a bare array", async () => { |
test/upstream-new-account.test.ts added +270
| @@ -0,0 +1,270 @@ | ||
| 1 | /** | |
| 2 | * Proposing upstream from a new account (#16416). The origin's new-account guard holds a fork by an | |
| 3 | * account younger than a week; `propose_upstream` used to answer only `origin_refused`. Now the | |
| 4 | * person hears the origin's reason and the way through in one sentence, and an account the | |
| 5 | * repository's admin invited as a contributor may fork that repository, so the same proposal goes | |
| 6 | * through. A stranger's new account is still held, and so is anything else the contributor makes. | |
| 7 | */ | |
| 8 | ||
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { changeCapacity } from "../src/actions/capacity.ts"; | |
| 14 | import { inviteContributor } from "../src/actions/invites.ts"; | |
| 15 | import { connectOrigin } from "../src/actions/origins.ts"; | |
| 16 | import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts"; | |
| 17 | import { createApp, type App } from "../src/app.ts"; | |
| 18 | import { NEW_ACCOUNT_GUARD_MESSAGE } from "../src/core/capacity.ts"; | |
| 19 | import { listPulls } from "../src/core/pulls.ts"; | |
| 20 | import { canWrite, getRepo } from "../src/core/repos.ts"; | |
| 21 | import { createToken } from "../src/core/tokens.ts"; | |
| 22 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 23 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 24 | import { syncsSettled } from "../src/origins/sync.ts"; | |
| 25 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 26 | import { promote } from "./helpers/members.ts"; | |
| 27 | import { proveAll } from "./helpers/verified.ts"; | |
| 28 | ||
| 29 | let originDir: string; | |
| 30 | let origin: App; | |
| 31 | let originServers: Servers; | |
| 32 | let homeDir: string; | |
| 33 | let home: App; | |
| 34 | let homeServers: Servers; | |
| 35 | let bob: User; | |
| 36 | let rpc = 1; | |
| 37 | ||
| 38 | const person = async (app: App, username: string): Promise<User> => { | |
| 39 | const made = await createUser(app.db, { | |
| 40 | origin: "seed", | |
| 41 | trusted: true, | |
| 42 | username, | |
| 43 | email: `${username}@forge.test`, | |
| 44 | password: `${username}-passphrase-long`, | |
| 45 | }); | |
| 46 | if (!made.ok) throw new Error(made.error); | |
| 47 | promote(app.db, made.value); | |
| 48 | proveAll(app); | |
| 49 | return made.value; | |
| 50 | }; | |
| 51 | ||
| 52 | const call = async ( | |
| 53 | token: string, | |
| 54 | name: string, | |
| 55 | args: Record<string, unknown>, | |
| 56 | ) => { | |
| 57 | const res = await fetch(`${homeServers.url}/mcp`, { | |
| 58 | method: "POST", | |
| 59 | headers: { | |
| 60 | "content-type": "application/json", | |
| 61 | accept: "application/json, text/event-stream", | |
| 62 | authorization: `Bearer ${token}`, | |
| 63 | }, | |
| 64 | body: JSON.stringify({ | |
| 65 | jsonrpc: "2.0", | |
| 66 | id: rpc++, | |
| 67 | method: "tools/call", | |
| 68 | params: { name, arguments: args }, | |
| 69 | }), | |
| 70 | }); | |
| 71 | const r = ( | |
| 72 | (await res.json()) as { | |
| 73 | result: { content: { text: string }[]; isError?: boolean }; | |
| 74 | } | |
| 75 | ).result; | |
| 76 | return { text: r.content[0]!.text, error: r.isError === true }; | |
| 77 | }; | |
| 78 | ||
| 79 | beforeAll(async () => { | |
| 80 | originDir = await mkdtemp(join(tmpdir(), "forge-upstream-new-origin-")); | |
| 81 | origin = createApp({ dataDir: originDir, port: 0 }); | |
| 82 | originServers = await serve(origin); | |
| 83 | const admin = await seedAdmin(origin, { | |
| 84 | username: "bob", | |
| 85 | email: "[email protected]", | |
| 86 | password: "bob-passphrase-long", | |
| 87 | }); | |
| 88 | if (!admin.ok) throw new Error(admin.error); | |
| 89 | bob = admin.value; | |
| 90 | proveAll(origin); | |
| 91 | const auth = { | |
| 92 | "content-type": "application/json", | |
| 93 | authorization: `Bearer ${createToken(origin.db, bob.id, "t", "rw").token}`, | |
| 94 | }; | |
| 95 | for (const name of ["voxel", "other"]) { | |
| 96 | expect( | |
| 97 | ( | |
| 98 | await fetch(`${originServers.url}/api/v1/repos`, { | |
| 99 | method: "POST", | |
| 100 | headers: auth, | |
| 101 | body: JSON.stringify({ name, visibility: "public" }), | |
| 102 | }) | |
| 103 | ).status, | |
| 104 | ).toBeLessThan(300); | |
| 105 | expect( | |
| 106 | ( | |
| 107 | await fetch(`${originServers.url}/api/v1/repos/bob/${name}/contents`, { | |
| 108 | method: "POST", | |
| 109 | headers: auth, | |
| 110 | body: JSON.stringify({ | |
| 111 | branch: "main", | |
| 112 | message: "first", | |
| 113 | files: [{ path: "README.md", content: `# ${name}\n` }], | |
| 114 | }), | |
| 115 | }) | |
| 116 | ).status, | |
| 117 | ).toBeLessThan(300); | |
| 118 | } | |
| 119 | // The main forge's setting in the experiment: forks by accounts under a week are held. | |
| 120 | expect(changeCapacity(origin, bob, "guard_new_accounts", "on").ok).toBe(true); | |
| 121 | ||
| 122 | homeDir = await mkdtemp(join(tmpdir(), "forge-upstream-new-home-")); | |
| 123 | home = createApp({ dataDir: homeDir, port: 0 }); | |
| 124 | homeServers = await serve(home); | |
| 125 | const homeAdmin = await seedAdmin(home, { | |
| 126 | username: "ada", | |
| 127 | email: "[email protected]", | |
| 128 | password: "ada-passphrase-long", | |
| 129 | }); | |
| 130 | if (!homeAdmin.ok) throw new Error(homeAdmin.error); | |
| 131 | }); | |
| 132 | ||
| 133 | afterAll(async () => { | |
| 134 | await syncsSettled(); | |
| 135 | originServers.stop(); | |
| 136 | homeServers.stop(); | |
| 137 | origin.close(); | |
| 138 | home.close(); | |
| 139 | await rm(originDir, { recursive: true, force: true, maxRetries: 5 }); | |
| 140 | await rm(homeDir, { recursive: true, force: true, maxRetries: 5 }); | |
| 141 | }); | |
| 142 | ||
| 143 | describe("propose upstream from an account the origin holds as new", () => { | |
| 144 | test("held: one sentence names the hold and the invite; invited as a contributor, the same proposal opens", async () => { | |
| 145 | // Frank's account on the origin is a day old; Gina, on her own forge, proposes through it. | |
| 146 | const frank = await person(origin, "frank"); | |
| 147 | const gina = await person(home, "gina"); | |
| 148 | const connected = await connectOrigin(home, gina, { | |
| 149 | host: originServers.url, | |
| 150 | token: createToken(origin.db, frank.id, "t", "rw").token, | |
| 151 | }); | |
| 152 | if (!connected.ok) throw new Error(JSON.stringify(connected.error)); | |
| 153 | const token = createToken(home.db, gina.id, "t", "rw").token; | |
| 154 | const brought = JSON.parse( | |
| 155 | (await call(token, "bring", { repo: `${originServers.url}/bob/voxel` })) | |
| 156 | .text, | |
| 157 | ) as { copy: string }; | |
| 158 | expect(brought.copy).toBe("/gina/voxel-work"); | |
| 159 | const copy = getRepo(home.db, "gina", "voxel-work")!; | |
| 160 | expect( | |
| 161 | ( | |
| 162 | await commitToBranch(home, gina, copy, { | |
| 163 | branch: "brighter", | |
| 164 | message: "Brighter blocks", | |
| 165 | files: [{ path: "README.md", content: "# voxel, brighter\n" }], | |
| 166 | }) | |
| 167 | ).ok, | |
| 168 | ).toBe(true); | |
| 169 | const HELD = | |
| 170 | "bob/voxel's forge holds forks by new accounts; ask bob to invite you to voxel, then propose again."; | |
| 171 | const planIt = () => | |
| 172 | call(token, "propose_upstream", { | |
| 173 | repo: "gina/voxel-work", | |
| 174 | branch: "brighter", | |
| 175 | }); | |
| 176 | ||
| 177 | // The plan asks the origin first: no yes is asked for a fork it would refuse. | |
| 178 | const refused = await planIt(); | |
| 179 | expect(refused.error).toBe(true); | |
| 180 | expect(refused.text).toContain(HELD); | |
| 181 | ||
| 182 | // Planned while the origin would take it, held by the time of the yes: the origin's own | |
| 183 | // refusal still reaches the person as the same sentence. | |
| 184 | expect(changeCapacity(origin, bob, "guard_new_accounts", "off").ok).toBe( | |
| 185 | true, | |
| 186 | ); | |
| 187 | const plan = JSON.parse((await planIt()).text) as { | |
| 188 | plan: { into: string; fork: string }; | |
| 189 | next: Record<string, unknown>; | |
| 190 | }; | |
| 191 | expect(plan.plan.into).toBe("fork"); | |
| 192 | expect(changeCapacity(origin, bob, "guard_new_accounts", "on").ok).toBe( | |
| 193 | true, | |
| 194 | ); | |
| 195 | const held = await call(token, "propose_upstream", { | |
| 196 | ...plan.next, | |
| 197 | title: "Brighter blocks", | |
| 198 | }); | |
| 199 | expect(held.error).toBe(true); | |
| 200 | expect(held.text).toContain(HELD); | |
| 201 | expect(getRepo(origin.db, "frank", "voxel")).toBeUndefined(); | |
| 202 | ||
| 203 | // Bob invites frank to voxel: the proposal Gina already planned now goes through. | |
| 204 | expect( | |
| 205 | inviteContributor( | |
| 206 | origin, | |
| 207 | bob, | |
| 208 | getRepo(origin.db, "bob", "voxel")!, | |
| 209 | "frank", | |
| 210 | ).ok, | |
| 211 | ).toBe(true); | |
| 212 | const opened = await call(token, "propose_upstream", { | |
| 213 | ...plan.next, | |
| 214 | title: "Brighter blocks", | |
| 215 | }); | |
| 216 | expect(opened.error).toBe(false); | |
| 217 | expect(getRepo(origin.db, "frank", "voxel")?.forkParentId).toBe( | |
| 218 | getRepo(origin.db, "bob", "voxel")!.id, | |
| 219 | ); | |
| 220 | expect( | |
| 221 | listPulls(origin.db, getRepo(origin.db, "bob", "voxel")!.id, { | |
| 222 | state: "all", | |
| 223 | }).map((p) => p.title), | |
| 224 | ).toContain("Brighter blocks"); | |
| 225 | // Nothing landed, and frank still writes nothing there: a contributor is not a writer. | |
| 226 | const voxel = getRepo(origin.db, "bob", "voxel")!; | |
| 227 | expect( | |
| 228 | listPulls(origin.db, voxel.id, { state: "all" }).every( | |
| 229 | (p) => p.mergedAt === null, | |
| 230 | ), | |
| 231 | ).toBe(true); | |
| 232 | expect(canWrite(origin.db, voxel, getUserByName(origin.db, "frank")!)).toBe( | |
| 233 | false, | |
| 234 | ); | |
| 235 | }); | |
| 236 | ||
| 237 | test("the exemption is for the repository vouched for alone; a stranger's new account is still held", async () => { | |
| 238 | const frank = getUserByName(origin.db, "frank")!; | |
| 239 | const other = getRepo(origin.db, "bob", "other")!; | |
| 240 | expect(await forkRepo(origin, frank, other)).toEqual({ | |
| 241 | ok: false, | |
| 242 | error: "refused", | |
| 243 | }); | |
| 244 | expect(await createRepo(origin, frank, { name: "own" })).toEqual({ | |
| 245 | ok: false, | |
| 246 | error: "refused", | |
| 247 | }); | |
| 248 | const stranger = await person(origin, "stranger"); | |
| 249 | expect( | |
| 250 | await forkRepo(origin, stranger, getRepo(origin.db, "bob", "voxel")!), | |
| 251 | ).toEqual({ ok: false, error: "refused" }); | |
| 252 | // Over the API, in the guard's own words, as a calling forge reads them. | |
| 253 | const res = await fetch( | |
| 254 | `${originServers.url}/api/v1/repos/bob/voxel/forks`, | |
| 255 | { | |
| 256 | method: "POST", | |
| 257 | headers: { | |
| 258 | "content-type": "application/json", | |
| 259 | authorization: `Bearer ${createToken(origin.db, stranger.id, "t", "rw").token}`, | |
| 260 | }, | |
| 261 | body: "{}", | |
| 262 | }, | |
| 263 | ); | |
| 264 | expect(res.status).toBe(403); | |
| 265 | expect(await res.json()).toMatchObject({ | |
| 266 | error: "refused", | |
| 267 | message: NEW_ACCOUNT_GUARD_MESSAGE, | |
| 268 | }); | |
| 269 | }); | |
| 270 | }); |
new above
offline
This new doc comment and function split the existing comment ("Either way what matters is one thing: when to come back.") from the code it described. Move
refusalSaidabove that comment so the original sits next to its code again.