@comforge/github 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -4
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +4 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/operations.d.ts +147 -0
- package/dist/operations.js +328 -0
- package/dist/request.d.ts +49 -0
- package/dist/request.js +88 -0
- package/dist/writer.d.ts +183 -0
- package/dist/writer.js +877 -0
- package/llms.txt +5 -3
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
- reviews, optionally only those submitted on an exact commit;
|
|
10
10
|
- check runs recorded for an exact commit, judged against the check names you require.
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
The evidence API **performs no writes** and grants nothing. A separate, opt-in writer (`createGitHubWriter`, [below](#caller-authorized-writes)) performs a fixed set of GitHub writes only when your own policy authorizes each exact request. GitHub is an external evidence source: a successful response is never an authorization, and every person-written text field (titles, bodies, review text) is returned as `{ text, truncated, trust: "untrusted" }` data, never as an instruction or a proof.
|
|
13
13
|
|
|
14
14
|
> **Pre-1.0.** Releases are tagged `github/vX.Y.Z` on the `releases/github` branch of the public Comforge repository (`github.com/vikramrao1994/comforge`), each with a `RELEASE.json` naming its source commit and checksums. The TypeScript API may still change before 1.0.
|
|
15
15
|
|
|
@@ -41,7 +41,7 @@ const files = await github.listPullRequestFiles(7, pr.head.sha); // refuses if t
|
|
|
41
41
|
if (!checks.ok) throw new Error("required checks are not green for this exact commit");
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
-
A complete, runnable consumer with a fake GitHub transport: [examples/factory-github-consumer](https://github.com/vikramrao1994/comforge/tree/github/v0.
|
|
44
|
+
A complete, runnable consumer with a fake GitHub transport: [examples/factory-github-consumer](https://github.com/vikramrao1994/comforge/tree/github/v0.3.0/examples/factory-github-consumer/).
|
|
45
45
|
|
|
46
46
|
## The transport
|
|
47
47
|
|
|
@@ -76,11 +76,62 @@ With a `SpecificationProtocol` from `@comforge/core` (`createSpecificationProtoc
|
|
|
76
76
|
- `readSpecificationIssue(github, protocol, n)` returns the issue, the marker, the delimited specification text and `verified` (the issue still hashes to its marker). A pull request is `wrong-target`; a body cut by the text limit is `incomplete`.
|
|
77
77
|
- `reconcileSpecification(github, protocol, { ticketId, digest, keyDigest })` reads every issue and answers `absent`, `existing` or `replayed`; a key or ticket already used for other content is a `conflict`. Call it before publishing so a retry never duplicates an issue.
|
|
78
78
|
|
|
79
|
-
Publishing the issue
|
|
79
|
+
Publishing the issue is not part of the specification protocol: `@comforge/core` has no authorization that covers creating an issue. If you publish with this package's writer, the authority is your own `authorize` policy, not core.
|
|
80
|
+
|
|
81
|
+
## Caller-authorized writes
|
|
82
|
+
|
|
83
|
+
`createGitHubWriter` is separate from everything above: the read transport and evidence objects have no write method and never gain one. Construct a writer only where you mean to write.
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { createGitHubWriter } from "@comforge/github";
|
|
87
|
+
|
|
88
|
+
const writer = createGitHubWriter({
|
|
89
|
+
repository: { owner: "acme", name: "widgets" },
|
|
90
|
+
token: () => mintInstallationToken(), // yours; never stored, logged or returned
|
|
91
|
+
capabilities: ["issues:comment"], // the only writes this writer performs
|
|
92
|
+
authorize: (descriptor) => myPolicy(descriptor), // yours: allow one exact descriptor, briefly
|
|
93
|
+
ledger: myDurableLedger, // yours: atomic create + version-checked replace
|
|
94
|
+
clock: Date.now,
|
|
95
|
+
expectedAuthor: "acme-bot[bot]", // the login the token writes as
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const outcome = await writer.execute({
|
|
99
|
+
kind: "issue.comment", operationId: "acme-2026-0042-c1", issueNumber: 42, body: "Thanks.",
|
|
100
|
+
});
|
|
101
|
+
// outcome.status: "verified" | "accepted" | "indeterminate"
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**Operations and capabilities.** Each operation needs exactly one capability; none implies another, and none is inferred from what the token permits.
|
|
105
|
+
|
|
106
|
+
| `kind` | Capability | GitHub request | Checked before the write |
|
|
107
|
+
|---|---|---|---|
|
|
108
|
+
| `issue.create` | `issues:create` | `POST /repos/{o}/{r}/issues` | — |
|
|
109
|
+
| `issue.comment` | `issues:comment` | `POST …/issues/{n}/comments` | the thread is an issue (or `thread: "pull-request"`), open, not locked |
|
|
110
|
+
| `pull.review` | `pulls:review` (COMMENT), `pulls:review:approve`, `pulls:review:request-changes` | `POST …/pulls/{n}/reviews` with `commit_id` | open, head is exactly `expectedHeadSha` |
|
|
111
|
+
| `pull.create` | `pulls:create` | `POST …/pulls` (same-repository head, `maintainer_can_modify: false`) | head (and optionally base) branch at the expected commit; no open PR for head and base |
|
|
112
|
+
| `issue.update` | `issues:update` | `PATCH …/issues/{n}` | `updatedAt`, and optionally body digest and state, unchanged |
|
|
113
|
+
| `comment.update` | `issues:comment:update` | `PATCH …/issues/comments/{id}` | on the expected issue; `updatedAt`, optionally body digest and author, unchanged |
|
|
114
|
+
|
|
115
|
+
Not supported, by design: merging, tags and releases, workflow dispatch, deletion, inline review comments, pending reviews and cross-repository pull requests.
|
|
116
|
+
|
|
117
|
+
**Authorization is yours and is bound to bytes.** `prepare(op)` returns the frozen `OperationDescriptor` (repository, target, capability, exact JSON payload, preconditions, and a `sha256:` digest of all of them) without sending anything. `execute(op)` builds the same descriptor and calls `authorize(descriptor)`. The decision must be `{ allow: true, descriptorDigest, expiresAt }`, with the digest of exactly this descriptor and an expiry no more than 15 minutes ahead (`limits.maxAuthorizationTtlMs`). Anything else, including a thrown error, is `authorization-denied` and nothing is sent; the expiry is checked again just before sending. The request body is derived from the descriptor only, so changing your input object after authorization changes nothing. A callback that returns `allow` is your policy, not evidence that a person approved anything.
|
|
118
|
+
|
|
119
|
+
**The ledger is what makes retries safe.** GitHub offers no idempotency key and no compare-and-swap for these endpoints, so the writer records every operation in your `OperationLedger` before sending: `reserved` → `sending` → `succeeded` | `failed` | `indeterminate` | `abandoned`. It relies on two atomic primitives — insert-if-absent (`create`) and replace-if-version (`replace`) — so two processes sharing the store cannot both send one operation. A process-local map gives that only within one process.
|
|
120
|
+
|
|
121
|
+
- The same `operationId` with the same content replays the recorded outcome without a request; with other content it is a `conflict`.
|
|
122
|
+
- Created bodies end with a correlation marker (`<!-- comforge-op v1 ns=… op=… fp=… -->`, digests only). A write whose answer is lost (timeout, network, 5xx, 408, unreadable 2xx) is searched for once by that marker, within `limits.reconcileMaxPages`. Found: the outcome is `recovered`. Not found: `indeterminate`, never resent automatically. Only markers by `expectedAuthor` count, since anyone with write access can copy one.
|
|
123
|
+
- `reconcile(operationId)` searches again; `abandon(operationId, reason)` ends the operation by your decision. A retry after a rate limit waits for `retry-after` and searches before its one resend.
|
|
124
|
+
- Updates carry no marker: reconciliation compares the target with the requested change.
|
|
125
|
+
|
|
126
|
+
Nothing here is exactly-once: a write can still be duplicated if it becomes visible only after you abandon it, and an expected-state check reads before it writes, so a change in between is not prevented (an edit within the same second as `updatedAt` is not even detected — pass `bodyDigest`, from `bodyDigest(body)`, to narrow that).
|
|
127
|
+
|
|
128
|
+
**Outcomes.** `verified`: a fresh read shows exactly what was authorized. `accepted`: the resource exists but differs or could not be re-read (`mismatches`, e.g. labels GitHub silently dropped for a caller without push access, or a branch that moved during a pull-request create). `indeterminate`: unknown; reconcile. Refusals throw a `GitHubAdapterError` and mean nothing was written.
|
|
129
|
+
|
|
130
|
+
**Permissions** (fine-grained token or GitHub App installation token; the writer cannot verify a token's permissions and does not try): Issues write for issue writes and issue comments; Pull requests write for reviews, pull requests and comments on pull requests; plus read access to issues, pull requests and contents (branch refs) for the checks.
|
|
80
131
|
|
|
81
132
|
## Errors
|
|
82
133
|
|
|
83
|
-
Every refusal is a `GitHubAdapterError` with a `code`: `invalid-input`, `unapproved-origin`, `not-found`, `unauthorized` (401), `forbidden` (403), `rate-limited` (429, or 403 with `retry-after` / an exhausted rate limit; `detail.retryAfterSeconds` when GitHub said), `http-error`, `timeout`, `network`, `too-large`, `malformed-response`, `incomplete`, `stale`, `wrong-target`, `conflict`.
|
|
134
|
+
Every refusal is a `GitHubAdapterError` with a `code`: `invalid-input`, `unapproved-origin`, `not-found`, `unauthorized` (401), `forbidden` (403), `rate-limited` (429, or 403 with `retry-after` / an exhausted rate limit; `detail.retryAfterSeconds` when GitHub said), `http-error`, `timeout`, `network`, `too-large`, `malformed-response`, `incomplete`, `stale`, `wrong-target`, `conflict`; and from the writer, refused before anything was sent: `capability-denied`, `authorization-denied`, `ledger-failure`.
|
|
84
135
|
|
|
85
136
|
## License
|
|
86
137
|
|
package/dist/errors.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Every refusal the adapter makes, with a stable code. A refusal is never a governance
|
|
3
3
|
* decision: it says GitHub could not supply trustworthy evidence, so the caller stops.
|
|
4
4
|
*/
|
|
5
|
-
export declare const GITHUB_ERROR_CODES: readonly ["invalid-input", "unapproved-origin", "not-found", "unauthorized", "forbidden", "rate-limited", "http-error", "timeout", "network", "too-large", "malformed-response", "incomplete", "stale", "wrong-target", "conflict"];
|
|
5
|
+
export declare const GITHUB_ERROR_CODES: readonly ["invalid-input", "unapproved-origin", "not-found", "unauthorized", "forbidden", "rate-limited", "http-error", "timeout", "network", "too-large", "malformed-response", "incomplete", "stale", "wrong-target", "conflict", "capability-denied", "authorization-denied", "ledger-failure"];
|
|
6
6
|
export type GitHubErrorCode = (typeof GITHUB_ERROR_CODES)[number];
|
|
7
7
|
export interface GitHubErrorDetail {
|
|
8
8
|
/** HTTP status, when GitHub answered. */
|
package/dist/errors.js
CHANGED
|
@@ -18,6 +18,10 @@ export const GITHUB_ERROR_CODES = [
|
|
|
18
18
|
"stale",
|
|
19
19
|
"wrong-target",
|
|
20
20
|
"conflict",
|
|
21
|
+
// The writer refuses with these before anything is sent.
|
|
22
|
+
"capability-denied",
|
|
23
|
+
"authorization-denied",
|
|
24
|
+
"ledger-failure",
|
|
21
25
|
];
|
|
22
26
|
export class GitHubAdapterError extends Error {
|
|
23
27
|
name = "GitHubAdapterError";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { GITHUB_ERROR_CODES, GitHubAdapterError, type GitHubErrorCode, type GitHubErrorDetail, } from "./errors.ts";
|
|
2
2
|
export { type ChangedFile, type CheckEvidence, type CommitComparison, createGitHubEvidence, type EvidenceLimits, type GitHubEvidence, type IssueEvidence, type PatchLimits, type PatchStatus, type PullRequestEvidence, type PullRequestFilesEvidence, type RepositoryRef, type ReviewEvidence, type UntrustedText, type WorkflowRunEvidence, } from "./evidence.ts";
|
|
3
|
+
export { bodyDigest, type DescriptorTarget, type OperationDescriptor, type ReviewEvent, WRITE_CAPABILITIES, type WriteCapability, type WriteKind, type WriteOperation, } from "./operations.ts";
|
|
3
4
|
export { type Reconciliation, readSpecificationIssue, reconcileSpecification, type SpecificationIssueEvidence, } from "./specification.ts";
|
|
4
5
|
export { createFetchTransport, type FetchTransportOptions, type GitHubTransport, } from "./transport.ts";
|
|
6
|
+
export { type AuthorizationDecision, createGitHubWriter, DEFAULT_WRITER_LIMITS, type GitHubWriter, type GitHubWriterOptions, type OperationLedger, type OperationRecord, type OperationState, type ReconciliationReport, type WriteOutcome, type WriterLimits, type WrittenResource, } from "./writer.ts";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { GITHUB_ERROR_CODES, GitHubAdapterError, } from "./errors.js";
|
|
2
2
|
export { createGitHubEvidence, } from "./evidence.js";
|
|
3
|
+
export { bodyDigest, WRITE_CAPABILITIES, } from "./operations.js";
|
|
3
4
|
export { readSpecificationIssue, reconcileSpecification, } from "./specification.js";
|
|
4
5
|
export { createFetchTransport, } from "./transport.js";
|
|
6
|
+
export { createGitHubWriter, DEFAULT_WRITER_LIMITS, } from "./writer.js";
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Write operations as canonical, frozen descriptors. A descriptor is the one object a consumer
|
|
3
|
+
* authorizes: the request the writer sends is derived from it and nothing else, so an
|
|
4
|
+
* authorization of one descriptor can never be spent on other bytes, another target or another
|
|
5
|
+
* capability. This module only validates and canonicalizes; it sends nothing.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Capabilities a writer may be constructed with. Each names exactly one kind of write; nothing
|
|
9
|
+
* is implied by a broader one, and none is inferred from what a token happens to permit.
|
|
10
|
+
*/
|
|
11
|
+
export declare const WRITE_CAPABILITIES: readonly ["issues:create", "issues:comment", "issues:update", "issues:comment:update", "pulls:create", "pulls:review", "pulls:review:approve", "pulls:review:request-changes"];
|
|
12
|
+
export type WriteCapability = (typeof WRITE_CAPABILITIES)[number];
|
|
13
|
+
export type ReviewEvent = "COMMENT" | "APPROVE" | "REQUEST_CHANGES";
|
|
14
|
+
export type WriteOperation = {
|
|
15
|
+
kind: "issue.create";
|
|
16
|
+
operationId: string;
|
|
17
|
+
title: string;
|
|
18
|
+
body: string;
|
|
19
|
+
labels?: readonly string[];
|
|
20
|
+
assignees?: readonly string[];
|
|
21
|
+
} | {
|
|
22
|
+
kind: "issue.comment";
|
|
23
|
+
operationId: string;
|
|
24
|
+
issueNumber: number;
|
|
25
|
+
body: string;
|
|
26
|
+
/** The thread the number must be. Defaults to `issue`; a mismatch is `wrong-target`. */
|
|
27
|
+
thread?: "issue" | "pull-request";
|
|
28
|
+
/** Defaults to false: a closed thread is refused. */
|
|
29
|
+
allowClosed?: boolean;
|
|
30
|
+
/** Defaults to false: a locked thread is refused. */
|
|
31
|
+
allowLocked?: boolean;
|
|
32
|
+
} | {
|
|
33
|
+
kind: "pull.review";
|
|
34
|
+
operationId: string;
|
|
35
|
+
pullNumber: number;
|
|
36
|
+
/** The head the review is of; sent as `commit_id`, and the pull request must still be at it. */
|
|
37
|
+
expectedHeadSha: string;
|
|
38
|
+
event: ReviewEvent;
|
|
39
|
+
body: string;
|
|
40
|
+
} | {
|
|
41
|
+
kind: "pull.create";
|
|
42
|
+
operationId: string;
|
|
43
|
+
title: string;
|
|
44
|
+
body: string;
|
|
45
|
+
/** A branch of this repository (cross-repository heads are not supported). */
|
|
46
|
+
head: string;
|
|
47
|
+
base: string;
|
|
48
|
+
/** The commit `head` must point at, checked before and after the create. */
|
|
49
|
+
expectedHeadSha: string;
|
|
50
|
+
/** When given, the commit `base` must point at before the create. */
|
|
51
|
+
expectedBaseSha?: string;
|
|
52
|
+
draft?: boolean;
|
|
53
|
+
} | {
|
|
54
|
+
kind: "issue.update";
|
|
55
|
+
operationId: string;
|
|
56
|
+
issueNumber: number;
|
|
57
|
+
/** The issue as the caller last read it; any difference before the write is `stale`. */
|
|
58
|
+
expected: {
|
|
59
|
+
updatedAt: string;
|
|
60
|
+
bodyDigest?: string;
|
|
61
|
+
state?: "open" | "closed";
|
|
62
|
+
};
|
|
63
|
+
changes: {
|
|
64
|
+
title?: string;
|
|
65
|
+
body?: string;
|
|
66
|
+
state?: "open" | "closed";
|
|
67
|
+
stateReason?: "completed" | "not_planned" | "reopened";
|
|
68
|
+
labels?: readonly string[];
|
|
69
|
+
};
|
|
70
|
+
} | {
|
|
71
|
+
kind: "comment.update";
|
|
72
|
+
operationId: string;
|
|
73
|
+
commentId: number;
|
|
74
|
+
/** The comment as the caller last read it; any difference before the write is `stale`. */
|
|
75
|
+
expected: {
|
|
76
|
+
issueNumber: number;
|
|
77
|
+
updatedAt: string;
|
|
78
|
+
bodyDigest?: string;
|
|
79
|
+
author?: string;
|
|
80
|
+
};
|
|
81
|
+
body: string;
|
|
82
|
+
};
|
|
83
|
+
export type WriteKind = WriteOperation["kind"];
|
|
84
|
+
/** The capability an operation needs. A review's event chooses among three. */
|
|
85
|
+
export declare function capabilityOf(op: Pick<WriteOperation, "kind"> & {
|
|
86
|
+
event?: ReviewEvent;
|
|
87
|
+
}): WriteCapability;
|
|
88
|
+
export type DescriptorTarget = {
|
|
89
|
+
type: "repository";
|
|
90
|
+
} | {
|
|
91
|
+
type: "issue";
|
|
92
|
+
number: number;
|
|
93
|
+
} | {
|
|
94
|
+
type: "pull";
|
|
95
|
+
number: number;
|
|
96
|
+
} | {
|
|
97
|
+
type: "comment";
|
|
98
|
+
id: number;
|
|
99
|
+
} | {
|
|
100
|
+
type: "branch";
|
|
101
|
+
head: string;
|
|
102
|
+
base: string;
|
|
103
|
+
};
|
|
104
|
+
/** What the consumer authorizes. Deeply frozen; `digest` covers every other field. */
|
|
105
|
+
export interface OperationDescriptor {
|
|
106
|
+
readonly schema: "comforge-github-write/v1";
|
|
107
|
+
readonly operationId: string;
|
|
108
|
+
readonly kind: WriteKind;
|
|
109
|
+
readonly capability: WriteCapability;
|
|
110
|
+
readonly repository: string;
|
|
111
|
+
readonly target: Readonly<DescriptorTarget>;
|
|
112
|
+
/** The exact JSON body the writer sends, before its correlation marker is appended. */
|
|
113
|
+
readonly payload: Readonly<Record<string, unknown>>;
|
|
114
|
+
/** What must hold on GitHub immediately before the write. */
|
|
115
|
+
readonly precondition: Readonly<Record<string, unknown>>;
|
|
116
|
+
/** `sha256:` of the canonical JSON of every field above. */
|
|
117
|
+
readonly digest: string;
|
|
118
|
+
}
|
|
119
|
+
/** GitHub's documented body limit for issues, comments, reviews and pull requests. */
|
|
120
|
+
export declare const MAX_BODY_CHARS = 65536;
|
|
121
|
+
export declare const MAX_TITLE_CHARS = 256;
|
|
122
|
+
/** Reserved for the writer's own correlation marker; refused in caller text. */
|
|
123
|
+
export declare const MARKER_PREFIX = "<!-- comforge-op ";
|
|
124
|
+
/** A branch name git and GitHub both accept, kept to a conservative subset. */
|
|
125
|
+
export declare function branch(value: unknown, what: string): string;
|
|
126
|
+
/** JSON with object keys sorted at every depth: the digest input. */
|
|
127
|
+
export declare function canonicalJson(value: unknown): string;
|
|
128
|
+
/** `sha256:<hex>` of a string's UTF-8 bytes, through Web Crypto (Node ≥ 22 and Bun). */
|
|
129
|
+
export declare function sha256(input: string): Promise<string>;
|
|
130
|
+
/** The digest a caller passes as `expected.bodyDigest`: of the body exactly as GitHub returned it. */
|
|
131
|
+
export declare const bodyDigest: (body: string | null | undefined) => Promise<string>;
|
|
132
|
+
/**
|
|
133
|
+
* Validates an operation and returns its descriptor. Only the named fields are read, each is
|
|
134
|
+
* copied, and the result is frozen: mutating the caller's object afterwards changes nothing.
|
|
135
|
+
*/
|
|
136
|
+
export declare function describe(repository: string, input: WriteOperation): Promise<OperationDescriptor>;
|
|
137
|
+
/**
|
|
138
|
+
* The correlation marker appended to a created body: digests only, never the raw operation id.
|
|
139
|
+
* Anyone who can write to the repository can copy it, so a match is evidence that needs the
|
|
140
|
+
* author check (`expectedAuthor`), not proof.
|
|
141
|
+
*/
|
|
142
|
+
export declare function correlationMarker(namespace: string, descriptor: OperationDescriptor): Promise<string>;
|
|
143
|
+
/** True when `body` carries exactly this operation's marker (same operation, same fingerprint). */
|
|
144
|
+
export declare function carriesMarker(body: string | null | undefined, marker: string): boolean;
|
|
145
|
+
/** The body sent for a create: the authorized body, a blank line, and the marker. */
|
|
146
|
+
export declare function markedBody(body: string, marker: string | null): string;
|
|
147
|
+
export declare const isSha: (value: unknown) => value is string;
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { GitHubAdapterError } from "./errors.js";
|
|
2
|
+
/**
|
|
3
|
+
* Write operations as canonical, frozen descriptors. A descriptor is the one object a consumer
|
|
4
|
+
* authorizes: the request the writer sends is derived from it and nothing else, so an
|
|
5
|
+
* authorization of one descriptor can never be spent on other bytes, another target or another
|
|
6
|
+
* capability. This module only validates and canonicalizes; it sends nothing.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Capabilities a writer may be constructed with. Each names exactly one kind of write; nothing
|
|
10
|
+
* is implied by a broader one, and none is inferred from what a token happens to permit.
|
|
11
|
+
*/
|
|
12
|
+
export const WRITE_CAPABILITIES = [
|
|
13
|
+
"issues:create",
|
|
14
|
+
"issues:comment",
|
|
15
|
+
"issues:update",
|
|
16
|
+
"issues:comment:update",
|
|
17
|
+
"pulls:create",
|
|
18
|
+
"pulls:review",
|
|
19
|
+
"pulls:review:approve",
|
|
20
|
+
"pulls:review:request-changes",
|
|
21
|
+
];
|
|
22
|
+
/** The capability an operation needs. A review's event chooses among three. */
|
|
23
|
+
export function capabilityOf(op) {
|
|
24
|
+
switch (op.kind) {
|
|
25
|
+
case "issue.create":
|
|
26
|
+
return "issues:create";
|
|
27
|
+
case "issue.comment":
|
|
28
|
+
return "issues:comment";
|
|
29
|
+
case "issue.update":
|
|
30
|
+
return "issues:update";
|
|
31
|
+
case "comment.update":
|
|
32
|
+
return "issues:comment:update";
|
|
33
|
+
case "pull.create":
|
|
34
|
+
return "pulls:create";
|
|
35
|
+
case "pull.review":
|
|
36
|
+
return op.event === "APPROVE"
|
|
37
|
+
? "pulls:review:approve"
|
|
38
|
+
: op.event === "REQUEST_CHANGES"
|
|
39
|
+
? "pulls:review:request-changes"
|
|
40
|
+
: "pulls:review";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** GitHub's documented body limit for issues, comments, reviews and pull requests. */
|
|
44
|
+
export const MAX_BODY_CHARS = 65_536;
|
|
45
|
+
export const MAX_TITLE_CHARS = 256;
|
|
46
|
+
const MAX_LABELS = 20;
|
|
47
|
+
const MAX_ASSIGNEES = 10;
|
|
48
|
+
const SHA = /^[0-9a-f]{40}$/;
|
|
49
|
+
const LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})(?:\[bot\])?$/;
|
|
50
|
+
const OPERATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$/;
|
|
51
|
+
const DIGEST = /^sha256:[0-9a-f]{64}$/;
|
|
52
|
+
const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
|
|
53
|
+
/** Control characters other than tab and line feed: binary or terminal-escape content. */
|
|
54
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: the point is to find them
|
|
55
|
+
const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f]/;
|
|
56
|
+
/** Reserved for the writer's own correlation marker; refused in caller text. */
|
|
57
|
+
export const MARKER_PREFIX = "<!-- comforge-op ";
|
|
58
|
+
function invalid(message) {
|
|
59
|
+
return new GitHubAdapterError("invalid-input", message);
|
|
60
|
+
}
|
|
61
|
+
function text(value, what, max, options = {}) {
|
|
62
|
+
if (typeof value !== "string")
|
|
63
|
+
throw invalid(`${what} must be a string`);
|
|
64
|
+
// The bytes authorized are the bytes sent: line endings are canonicalized before the digest.
|
|
65
|
+
const canonical = value.replace(/\r\n?/g, "\n");
|
|
66
|
+
if (CONTROL.test(canonical))
|
|
67
|
+
throw invalid(`${what} contains control characters`);
|
|
68
|
+
if (!options.allowEmpty && canonical.trim().length === 0)
|
|
69
|
+
throw invalid(`${what} must not be empty`);
|
|
70
|
+
if (canonical.length > max)
|
|
71
|
+
throw invalid(`${what} exceeds ${max} characters`);
|
|
72
|
+
if (canonical.includes(MARKER_PREFIX))
|
|
73
|
+
throw invalid(`${what} contains the reserved marker prefix`);
|
|
74
|
+
return canonical;
|
|
75
|
+
}
|
|
76
|
+
function positive(value, what) {
|
|
77
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
|
|
78
|
+
throw invalid(`Invalid ${what}`);
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
function sha(value, what) {
|
|
82
|
+
if (typeof value !== "string" || !SHA.test(value))
|
|
83
|
+
throw invalid(`${what} must be a full 40-character lowercase SHA`);
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
function timestamp(value, what) {
|
|
87
|
+
if (typeof value !== "string" || !TIMESTAMP.test(value))
|
|
88
|
+
throw invalid(`${what} must be an ISO-8601 UTC timestamp`);
|
|
89
|
+
return value;
|
|
90
|
+
}
|
|
91
|
+
function optionalDigest(value, what) {
|
|
92
|
+
if (value === undefined)
|
|
93
|
+
return undefined;
|
|
94
|
+
if (typeof value !== "string" || !DIGEST.test(value))
|
|
95
|
+
throw invalid(`${what} must be sha256:<64 hex>`);
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
function list(value, what, max, item) {
|
|
99
|
+
if (value === undefined)
|
|
100
|
+
return undefined;
|
|
101
|
+
if (!Array.isArray(value) || value.length > max)
|
|
102
|
+
throw invalid(`${what} must be a list of at most ${max}`);
|
|
103
|
+
const items = value.map(item);
|
|
104
|
+
if (new Set(items).size !== items.length)
|
|
105
|
+
throw invalid(`${what} has duplicates`);
|
|
106
|
+
return items;
|
|
107
|
+
}
|
|
108
|
+
const label = (v) => {
|
|
109
|
+
const name = text(v, "A label", 50);
|
|
110
|
+
if (name.includes("\n") || name.includes(","))
|
|
111
|
+
throw invalid("A label must be one line without commas");
|
|
112
|
+
return name;
|
|
113
|
+
};
|
|
114
|
+
const login = (v) => {
|
|
115
|
+
if (typeof v !== "string" || !LOGIN.test(v))
|
|
116
|
+
throw invalid("Invalid GitHub login");
|
|
117
|
+
return v;
|
|
118
|
+
};
|
|
119
|
+
/** A branch name git and GitHub both accept, kept to a conservative subset. */
|
|
120
|
+
export function branch(value, what) {
|
|
121
|
+
if (typeof value !== "string" ||
|
|
122
|
+
!/^[A-Za-z0-9._/-]{1,200}$/.test(value) ||
|
|
123
|
+
/^[-./]|\/$|\/\/|\.\.|\.lock(\/|$)|\/\.|^\.|@\{/.test(value))
|
|
124
|
+
throw invalid(`${what} is not a supported branch name`);
|
|
125
|
+
return value;
|
|
126
|
+
}
|
|
127
|
+
function bool(value, what) {
|
|
128
|
+
if (value === undefined)
|
|
129
|
+
return undefined;
|
|
130
|
+
if (typeof value !== "boolean")
|
|
131
|
+
throw invalid(`${what} must be a boolean`);
|
|
132
|
+
return value;
|
|
133
|
+
}
|
|
134
|
+
function oneOf(value, allowed, what) {
|
|
135
|
+
if (value === undefined)
|
|
136
|
+
return undefined;
|
|
137
|
+
if (typeof value !== "string" || !allowed.includes(value))
|
|
138
|
+
throw invalid(`Invalid ${what}`);
|
|
139
|
+
return value;
|
|
140
|
+
}
|
|
141
|
+
/** Object with `undefined` fields removed: absent and undefined must digest identically. */
|
|
142
|
+
function defined(record) {
|
|
143
|
+
return Object.fromEntries(Object.entries(record).filter(([, v]) => v !== undefined));
|
|
144
|
+
}
|
|
145
|
+
/** JSON with object keys sorted at every depth: the digest input. */
|
|
146
|
+
export function canonicalJson(value) {
|
|
147
|
+
if (value === null || typeof value !== "object")
|
|
148
|
+
return JSON.stringify(value);
|
|
149
|
+
if (Array.isArray(value))
|
|
150
|
+
return `[${value.map(canonicalJson).join(",")}]`;
|
|
151
|
+
const entries = Object.entries(value)
|
|
152
|
+
.filter(([, v]) => v !== undefined)
|
|
153
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
154
|
+
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
|
|
155
|
+
}
|
|
156
|
+
/** `sha256:<hex>` of a string's UTF-8 bytes, through Web Crypto (Node ≥ 22 and Bun). */
|
|
157
|
+
export async function sha256(input) {
|
|
158
|
+
const bytes = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
|
|
159
|
+
return `sha256:${[...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
160
|
+
}
|
|
161
|
+
/** The digest a caller passes as `expected.bodyDigest`: of the body exactly as GitHub returned it. */
|
|
162
|
+
export const bodyDigest = (body) => sha256(body ?? "");
|
|
163
|
+
function deepFreeze(value) {
|
|
164
|
+
if (value && typeof value === "object") {
|
|
165
|
+
for (const inner of Object.values(value))
|
|
166
|
+
deepFreeze(inner);
|
|
167
|
+
Object.freeze(value);
|
|
168
|
+
}
|
|
169
|
+
return value;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Validates an operation and returns its descriptor. Only the named fields are read, each is
|
|
173
|
+
* copied, and the result is frozen: mutating the caller's object afterwards changes nothing.
|
|
174
|
+
*/
|
|
175
|
+
export async function describe(repository, input) {
|
|
176
|
+
if (!input || typeof input !== "object")
|
|
177
|
+
throw invalid("An operation is required");
|
|
178
|
+
const operationId = input.operationId;
|
|
179
|
+
if (typeof operationId !== "string" || !OPERATION_ID.test(operationId))
|
|
180
|
+
throw invalid("operationId must be 8–128 characters of [A-Za-z0-9._:-]");
|
|
181
|
+
let target;
|
|
182
|
+
let payload;
|
|
183
|
+
let precondition = {};
|
|
184
|
+
let capability;
|
|
185
|
+
const kind = input.kind;
|
|
186
|
+
switch (kind) {
|
|
187
|
+
case "issue.create": {
|
|
188
|
+
target = { type: "repository" };
|
|
189
|
+
payload = defined({
|
|
190
|
+
title: text(input.title, "title", MAX_TITLE_CHARS),
|
|
191
|
+
body: text(input.body, "body", MAX_BODY_CHARS),
|
|
192
|
+
labels: list(input.labels, "labels", MAX_LABELS, label),
|
|
193
|
+
assignees: list(input.assignees, "assignees", MAX_ASSIGNEES, login),
|
|
194
|
+
});
|
|
195
|
+
capability = capabilityOf({ kind });
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
case "issue.comment": {
|
|
199
|
+
const number = positive(input.issueNumber, "issue number");
|
|
200
|
+
target = { type: "issue", number };
|
|
201
|
+
payload = { body: text(input.body, "body", MAX_BODY_CHARS) };
|
|
202
|
+
precondition = {
|
|
203
|
+
thread: oneOf(input.thread, ["issue", "pull-request"], "thread") ?? "issue",
|
|
204
|
+
allowClosed: bool(input.allowClosed, "allowClosed") ?? false,
|
|
205
|
+
allowLocked: bool(input.allowLocked, "allowLocked") ?? false,
|
|
206
|
+
};
|
|
207
|
+
capability = capabilityOf({ kind });
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
case "pull.review": {
|
|
211
|
+
const number = positive(input.pullNumber, "pull request number");
|
|
212
|
+
const event = oneOf(input.event, ["COMMENT", "APPROVE", "REQUEST_CHANGES"], "review event");
|
|
213
|
+
if (!event)
|
|
214
|
+
throw invalid("A review event is required; a pending review is not supported");
|
|
215
|
+
const head = sha(input.expectedHeadSha, "expectedHeadSha");
|
|
216
|
+
target = { type: "pull", number };
|
|
217
|
+
payload = {
|
|
218
|
+
commit_id: head,
|
|
219
|
+
event,
|
|
220
|
+
// GitHub requires a body for COMMENT and REQUEST_CHANGES; APPROVE may be empty.
|
|
221
|
+
body: text(input.body, "body", MAX_BODY_CHARS, { allowEmpty: event === "APPROVE" }),
|
|
222
|
+
};
|
|
223
|
+
precondition = { headSha: head, open: true };
|
|
224
|
+
capability = capabilityOf({ kind, event });
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
case "pull.create": {
|
|
228
|
+
const head = branch(input.head, "head");
|
|
229
|
+
const base = branch(input.base, "base");
|
|
230
|
+
if (head === base)
|
|
231
|
+
throw invalid("head and base must differ");
|
|
232
|
+
target = { type: "branch", head, base };
|
|
233
|
+
payload = defined({
|
|
234
|
+
title: text(input.title, "title", MAX_TITLE_CHARS),
|
|
235
|
+
body: text(input.body, "body", MAX_BODY_CHARS),
|
|
236
|
+
head,
|
|
237
|
+
base,
|
|
238
|
+
draft: bool(input.draft, "draft"),
|
|
239
|
+
// Never let a head-branch owner's maintainers push into the PR implicitly.
|
|
240
|
+
maintainer_can_modify: false,
|
|
241
|
+
});
|
|
242
|
+
precondition = defined({
|
|
243
|
+
headSha: sha(input.expectedHeadSha, "expectedHeadSha"),
|
|
244
|
+
baseSha: input.expectedBaseSha === undefined
|
|
245
|
+
? undefined
|
|
246
|
+
: sha(input.expectedBaseSha, "expectedBaseSha"),
|
|
247
|
+
});
|
|
248
|
+
capability = capabilityOf({ kind });
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
case "issue.update": {
|
|
252
|
+
const number = positive(input.issueNumber, "issue number");
|
|
253
|
+
const changes = input.changes ?? {};
|
|
254
|
+
const expected = input.expected ?? {};
|
|
255
|
+
target = { type: "issue", number };
|
|
256
|
+
payload = defined({
|
|
257
|
+
title: changes.title === undefined ? undefined : text(changes.title, "title", MAX_TITLE_CHARS),
|
|
258
|
+
body: changes.body === undefined
|
|
259
|
+
? undefined
|
|
260
|
+
: text(changes.body, "body", MAX_BODY_CHARS, { allowEmpty: true }),
|
|
261
|
+
state: oneOf(changes.state, ["open", "closed"], "state"),
|
|
262
|
+
state_reason: oneOf(changes.stateReason, ["completed", "not_planned", "reopened"], "stateReason"),
|
|
263
|
+
labels: list(changes.labels, "labels", MAX_LABELS, label),
|
|
264
|
+
});
|
|
265
|
+
if (Object.keys(payload).length === 0)
|
|
266
|
+
throw invalid("An update needs at least one change");
|
|
267
|
+
if (payload.state_reason !== undefined && payload.state === undefined)
|
|
268
|
+
throw invalid("stateReason needs state");
|
|
269
|
+
precondition = defined({
|
|
270
|
+
updatedAt: timestamp(expected.updatedAt, "expected.updatedAt"),
|
|
271
|
+
bodyDigest: optionalDigest(expected.bodyDigest, "expected.bodyDigest"),
|
|
272
|
+
state: oneOf(expected.state, ["open", "closed"], "expected.state"),
|
|
273
|
+
});
|
|
274
|
+
capability = capabilityOf({ kind });
|
|
275
|
+
break;
|
|
276
|
+
}
|
|
277
|
+
case "comment.update": {
|
|
278
|
+
const id = positive(input.commentId, "comment id");
|
|
279
|
+
const expected = input.expected ?? {};
|
|
280
|
+
target = { type: "comment", id };
|
|
281
|
+
payload = { body: text(input.body, "body", MAX_BODY_CHARS) };
|
|
282
|
+
precondition = defined({
|
|
283
|
+
issueNumber: positive(expected.issueNumber, "expected.issueNumber"),
|
|
284
|
+
updatedAt: timestamp(expected.updatedAt, "expected.updatedAt"),
|
|
285
|
+
bodyDigest: optionalDigest(expected.bodyDigest, "expected.bodyDigest"),
|
|
286
|
+
author: expected.author === undefined ? undefined : login(expected.author),
|
|
287
|
+
});
|
|
288
|
+
capability = capabilityOf({ kind });
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
default:
|
|
292
|
+
throw invalid("Unknown write operation kind");
|
|
293
|
+
}
|
|
294
|
+
const unsigned = {
|
|
295
|
+
schema: "comforge-github-write/v1",
|
|
296
|
+
operationId,
|
|
297
|
+
kind,
|
|
298
|
+
capability,
|
|
299
|
+
repository,
|
|
300
|
+
target,
|
|
301
|
+
payload,
|
|
302
|
+
precondition,
|
|
303
|
+
};
|
|
304
|
+
return deepFreeze({ ...unsigned, digest: await sha256(canonicalJson(unsigned)) });
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* The correlation marker appended to a created body: digests only, never the raw operation id.
|
|
308
|
+
* Anyone who can write to the repository can copy it, so a match is evidence that needs the
|
|
309
|
+
* author check (`expectedAuthor`), not proof.
|
|
310
|
+
*/
|
|
311
|
+
export async function correlationMarker(namespace, descriptor) {
|
|
312
|
+
const op = (await sha256(`${descriptor.repository}\n${descriptor.operationId}`)).slice(7, 39);
|
|
313
|
+
return `${MARKER_PREFIX}v1 ns=${namespace} op=${op} fp=${descriptor.digest.slice(7, 39)} -->`;
|
|
314
|
+
}
|
|
315
|
+
/** True when `body` carries exactly this operation's marker (same operation, same fingerprint). */
|
|
316
|
+
export function carriesMarker(body, marker) {
|
|
317
|
+
return typeof body === "string" && body.endsWith(marker);
|
|
318
|
+
}
|
|
319
|
+
/** The body sent for a create: the authorized body, a blank line, and the marker. */
|
|
320
|
+
export function markedBody(body, marker) {
|
|
321
|
+
if (marker === null)
|
|
322
|
+
return body;
|
|
323
|
+
const joined = body.length === 0 ? marker : `${body}\n\n${marker}`;
|
|
324
|
+
if (joined.length > MAX_BODY_CHARS)
|
|
325
|
+
throw invalid(`body exceeds ${MAX_BODY_CHARS} characters with the correlation marker`);
|
|
326
|
+
return joined;
|
|
327
|
+
}
|
|
328
|
+
export const isSha = (value) => typeof value === "string" && SHA.test(value);
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { GitHubAdapterError } from "./errors.ts";
|
|
2
|
+
/**
|
|
3
|
+
* The package's only non-GET request, used by the writer alone and not exported from the
|
|
4
|
+
* package. Trust boundary:
|
|
5
|
+
* - the method comes from a fixed table keyed by operation kind, never from a caller;
|
|
6
|
+
* - the path is built by the writer from fixed templates under the bound repository and checked
|
|
7
|
+
* here again; the origin is fixed and redirects fail;
|
|
8
|
+
* - the token is attached here and never appears in a result, error or ledger record;
|
|
9
|
+
* - nothing retries. A request that may have reached GitHub and has no definite answer is
|
|
10
|
+
* `sent-unknown`, never a refusal: the caller must not treat it as "nothing happened".
|
|
11
|
+
*/
|
|
12
|
+
export declare const WRITE_METHODS: {
|
|
13
|
+
readonly "issue.create": "POST";
|
|
14
|
+
readonly "issue.comment": "POST";
|
|
15
|
+
readonly "pull.review": "POST";
|
|
16
|
+
readonly "pull.create": "POST";
|
|
17
|
+
readonly "issue.update": "PATCH";
|
|
18
|
+
readonly "comment.update": "PATCH";
|
|
19
|
+
};
|
|
20
|
+
export type WriteMethodKind = keyof typeof WRITE_METHODS;
|
|
21
|
+
export interface SendOptions {
|
|
22
|
+
origin: string;
|
|
23
|
+
base: string;
|
|
24
|
+
token: () => Promise<string>;
|
|
25
|
+
fetchImpl: typeof fetch;
|
|
26
|
+
timeoutMs: number;
|
|
27
|
+
maxBodyBytes: number;
|
|
28
|
+
userAgent?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* - `answered`: a 2xx whose JSON body was read.
|
|
32
|
+
* - `refused`: a definite non-2xx answer from GitHub (4xx), with its typed error.
|
|
33
|
+
* - `sent-unknown`: the request may have been applied: no answer, a 5xx, a 408, or a 2xx whose
|
|
34
|
+
* body could not be read or parsed (`accepted` says GitHub did answer 2xx).
|
|
35
|
+
*/
|
|
36
|
+
export type SendResult = {
|
|
37
|
+
kind: "answered";
|
|
38
|
+
status: number;
|
|
39
|
+
body: unknown;
|
|
40
|
+
} | {
|
|
41
|
+
kind: "refused";
|
|
42
|
+
error: GitHubAdapterError;
|
|
43
|
+
} | {
|
|
44
|
+
kind: "sent-unknown";
|
|
45
|
+
reason: string;
|
|
46
|
+
status?: number;
|
|
47
|
+
accepted: boolean;
|
|
48
|
+
};
|
|
49
|
+
export declare function sendWrite(options: SendOptions, kind: WriteMethodKind, path: string, payload: Record<string, unknown>): Promise<SendResult>;
|