Public: anyone can read this; the crew can change it.
Every hosted forge holds a proposal credential, and a refusal says when it does not #13725
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/13706-every-hosted-forge-holds-a-proposal-cred → main 6 commits fork 3 threads · 3 unresolved
16 files
changed +563
−52
docs/features/README.md +1
| @@ -18,6 +18,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md). | ||
| 18 | 18 | |
| 19 | 19 | - [](started-from.md) |
| 20 | 20 | - [](first-week.md) |
| 21 | - [](propose-to-parent.md) | |
| 21 | 22 | - [](template-timing.md) |
| 22 | 23 | - [](feed-look.md) |
| 23 | 24 | - [](red-pulls.md) |
docs/features/propose-to-parent.md added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | # Proposing to the parent forge | |
| 2 | ||
| 3 | A hosted forge that follows its parent's code can offer a change up as a pull on the parent. That needs a **proposal credential**: a token that may read the parent repository, push `child/<name>/…` branches there and open a pull from one, and nothing else. | |
| 4 | ||
| 5 | ## When a forge holds one | |
| 6 | ||
| 7 | The parent hands every finished child with a live chain a credential on its own pass, which runs every 5 minutes, and renews it a week before it ends (it lives 30 days). A child that keeps reporting never lapses; one that stops ends by itself. A forge that severed its code link is handed nothing. | |
| 8 | ||
| 9 | The parent mints it as the person who spawned the child, and only while that person may write to the parent repository. If they cannot, or the child has no https address, the child is skipped and holds none. | |
| 10 | ||
| 11 | ## When it does not | |
| 12 | ||
| 13 | Proposing before the credential arrives is refused on every door with the same words, `this forge holds no proposal credential: its parent hands one over on its next pass (every 5 minutes), so wait for that or ask the parent's admin to check the forge is reporting`: | |
| 14 | ||
| 15 | - **API:** `POST /api/v1/repos/:owner/:name/following/propose-parent` answers `409` with `no_credential`. | |
| 16 | - **MCP:** `propose_to_parent_forge` answers `no_credential: …`. | |
| 17 | - **Web:** the Offer this change button flashes the sentence on the following page. | |
| 18 | ||
| 19 | Wait one pass and press again. If it still refuses, the parent's admin should check the forge is reporting and that its spawner still writes to the parent repository. | |
| 20 | ||
| 21 | The words live in `src/actions/family_words.ts`; the interval there is the one `src/spawn/proposal_handout.ts` runs on. |
src/actions/family_words.ts +9
| @@ -3,11 +3,20 @@ | ||
| 3 | 3 | * rules is told, typed once so the API, MCP and the contract read the same |
| 4 | 4 | * sentence from one place. |
| 5 | 5 | */ |
| 6 | /** | |
| 7 | * How often a parent looks over its children's proposal credentials; the refusal below types the | |
| 8 | * same number. | |
| 9 | */ | |
| 10 | export const HANDOUT_EVERY_MINUTES = 5; | |
| 11 | ||
| 6 | 12 | export const FAMILY_WORDS = { |
| 7 | 13 | /** Proposing to the parent forge with no commit ahead of it. */ |
| 8 | 14 | nothing_to_propose: "nothing here is ahead of the parent forge", |
| 9 | 15 | /** Taking, severing or changing the mode of a repository with no chain across forges. */ |
| 10 | 16 | not_following: "this repository follows nothing across forges", |
| 17 | /** Proposing from a forge whose parent has not yet handed it a proposal credential. */ | |
| 18 | no_credential: | |
| 19 | "this forge holds no proposal credential: its parent hands one over on its next pass (every 5 minutes), so wait for that or ask the parent's admin to check the forge is reporting", | |
| 11 | 20 | /** Showing or hiding a migration trail on a repository that was never migrated. */ |
| 12 | 21 | no_provenance: "this repository was not migrated here", |
| 13 | 22 | } as const; |
src/actions/upstream.ts +4 −2
| @@ -145,6 +145,7 @@ export interface ForgeProposal { | ||
| 145 | 145 | export type ProposeForgeError = |
| 146 | 146 | | AccessError |
| 147 | 147 | | "no_parent_forge" |
| 148 | | "no_credential" | |
| 148 | 149 | | "nothing_to_propose" |
| 149 | 150 | | { readonly kind: "refused"; readonly reason: string } |
| 150 | 151 | | { readonly kind: "unreachable" }; |
| @@ -206,8 +207,9 @@ export async function proposeToParentForge( | ||
| 206 | 207 | if (!writer.ok) return writer; |
| 207 | 208 | const link = await forgeLinkOf(app); |
| 208 | 209 | const cred = await parentCredential(app); |
| 209 | if (link === undefined || cred === undefined || link.repo !== `${repo.ownerName}/${repo.name}`) | |
| 210 | return err("no_parent_forge"); | |
| 210 | if (link === undefined || link.repo !== `${repo.ownerName}/${repo.name}`) return err("no_parent_forge"); | |
| 211 | // A forge with a live chain but no handed credential says so, rather than that it has no parent. | |
| 212 | if (cred === undefined) return err("no_credential"); | |
| 211 | 213 | |
| 212 | 214 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); |
| 213 | 215 | const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`); |
src/contract/openapi/routes/postApiV1ReposOwnerNameFollowingProposeParent.ts +1
| @@ -9,6 +9,7 @@ export const route: Route = { | ||
| 9 | 9 | role: "member", |
| 10 | 10 | refusals: { |
| 11 | 11 | no_parent_forge: "404: this repository has no parent forge to propose to", |
| 12 | no_credential: `409: ${FAMILY_WORDS.no_credential}`, | |
| 12 | 13 | nothing_to_propose: `409: ${FAMILY_WORDS.nothing_to_propose}`, |
| 13 | 14 | parent_unreachable: "502: the parent forge did not answer", |
| 14 | 15 | refused: "409: the parent forge refused, with the reason", |
src/core/proposal_token.ts +19 −2
| @@ -123,7 +123,21 @@ export function renewFollowTokens(db: Database, repoId: string, child: string, n | ||
| 123 | 123 | .all(repoId, child, new Date(now + FOLLOW_TTL_MS).toISOString()).length; |
| 124 | 124 | } |
| 125 | 125 | |
| 126 | /** End every follow token minted for a child, whatever the repository: the child is gone. How many ended. */ | |
| 126 | /** End the proposal tokens a child holds for one repository, except `keep`; how many ended. */ | |
| 127 | export function revokeProposalTokens(db: Database, repoId: string, child: string, keep: string): number { | |
| 128 | return db | |
| 129 | .query<{ id: string }, [string, string, string]>( | |
| 130 | `DELETE FROM token WHERE id IN | |
| 131 | (SELECT token_id FROM proposal_token WHERE repo_id = ?1 AND child = ?2 AND read_only = 0 AND token_id != ?3) | |
| 132 | RETURNING id`, | |
| 133 | ) | |
| 134 | .all(repoId, child, keep).length; | |
| 135 | } | |
| 136 | ||
| 137 | /** | |
| 138 | * End every follow token minted for a child, whatever the repository: the child is gone. How many | |
| 139 | * ended. | |
| 140 | */ | |
| 127 | 141 | export function revokeChildFollowTokens(db: Database, child: string): number { |
| 128 | 142 | return db |
| 129 | 143 | .query<{ id: string }, [string]>( |
| @@ -246,7 +260,10 @@ export function listProposalTokens( | ||
| 246 | 260 | })); |
| 247 | 261 | } |
| 248 | 262 | |
| 249 | /** End one proposal token of this person's for this repository; with `follows`, also a follow token anyone's. */ | |
| 263 | /** | |
| 264 | * End one proposal token of this person's for this repository; with `follows`, also a follow token | |
| 265 | * anyone's. | |
| 266 | */ | |
| 250 | 267 | export function deleteProposalToken( |
| 251 | 268 | db: Database, |
| 252 | 269 | userId: string, |
src/http/api/following.ts +3 −2
| @@ -24,8 +24,8 @@ import { apiError, body, json, notFound, requireScope, respondAccess, tryAgain, | ||
| 24 | 24 | import type { Router } from "../router.ts"; |
| 25 | 25 | |
| 26 | 26 | /** |
| 27 | * A body tagged by its own bytes (the standing, or the proposals to the parent): a push to the fork or to the parent's | |
| 28 | * default branch, or a severed chain, changes them, and a viewer who cannot see | |
| 27 | * A body tagged by its own bytes (the standing, or the proposals to the parent): a push to the fork | |
| 28 | * or to the parent's default branch, or a severed chain, changes them, and a viewer who cannot see | |
| 29 | 29 | * the parent is rendered a different body, so never shares a tag with one who can. |
| 30 | 30 | */ |
| 31 | 31 | function tagged(request: Request, payload: unknown): Response { |
| @@ -197,6 +197,7 @@ export function followingRoutes(router: Router<Handler>): void { | ||
| 197 | 197 | const e = made.error; |
| 198 | 198 | if (e === "no_parent_forge") |
| 199 | 199 | return apiError("no_parent_forge", 404, "this repository has no parent forge to propose to"); |
| 200 | if (e === "no_credential") return apiError("no_credential", 409, FAMILY_WORDS.no_credential); | |
| 200 | 201 | if (e === "nothing_to_propose") |
| 201 | 202 | return apiError("nothing_to_propose", 409, FAMILY_WORDS.nothing_to_propose); |
| 202 | 203 | if (typeof e === "string") return respondAccess(e, 403); |
src/http/mcp/tools/propose_to_parent_forge.ts +1
| @@ -44,6 +44,7 @@ export const tool: Tool = { | ||
| 44 | 44 | }); |
| 45 | 45 | const e = made.error; |
| 46 | 46 | if (e === "no_parent_forge") return bad(e, "this forge has no parent forge to propose to"); |
| 47 | if (e === "no_credential") return bad(e, FAMILY_WORDS.no_credential); | |
| 47 | 48 | if (e === "nothing_to_propose") return bad(e, FAMILY_WORDS.nothing_to_propose); |
| 48 | 49 | if (typeof e === "string") return bad(e, "you need write access to propose from here"); |
| 49 | 50 | return e.kind === "unreachable" |
src/spawn/app_follow.ts +19 −6
| @@ -23,6 +23,7 @@ import { applyAppLinks, entriesOf, reasonOf, reconcileAppLinks } from "./app_lin | ||
| 23 | 23 | import { noticeOwners } from "./archive.ts"; |
| 24 | 24 | import { refreshServed } from "./clients.ts"; |
| 25 | 25 | import { hostedChildOpen, openChildren } from "./host.ts"; |
| 26 | import { handProposalCredentials } from "./proposal_handout.ts"; | |
| 26 | 27 | |
| 27 | 28 | /** Look at every app this forge follows from its parent, now, whatever the clock says. */ |
| 28 | 29 | export async function followParentNow(app: App, label = "this forge"): Promise<number> { |
| @@ -35,7 +36,8 @@ export async function followParentNow(app: App, label = "this forge"): Promise<n | ||
| 35 | 36 | const result = await checkUpstream(app, repo); |
| 36 | 37 | if (result.ok) { |
| 37 | 38 | checked++; |
| 38 | // What taking it did, said when it did something: moved the branch, or (the app has commits of its own) proposed a pull. | |
| 39 | // What taking it did, said when it did something: moved the branch, or (the app has commits | |
| 40 | // of its own) proposed a pull. | |
| 39 | 41 | if (result.value.outcome !== "none") |
| 40 | 42 | app.log.info("app followed", { |
| 41 | 43 | forge: label, |
| @@ -70,7 +72,9 @@ export async function followTick(app: App, boot = false): Promise<void> { | ||
| 70 | 72 | const applied = await applyAppLinks(app); |
| 71 | 73 | if (applied.linked.length > 0) await followParentNow(app); |
| 72 | 74 | await reconcileAppLinks(app); |
| 73 | // One child that cannot be opened or linked is that child's trouble: the rest are looked at all the same. | |
| 75 | await handProposalCredentials(app); | |
| 76 | // One child that cannot be opened or linked is that child's trouble: the rest are looked at all | |
| 77 | // the same. | |
| 74 | 78 | for (const { name, app: child } of openChildren(app)) { |
| 75 | 79 | try { |
| 76 | 80 | if (!hostedChildOpen(app, child)) continue; |
| @@ -81,7 +85,8 @@ export async function followTick(app: App, boot = false): Promise<void> { | ||
| 81 | 85 | app.log.warn("a hosted child's follow pass failed", { forge: name, reason: reasonOf(error) }); |
| 82 | 86 | } |
| 83 | 87 | } |
| 84 | // The list /forges serves is read here, off any request: with a question to each child at a start, never after. | |
| 88 | // The list /forges serves is read here, off any request: with a question to each child at a | |
| 89 | // start, never after. | |
| 85 | 90 | const rows = await refreshServed(app, { probe: boot }).catch((error) => { |
| 86 | 91 | app.log.warn("the forges list was not read", { reason: reasonOf(error) }); |
| 87 | 92 | return []; |
| @@ -111,7 +116,9 @@ export function watchLandings(parent: App): () => void { | ||
| 111 | 116 | }); |
| 112 | 117 | } |
| 113 | 118 | |
| 114 | /** A hosted child's `parent.json` as its parent reads it: the child's own regular file, or nothing. */ | |
| 119 | /** | |
| 120 | * A hosted child's `parent.json` as its parent reads it: the child's own regular file, or nothing. | |
| 121 | */ | |
| 115 | 122 | function readParentDoc(dir: string): Record<string, unknown> | undefined { |
| 116 | 123 | try { |
| 117 | 124 | const doc: unknown = JSON.parse(readPrivate(join(dir, "parent.json")) ?? ""); |
| @@ -138,7 +145,10 @@ async function landed(parent: App, child: App, ref: string): Promise<void> { | ||
| 138 | 145 | const OID = /^[0-9a-f]{40,64}$/; |
| 139 | 146 | const REPO = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/; |
| 140 | 147 | |
| 141 | /** What the parent's heartbeat answer carries, as the child reads it: bounded, shaped, never trusted for more than "look now". */ | |
| 148 | /** | |
| 149 | * What the parent's heartbeat answer carries, as the child reads it: bounded, shaped, never trusted | |
| 150 | * for more than "look now". | |
| 151 | */ | |
| 142 | 152 | export function parseHints(v: unknown): Record<string, string> { |
| 143 | 153 | const out: Record<string, string> = {}; |
| 144 | 154 | if (typeof v !== "object" || v === null || Array.isArray(v)) return out; |
| @@ -147,7 +157,10 @@ export function parseHints(v: unknown): Record<string, string> { | ||
| 147 | 157 | return out; |
| 148 | 158 | } |
| 149 | 159 | |
| 150 | /** The parent said these apps now stand at these tips: look at each whose tip this forge has not fetched. */ | |
| 160 | /** | |
| 161 | * The parent said these apps now stand at these tips: look at each whose tip this forge has not | |
| 162 | * fetched. | |
| 163 | */ | |
| 151 | 164 | export async function hearLandings(app: App, hints: Record<string, string>): Promise<void> { |
| 152 | 165 | for (const [name, tip] of Object.entries(hints)) { |
| 153 | 166 | const [o, n] = name.split("/") as [string, string]; |
src/spawn/app_links.ts +83 −28
| @@ -15,8 +15,8 @@ | ||
| 15 | 15 | * database open). A child spawned before this existed is offered the link by its parent |
| 16 | 16 | * (`reconcileAppLinks`, which only offers); the child applies it (`applyAppLinks`) when its |
| 17 | 17 | * repository's history still contains `anchor`, the parent repository's first commit (the one |
| 18 | * the child's copy was made from), so an unrelated repository that happens to share a name is never linked, and only | |
| 19 | * while its owner has not severed it. | |
| 18 | * the child's copy was made from), so an unrelated repository that happens to share a name is never | |
| 19 | * linked, and only while its owner has not severed it. | |
| 20 | 20 | * |
| 21 | 21 | * A private parent repository is read with a follow token (`core/proposal_token.ts`, read-only, |
| 22 | 22 | * one repository, ended by the parent or by the child's sever); the child seals it with its own |
| @@ -77,9 +77,14 @@ export interface AppEntry { | ||
| 77 | 77 | readonly offeredAt?: string; |
| 78 | 78 | readonly appliedAt?: string; |
| 79 | 79 | readonly severedAt?: string; |
| 80 | /** Why the child did not link it: its history does not hold `anchor`, or its owner had set the repository up otherwise. */ | |
| 80 | /** | |
| 81 | * Why the child did not link it: its history does not hold `anchor`, or its owner had set the | |
| 82 | * repository up otherwise. | |
| 83 | */ | |
| 81 | 84 | readonly refused?: "history" | "own" | "code"; |
| 82 | /** Why the child could not link it yet (one line, no path); the offer stands and is tried again. */ | |
| 85 | /** | |
| 86 | * Why the child could not link it yet (one line, no path); the offer stands and is tried again. | |
| 87 | */ | |
| 83 | 88 | readonly failed?: string; |
| 84 | 89 | } |
| 85 | 90 | |
| @@ -148,11 +153,11 @@ function readEntry(v: unknown): AppEntry | undefined { | ||
| 148 | 153 | |
| 149 | 154 | const docPath = (dir: string): string => join(dir, "parent.json"); |
| 150 | 155 | |
| 151 | async function readDoc( | |
| 152 | dir: string, | |
| 153 | ): Promise<Record<string, unknown> | undefined> { | |
| 156 | /** A child's `parent.json` as an object, or nothing; read by the parent and by the child. */ | |
| 157 | export function readDoc(dir: string): Record<string, unknown> | undefined { | |
| 154 | 158 | try { |
| 155 | // The forge's own regular file, never one a link there names: a parent reads this in a child's directory and writes it back. | |
| 159 | // The forge's own regular file, never one a link there names: a parent reads this in a child's | |
| 160 | // directory and writes it back. | |
| 156 | 161 | const doc: unknown = JSON.parse(readPrivate(docPath(dir)) ?? ""); |
| 157 | 162 | return typeof doc === "object" && doc !== null && !Array.isArray(doc) |
| 158 | 163 | ? (doc as Record<string, unknown>) |
| @@ -172,7 +177,9 @@ export const entriesOf = ( | ||
| 172 | 177 | .filter((e): e is AppEntry => e !== undefined) |
| 173 | 178 | : []; |
| 174 | 179 | |
| 175 | /** The document with `apps` replaced, everything else it holds kept; atomic, private to its owner. */ | |
| 180 | /** | |
| 181 | * The document with `apps` replaced, everything else it holds kept; atomic, private to its owner. | |
| 182 | */ | |
| 176 | 183 | async function writeEntries( |
| 177 | 184 | dir: string, |
| 178 | 185 | doc: Record<string, unknown>, |
| @@ -181,7 +188,10 @@ async function writeEntries( | ||
| 181 | 188 | writePrivate(docPath(dir), JSON.stringify({ ...doc, apps })); |
| 182 | 189 | } |
| 183 | 190 | |
| 184 | /** Change one entry of a child's `parent.json` (re-read just before, so a parallel writer's other entries stand). */ | |
| 191 | /** | |
| 192 | * Change one entry of a child's `parent.json` (re-read just before, so a parallel writer's other | |
| 193 | * entries stand). | |
| 194 | */ | |
| 185 | 195 | async function patchEntry( |
| 186 | 196 | dir: string, |
| 187 | 197 | upstream: string, |
| @@ -233,7 +243,10 @@ export async function anchorsOf(app: App, parent: Repo): Promise<string[]> { | ||
| 233 | 243 | |
| 234 | 244 | const ANCHORS_MAX = 8; |
| 235 | 245 | |
| 236 | /** The person a follow token for `repo` is minted as: the spawner, when they may read it, else the repository's owner when that is a person. */ | |
| 246 | /** | |
| 247 | * The person a follow token for `repo` is minted as: the spawner, when they may read it, else the | |
| 248 | * repository's owner when that is a person. | |
| 249 | */ | |
| 237 | 250 | function mintingUser( |
| 238 | 251 | app: App, |
| 239 | 252 | parent: Repo, |
| @@ -246,7 +259,19 @@ function mintingUser( | ||
| 246 | 259 | return owner?.kind === "user" ? owner : undefined; |
| 247 | 260 | } |
| 248 | 261 | |
| 249 | /** A read credential for a private parent repository, made for one child; undefined for a public one or when none can be made. */ | |
| 262 | /** | |
| 263 | * The person a proposal credential is minted as: the spawner, and only when they may write to the | |
| 264 | * parent repository. The repository's owner is never stood in: the token pushes there. | |
| 265 | */ | |
| 266 | export function proposalUser(app: App, parent: Repo, ownerId: string | undefined): User | undefined { | |
| 267 | const spawner = ownerId === undefined ? undefined : getUserById(app.db, ownerId); | |
| 268 | return spawner !== undefined && spawner.kind === "user" && canWrite(app.db, parent, spawner) ? spawner : undefined; | |
| 269 | } | |
| 270 | ||
| 271 | /** | |
| 272 | * A read credential for a private parent repository, made for one child; undefined for a public one | |
| 273 | * or when none can be made. | |
| 274 | */ | |
| 250 | 275 | function followToken( |
| 251 | 276 | app: App, |
| 252 | 277 | parent: Repo, |
| @@ -272,7 +297,10 @@ export interface Offered { | ||
| 272 | 297 | readonly revoked: string[]; |
| 273 | 298 | } |
| 274 | 299 | |
| 275 | /** Why an app was not offered, by `<child>:<app>`, as the last pass found it; absent when it was or needs none. */ | |
| 300 | /** | |
| 301 | * Why an app was not offered, by `<child>:<app>`, as the last pass found it; absent when it was or | |
| 302 | * needs none. | |
| 303 | */ | |
| 276 | 304 | const notOffered = new Map<string, string>(); |
| 277 | 305 | |
| 278 | 306 | /** The forge's own code is followed as the forge's code (`forgeCode`), not as an app. */ |
| @@ -318,7 +346,8 @@ export async function offerAppLinks(app: App, child: Child): Promise<Offered> { | ||
| 318 | 346 | if (revokeFollowTokens(app.db, parent.id, child.name) > 0) out.revoked.push(ref); |
| 319 | 347 | continue; |
| 320 | 348 | } |
| 321 | // A refusal on the first commit alone (an earlier release) is asked again with more of its history to hold. | |
| 349 | // A refusal on the first commit alone (an earlier release) is asked again with more of its | |
| 350 | // history to hold. | |
| 322 | 351 | const reask = have?.refused === "history" && have.anchors === undefined; |
| 323 | 352 | // An offer the child refused: the credential minted for it is ended, as a sever's is. |
| 324 | 353 | if (have?.refused !== undefined && !reask) { |
| @@ -349,7 +378,8 @@ export async function offerAppLinks(app: App, child: Child): Promise<Offered> { | ||
| 349 | 378 | upstream: ref, |
| 350 | 379 | url: repoUrl(app, ref), |
| 351 | 380 | branch: parent.defaultBranch, |
| 352 | // An app's default is to take its updates: it falls back to a pull by itself when the child has commits of its own. | |
| 381 | // An app's default is to take its updates: it falls back to a pull by itself when the child | |
| 382 | // has commits of its own. | |
| 353 | 383 | mode: DEFAULT_MODE, |
| 354 | 384 | anchor: anchors[0]!, |
| 355 | 385 | anchors, |
| @@ -421,7 +451,10 @@ export async function reconcileAppLinks( | ||
| 421 | 451 | |
| 422 | 452 | // ---- the child's side ------------------------------------------------------ |
| 423 | 453 | |
| 424 | /** Who the child's follow acts as: the repository's owner when a person, else the first of its organisation's Owners. */ | |
| 454 | /** | |
| 455 | * Who the child's follow acts as: the repository's owner when a person, else the first of its | |
| 456 | * organisation's Owners. | |
| 457 | */ | |
| 425 | 458 | export function ownerOf(app: App, repo: Repo): User | undefined { |
| 426 | 459 | const owner = getUserById(app.db, repo.ownerId); |
| 427 | 460 | if (owner?.kind === "user") return owner; |
| @@ -585,12 +618,16 @@ const REFUSED_WORDS = { | ||
| 585 | 618 | code: "it is the forge's own code, which the forge follows as its code (the chain), not as an app", |
| 586 | 619 | } as const; |
| 587 | 620 | |
| 588 | /** An app linked before: said once, and a link the repair made with `tell-me` is brought to the default (take-updates). */ | |
| 621 | /** | |
| 622 | * An app linked before: said once, and a link the repair made with `tell-me` is brought to the | |
| 623 | * default (take-updates). | |
| 624 | */ | |
| 589 | 625 | async function keepApplied(app: App, dir: string, e: AppEntry, label: string): Promise<void> { |
| 590 | 626 | const repo = findCopy(app, e); |
| 591 | 627 | const row = repo === undefined ? undefined : getFollow(app.db, repo.id); |
| 592 | // The repair first offered `tell-me` to children whose forge code was `tell-me`: that was never a person's choice for an app. | |
| 593 | // A person's choice since is a change of the row alone, which the entry does not know of, so only a row still equal to the offer is moved. | |
| 628 | // The repair first offered `tell-me` to children whose forge code was `tell-me`: that was never a | |
| 629 | // person's choice for an app. A person's choice since is a change of the row alone, which the | |
| 630 | // entry does not know of, so only a row still equal to the offer is moved. | |
| 594 | 631 | if (repo !== undefined && row?.via === "parent" && row.enabled && row.mode === "tell-me" && e.mode === "tell-me" && e.offeredAt !== e.appliedAt) { |
| 595 | 632 | setFollowTaking(app.db, repo.id, DEFAULT_MODE); |
| 596 | 633 | await patchEntry(dir, e.upstream, (x) => ({ ...x, mode: DEFAULT_MODE })); |
| @@ -602,7 +639,10 @@ async function keepApplied(app: App, dir: string, e: AppEntry, label: string): P | ||
| 602 | 639 | say(app, "info", label, e.upstream, `already linked, ${how}`); |
| 603 | 640 | } |
| 604 | 641 | |
| 605 | /** Where a child's copy of an app is: where it was sent, or else the repository of the same name or one of its owner's that holds the parent's history. */ | |
| 642 | /** | |
| 643 | * Where a child's copy of an app is: where it was sent, or else the repository of the same name or | |
| 644 | * one of its owner's that holds the parent's history. | |
| 645 | */ | |
| 606 | 646 | function findCopy(app: App, e: AppEntry): Repo | undefined { |
| 607 | 647 | const [o, n] = e.repo.split("/") as [string, string]; |
| 608 | 648 | return getRepo(app.db, o, n); |
| @@ -659,7 +699,8 @@ async function applyOne(app: App, dir: string, e: AppEntry, done: Applied, label | ||
| 659 | 699 | return; |
| 660 | 700 | } |
| 661 | 701 | if (row !== undefined) { |
| 662 | // A person already set this repository up (an upstream of their own, or turned following off): theirs stands. | |
| 702 | // A person already set this repository up (an upstream of their own, or turned following off): | |
| 703 | // theirs stands. | |
| 663 | 704 | const same = row.enabled && row.via === "parent" && row.url === e.url; |
| 664 | 705 | await patchEntry(dir, e.upstream, (x) => |
| 665 | 706 | same ? { ...withoutToken(x), repo: here, appliedAt: x.appliedAt ?? new Date().toISOString() } : { ...withoutToken(x), repo: here, refused: "own" }, |
| @@ -680,7 +721,8 @@ async function applyOne(app: App, dir: string, e: AppEntry, done: Applied, label | ||
| 680 | 721 | if (e.failed !== why) await patchEntry(dir, e.upstream, (x) => ({ ...x, failed: why })); |
| 681 | 722 | return; |
| 682 | 723 | } |
| 683 | // Sealed by this forge's own app instance, with its own key: the parent never opens a child's key for this. | |
| 724 | // Sealed by this forge's own app instance, with its own key: the parent never opens a child's key | |
| 725 | // for this. | |
| 684 | 726 | const credentialEnc = e.token === undefined ? "" : seal(dir, e.token, followAad(repo.id)); |
| 685 | 727 | putFollow(app.db, { |
| 686 | 728 | repoId: repo.id, |
| @@ -689,7 +731,8 @@ async function applyOne(app: App, dir: string, e: AppEntry, done: Applied, label | ||
| 689 | 731 | enabled: true, |
| 690 | 732 | byId: by.id, |
| 691 | 733 | originId: "", |
| 692 | // An app takes its updates by default; with commits of its own the same mode proposes them as a pull. | |
| 734 | // An app takes its updates by default; with commits of its own the same mode proposes them as a | |
| 735 | // pull. | |
| 693 | 736 | mode: DEFAULT_MODE, |
| 694 | 737 | via: "parent", |
| 695 | 738 | credentialEnc, |
| @@ -707,7 +750,10 @@ const withoutToken = (e: AppEntry): AppEntry => { | ||
| 707 | 750 | return rest; |
| 708 | 751 | }; |
| 709 | 752 | |
| 710 | /** The child severed this app's link: written where the parent reads it, the credential's plain copy gone. */ | |
| 753 | /** | |
| 754 | * The child severed this app's link: written where the parent reads it, the credential's plain copy | |
| 755 | * gone. | |
| 756 | */ | |
| 711 | 757 | export async function markAppSevered( |
| 712 | 758 | app: App, |
| 713 | 759 | repo: Repo, |
| @@ -738,7 +784,10 @@ export interface AppLinkLine { | ||
| 738 | 784 | /** `<org>/<name>` in the child. */ |
| 739 | 785 | readonly repo: string; |
| 740 | 786 | readonly state: "following" | "offered" | "severed" | "not-linked" | "not-offered" | "failed"; |
| 741 | /** Why, for every state but `severed`, and for `following` only when something is wrong: one line, no path. */ | |
| 787 | /** | |
| 788 | * Why, for every state but `severed`, and for `following` only when something is wrong: one line, | |
| 789 | * no path. | |
| 790 | */ | |
| 742 | 791 | readonly why?: string; |
| 743 | 792 | /** For `offered`: since when, ISO. */ |
| 744 | 793 | readonly since?: string; |
| @@ -771,7 +820,9 @@ export async function appLinkLines(app: App, child: Child): Promise<AppLinkLine[ | ||
| 771 | 820 | }); |
| 772 | 821 | } |
| 773 | 822 | |
| 774 | /** What a followed private app says when this forge holds no working read credential for the child. */ | |
| 823 | /** | |
| 824 | * What a followed private app says when this forge holds no working read credential for the child. | |
| 825 | */ | |
| 775 | 826 | const CREDENTIAL_ENDED = "its read credential here was revoked, so it takes no new commits of this private repository"; |
| 776 | 827 | |
| 777 | 828 | /** The sentence a line says on the parent's page and in its log. */ |
| @@ -808,7 +859,8 @@ export function appLinkSummary(lines: readonly AppLinkLine[]): string | null { | ||
| 808 | 859 | /** Say each app's condition in the log, once while it holds. */ |
| 809 | 860 | export function reportLines(app: App, forge: string, lines: readonly AppLinkLine[]): void { |
| 810 | 861 | for (const l of lines) { |
| 811 | // An offer the child has not taken in ten minutes is said again, louder: it is not running the code that takes it, or cannot. | |
| 862 | // An offer the child has not taken in ten minutes is said again, louder: it is not running the | |
| 863 | // code that takes it, or cannot. | |
| 812 | 864 | const stale = l.state === "offered" && l.since !== undefined && Date.now() - Date.parse(l.since) > 10 * 60_000; |
| 813 | 865 | const words = `parent sees: ${appLinkWords(l)}${stale ? "; not applied after ten minutes (is the child awake and on this release?)" : ""}`; |
| 814 | 866 | const ended = l.state === "following" && l.why !== undefined; |
| @@ -845,7 +897,10 @@ export async function appTipsFor( | ||
| 845 | 897 | return tips; |
| 846 | 898 | } |
| 847 | 899 | |
| 848 | /** Whether the actor may sever here: the follow's own check is `canAdmin`; this names the person a follow acts as. */ | |
| 900 | /** | |
| 901 | * Whether the actor may sever here: the follow's own check is `canAdmin`; this names the person a | |
| 902 | * follow acts as. | |
| 903 | */ | |
| 849 | 904 | export const followsAs = ( |
| 850 | 905 | app: App, |
| 851 | 906 | repo: Repo, |
src/spawn/parent_credential.ts +30 −6
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | import { join } from "node:path"; |
| 10 | 10 | import type { App } from "../app.ts"; |
| 11 | 11 | import { isChildName } from "../core/proposal_token.ts"; |
| 12 | import { writePrivate } from "../kernel/file_modes.ts"; | |
| 12 | import { readPrivate, writePrivate } from "../kernel/file_modes.ts"; | |
| 13 | 13 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 14 | 14 | import { forgeLinkOf, originOf } from "./chain.ts"; |
| 15 | 15 | |
| @@ -49,14 +49,38 @@ export async function parentCredential(app: App): Promise<ParentCredential | und | ||
| 49 | 49 | return { url, repo: link.upstream, child, token }; |
| 50 | 50 | } |
| 51 | 51 | |
| 52 | const TOKEN = /^[\x21-\x7e]{8,200}$/; | |
| 53 | ||
| 54 | /** | |
| 55 | * Write the proposal block into the `parent.json` of the data directory `dataDir`, keeping the | |
| 56 | * rest. The parent calls this on a child's directory from outside its cell (what it keeps is what | |
| 57 | * `readPrivate` read, never a file a link there names); the child calls it on its own. `expiresAt` | |
| 58 | * (ms) is the parent's note of when to mint a fresh one; the child never reads it. | |
| 59 | */ | |
| 60 | export function storeProposal( | |
| 61 | dataDir: string, | |
| 62 | input: { child: string; token: string; expiresAt?: number }, | |
| 63 | ): Result<void, "invalid" | "no_parent"> { | |
| 64 | if (!isChildName(input.child) || !TOKEN.test(input.token)) return err("invalid"); | |
| 65 | let doc: unknown; | |
| 66 | try { | |
| 67 | doc = JSON.parse(readPrivate(join(dataDir, "parent.json")) ?? ""); | |
| 68 | } catch { | |
| 69 | return err("no_parent"); | |
| 70 | } | |
| 71 | if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return err("no_parent"); | |
| 72 | const { child, token, expiresAt } = input; | |
| 73 | writePrivate( | |
| 74 | join(dataDir, "parent.json"), | |
| 75 | JSON.stringify({ ...doc, proposal: { child, token, ...(expiresAt === undefined ? {} : { expiresAt }) } }), | |
| 76 | ); | |
| 77 | return ok(); | |
| 78 | } | |
| 79 | ||
| 52 | 80 | /** Keep the token a parent minted for this child. The rest of `parent.json` stays as it is. */ |
| 53 | 81 | export async function keepParentCredential( |
| 54 | 82 | app: App, |
| 55 | 83 | input: { child: string; token: string }, |
| 56 | 84 | ): Promise<Result<void, "invalid" | "no_parent">> { |
| 57 | if (!isChildName(input.child) || !/^[\x21-\x7e]{8,200}$/.test(input.token)) return err("invalid"); | |
| 58 | const doc = await readDoc(app); | |
| 59 | if (doc === undefined) return err("no_parent"); | |
| 60 | writePrivate(path(app), JSON.stringify({ ...doc, proposal: { child: input.child, token: input.token } })); | |
| 61 | return ok(); | |
| 85 | return storeProposal(app.config.dataDir, input); | |
| 62 | 86 | } |
src/spawn/proposal_handout.ts added +92
| @@ -0,0 +1,92 @@ | ||
| 1 | /** | |
| 2 | * Every forge this one made holds its proposal credential: a token that may read the child's | |
| 3 | * parent repository, push `child/<name>/…` branches there and open a pull from one, and nothing | |
| 4 | * else (`http/proposal_gate.ts`). The parent mints it and writes it into the child's `parent.json` | |
| 5 | * beside the heartbeat key (`storeProposal`), the way it already hands over the lent credit | |
| 6 | * (`funding.ts`). The token lives `PROPOSAL_TTL_MS`; the parent's pass looks every few minutes and | |
| 7 | * mints a fresh one when the child has none or its token is within `RENEW_BEFORE_MS` of its end, so | |
| 8 | * a child that keeps reporting never lapses and one that stops ends by itself. A child that severed | |
| 9 | * its code link is handed nothing, and its token is not renewed. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { App } from "../app.ts"; | |
| 13 | import { HANDOUT_EVERY_MINUTES } from "../actions/family_words.ts"; | |
| 14 | import { childDirOf, listChildren, type Child } from "../actions/spawn.ts"; | |
| 15 | import { mintProposalToken, parseOrigin, PROPOSAL_TTL_MS, revokeProposalTokens } from "../core/proposal_token.ts"; | |
| 16 | import { getRepo } from "../core/repos.ts"; | |
| 17 | import { proposalUser, readDoc } from "./app_links.ts"; | |
| 18 | import { storeProposal } from "./parent_credential.ts"; | |
| 19 | ||
| 20 | /** A token this near its end is replaced. */ | |
| 21 | export const RENEW_BEFORE_MS = 7 * 24 * 3600_000; | |
| 22 | /** How often the parent looks over its children's credentials. */ | |
| 23 | export const HANDOUT_EVERY_MS = HANDOUT_EVERY_MINUTES * 60_000; | |
| 24 | ||
outdated
This constant is 5 minutes while the user-facing refusal promises 10. Reconcile. |
||
| 25 | type Handed = "handed" | "kept" | "skipped"; | |
| 26 | ||
| 27 | /** Give one child a proposal credential when it has none or its own is nearly spent. Idempotent. */ | |
| 28 | export function handProposalCredential(app: App, child: Child, now: number = Date.now()): Handed { | |
| 29 | const dir = childDirOf(app, child.bodyId); | |
| 30 | const doc = readDoc(dir); | |
| 31 | const code = doc?.["forgeCode"]; | |
| 32 | if (doc === undefined || typeof code !== "object" || code === null) return "skipped"; | |
| 33 | const link = code as Record<string, unknown>; | |
| 34 | if (link["severedAt"] !== undefined || typeof link["upstream"] !== "string") return "skipped"; | |
| 35 | const [owner, name, ...rest] = link["upstream"].split("/"); | |
| 36 | const parent = owner && name && rest.length === 0 ? getRepo(app.db, owner, name) : undefined; | |
| 37 | if (parent === undefined) return "skipped"; | |
| 38 | const have = doc["proposal"]; | |
| 39 | const expiresAt = typeof have === "object" && have !== null ? (have as Record<string, unknown>)["expiresAt"] : undefined; | |
| 40 | if (typeof expiresAt === "number" && expiresAt - now > RENEW_BEFORE_MS) return "kept"; | |
| 41 | // Only the spawner, and only while they may write to the parent; and only for an origin that | |
| 42 | // parses. | |
| 43 | const as = proposalUser(app, parent, child.ownerId); | |
| 44 | const origin = parseOrigin(child.url); | |
| 45 | if (as === undefined || origin === undefined) return "skipped"; | |
| 46 | const minted = mintProposalToken( | |
| 47 | app.db, | |
| 48 | as.id, | |
| 49 | parent.id, | |
| 50 | { child: child.name, origin }, | |
| 51 | now, | |
| 52 | ); | |
| 53 | if (!minted.ok) return "skipped"; | |
| 54 | // A token the child never received is not left standing, whether the write refused or threw. | |
| 55 | const unminted = (): void => void app.db.query("DELETE FROM token WHERE id = ?1").run(minted.value.id); | |
| 56 | let stored: ReturnType<typeof storeProposal>; | |
outdated
Fallback origin |
||
| 57 | try { | |
| 58 | stored = storeProposal(dir, { child: child.name, token: minted.value.token, expiresAt: now + PROPOSAL_TTL_MS }); | |
| 59 | } catch (error) { | |
| 60 | unminted(); | |
| 61 | throw error; | |
| 62 | } | |
| 63 | if (!stored.ok) { | |
| 64 | unminted(); | |
| 65 | return "skipped"; | |
| 66 | } | |
| 67 | // Only once the child holds the new one does the old one end. | |
| 68 | revokeProposalTokens(app.db, parent.id, child.name, minted.value.id); | |
| 69 | return "handed"; | |
| 70 | } | |
| 71 | ||
| 72 | let lastPass = 0; | |
| 73 | ||
| 74 | /** The parent's pass over every finished child; the names handed a credential. Never throws. */ | |
| 75 | export async function handProposalCredentials(app: App, force = false, now: number = Date.now()): Promise<string[]> { | |
| 76 | if (!force && now - lastPass < HANDOUT_EVERY_MS) return []; | |
| 77 | lastPass = now; | |
| 78 | const handed: string[] = []; | |
| 79 | try { | |
| 80 | for (const child of await listChildren(app)) { | |
| 81 | if (!child.done) continue; | |
| 82 | try { | |
| 83 | if (handProposalCredential(app, child, now) === "handed") handed.push(child.name); | |
| 84 | } catch (error) { | |
| 85 | app.log.warn("proposal credential not handed", { forge: child.name, reason: String(error) }); | |
| 86 | } | |
| 87 | } | |
| 88 | } catch (error) { | |
| 89 | app.log.warn("proposal credential pass failed", { error: String(error) }); | |
| 90 | } | |
| 91 | return handed; | |
| 92 | } |
src/web/pages/chain.ts +11 −2
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * sever. A severed forge says so with the date and nothing is deleted. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { FAMILY_WORDS } from "../../actions/family_words.ts"; | |
| 8 | 9 | import { FOLLOW_MODE_REFUSALS, followModeSaid, setFollowMode, severForge, takeForgeCode, takeForgeWords } from "../../actions/follow.ts"; |
| 9 | 10 | import { FOLLOWS_NOTHING, PROPOSE_NEEDS_WRITE } from "../../actions/follow_words.ts"; |
| 10 | 11 | import { forgeProposals, proposeToParentForge, type ForgeProposal } from "../../actions/upstream.ts"; |
| @@ -228,7 +229,10 @@ export async function takeSubmit(ctx: Ctx): Promise<Response> { | ||
| 228 | 229 | return flashOrJson(ctx, to, takeForgeWords(took.value)); |
| 229 | 230 | } |
| 230 | 231 | |
| 231 | /** POST /:owner/:name/following/mode {mode} or /following/mode/:mode (what the confirm step posts); the owner only. */ | |
| 232 | /** | |
| 233 | * POST /:owner/:name/following/mode {mode} or /following/mode/:mode (what the confirm step posts); | |
| 234 | * the owner only. | |
| 235 | */ | |
| 232 | 236 | export async function modeSubmit(ctx: Ctx): Promise<Response> { |
| 233 | 237 | const repo = loadRepo(ctx); |
| 234 | 238 | if (!repo) return notFoundPage(ctx); |
| @@ -241,7 +245,10 @@ export async function modeSubmit(ctx: Ctx): Promise<Response> { | ||
| 241 | 245 | return flashOrJson(ctx, to, { message: followModeSaid(forkParentFor(ctx.app.db, repo, ctx.auth.user), set.value) }); |
| 242 | 246 | } |
| 243 | 247 | |
| 244 | /** POST /:owner/:name/following/propose: push to the parent forge and open the pull there; a writer only. */ | |
| 248 | /** | |
| 249 | * POST /:owner/:name/following/propose: push to the parent forge and open the pull there; a writer | |
| 250 | * only. | |
| 251 | */ | |
| 245 | 252 | export async function proposeParentSubmit(ctx: Ctx): Promise<Response> { |
| 246 | 253 | const repo = loadRepo(ctx); |
| 247 | 254 | if (!repo) return notFoundPage(ctx); |
| @@ -257,6 +264,8 @@ export async function proposeParentSubmit(ctx: Ctx): Promise<Response> { | ||
| 257 | 264 | message: |
| 258 | 265 | e === "no_parent_forge" |
| 259 | 266 | ? "This forge has no parent forge to propose to." |
| 267 | : e === "no_credential" | |
| 268 | ? `${FAMILY_WORDS.no_credential[0]!.toUpperCase()}${FAMILY_WORDS.no_credential.slice(1)}.` | |
| 260 | 269 | : e === "nothing_to_propose" |
| 261 | 270 | ? "Nothing here is ahead of the parent forge." |
| 262 | 271 | : typeof e === "string" |
test/parent-forge-refusals.test.ts +4 −4
| @@ -77,10 +77,10 @@ describe("proposing to a parent forge that is not there for this repository", () | ||
| 77 | 77 | forgeCode: { repo, upstream: "alice/app", mode: "tell-me", tip: "", chain: [] }, |
| 78 | 78 | }); |
| 79 | 79 | |
| 80 | const refused = async (c: { app: App; user: User; repo: Repo }) => { | |
| 80 | const refused = async (c: { app: App; user: User; repo: Repo }, why = "no_parent_forge") => { | |
| 81 | 81 | seen = []; |
| 82 | 82 | const r = await proposeToParentForge(c.app, c.user, c.repo); |
| 83 | expect(r.ok ? "ok" : r.error).toBe("no_parent_forge"); | |
| 83 | expect(r.ok ? "ok" : r.error).toBe(why); | |
| 84 | 84 | expect(seen).toEqual([]); |
| 85 | 85 | }; |
| 86 | 86 | |
| @@ -95,8 +95,8 @@ describe("proposing to a parent forge that is not there for this repository", () | ||
| 95 | 95 | await refused(c); |
| 96 | 96 | }); |
| 97 | 97 | |
| 98 | test("a link with no stored credential is refused", async () => { | |
| 99 | await refused(await child("alice", "app", () => doc("alice/app"))); | |
| 98 | test("a link with no stored credential is refused as holding none", async () => { | |
| 99 | await refused(await child("alice", "app", () => doc("alice/app")), "no_credential"); | |
| 100 | 100 | }); |
| 101 | 101 | |
| 102 | 102 | test("the same link with a credential gets past the refusal", async () => { |
test/proposal-handout.test.ts added +188
| @@ -0,0 +1,188 @@ | ||
| 1 | /** | |
| 2 | * Every hosted forge holds a proposal credential (#13725): the parent hands one to each finished | |
| 3 | * child with a live chain, renews it before it ends, and the child's refusal says when it has none. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { chmodSync, readFileSync, writeFileSync } from "node:fs"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { proposeToParentForge } from "../src/actions/upstream.ts"; | |
| 11 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { childDirOf, listChildren, spawnForge } from "../src/actions/spawn.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { FAMILY_WORDS, HANDOUT_EVERY_MINUTES } from "../src/actions/family_words.ts"; | |
| 15 | import { PROPOSAL_TTL_MS } from "../src/core/proposal_token.ts"; | |
| 16 | import { getRepo, type Repo } from "../src/core/repos.ts"; | |
| 17 | import { verifyToken } from "../src/core/tokens.ts"; | |
| 18 | import { createUser, type User } from "../src/core/users.ts"; | |
| 19 | import { hostedPlacement } from "../src/spawn/placement.ts"; | |
| 20 | import { parentCredential } from "../src/spawn/parent_credential.ts"; | |
| 21 | import { handProposalCredential, handProposalCredentials, HANDOUT_EVERY_MS, RENEW_BEFORE_MS } from "../src/spawn/proposal_handout.ts"; | |
| 22 | import { quietLogs } from "./helpers/globals.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | describe("the proposal credential a parent hands each child", () => { | |
| 27 | let dir = ""; | |
| 28 | let parent: App; | |
| 29 | let alice: User; | |
| 30 | let forge: Repo; | |
| 31 | let child: App; | |
| 32 | let dataDir = ""; | |
| 33 | ||
| 34 | beforeAll(async () => { | |
| 35 | dir = await mkdtemp(join(tmpdir(), "forge-handout-")); | |
| 36 | parent = createApp({ dataDir: join(dir, "parent"), port: 0, host: "root.test", url: "https://root.test" }); | |
| 37 | const u = await createUser(parent.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-handout-passphrase", adminIfFirst: true }); | |
| 38 | if (!u.ok) throw new Error(String(u.error)); | |
| 39 | alice = u.value; | |
| 40 | const made = await createRepo(parent, alice, { name: "forge", visibility: "public" }); | |
| 41 | if (!made.ok) throw new Error(String(made.error)); | |
| 42 | forge = made.value; | |
| 43 | const c = await commitToBranch(parent, alice, forge, { | |
| 44 | branch: "main", | |
| 45 | message: "Start", | |
| 46 | files: [{ path: "README.md", content: "hi\n" }], | |
| 47 | }); | |
| 48 | if (!c.ok) throw new Error(JSON.stringify(c.error)); | |
| 49 | const r = await spawnForge( | |
| 50 | parent, | |
| 51 | alice, | |
| 52 | { name: "kid", org: "kid", apps: [], carryBriefs: false, carrySubscriptions: false }, | |
| 53 | { catalog: [], briefs: [], subscriptions: [] }, | |
| 54 | { | |
| 55 | placement: hostedPlacement({ host: "root.test" }), | |
| 56 | request: new Request("https://root.test/x", { method: "POST", headers: { origin: "https://root.test" } }), | |
| 57 | url: new URL("https://root.test/x"), | |
| 58 | }, | |
| 59 | ); | |
| 60 | if (!r.ok) throw new Error(JSON.stringify(r.error)); | |
| 61 | dataDir = childDirOf(parent, r.value.bodyId); | |
| 62 | child = createApp({ dataDir, port: 0 }); | |
| 63 | // A live chain: the child's code is a fork of alice/forge. | |
| 64 | const file = join(dataDir, "parent.json"); | |
| 65 | const doc = JSON.parse(readFileSync(file, "utf8")); | |
| 66 | writeFileSync( | |
| 67 | file, | |
| 68 | JSON.stringify({ | |
| 69 | ...doc, | |
| 70 | upstream: "http://127.0.0.1:1", | |
| 71 | forgeCode: { repo: "kid/forge", upstream: "alice/forge", mode: "tell-me", tip: "", chain: [] }, | |
| 72 | }), | |
| 73 | ); | |
| 74 | }); | |
| 75 | ||
| 76 | afterAll(async () => { | |
| 77 | child.db.close(); | |
| 78 | parent.db.close(); | |
| 79 | await rm(dir, { recursive: true, force: true }); | |
| 80 | }); | |
| 81 | ||
| 82 | const kid = async () => (await listChildren(parent)).find((c) => c.name === "kid")!; | |
| 83 | const docOf = () => JSON.parse(readFileSync(join(dataDir, "parent.json"), "utf8")); | |
| 84 | ||
| 85 | test("a child with a live chain and no credential is refused in words that say so", async () => { | |
| 86 | expect(await parentCredential(child)).toBeUndefined(); | |
| 87 | const solo = createApp({ dataDir: join(dir, "solo"), port: 0, host: "kid.test" }); | |
| 88 | const owner = await createUser(solo.db, { origin: "seed", trusted: true, username: "kidowner", email: "[email protected]", password: "a-long-handout-passphrase", adminIfFirst: true }); | |
| 89 | if (!owner.ok) throw new Error(String(owner.error)); | |
| 90 | const mine = await createRepo(solo, owner.value, { name: "forge", visibility: "public" }); | |
| 91 | if (!mine.ok) throw new Error(String(mine.error)); | |
| 92 | writeFileSync( | |
| 93 | join(dir, "solo", "parent.json"), | |
| 94 | JSON.stringify({ upstream: "http://127.0.0.1:1", name: "kid", forgeCode: { repo: "kidowner/forge", upstream: "alice/forge", mode: "tell-me", tip: "", chain: [] } }), | |
| 95 | ); | |
| 96 | const r = await proposeToParentForge(solo, owner.value, mine.value); | |
| 97 | expect(r.ok ? "ok" : r.error).toBe("no_credential"); | |
| 98 | }); | |
| 99 | ||
| 100 | test("the parent hands one over, and the child reads it as its own", async () => { | |
| 101 | expect(handProposalCredential(parent, await kid())).toBe("handed"); | |
| 102 | const cred = await parentCredential(child); | |
| 103 | expect(cred?.child).toBe("kid"); | |
| 104 | expect(cred?.repo).toBe("alice/forge"); | |
| 105 | const known = verifyToken(parent.db, cred!.token); | |
| 106 | expect(known.ok).toBe(true); | |
| 107 | const p = known.ok ? known.value.proposal : undefined; | |
| 108 | expect(p?.repoId).toBe(forge.id); | |
| 109 | expect(p?.child).toBe("kid"); | |
| 110 | expect(p?.readOnly).toBeFalsy(); | |
| 111 | }); | |
| 112 | ||
| 113 | test("while it has time left, nothing is minted again", async () => { | |
| 114 | const before = docOf().proposal.token; | |
| 115 | expect(handProposalCredential(parent, await kid())).toBe("kept"); | |
| 116 | expect(docOf().proposal.token).toBe(before); | |
| 117 | }); | |
| 118 | ||
| 119 | test("near its end a fresh one replaces it and the old one stops working", async () => { | |
| 120 | const old = docOf().proposal.token; | |
| 121 | const at = Date.now() + PROPOSAL_TTL_MS - RENEW_BEFORE_MS + 1000; | |
| 122 | expect(handProposalCredential(parent, await kid(), at)).toBe("handed"); | |
| 123 | const now = docOf().proposal.token; | |
| 124 | expect(now).not.toBe(old); | |
| 125 | expect(verifyToken(parent.db, old).ok).toBe(false); | |
| 126 | expect(verifyToken(parent.db, now).ok).toBe(true); | |
| 127 | }); | |
| 128 | ||
| 129 | const tokens = () => parent.db.query<{ n: number }, []>("SELECT count(*) AS n FROM token").get()!.n; | |
| 130 | ||
| 131 | test("the refusal's wait is the pass's own interval", () => { | |
| 132 | expect(HANDOUT_EVERY_MS).toBe(HANDOUT_EVERY_MINUTES * 60_000); | |
| 133 | expect(FAMILY_WORDS.no_credential).toContain(`every ${HANDOUT_EVERY_MINUTES} minutes`); | |
| 134 | }); | |
| 135 | ||
| 136 | test("a spawner who cannot write to the parent repository gets nothing, and the owner is not stood in", async () => { | |
| 137 | const bob = await createUser(parent.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-long-handout-passphrase" }); | |
| 138 | if (!bob.ok) throw new Error(String(bob.error)); | |
| 139 | const before = tokens(); | |
| 140 | const old = docOf().proposal?.token; | |
| 141 | const at = Date.now() + 4 * PROPOSAL_TTL_MS; | |
| 142 | expect(handProposalCredential(parent, { ...(await kid()), ownerId: bob.value.id }, at)).toBe("skipped"); | |
| 143 | expect(handProposalCredential(parent, (({ ownerId: _gone, ...rest }) => rest)(await kid()), at)).toBe("skipped"); | |
| 144 | expect(tokens()).toBe(before); | |
| 145 | expect(docOf().proposal?.token).toBe(old); | |
| 146 | }); | |
| 147 | ||
| 148 | test("a child with no parseable origin is skipped, not given a token bound to a made-up host", async () => { | |
| 149 | const before = tokens(); | |
| 150 | const at = Date.now() + 4 * PROPOSAL_TTL_MS; | |
| 151 | expect(handProposalCredential(parent, { ...(await kid()), url: "not a url" }, at)).toBe("skipped"); | |
| 152 | expect(tokens()).toBe(before); | |
| 153 | }); | |
| 154 | ||
| 155 | test("a credential the child could not be given is not left minted", async () => { | |
| 156 | const before = tokens(); | |
| 157 | const at = Date.now() + 4 * PROPOSAL_TTL_MS; | |
| 158 | chmodSync(dataDir, 0o500); | |
| 159 | try { | |
| 160 | let threw = false; | |
| 161 | let result = ""; | |
| 162 | try { | |
| 163 | result = handProposalCredential(parent, await kid(), at); | |
| 164 | } catch { | |
| 165 | threw = true; | |
| 166 | } | |
| 167 | if (!threw && result === "handed") return; // a user who ignores the mode (root): nothing to prove | |
| 168 | expect(threw || result === "skipped").toBe(true); | |
| 169 | } finally { | |
| 170 | chmodSync(dataDir, 0o700); | |
| 171 | } | |
| 172 | expect(tokens()).toBe(before); | |
| 173 | }); | |
| 174 | ||
| 175 | test("the pass hands to every finished child and a severed chain gets nothing", async () => { | |
| 176 | const file = join(dataDir, "parent.json"); | |
| 177 | const doc = docOf(); | |
| 178 | delete doc.proposal; | |
| 179 | doc.forgeCode.severedAt = new Date().toISOString(); | |
| 180 | writeFileSync(file, JSON.stringify(doc)); | |
| 181 | expect(await handProposalCredentials(parent, true)).toEqual([]); | |
| 182 | expect(docOf().proposal).toBeUndefined(); | |
| 183 | delete doc.forgeCode.severedAt; | |
| 184 | writeFileSync(file, JSON.stringify(doc)); | |
| 185 | expect(await handProposalCredentials(parent, true)).toEqual(["kid"]); | |
| 186 | expect(getRepo(parent.db, "alice", "forge")).toBeDefined(); | |
| 187 | }); | |
| 188 | }); |
test/propose-no-credential.test.ts added +77
| @@ -0,0 +1,77 @@ | ||
| 1 | /** | |
| 2 | * A forge with a live chain and no proposal credential (#13725) says so on every door: the API | |
| 3 | * answers 409 `no_credential`, the MCP tool and the page say the same words, and nothing is sent. | |
| 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 { FAMILY_WORDS } from "../src/actions/family_words.ts"; | |
| 10 | import { createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createSession } from "../src/core/sessions.ts"; | |
| 13 | import { createToken } from "../src/core/tokens.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | describe("a forge whose parent has not yet handed it a credential", () => { | |
| 21 | let dir = ""; | |
| 22 | let app: App; | |
| 23 | let server: Servers; | |
| 24 | let user: User; | |
| 25 | ||
| 26 | beforeAll(async () => { | |
| 27 | dir = await mkdtemp(join(tmpdir(), "forge-nocred-")); | |
| 28 | app = createApp({ dataDir: join(dir, "kid"), port: 0, host: "kid.test", url: "https://kid.example.com" }); | |
| 29 | server = await serve(app); | |
| 30 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "kid", email: "[email protected]", password: "a-long-nocred-passphrase", adminIfFirst: true }); | |
| 31 | if (!made.ok) throw new Error(String(made.error)); | |
| 32 | user = made.value; | |
| 33 | const repo = await createRepo(app, user, { name: "forge", visibility: "public" }); | |
| 34 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 35 | await Bun.write( | |
| 36 | join(dir, "kid", "parent.json"), | |
| 37 | JSON.stringify({ upstream: "http://127.0.0.1:1", name: "kid", forgeCode: { repo: "kid/forge", upstream: "alice/forge", mode: "tell-me", tip: "", chain: [] } }), | |
| 38 | ); | |
| 39 | }); | |
| 40 | ||
| 41 | afterAll(async () => { | |
| 42 | await server.stop(); | |
| 43 | await rm(dir, { recursive: true, force: true }); | |
| 44 | }); | |
| 45 | ||
| 46 | test("the API answers 409 no_credential with the words", async () => { | |
| 47 | const token = createToken(app.db, user.id, "api", "rw").token; | |
| 48 | const res = await fetch(`${server.url}/api/v1/repos/kid/forge/following/propose-parent`, { method: "POST", headers: { authorization: `Bearer ${token}` } }); | |
| 49 | expect(res.status).toBe(409); | |
| 50 | const body = (await res.json()) as { error: { code?: string; message?: string } | string; code?: string; message?: string }; | |
| 51 | expect(JSON.stringify(body)).toContain("no_credential"); | |
| 52 | expect(JSON.stringify(body)).toContain(FAMILY_WORDS.no_credential); | |
| 53 | }); | |
| 54 | ||
| 55 | test("the MCP tool says the same", async () => { | |
| 56 | const token = createToken(app.db, user.id, "mcp", "rw").token; | |
| 57 | const res = await fetch(`${server.url}/mcp`, { | |
| 58 | method: "POST", | |
| 59 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, | |
| 60 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "propose_to_parent_forge", arguments: { repo: "kid/forge" } } }), | |
| 61 | }); | |
| 62 | const body = (await res.json()) as any; | |
| 63 | expect(body.result.isError).toBe(true); | |
| 64 | expect(body.result.content[0].text).toStartWith(`no_credential: ${FAMILY_WORDS.no_credential}`); | |
| 65 | }); | |
| 66 | ||
| 67 | test("the page says it, capitalised and ended", async () => { | |
| 68 | const cookie = `forge_session=${createSession(app.db, user.id).token}`; | |
| 69 | const res = await fetch(`${server.url}/kid/forge/following/propose`, { | |
| 70 | method: "POST", | |
| 71 | redirect: "manual", | |
| 72 | headers: { cookie, origin: "https://kid.example.com", accept: "application/json" }, | |
| 73 | }); | |
| 74 | const said = (await res.json()) as { error: string }; | |
| 75 | expect(said.error).toBe(`${FAMILY_WORDS.no_credential[0]!.toUpperCase()}${FAMILY_WORDS.no_credential.slice(1)}.`); | |
| 76 | }); | |
| 77 | }); |
new above
offline
Says 'every ten minutes'; the handout pass runs every 5 minutes (HANDOUT_EVERY_MS). Make them agree.