@comforge/github 0.2.0 → 0.4.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.
@@ -0,0 +1,50 @@
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 "pull.update": "PATCH";
18
+ readonly "issue.update": "PATCH";
19
+ readonly "comment.update": "PATCH";
20
+ };
21
+ export type WriteMethodKind = keyof typeof WRITE_METHODS;
22
+ export interface SendOptions {
23
+ origin: string;
24
+ base: string;
25
+ token: () => Promise<string>;
26
+ fetchImpl: typeof fetch;
27
+ timeoutMs: number;
28
+ maxBodyBytes: number;
29
+ userAgent?: string;
30
+ }
31
+ /**
32
+ * - `answered`: a 2xx whose JSON body was read.
33
+ * - `refused`: a definite non-2xx answer from GitHub (4xx), with its typed error.
34
+ * - `sent-unknown`: the request may have been applied: no answer, a 5xx, a 408, or a 2xx whose
35
+ * body could not be read or parsed (`accepted` says GitHub did answer 2xx).
36
+ */
37
+ export type SendResult = {
38
+ kind: "answered";
39
+ status: number;
40
+ body: unknown;
41
+ } | {
42
+ kind: "refused";
43
+ error: GitHubAdapterError;
44
+ } | {
45
+ kind: "sent-unknown";
46
+ reason: string;
47
+ status?: number;
48
+ accepted: boolean;
49
+ };
50
+ export declare function sendWrite(options: SendOptions, kind: WriteMethodKind, path: string, payload: Record<string, unknown>): Promise<SendResult>;
@@ -0,0 +1,89 @@
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
+ "pull.update": "PATCH",
19
+ "issue.update": "PATCH",
20
+ "comment.update": "PATCH",
21
+ };
22
+ 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]+$/;
23
+ export async function sendWrite(options, kind, path, payload) {
24
+ const method = WRITE_METHODS[kind];
25
+ if (!PATH.test(path))
26
+ throw new GitHubAdapterError("invalid-input", "The write path is not a supported API path");
27
+ const url = new URL(`${options.base}${path}`);
28
+ if (url.origin !== options.origin)
29
+ throw new GitHubAdapterError("unapproved-origin", "Unapproved outbound host");
30
+ // Resolved before sending: a failing token provider is a refusal, never an uncertain write.
31
+ let token;
32
+ try {
33
+ token = await options.token();
34
+ }
35
+ catch {
36
+ throw new GitHubAdapterError("unauthorized", "The token provider failed; nothing was sent");
37
+ }
38
+ if (typeof token !== "string" || token.length === 0)
39
+ throw new GitHubAdapterError("unauthorized", "The token provider returned no token; nothing was sent");
40
+ let res;
41
+ try {
42
+ res = await options.fetchImpl(url, {
43
+ method,
44
+ redirect: "error",
45
+ signal: AbortSignal.timeout(options.timeoutMs),
46
+ headers: {
47
+ Accept: "application/vnd.github+json",
48
+ "Content-Type": "application/json",
49
+ "X-GitHub-Api-Version": API_VERSION,
50
+ Authorization: `Bearer ${token}`,
51
+ ...(options.userAgent ? { "User-Agent": options.userAgent } : {}),
52
+ },
53
+ body: JSON.stringify(payload),
54
+ });
55
+ }
56
+ catch {
57
+ return { kind: "sent-unknown", reason: "no answer (network or timeout)", accepted: false };
58
+ }
59
+ if (!res.ok) {
60
+ // A gateway error or timeout from GitHub's edge says nothing about whether the write applied.
61
+ if (res.status >= 500 || res.status === 408)
62
+ return {
63
+ kind: "sent-unknown",
64
+ reason: `HTTP ${res.status}`,
65
+ status: res.status,
66
+ accepted: false,
67
+ };
68
+ return { kind: "refused", error: classifyStatus(res.status, res.headers) };
69
+ }
70
+ const status = res.status;
71
+ const declared = Number(res.headers.get("content-length") ?? "0");
72
+ if (Number.isFinite(declared) && declared > options.maxBodyBytes)
73
+ return { kind: "sent-unknown", reason: "response too large", status, accepted: true };
74
+ let text;
75
+ try {
76
+ text = await res.text();
77
+ }
78
+ catch {
79
+ return { kind: "sent-unknown", reason: "response body unreadable", status, accepted: true };
80
+ }
81
+ if (text.length > options.maxBodyBytes)
82
+ return { kind: "sent-unknown", reason: "response too large", status, accepted: true };
83
+ try {
84
+ return { kind: "answered", status, body: JSON.parse(text) };
85
+ }
86
+ catch {
87
+ return { kind: "sent-unknown", reason: "response not JSON", status, accepted: true };
88
+ }
89
+ }
@@ -0,0 +1,199 @@
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
+ * The written resource exactly as this call's verification read returned it, so a caller
78
+ * needs no second GET for its body. Present only when this call read the resource back and
79
+ * every authorized field matched (`verification: "matched"`, fresh or recovered); absent on a
80
+ * replay (the ledger keeps no response), on `accepted` and on `indeterminate`. Bounded by
81
+ * `maxBodyBytes`; untrusted JSON the caller still validates with its own schema. Never stored.
82
+ */
83
+ response?: VerifiedResponse;
84
+ }
85
+ /** A body the writer read back and matched against the authorized write in the same call. */
86
+ export interface VerifiedResponse {
87
+ /** The GET it came from: the resource itself (an issue, comment, review or pull request). */
88
+ source: "verification-read";
89
+ body: unknown;
90
+ }
91
+ /** An outcome as the ledger keeps it: no per-call flags and never a response body. */
92
+ export type StoredOutcome = Omit<WriteOutcome, "replayed" | "recorded" | "response">;
93
+ export interface OperationRecord {
94
+ schema: "comforge-github-operation/v1";
95
+ operationId: string;
96
+ repository: string;
97
+ kind: WriteKind;
98
+ capability: WriteCapability;
99
+ /** The descriptor digest: a retry with other content under the same id is a `conflict`. */
100
+ fingerprint: string;
101
+ /** The authorized descriptor, kept so `reconcile` needs nothing else. Holds no secret. */
102
+ descriptor: OperationDescriptor;
103
+ /** Incremented by every replace; the ledger's compare-and-swap key. */
104
+ version: number;
105
+ state: OperationState;
106
+ /** While `reserved` or `sending`, another caller must wait until this clock time. */
107
+ leaseUntil: number | null;
108
+ attempts: number;
109
+ /** Clock time of the first request that may have reached GitHub. */
110
+ firstSentAt: number | null;
111
+ changedAt: number;
112
+ authorizationReference: string | null;
113
+ marker: string | null;
114
+ outcome: StoredOutcome | null;
115
+ failure: {
116
+ code: GitHubErrorCode;
117
+ message: string;
118
+ status?: number;
119
+ retryable: boolean;
120
+ notBefore: number | null;
121
+ } | null;
122
+ note: string | null;
123
+ }
124
+ /**
125
+ * Durable, consumer-owned storage. Preconditions the writer relies on (a process-local map meets
126
+ * them only within one process):
127
+ * - `create` inserts only when no record has that `operationId`, atomically, and says whether it did;
128
+ * - `replace` writes only when the stored `version` equals `expectedVersion`, atomically;
129
+ * - records are returned as stored (a copy), never shared mutable objects.
130
+ * A thrown error from any method is `ledger-failure`: before a send, nothing is sent.
131
+ */
132
+ export interface OperationLedger {
133
+ get(operationId: string): Promise<OperationRecord | null>;
134
+ create(record: OperationRecord): Promise<boolean>;
135
+ replace(operationId: string, expectedVersion: number, next: OperationRecord): Promise<boolean>;
136
+ }
137
+ export type AuthorizationDecision = {
138
+ allow: true;
139
+ descriptorDigest: string;
140
+ expiresAt: number;
141
+ reference?: string;
142
+ } | {
143
+ allow: false;
144
+ reason?: string;
145
+ };
146
+ export interface WriterLimits {
147
+ /** Pages read when searching for an uncertain create (100 items each). */
148
+ reconcileMaxPages: number;
149
+ /** How long a `reserved`/`sending` record excludes other callers. */
150
+ leaseMs: number;
151
+ /** The longest authorization lifetime accepted; a longer `expiresAt` is refused. */
152
+ maxAuthorizationTtlMs: number;
153
+ /** How far before the first send a reconciliation search starts (clock skew allowance). */
154
+ searchSkewMs: number;
155
+ }
156
+ export declare const DEFAULT_WRITER_LIMITS: WriterLimits;
157
+ export interface GitHubWriterOptions {
158
+ repository: {
159
+ owner: string;
160
+ name: string;
161
+ };
162
+ /** A token, or a function returning one per request. Never stored, logged or returned. */
163
+ token: string | (() => string | Promise<string>);
164
+ /** The only writes this writer performs, whatever the token permits. */
165
+ capabilities: readonly WriteCapability[];
166
+ /** The consumer's policy decision for one exact descriptor. */
167
+ authorize: (descriptor: OperationDescriptor) => AuthorizationDecision | Promise<AuthorizationDecision>;
168
+ ledger: OperationLedger;
169
+ /** Milliseconds since the epoch. Injected: the package reads no ambient clock. */
170
+ clock: () => number;
171
+ /**
172
+ * Correlation markers appended to created bodies, so an uncertain create can be found.
173
+ * `false` disables them; an uncertain create then stays `indeterminate` until you resolve it.
174
+ */
175
+ markers?: {
176
+ namespace?: string;
177
+ } | false;
178
+ /** The login the token writes as (an App writes as `<slug>[bot]`). Reconciliation trusts only its markers. */
179
+ expectedAuthor?: string;
180
+ fetchImpl?: typeof fetch;
181
+ apiOrigin?: string;
182
+ timeoutMs?: number;
183
+ maxBodyBytes?: number;
184
+ userAgent?: string;
185
+ limits?: Partial<WriterLimits>;
186
+ }
187
+ export interface GitHubWriter {
188
+ readonly repository: string;
189
+ readonly capabilities: readonly WriteCapability[];
190
+ /** The descriptor `execute` would authorize and send; sends and records nothing. */
191
+ prepare(operation: WriteOperation): Promise<OperationDescriptor>;
192
+ /** Authorize, record, check preconditions, send once, read back. Refusals throw; nothing was written. */
193
+ execute(operation: WriteOperation): Promise<WriteOutcome>;
194
+ /** Looks for an `indeterminate` operation's write on GitHub (reads only) and records what it finds. */
195
+ reconcile(operationId: string): Promise<WriteOutcome>;
196
+ /** Ends an unfinished operation by the caller's decision; it is never sent again under this id. */
197
+ abandon(operationId: string, reason: string): Promise<void>;
198
+ }
199
+ export declare function createGitHubWriter(options: GitHubWriterOptions): GitHubWriter;