Skip to content

Commit f230e8f

Browse files
authored
🔎 Let a workflow read the objections a pull request already holds (#580)
* 🔎 Let a workflow read the objections a pull request already holds A network-denied reviewer judges what its prompt renders, so an objection the document does not fetch is one the review never sees. `<PullRequest>` returns only what it reconciled; reviews, comments and checks are separate reads, and until now there was no supported way to make them — `<Fetch>` is credential-free by design, one request per invocation, with no pagination, and cannot reach a private repository at all. Three self-closing components read them: <PullRequest.Reviews number={pullRequest.number} as="reviews" /> <PullRequest.Comments number={pullRequest.number} as="comments" /> <PullRequest.Checks number={pullRequest.number} as="checks" /> One required `number`; the enclosing <Repository> and the contextual working directory decide the rest, so no prop names a host and none carries a credential. The host's own credential is acquired for the retained locator and disposed with the invocation, and nothing of it, the endpoint, the raw response or the pagination state is retained. Complete or unavailable, and never in between. A transport failure, a rate limit, a rejected credential, an ambiguous 404, malformed content, an unreadable item, a next relation off the authorized origin and a walk still going at the page limit all fail the read rather than binding a shorter list. An empty array means the provider completed the collection and found none, which is the one thing a truncated list would be indistinguishable from. Three components rather than one, and three durable effects: completing one manufactures neither of the others, and each replays and fails alone. A read is *not* a reconciled Git-host effect — that engine exists for a mutation that must adopt an interrupted attempt, and a read has no natural key, no pre-state and nothing to perform. It is an ordinary durable read, so an interruption may repeat its GETs and a completed replay restores the array without opening a session. Answers are held to the request. Checks observe the head first and read every result at that exact SHA, each record carrying it, so evidence always says which revision it describes; a payload naming another repository, number or head is a protocol failure. Check runs and commit statuses keep separate vocabularies under `kind`, because a status's `error` is not a run's `failure`. Evidence is PRR1–PRR11, every one mutation-checked. Two of them were green for the wrong reason first: PRR2 passed while the component's number check was dead (the props schema is the real gate, so that check is gone), and PRR11 passed against a completed replay that never re-entered the procedure until the root Close was dropped. That investigation found a real defect. The components asked `hasContent()` to refuse a paired invocation, and it answered `true` for a self-closing one — the contextual answer #369 documented as untrustworthy. They now declare `forms: "self-closing"` and the engine builds the dispatcher, the way `<Dir>` and `<File.Delete>` do. Refs #576 * 🔎 Keep the evidence off the route the request travels Revises the pull-request evidence read. The three-component product surface is unchanged; what changes is what crosses which boundary, and what a record has to prove before it becomes evidence. The request now crosses a public contextual route, `executablemd.workflow.pull-request-evidence`, and the evidence crosses nothing public at all. Middleware may see exactly what is about to be read, refuse it, narrow which reads a run performs, or delegate — and the route answers with a *request*, so there is nothing there it could answer with instead. Behind it is an exact-invocation terminal: the request is minted for one invocation and branded with a private class field, so a copy carrying the same members, a request another invocation issued, one rebuilt from the retained journal, and one a handler kept from an earlier read are each refused before anything is sent. Structural equality would not do — two elements reading the same number produce identical requests. Durable and live are now separate. The journal holds `GitPushRepositoryIdentity` — the Repository identity without its Workspace checkout path — plus the number and the collection, and the effect's fingerprint covers those same members. The full Repository record and the working directory stay live provider-private attachment data. Every parser is closed on exact membership rather than on presence, so a payload one member wider than the contract is refused instead of reaching a binding. Normalization corrections: `reviewId` is nullable, because an inline comment can belong to no review; a check run's link is `html_url` and a commit status's is `target_url`; an identifier that cannot be held exactly is refused rather than rounded into one naming a different object; the status, conclusion and state vocabularies are closed TypeScript unions; and *unavailable* is told apart from *protocol-invalid* — a host that did not answer versus one that answered about the wrong subject. Every field an answer is authenticated by is now required: reviews and comments must name their pull request, checks and statuses must name the commit, and the pull request must name its own number and repository. Each component declares the exact array it binds, which is what makes `as` mandatory and refuses an invocation that forgot it before a credential is read. The engine-owned self-closing form dispatch is unchanged. Evidence is PRR1–PRR24 in `pull-request-read.test.ts`, including the five terminal attacks, the exact URL and field mappings, a null review id, session teardown, a failed read retaining no array, and a changed question being a different effect. Three of the new cases were wrong before they were right: a failed durable read *is* journaled (with a refusal and no `value`), a changed request at a replayed position is a divergence rather than a fresh read, and a plain `Error` from middleware escapes differently than a domain refusal. Two repository rules caught real mistakes: the first terminal was a module-scoped `WeakMap` — a process-lifetime registry shared by every run — and the adapter returned `{ok}` unions instead of Effection `Result<T>`. Architecture, both specifications, both inventories and the #300 scheduling boundary are updated; scheduling is #300's rather than blocked on #301. Refs #576 * 🔒 Give the evidence no public route to be answered on Addresses the review of 83b0d9d. The bypass was real: the component routed its request through the new request-only Api and then took the evidence from `GitComposition.readPullRequestEvidence`, which is public and exported. Anything in scope could answer it without delegating, and the fabricated collection became what a document bound and the journal retained — the branded-request check sat behind a door nobody had to walk through. That operation is gone. There is no public Api that returns evidence. The three components are built by the trusted host over a terminal and capture it in their closure, so the only thing that can author a result is the host; `PRR25` asserts both halves — the operation is absent from the public Api, and middleware installed on that Api observes no read at all. The public request is now structural: the retained Repository identity, the number and the collection. The attachment a provider needs — the whole Repository record and the working directory — goes from the component to the terminal directly and appears in no request, so middleware never sees a host path. The retained result is the discriminated envelope: `{kind:"reviews",items}`, `{kind:"comments",items}`, `{kind:"checks",headSha,items}`. Only a checks result carries a head, and only `items` becomes the binding. The adapter builds it directly — the collector is generic, so each branch produces its own item type and nothing is narrowed back out of a union. `PRR26` covers interruption in flight: a transport that reaches the wire and suspends, the owning task halted, and then the session unwound, no successful result or partial array retained, and a continuation performing the whole collection. `PRR27` — the changed-request replay at one position — is not here, and deliberately: see the handback. Architecture, the workflow Workspace specification (§7.7) and the executable-MDX specification all describe the corrected boundary; the last of those had not been touched before. Refs #576 * 🔒 Authenticate the request this activation is holding, not a name for it Addresses the Architect's review of 1fff3bb. The issuance check was `expansion.id`, and that identifier outlives one activation. Middleware could keep a genuine request from one execution and hand it back during the next execution of the same element, and `isReadRequestFor()` would call it current. PRR28 is that attack: the first execution is halted on the wire so the root stays open, the handler keeps the request it saw, and the next execution of the same element receives it back. The fix is smaller than what it replaces. The component creates one request object for the activation it is running and keeps it; the terminal is given both that object and whatever came back from the route, and reads only when they are the same object. Identity needs no registry, so the branded-request module is gone entirely — no `WeakMap`, no class brand, no name. A copy, a sibling's request, a reconstructed one and a stale one are all simply a different object. `expansion.id` still names the durable position; it no longer authenticates issuance. The route is renamed throughout: `PullRequestAPI` in `pull-request-api.ts`, companion interface `PullRequestApi`, contextual name `executablemd.workflow.pull-request`. "Evidence" stays where it belongs — on the normalized review, comment and check records, the adapter that produces them, and the module they live in. `upsertPullRequest` is untouched. PRR28 is mutation-checked: replacing the identity comparison with a structural one fails it, and fails PRR19 with it. Architecture, the workflow Workspace specification and the executable-MDX specification all describe exact live object identity and the new name. The public request is still `{repository, number, kind}`, the attachment is still private, the envelopes are unchanged, only `items` binds, and no public Api returns evidence. The second required case — a changed durable request at the same position — is not here. See the handback: it needs a fork fixture in another package. Refs #576 * 🔎 Ask one surface for a pull request, and name it by URL Replaces the request-only route and invocation-private terminal with the topology `<Issue>` already has: one `PullRequestApi` carrying `read(url, options)` and `upsert(pullRequest, options)`, reached under `executablemd.workflow.pull-request`, where a provider is ordinary middleware. It recognizes the URLs it can act on, delegates the rest untouched, and once it matches, its answer and its refusal are final. Reads name a pull request by canonical URL. No `<Repository>`, no working directory, no attachment: the URL is the identity and the selected provider parses the repository and number out of it. Canonicalization is provider-neutral and happens first, so the component, the durable request and every adapter read one answer. Implicit selection is public `github.com`; an explicit `provider="github"` reaches the same path shape on a self-hosted host. `upsertPullRequest` moves off `GitComposition` onto the same surface and keeps returning the complete `PullRequestResult`. Issue answers with a URL alone because that is the whole of its portable contract; a pull request already has a stronger shipped one, and #301's create/update loop reads `number` back on its next pass. Which pull requests may be read is now operator configuration: `XMD_WORKFLOW_GITHUB_PULL_REQUESTS` with `allowed` and an optional `endpoint`, read once when the Deno host is constructed and refused rather than narrowed when it is malformed. `allowed` rather than `ceiling` — the shipped issues contract keeps its word, and an operator writes the list of places this host may reach. Absence authorizes no URL read and disables nothing else: the adapter is installed on every live or partial attachment, its read method delegates to the surface's base error, and `<PullRequest>` upserts on this run's own Push evidence, which no configuration grants or withdraws. Two things the fork evidence found. A `pull_request_read` was classified `unsupported-effect`, so no checkpoint at or after one could be forked; it joins `fetch` in the inheritable set for the same reason — it changed nothing at the host, and the record holds the collection itself. And the run was in the effect *name*, which made every inherited read a different effect: it stays in the retained request, where it says who asked, and leaves the name to the question. PRR27 forks at the completed read itself. The control fork with the inherited URL restores the collection and sends no second request; a fork overriding `--props-url` diverges at that position and neither restores nor binds the earlier evidence. The unchanged control is asserted first on purpose — without it the changed branch would diverge for reasons that have nothing to do with the URL. PRR19, PRR20/20b, PRR21, PRR25 and PRR28 replace the superseded terminal attacks; PRR23 now proves URL, discriminator and collection all name the effect. Architecture, both specifications and the PR description follow. Refs #576 * 🩹 Hold a pull-request answer to the whole subject it was asked about Three corrections to the URL-based reading surface. The composition provider carried a `gitHub` source option that nothing read after reading moved to its own middleware, so every consumer injecting a transport through it reached the real host instead. It is removed, and its consumers now inject through `gitHubPullRequests.access`, which is the seam that is actually installed. An answer was matched to its request by the trailing number alone, so a response about someone else's pull request numbered the same was published as this one's evidence. The adapter now compares the complete API subject — endpoint, owner, repository, collection and number — and the loopback fixture answers with the absolute subject a real host returns. The specifications still described the superseded Repository-and-number request. They describe the URL the run retains. PRR7 covers the same-number, wrong-repository answer for reviews and for conversation comments. PRR27's changed-URL fork writes its property after the positional, so it is refused as a divergence at the checkpoint rather than for its arguments. * 🩹 Read a repository name in any casing, the way GitHub does The subject check compared the answer's URL byte for byte, so a request naming `OCTO/PROJECT` — which GitHub accepts — was refused as protocol-invalid when the host answered about `octo/project`, its own canonical spelling. The comparison is now part by part: the endpoint, the collection and the number are exactly what was asked for, and the owner and repository are the same name in any casing. That is the identity the head check already applied to `full_name`, and it now shares the one helper. PRR7 keeps its wrong-repository rejection and gains the border case: a canonical answer to a differently cased request is read. Restoring a byte comparison fails it, and accepting any name fails it too. The fixture builds its foreign review through an overrides parameter instead of a cast. * 🧪 Prove every published URL is the one a person opens PRR3 asserted that bodies and messages survive normalization byte for byte, but nothing held the links to their source fields. A payload carries three URL families — what a person opens, what the API answers on, and where a build lives — and a reader that published the wrong one would send a reviewer to JSON or to a CI page instead of to the objection they were shown. PRR3b gives each family a visibly distinct value and pins all six answers: a review, a conversation comment and an inline comment are opened at `html_url` rather than at the subject URL beside it; a check run is opened at `html_url` and stays null without one, because `details_url` names a different place and is not a substitute; a commit status is opened at `target_url` and stays null without one. An inline comment left outside a review carries an explicit `pull_request_review_id: null`, and it is an ordinary comment — retained with a null review rather than dropping the collection. Each answer discriminates: six independent mutations, one per field, each fail this case and nothing else. No production change was needed. --------- Co-authored-by: Taras Mankovski <[email protected]>
1 parent d58c3db commit f230e8f

32 files changed

Lines changed: 4286 additions & 84 deletions

‎architecture.md‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ Existing documents and code get aligned to this section retroactively.
6868
| effect transaction | the single atomic SQLite transaction that publishes one Workspace-local mutation together with that effect's journal result |
6969
| external effect | an effect whose provider-owned outcome cannot participate in the Workspace SQLite transaction and therefore requires a stable identity and provider reconciliation |
7070
| XMD-mediated HTTP read | one bounded, non-mutating HTTP request an authored document performs through the contextual Fetch capability, whose detached response is retained as an ordinary durable observation. It is distinct from an Agent's own network authority, which it does not grant, and from a reconciled mutating external effect, which it does not claim: an interruption before its record commits may repeat the read |
71+
| Git-host evidence read | one bounded, non-mutating read of a collection a Git host already holds about the pull request a canonical URL names — its reviews, its comments, or the checks on its head. It needs no Repository in scope: the URL is the identity, and the selected provider parses the repository and number out of it. It is authenticated with the host's own credential, bounded by the operator's `allowed` list, and paginated by the adapter, and it is *not* a reconciled external effect: it has no natural key, no pre-state and nothing to adopt, so it is an ordinary durable read whose interrupted attempt may repeat, whose completed record replays without contacting a provider, and which a fork inherits. It answers completely or not at all — an empty collection and a collection nobody could finish reading are different answers |
7172
| object-source attachment | adapter-private composition data the trusted host builds for exactly one external-effect reconciliation, giving the selected provider authorized live access to local state the frozen request cannot describe — the Git objects a push publishes, and the retained locator it is authorized to reach. It is authenticated against the durable identity it belongs to and proven contained before its first use — the local state behind one can name further state, so the graph a provider could traverse through it is validated rather than assumed — held in that provider's own closure, disposed with the invocation, and is never durable, never part of a natural key and never visible to routing middleware |
7273
| checkpoint | a completed journal boundary associated with the logical Workspace root visible after that effect |
7374
| history fork | a new workflow run that replays a compatible journal prefix and continues from its checkpoint and Workspace root under a new immutable document definition |
@@ -906,8 +907,9 @@ transaction commits restores the recorded answer event without reaching the live
906907
controller and without consuming or publishing again.
907908

908909
Scheduling — automatic resume, watchers, unattended iteration and remote host
909-
selection — remains blocked on #301's supervised-workflow contract and is not
910-
part of this behavior.
910+
selection — is #300's and is not part of this behavior. Nothing here waits on
911+
it: a suspended run continues through `xmd workflow answer` followed by an
912+
explicit `xmd workflow resume`.
911913

912914
This contract folds issue #322's suspension effect into #367. Issue #322 no
913915
longer supplies a separate implementation prerequisite; its typed correlated
@@ -1270,6 +1272,34 @@ the inherited prefix under a compatible modified definition and appends new
12701272
history under a new run ID. It never rewinds external branches, pushes, pull
12711273
requests or provider state.
12721274

1275+
Reading what a Git host holds is not reconciling what it owns. A reconciliation
1276+
exists to mutate a remote at most once across interruption, and everything it
1277+
carries — the natural key, the pre-state, the observe-then-perform pair — is
1278+
there to decide whether an attempt already landed. A read decides nothing of the
1279+
kind: repeating it is safe, and a completed one restores from the journal. So a
1280+
Git-host evidence read is an ordinary durable effect, and the machinery that
1281+
makes a mutation exactly-once is deliberately absent rather than reused where it
1282+
would only add a second identity to keep in agreement.
1283+
1284+
What such a read must not do is answer partially. A collection the host
1285+
completed and a collection nobody could finish reading are opposite facts, and
1286+
only one of them is `[]`; a truncated list would report the first while meaning
1287+
the second, so an incomplete walk fails the read and retains no array at all.
1288+
Both questions about a pull request — what it holds, and what it should say —
1289+
are asked of one surface, and a provider is ordinary middleware around it. That
1290+
is the Issue surface's topology, adopted deliberately: an adapter recognizes the
1291+
URLs it can act on and delegates the rest, and once it matches, its validation
1292+
and its refusal are final. A refusal ends the request rather than starting a
1293+
search for another provider, because a search is how a document that named one
1294+
service quietly reaches a different one.
1295+
1296+
Authority here is the operator's `allowed` list, checked before a session is
1297+
opened, a credential is read or anything is sent. It bounds reads alone: an
1298+
upsert names a branch this run published rather than a URL a document wrote, and
1299+
its authority is this run's own matching Push evidence, which no configuration
1300+
grants or withdraws. "Authority ceiling" remains the word for the bound; what an
1301+
operator writes is the list of places this host is allowed to reach.
1302+
12731303
An external effect is judged by its retained record rather than by its type. A
12741304
completed Git-host reconciliation record replays without contacting a provider,
12751305
so a fork inherits it and the remote is mutated once; the record keeps the
@@ -3092,7 +3122,8 @@ Status is measured against main.
30923122
| `suspendFor()` | publishes one filtered suspension request, settles `suspended`, releases the executor lock, and re-enters the same wait without duplicating it | built on the #367 stack |
30933123
| `xmd workflow answer <run-id> <suspension-id> <json>` | retains one schema-validated value for one retained wait, taking no executor lock and changing no run state | built by #300 |
30943124
| `suspension_answer` durable effect | ends a wait from retained delivery state, publishing the answer and consuming that state in one transaction | built by #300 |
3095-
| workflow scheduling (watchers, unattended iteration, remote host selection) | — | blocked on #301 |
3125+
| `<PullRequest.Reviews>` · `<PullRequest.Comments>` · `<PullRequest.Checks>` | read the reviews, comments and checks a Git host already holds for one numbered pull request, completely or not at all | built by #576 |
3126+
| workflow scheduling (watchers, unattended iteration, remote host selection) | — | #300 |
30963127
| `<Result as>` | binds `{ok: true, value}` or `{ok: false, error}`; a failure becomes a bound value, not a raise | defined, unbuilt |
30973128
| error middleware (JS api) | retry · suspend · decline | defined, unbuilt |
30983129

‎packages/cli/src/deno-workflow.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import type { WorkflowRunDatabase } from "@executablemd/workflow";
3434
import type { HelperAssembly } from "@executablemd/workflow/credential-helper";
3535
import type { WorkflowHost } from "./workflow.ts";
3636
import { gitHubIssuesConfiguration } from "./github-issues-config.ts";
37+
import { gitHubPullRequestsConfiguration } from "./github-pull-requests-config.ts";
3738
import { useWorkflowAgentProfile } from "./workflow-agent.ts";
3839

3940
/** Where a run lives when nothing says otherwise. */
@@ -50,6 +51,9 @@ export function* useDenoWorkflowHost(helper: HelperAssembly): Operation<Workflow
5051
// host cannot use learns it before a document runs rather than in the middle
5152
// of one. Absent installs no issue provider at all.
5253
const gitHubIssues = yield* gitHubIssuesConfiguration();
54+
// Read once, here, for the same reason: an operator who wrote something this
55+
// host cannot use learns it before a document runs.
56+
const gitHubPullRequests = yield* gitHubPullRequestsConfiguration();
5357
return {
5458
useRunHost(): Operation<WorkflowExecutionTransitions> {
5559
return useWorkflowRunHost({ root });
@@ -63,6 +67,7 @@ export function* useDenoWorkflowHost(helper: HelperAssembly): Operation<Workflow
6367
attach<T>(database: WorkflowRunDatabase, operation: Operation<T>): Operation<T> {
6468
return withWorkflowWorkspace(database, operation, {
6569
...(gitHubIssues === undefined ? {} : { gitHubIssues }),
70+
...(gitHubPullRequests === undefined ? {} : { gitHubPullRequests }),
6671
helper,
6772
// Only a live or partial attachment reaches this, which is what keeps a
6873
// completed replay from starting an agent process to restore a turn it
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
/**
2+
* Where the production host learns which pull requests it may read.
3+
*
4+
* A URL a document writes is composition data: it says which pull request is
5+
* wanted, not that this deployment allows reading it. What allows it is here,
6+
* beside the credential, and it is the operator's to state — so it is read from
7+
* the environment rather than from anything a run can influence.
8+
*
9+
* Absence authorizes no URL read, and that is fail-closed by construction: with
10+
* nothing allowed, `<PullRequest.Reviews>` and its two siblings reach
11+
* `PullRequestAPI`'s own base error and say that nothing handles the
12+
* destination. A deployment that wants to read pull requests says so.
13+
*
14+
* **It does not disable `<PullRequest>`.** An upsert names a branch this run
15+
* published rather than a URL a document wrote, and its authority is this run's
16+
* own matching Push evidence and the Git-host reconciliation behind it. Nothing
17+
* here is what admits it, so nothing here can withdraw it.
18+
*
19+
* Malformed configuration is refused rather than narrowed to what parsed. An
20+
* operator who wrote a list this host could not read has not authorized the
21+
* empty set — they have made a mistake, and running with fewer targets than
22+
* they wrote would hide it until the day it mattered.
23+
*
24+
* The member is `allowed`, not `ceiling`. "Authority ceiling" is what the
25+
* architecture calls the bound; what an operator writes is the list of places
26+
* this host is allowed to read, and naming it after the thing they are stating
27+
* is the difference between configuration and jargon. `XMD_WORKFLOW_GITHUB_ISSUES`
28+
* keeps `ceiling`: it is shipped, and renaming a live contract to match a new
29+
* one is a break with nothing behind it.
30+
*/
31+
32+
import { env as readEnv } from "@executablemd/runtime";
33+
import type { Operation } from "effection";
34+
import { canonicalPullRequestUrl } from "@executablemd/workflow";
35+
import type { GitHubPullRequestsOptions } from "@executablemd/workflow/deno";
36+
37+
/** The variable that configures GitHub pull-request reading. */
38+
export const GITHUB_PULL_REQUESTS_ENV = "XMD_WORKFLOW_GITHUB_PULL_REQUESTS";
39+
40+
/** What an operator wrote there, once it is something this host cannot use. */
41+
export class GitHubPullRequestsConfigError extends Error {
42+
override name = "GitHubPullRequestsConfigError";
43+
44+
constructor(sentence: string) {
45+
super(
46+
`${GITHUB_PULL_REQUESTS_ENV} is not usable: ${sentence} Expected JSON such as ` +
47+
`{"allowed":["https://github.com/owner/repository"],"endpoint":"https://api.github.com"} — ` +
48+
"allowed is required, endpoint is optional. Unset it to authorize no URL read.",
49+
);
50+
}
51+
}
52+
53+
/**
54+
* The canonical form of an API base, or `undefined` when it is not one.
55+
*
56+
* Looser than a container URL in exactly one way: a port is admitted, because a
57+
* loopback endpoint is how a deployment points this at something other than
58+
* GitHub's own. Credentials, a query and a fragment are refused for the same
59+
* reason they are refused everywhere else — none of them is part of naming a
60+
* place, and none is guessed at or stripped.
61+
*/
62+
function canonicalEndpoint(value: unknown): string | undefined {
63+
if (typeof value !== "string" || value === "") {
64+
return undefined;
65+
}
66+
let url: URL;
67+
try {
68+
url = new URL(value);
69+
} catch {
70+
return undefined;
71+
}
72+
if (url.protocol !== "https:" && url.protocol !== "http:") {
73+
return undefined;
74+
}
75+
if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") {
76+
return undefined;
77+
}
78+
if (url.hostname === "") {
79+
return undefined;
80+
}
81+
const path = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
82+
return `${url.protocol}//${url.host}${path}`;
83+
}
84+
85+
/**
86+
* The GitHub pull-request options this host is configured with, or none.
87+
*
88+
* Strict about shape and about the URLs it holds. An entry that is not the
89+
* canonical name of a container is refused here rather than at the first
90+
* request, because an operator reading a startup failure can fix it and a
91+
* document author reading a refusal mid-run cannot.
92+
*/
93+
export function* gitHubPullRequestsConfiguration(): Operation<
94+
GitHubPullRequestsOptions | undefined
95+
> {
96+
const written = yield* readEnv(GITHUB_PULL_REQUESTS_ENV);
97+
if (written === undefined || written === "") {
98+
return undefined;
99+
}
100+
let parsed: unknown;
101+
try {
102+
parsed = JSON.parse(written);
103+
} catch {
104+
throw new GitHubPullRequestsConfigError("it is not JSON.");
105+
}
106+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
107+
throw new GitHubPullRequestsConfigError("it is not a JSON object.");
108+
}
109+
for (const key of Object.keys(parsed)) {
110+
if (key !== "allowed" && key !== "endpoint") {
111+
throw new GitHubPullRequestsConfigError(
112+
`it carries ${JSON.stringify(key)}, which is not a member.`,
113+
);
114+
}
115+
}
116+
const declared = Reflect.get(parsed, "allowed");
117+
if (!Array.isArray(declared) || declared.length === 0) {
118+
throw new GitHubPullRequestsConfigError(
119+
"its allowed is not a non-empty array of container URLs.",
120+
);
121+
}
122+
const allowed: string[] = [];
123+
for (const entry of declared) {
124+
const canonical = canonicalPullRequestUrl(entry);
125+
if (canonical === undefined) {
126+
throw new GitHubPullRequestsConfigError(
127+
"one of its allowed entries is not an http or https URL naming one container, free of " +
128+
"credentials, query and fragment.",
129+
);
130+
}
131+
allowed.push(canonical);
132+
}
133+
const written_endpoint = Reflect.get(parsed, "endpoint");
134+
if (written_endpoint === undefined) {
135+
return Object.freeze({ allowed: Object.freeze(allowed) });
136+
}
137+
const endpoint = canonicalEndpoint(written_endpoint);
138+
if (endpoint === undefined) {
139+
throw new GitHubPullRequestsConfigError(
140+
"its endpoint is not an http or https API base, free of credentials, query and fragment.",
141+
);
142+
}
143+
return Object.freeze({ allowed: Object.freeze(allowed), endpoint });
144+
}

0 commit comments

Comments
 (0)