@comforge/github 0.1.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/evidence.d.ts +56 -2
- package/dist/evidence.js +109 -9
- package/dist/index.d.ts +3 -1
- 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/transport.js +7 -1
- package/dist/writer.d.ts +183 -0
- package/dist/writer.js +877 -0
- package/llms.txt +5 -3
- package/package.json +2 -2
|
@@ -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>;
|
package/dist/request.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { GitHubAdapterError } from "./errors.js";
|
|
2
|
+
import { API_VERSION, classifyStatus } from "./transport.js";
|
|
3
|
+
/**
|
|
4
|
+
* The package's only non-GET request, used by the writer alone and not exported from the
|
|
5
|
+
* package. Trust boundary:
|
|
6
|
+
* - the method comes from a fixed table keyed by operation kind, never from a caller;
|
|
7
|
+
* - the path is built by the writer from fixed templates under the bound repository and checked
|
|
8
|
+
* here again; the origin is fixed and redirects fail;
|
|
9
|
+
* - the token is attached here and never appears in a result, error or ledger record;
|
|
10
|
+
* - nothing retries. A request that may have reached GitHub and has no definite answer is
|
|
11
|
+
* `sent-unknown`, never a refusal: the caller must not treat it as "nothing happened".
|
|
12
|
+
*/
|
|
13
|
+
export const WRITE_METHODS = {
|
|
14
|
+
"issue.create": "POST",
|
|
15
|
+
"issue.comment": "POST",
|
|
16
|
+
"pull.review": "POST",
|
|
17
|
+
"pull.create": "POST",
|
|
18
|
+
"issue.update": "PATCH",
|
|
19
|
+
"comment.update": "PATCH",
|
|
20
|
+
};
|
|
21
|
+
const PATH = /^\/repos\/[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+\/(issues|pulls)(\/[0-9]+)?(\/(comments|reviews))?$|^\/repos\/[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+\/issues\/comments\/[0-9]+$/;
|
|
22
|
+
export async function sendWrite(options, kind, path, payload) {
|
|
23
|
+
const method = WRITE_METHODS[kind];
|
|
24
|
+
if (!PATH.test(path))
|
|
25
|
+
throw new GitHubAdapterError("invalid-input", "The write path is not a supported API path");
|
|
26
|
+
const url = new URL(`${options.base}${path}`);
|
|
27
|
+
if (url.origin !== options.origin)
|
|
28
|
+
throw new GitHubAdapterError("unapproved-origin", "Unapproved outbound host");
|
|
29
|
+
// Resolved before sending: a failing token provider is a refusal, never an uncertain write.
|
|
30
|
+
let token;
|
|
31
|
+
try {
|
|
32
|
+
token = await options.token();
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw new GitHubAdapterError("unauthorized", "The token provider failed; nothing was sent");
|
|
36
|
+
}
|
|
37
|
+
if (typeof token !== "string" || token.length === 0)
|
|
38
|
+
throw new GitHubAdapterError("unauthorized", "The token provider returned no token; nothing was sent");
|
|
39
|
+
let res;
|
|
40
|
+
try {
|
|
41
|
+
res = await options.fetchImpl(url, {
|
|
42
|
+
method,
|
|
43
|
+
redirect: "error",
|
|
44
|
+
signal: AbortSignal.timeout(options.timeoutMs),
|
|
45
|
+
headers: {
|
|
46
|
+
Accept: "application/vnd.github+json",
|
|
47
|
+
"Content-Type": "application/json",
|
|
48
|
+
"X-GitHub-Api-Version": API_VERSION,
|
|
49
|
+
Authorization: `Bearer ${token}`,
|
|
50
|
+
...(options.userAgent ? { "User-Agent": options.userAgent } : {}),
|
|
51
|
+
},
|
|
52
|
+
body: JSON.stringify(payload),
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return { kind: "sent-unknown", reason: "no answer (network or timeout)", accepted: false };
|
|
57
|
+
}
|
|
58
|
+
if (!res.ok) {
|
|
59
|
+
// A gateway error or timeout from GitHub's edge says nothing about whether the write applied.
|
|
60
|
+
if (res.status >= 500 || res.status === 408)
|
|
61
|
+
return {
|
|
62
|
+
kind: "sent-unknown",
|
|
63
|
+
reason: `HTTP ${res.status}`,
|
|
64
|
+
status: res.status,
|
|
65
|
+
accepted: false,
|
|
66
|
+
};
|
|
67
|
+
return { kind: "refused", error: classifyStatus(res.status, res.headers) };
|
|
68
|
+
}
|
|
69
|
+
const status = res.status;
|
|
70
|
+
const declared = Number(res.headers.get("content-length") ?? "0");
|
|
71
|
+
if (Number.isFinite(declared) && declared > options.maxBodyBytes)
|
|
72
|
+
return { kind: "sent-unknown", reason: "response too large", status, accepted: true };
|
|
73
|
+
let text;
|
|
74
|
+
try {
|
|
75
|
+
text = await res.text();
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return { kind: "sent-unknown", reason: "response body unreadable", status, accepted: true };
|
|
79
|
+
}
|
|
80
|
+
if (text.length > options.maxBodyBytes)
|
|
81
|
+
return { kind: "sent-unknown", reason: "response too large", status, accepted: true };
|
|
82
|
+
try {
|
|
83
|
+
return { kind: "answered", status, body: JSON.parse(text) };
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return { kind: "sent-unknown", reason: "response not JSON", status, accepted: true };
|
|
87
|
+
}
|
|
88
|
+
}
|
package/dist/transport.js
CHANGED
|
@@ -36,6 +36,12 @@ export function classifyStatus(status, headers) {
|
|
|
36
36
|
return new GitHubAdapterError("http-error", `GitHub returned HTTP ${status}`, { status });
|
|
37
37
|
}
|
|
38
38
|
const PATH = /^\/[A-Za-z0-9._~%/-]*$/;
|
|
39
|
+
/**
|
|
40
|
+
* GitHub's commit-comparison range (`compare/BASE...HEAD`) is the only API path with dots in a
|
|
41
|
+
* row. It is accepted only as the last segment and only between two full commit SHAs, so it can
|
|
42
|
+
* never spell a parent-directory step; every other `..` is refused.
|
|
43
|
+
*/
|
|
44
|
+
const COMPARE_RANGE = /\/compare\/[0-9a-f]{40}\.\.\.[0-9a-f]{40}$/;
|
|
39
45
|
/** A request that never completed: a timeout, or the network. */
|
|
40
46
|
function unreachable(error, message, status) {
|
|
41
47
|
const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
@@ -52,7 +58,7 @@ export function createFetchTransport(options) {
|
|
|
52
58
|
async get(path, query) {
|
|
53
59
|
if (typeof path !== "string" ||
|
|
54
60
|
!PATH.test(path) ||
|
|
55
|
-
path.includes("..") ||
|
|
61
|
+
path.replace(COMPARE_RANGE, "/compare/range").includes("..") ||
|
|
56
62
|
path.includes("//"))
|
|
57
63
|
throw new GitHubAdapterError("invalid-input", "The request path is not an API path");
|
|
58
64
|
const url = new URL(`${base}${path}`);
|
package/dist/writer.d.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { type GitHubErrorCode } from "./errors.ts";
|
|
2
|
+
import { type OperationDescriptor, type WriteCapability, type WriteKind, type WriteOperation } from "./operations.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Caller-authorized GitHub writes. Opt-in and separate from every read
|
|
5
|
+
* API: `createFetchTransport` and `createGitHubEvidence` stay GET-only, and nothing they return
|
|
6
|
+
* can reach this module.
|
|
7
|
+
*
|
|
8
|
+
* Authority stays with the consumer. The writer validates and binds; it decides nothing:
|
|
9
|
+
* - `authorize` is the consumer's policy, called with the frozen descriptor of exactly what will
|
|
10
|
+
* be sent. Its `allow` is a policy decision, never evidence that a human approved anything;
|
|
11
|
+
* - the token is the consumer's, and whatever it permits on GitHub, the writer performs only the
|
|
12
|
+
* capabilities it was constructed with;
|
|
13
|
+
* - the operation ledger is the consumer's durable storage. The writer's guarantees across
|
|
14
|
+
* processes are exactly those of the ledger's atomic `create` and `replace`.
|
|
15
|
+
*
|
|
16
|
+
* GitHub has no idempotency keys and no compare-and-swap for these endpoints, so nothing here is
|
|
17
|
+
* exactly-once. A write that may have reached GitHub without a definite answer is reported
|
|
18
|
+
* `indeterminate`, recorded, and never resent automatically; `reconcile` looks for it.
|
|
19
|
+
*/
|
|
20
|
+
export type OperationState = "reserved" | "sending" | "succeeded" | "failed" | "indeterminate" | "abandoned";
|
|
21
|
+
export type WrittenResource = {
|
|
22
|
+
type: "issue";
|
|
23
|
+
number: number;
|
|
24
|
+
url: string;
|
|
25
|
+
} | {
|
|
26
|
+
type: "comment";
|
|
27
|
+
id: number;
|
|
28
|
+
issueNumber: number;
|
|
29
|
+
url: string;
|
|
30
|
+
} | {
|
|
31
|
+
type: "review";
|
|
32
|
+
id: number;
|
|
33
|
+
pullNumber: number;
|
|
34
|
+
commitSha: string | null;
|
|
35
|
+
state: string;
|
|
36
|
+
} | {
|
|
37
|
+
type: "pull";
|
|
38
|
+
number: number;
|
|
39
|
+
url: string;
|
|
40
|
+
headSha: string;
|
|
41
|
+
};
|
|
42
|
+
export interface ReconciliationReport {
|
|
43
|
+
/** Every page that could hold the write was read. */
|
|
44
|
+
complete: boolean;
|
|
45
|
+
/** Bodies with this operation's marker, by the expected author when one is configured. */
|
|
46
|
+
matches: number;
|
|
47
|
+
/** Bodies with this operation's marker by another author: copies, never accepted as the write. */
|
|
48
|
+
foreignMarkers: number;
|
|
49
|
+
/** Extra matches beyond the first: duplicates GitHub holds for this one operation. */
|
|
50
|
+
duplicates: number[];
|
|
51
|
+
}
|
|
52
|
+
export interface WriteOutcome {
|
|
53
|
+
/**
|
|
54
|
+
* - `verified`: GitHub answered, and a fresh read shows exactly what was authorized.
|
|
55
|
+
* - `accepted`: the resource exists but the read-back differs or was unavailable (`mismatches`).
|
|
56
|
+
* - `indeterminate`: the write may or may not have happened. Never resend blindly: `reconcile`.
|
|
57
|
+
*/
|
|
58
|
+
status: "verified" | "accepted" | "indeterminate";
|
|
59
|
+
operationId: string;
|
|
60
|
+
kind: WriteKind;
|
|
61
|
+
repository: string;
|
|
62
|
+
descriptorDigest: string;
|
|
63
|
+
/** Answered from the ledger; nothing was sent by this call. */
|
|
64
|
+
replayed: boolean;
|
|
65
|
+
/** The resource was identified by reconciliation, not by GitHub's response to the write. */
|
|
66
|
+
recovered: boolean;
|
|
67
|
+
resource: WrittenResource | null;
|
|
68
|
+
verification: "matched" | "mismatch" | "unavailable" | "not-attempted";
|
|
69
|
+
mismatches: string[];
|
|
70
|
+
/** For a review: the pull request head moved between the precondition and the read-back. */
|
|
71
|
+
headMovedDuringPublication?: boolean;
|
|
72
|
+
reconciliation?: ReconciliationReport;
|
|
73
|
+
reason?: string;
|
|
74
|
+
/** False when the ledger could not record this outcome; the write's result above still stands. */
|
|
75
|
+
recorded: boolean;
|
|
76
|
+
}
|
|
77
|
+
export interface OperationRecord {
|
|
78
|
+
schema: "comforge-github-operation/v1";
|
|
79
|
+
operationId: string;
|
|
80
|
+
repository: string;
|
|
81
|
+
kind: WriteKind;
|
|
82
|
+
capability: WriteCapability;
|
|
83
|
+
/** The descriptor digest: a retry with other content under the same id is a `conflict`. */
|
|
84
|
+
fingerprint: string;
|
|
85
|
+
/** The authorized descriptor, kept so `reconcile` needs nothing else. Holds no secret. */
|
|
86
|
+
descriptor: OperationDescriptor;
|
|
87
|
+
/** Incremented by every replace; the ledger's compare-and-swap key. */
|
|
88
|
+
version: number;
|
|
89
|
+
state: OperationState;
|
|
90
|
+
/** While `reserved` or `sending`, another caller must wait until this clock time. */
|
|
91
|
+
leaseUntil: number | null;
|
|
92
|
+
attempts: number;
|
|
93
|
+
/** Clock time of the first request that may have reached GitHub. */
|
|
94
|
+
firstSentAt: number | null;
|
|
95
|
+
changedAt: number;
|
|
96
|
+
authorizationReference: string | null;
|
|
97
|
+
marker: string | null;
|
|
98
|
+
outcome: Omit<WriteOutcome, "replayed" | "recorded"> | null;
|
|
99
|
+
failure: {
|
|
100
|
+
code: GitHubErrorCode;
|
|
101
|
+
message: string;
|
|
102
|
+
status?: number;
|
|
103
|
+
retryable: boolean;
|
|
104
|
+
notBefore: number | null;
|
|
105
|
+
} | null;
|
|
106
|
+
note: string | null;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Durable, consumer-owned storage. Preconditions the writer relies on (a process-local map meets
|
|
110
|
+
* them only within one process):
|
|
111
|
+
* - `create` inserts only when no record has that `operationId`, atomically, and says whether it did;
|
|
112
|
+
* - `replace` writes only when the stored `version` equals `expectedVersion`, atomically;
|
|
113
|
+
* - records are returned as stored (a copy), never shared mutable objects.
|
|
114
|
+
* A thrown error from any method is `ledger-failure`: before a send, nothing is sent.
|
|
115
|
+
*/
|
|
116
|
+
export interface OperationLedger {
|
|
117
|
+
get(operationId: string): Promise<OperationRecord | null>;
|
|
118
|
+
create(record: OperationRecord): Promise<boolean>;
|
|
119
|
+
replace(operationId: string, expectedVersion: number, next: OperationRecord): Promise<boolean>;
|
|
120
|
+
}
|
|
121
|
+
export type AuthorizationDecision = {
|
|
122
|
+
allow: true;
|
|
123
|
+
descriptorDigest: string;
|
|
124
|
+
expiresAt: number;
|
|
125
|
+
reference?: string;
|
|
126
|
+
} | {
|
|
127
|
+
allow: false;
|
|
128
|
+
reason?: string;
|
|
129
|
+
};
|
|
130
|
+
export interface WriterLimits {
|
|
131
|
+
/** Pages read when searching for an uncertain create (100 items each). */
|
|
132
|
+
reconcileMaxPages: number;
|
|
133
|
+
/** How long a `reserved`/`sending` record excludes other callers. */
|
|
134
|
+
leaseMs: number;
|
|
135
|
+
/** The longest authorization lifetime accepted; a longer `expiresAt` is refused. */
|
|
136
|
+
maxAuthorizationTtlMs: number;
|
|
137
|
+
/** How far before the first send a reconciliation search starts (clock skew allowance). */
|
|
138
|
+
searchSkewMs: number;
|
|
139
|
+
}
|
|
140
|
+
export declare const DEFAULT_WRITER_LIMITS: WriterLimits;
|
|
141
|
+
export interface GitHubWriterOptions {
|
|
142
|
+
repository: {
|
|
143
|
+
owner: string;
|
|
144
|
+
name: string;
|
|
145
|
+
};
|
|
146
|
+
/** A token, or a function returning one per request. Never stored, logged or returned. */
|
|
147
|
+
token: string | (() => string | Promise<string>);
|
|
148
|
+
/** The only writes this writer performs, whatever the token permits. */
|
|
149
|
+
capabilities: readonly WriteCapability[];
|
|
150
|
+
/** The consumer's policy decision for one exact descriptor. */
|
|
151
|
+
authorize: (descriptor: OperationDescriptor) => AuthorizationDecision | Promise<AuthorizationDecision>;
|
|
152
|
+
ledger: OperationLedger;
|
|
153
|
+
/** Milliseconds since the epoch. Injected: the package reads no ambient clock. */
|
|
154
|
+
clock: () => number;
|
|
155
|
+
/**
|
|
156
|
+
* Correlation markers appended to created bodies, so an uncertain create can be found.
|
|
157
|
+
* `false` disables them; an uncertain create then stays `indeterminate` until you resolve it.
|
|
158
|
+
*/
|
|
159
|
+
markers?: {
|
|
160
|
+
namespace?: string;
|
|
161
|
+
} | false;
|
|
162
|
+
/** The login the token writes as (an App writes as `<slug>[bot]`). Reconciliation trusts only its markers. */
|
|
163
|
+
expectedAuthor?: string;
|
|
164
|
+
fetchImpl?: typeof fetch;
|
|
165
|
+
apiOrigin?: string;
|
|
166
|
+
timeoutMs?: number;
|
|
167
|
+
maxBodyBytes?: number;
|
|
168
|
+
userAgent?: string;
|
|
169
|
+
limits?: Partial<WriterLimits>;
|
|
170
|
+
}
|
|
171
|
+
export interface GitHubWriter {
|
|
172
|
+
readonly repository: string;
|
|
173
|
+
readonly capabilities: readonly WriteCapability[];
|
|
174
|
+
/** The descriptor `execute` would authorize and send; sends and records nothing. */
|
|
175
|
+
prepare(operation: WriteOperation): Promise<OperationDescriptor>;
|
|
176
|
+
/** Authorize, record, check preconditions, send once, read back. Refusals throw; nothing was written. */
|
|
177
|
+
execute(operation: WriteOperation): Promise<WriteOutcome>;
|
|
178
|
+
/** Looks for an `indeterminate` operation's write on GitHub (reads only) and records what it finds. */
|
|
179
|
+
reconcile(operationId: string): Promise<WriteOutcome>;
|
|
180
|
+
/** Ends an unfinished operation by the caller's decision; it is never sent again under this id. */
|
|
181
|
+
abandon(operationId: string, reason: string): Promise<void>;
|
|
182
|
+
}
|
|
183
|
+
export declare function createGitHubWriter(options: GitHubWriterOptions): GitHubWriter;
|