@fabrika/github-app 0.3.3 → 0.4.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/github-app",
3
- "version": "0.3.3",
3
+ "version": "0.4.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
package/src/client.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { configurationError, requestStatusError, responseError } from './errors'
2
+ import { createRepositoryClient } from './repository'
3
+ import type { GitHubRepositoryClient, GitHubRepositoryOpenRequest } from './repository-types'
2
4
  import { pemToPkcs8, signAppJwt } from './signing'
3
- import { createCancellation, GITHUB_ACCEPT, GITHUB_API_VERSION, readBoundedJson } from './transport'
5
+ import { createCancellation, GITHUB_ACCEPT, GITHUB_API_VERSION, GITHUB_USER_AGENT, readBoundedJson } from './transport'
4
6
  import type {
5
7
  GitHubAppClientConfig,
6
8
  GitHubAppFetch,
@@ -27,7 +29,6 @@ import {
27
29
  const DEFAULT_API_BASE_URL = 'https://api.github.com'
28
30
  const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
29
31
  const MAX_REQUEST_TIMEOUT_MS = 120_000
30
- const GITHUB_USER_AGENT = 'vozka'
31
32
  const APP_ID_PATTERN = /^[1-9][0-9]*$/
32
33
  const NOT_FOUND = Symbol('not-found')
33
34
 
@@ -142,6 +143,30 @@ export class GitHubAppClient {
142
143
 
143
144
  /** Mint a read-only token restricted to one repository in the selected installation. */
144
145
  async mintRepositoryToken(input: GitHubRepositoryTokenRequest): Promise<GitHubInstallationToken> {
146
+ return this.mintToken(input, { contents: 'read' })
147
+ }
148
+
149
+ /**
150
+ * Mint a token restricted to one repository with `contents: write` and `pull_requests: write`,
151
+ * and return a client bound to it. The token never leaves the returned client.
152
+ */
153
+ async openRepository(input: GitHubRepositoryOpenRequest): Promise<GitHubRepositoryClient> {
154
+ const token = await this.mintToken(input, { contents: 'write', pull_requests: 'write' })
155
+ return createRepositoryClient({
156
+ owner: input.owner,
157
+ repository: input.repository,
158
+ token,
159
+ now: () => this.now(),
160
+ apiBaseUrl: this.apiBaseUrl,
161
+ fetch: this.fetchImplementation,
162
+ timeoutMs: this.timeoutMs,
163
+ })
164
+ }
165
+
166
+ private async mintToken(
167
+ input: GitHubRepositoryTokenRequest,
168
+ permissions: Readonly<Record<string, 'read' | 'write'>>,
169
+ ): Promise<GitHubInstallationToken> {
145
170
  if (!isPositiveSafeInteger(input.installationId)) {
146
171
  throw configurationError()
147
172
  }
@@ -152,7 +177,7 @@ export class GitHubAppClient {
152
177
  {
153
178
  method: 'POST',
154
179
  headers: { 'content-type': 'application/json' },
155
- body: JSON.stringify({ repositories: [input.repository], permissions: { contents: 'read' } }),
180
+ body: JSON.stringify({ repositories: [input.repository], permissions }),
156
181
  },
157
182
  input.signal,
158
183
  false,
package/src/errors.ts CHANGED
@@ -9,3 +9,27 @@ export function requestStatusError(status: number): Error {
9
9
  export function responseError(): Error {
10
10
  return new Error('GitHub App response is invalid')
11
11
  }
12
+
13
+ /** The branch moved since the caller read it; re-read the head and retry the change on top of it. */
14
+ export class GitHubStaleHeadError extends Error {
15
+ constructor() {
16
+ super('GitHub branch head changed')
17
+ this.name = 'GitHubStaleHeadError'
18
+ }
19
+ }
20
+
21
+ /** The branch exists at a different commit than the one it was to be created from. */
22
+ export class GitHubBranchConflictError extends Error {
23
+ constructor() {
24
+ super('GitHub branch already exists at a different commit')
25
+ this.name = 'GitHubBranchConflictError'
26
+ }
27
+ }
28
+
29
+ /** A commit, tree or blob sha the caller named does not exist in the repository. */
30
+ export class GitHubNotFoundError extends Error {
31
+ constructor() {
32
+ super('GitHub commit or tree was not found')
33
+ this.name = 'GitHubNotFoundError'
34
+ }
35
+ }
package/src/index.ts CHANGED
@@ -1,5 +1,21 @@
1
1
  export { GitHubAppClient } from './client'
2
+ export { GitHubBranchConflictError, GitHubNotFoundError, GitHubStaleHeadError } from './errors'
2
3
  export { buildGitHubAppManifest, exchangeGitHubAppManifestCode } from './manifest'
4
+ export type {
5
+ GitHubCommit,
6
+ GitHubCommitFilesInput,
7
+ GitHubCreateBranchInput,
8
+ GitHubFileChange,
9
+ GitHubFileRead,
10
+ GitHubOpenPullRequestInput,
11
+ GitHubPullRequestRef,
12
+ GitHubRef,
13
+ GitHubRepositoryClient,
14
+ GitHubRepositoryOpenRequest,
15
+ GitHubTextFile,
16
+ GitHubTreeEntry,
17
+ GitHubTreeListing,
18
+ } from './repository-types'
3
19
  export { pemToPkcs8 } from './signing'
4
20
  export type {
5
21
  CreatedGitHubApp,
package/src/manifest.ts CHANGED
@@ -15,7 +15,7 @@ const manifestConversionSchema = appReferenceSchema.extend({
15
15
  webhook_secret: z.string().min(1).max(4096).refine((secret) => !hasAsciiControl(secret)),
16
16
  })
17
17
 
18
- /** Build the one least-authority App manifest used by Fabrika repository source. */
18
+ /** Build the one least-authority App manifest used by Fabrika repository source and MCP authoring. */
19
19
  export function buildGitHubAppManifest(input: GitHubAppManifestInput): Readonly<Record<string, unknown>> {
20
20
  validateManifestInput(input)
21
21
  return {
@@ -24,7 +24,7 @@ export function buildGitHubAppManifest(input: GitHubAppManifestInput): Readonly<
24
24
  hook_attributes: { url: input.webhookUrl, active: true },
25
25
  ...(input.redirectUrl === undefined ? {} : { redirect_url: input.redirectUrl }),
26
26
  public: input.public,
27
- default_permissions: { contents: 'read' },
27
+ default_permissions: { contents: 'write', pull_requests: 'write', metadata: 'read' },
28
28
  default_events: ['push'],
29
29
  }
30
30
  }
@@ -0,0 +1,99 @@
1
+ export interface GitHubRef {
2
+ readonly branch: string
3
+ readonly sha: string
4
+ }
5
+
6
+ export interface GitHubCommit {
7
+ readonly sha: string
8
+ readonly treeSha: string
9
+ readonly parents: readonly string[]
10
+ }
11
+
12
+ export type GitHubTreeEntry =
13
+ & { readonly path: string; readonly sha: string }
14
+ & (
15
+ | { readonly type: 'tree'; readonly mode: '040000' }
16
+ | { readonly type: 'blob'; readonly mode: '100644' | '100755' | '120000'; readonly size: number }
17
+ | { readonly type: 'commit'; readonly mode: '160000' }
18
+ )
19
+
20
+ export interface GitHubTreeListing {
21
+ readonly commitSha: string
22
+ /** Empty for the root; entries use repository-relative paths. */
23
+ readonly directory: string
24
+ /** Every entry below `directory`, recursively, up to the client's bound. */
25
+ readonly entries: readonly GitHubTreeEntry[]
26
+ /** True when the bound cut the listing short. */
27
+ readonly truncated: boolean
28
+ }
29
+
30
+ export interface GitHubTextFile {
31
+ readonly path: string
32
+ readonly content: string
33
+ }
34
+
35
+ export interface GitHubFileRead {
36
+ readonly commitSha: string
37
+ readonly files: readonly GitHubTextFile[]
38
+ /** Requested paths that do not exist (or are not regular UTF-8 files) at `commitSha`. */
39
+ readonly missingPaths: readonly string[]
40
+ }
41
+
42
+ export interface GitHubFileChange {
43
+ readonly path: string
44
+ /** UTF-8 regular-file contents, or null to delete the path. */
45
+ readonly content: string | null
46
+ }
47
+
48
+ export interface GitHubCreateBranchInput {
49
+ readonly branch: string
50
+ readonly fromSha: string
51
+ readonly signal?: AbortSignal
52
+ }
53
+
54
+ export interface GitHubCommitFilesInput {
55
+ readonly branch: string
56
+ /** The branch head the changes were made against; a different live head fails with `GitHubStaleHeadError`. */
57
+ readonly expectedHeadSha: string
58
+ readonly message: string
59
+ readonly author: { readonly name: string; readonly email: string }
60
+ readonly changes: readonly GitHubFileChange[]
61
+ readonly signal?: AbortSignal
62
+ }
63
+
64
+ export interface GitHubOpenPullRequestInput {
65
+ readonly head: string
66
+ readonly base: string
67
+ readonly title: string
68
+ readonly body: string
69
+ readonly signal?: AbortSignal
70
+ }
71
+
72
+ export interface GitHubPullRequestRef {
73
+ readonly number: number
74
+ readonly url: string
75
+ /** False when an open pull request for the same head and base already existed and was returned instead. */
76
+ readonly created: boolean
77
+ }
78
+
79
+ /**
80
+ * One repository, reached with an installation token restricted to it. The caller (Source) decides
81
+ * which branches it may write; the client only refuses a non-fast-forward or stale update.
82
+ */
83
+ export interface GitHubRepositoryClient {
84
+ readRef(branch: string, signal?: AbortSignal): Promise<GitHubRef | null>
85
+ readTree(commitSha: string, directory?: string, signal?: AbortSignal): Promise<GitHubTreeListing>
86
+ readFiles(commitSha: string, paths: readonly string[], signal?: AbortSignal): Promise<GitHubFileRead>
87
+ /** Idempotent: an existing branch already at `fromSha` is returned; one elsewhere is a conflict. */
88
+ createBranch(input: GitHubCreateBranchInput): Promise<GitHubRef>
89
+ /** Creates exactly one commit on top of `expectedHeadSha` and moves the branch to it without force. */
90
+ commitFiles(input: GitHubCommitFilesInput): Promise<GitHubCommit>
91
+ openPullRequest(input: GitHubOpenPullRequestInput): Promise<GitHubPullRequestRef>
92
+ }
93
+
94
+ export interface GitHubRepositoryOpenRequest {
95
+ readonly installationId: number
96
+ readonly owner: string
97
+ readonly repository: string
98
+ readonly signal?: AbortSignal
99
+ }
@@ -0,0 +1,152 @@
1
+ import { z } from 'zod'
2
+ import { configurationError, responseError } from './errors'
3
+ import type { GitHubCommit, GitHubPullRequestRef, GitHubRef, GitHubTreeEntry } from './repository-types'
4
+ import { hasAsciiControl } from './validation'
5
+
6
+ export const MAX_TREE_ENTRIES = 5000
7
+ export const MAX_TREE_RESPONSE_BYTES = 8 * 1024 * 1024
8
+ export const MAX_READ_PATHS = 100
9
+ export const MAX_FILE_BYTES = 512 * 1024
10
+ export const MAX_READ_BYTES = 2 * 1024 * 1024
11
+ // Base64 inflates a blob by 4/3 and GitHub wraps it in lines.
12
+ export const MAX_BLOB_RESPONSE_BYTES = 1024 * 1024
13
+ export const MAX_CHANGED_FILES = 256
14
+ export const MAX_CHANGED_BYTES = 2 * 1024 * 1024
15
+ export const MAX_COMMIT_MESSAGE_BYTES = 16 * 1024
16
+ export const MAX_PULL_REQUEST_TITLE_BYTES = 1024
17
+ export const MAX_PULL_REQUEST_BODY_BYTES = 64 * 1024
18
+ // A pull request echoes its body plus full head and base repository objects.
19
+ export const MAX_PULL_REQUEST_RESPONSE_BYTES = 1024 * 1024
20
+ // A commit echoes its message, which existing history does not bound.
21
+ export const MAX_COMMIT_RESPONSE_BYTES = 1024 * 1024
22
+ export const MAX_PATH_SEGMENTS = 64
23
+
24
+ const SHA_PATTERN = /^[a-f0-9]{40}$/
25
+ const LONE_SURROGATE_PATTERN = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
26
+
27
+ export function validateSha(value: string): void {
28
+ if (!SHA_PATTERN.test(value)) throw configurationError()
29
+ }
30
+
31
+ /** A subset of `git check-ref-format` that is safe to place in a URL path segment by segment. */
32
+ export function validateBranch(value: string): void {
33
+ if (
34
+ value.length === 0 || value.length > 200 || value === '@' || value.startsWith('-') || value.includes('..') || value.includes('@{')
35
+ || hasAsciiControl(value) || /[\s~^:?*[\\]/.test(value)
36
+ || value.split('/').some((part) => part.length === 0 || part.startsWith('.') || part.endsWith('.') || part.endsWith('.lock'))
37
+ ) throw configurationError()
38
+ }
39
+
40
+ /** Repository-relative path: no leading, trailing or doubled slash, no `.`/`..` segment, never inside `.git`. */
41
+ export function validatePath(value: string): void {
42
+ if (
43
+ value.length === 0 || value.length > 1024 || hasAsciiControl(value) || value.includes('\\') || LONE_SURROGATE_PATTERN.test(value)
44
+ || value.split('/').length > MAX_PATH_SEGMENTS
45
+ || value.split('/').some((part) => part === '' || part === '.' || part === '..' || part.toLowerCase() === '.git')
46
+ ) throw configurationError()
47
+ }
48
+
49
+ export function validateText(value: string, maxBytes: number, allowEmpty: boolean): void {
50
+ if (
51
+ (!allowEmpty && value.trim().length === 0) || value.includes('\0') || LONE_SURROGATE_PATTERN.test(value)
52
+ || utf8Length(value) > maxBytes
53
+ ) throw configurationError()
54
+ }
55
+
56
+ export function utf8Length(value: string): number {
57
+ return new TextEncoder().encode(value).byteLength
58
+ }
59
+
60
+ export function encodeBranch(branch: string): string {
61
+ return branch.split('/').map(encodeURIComponent).join('/')
62
+ }
63
+
64
+ const shaSchema = z.string().regex(SHA_PATTERN)
65
+
66
+ const refSchema = z.object({ ref: z.string(), object: z.object({ type: z.literal('commit'), sha: shaSchema }) })
67
+
68
+ export function decodeRef(body: unknown, branch: string): GitHubRef {
69
+ const result = refSchema.safeParse(body)
70
+ if (!result.success || result.data.ref !== `refs/heads/${branch}`) throw responseError()
71
+ return { branch, sha: result.data.object.sha }
72
+ }
73
+
74
+ const commitSchema = z.object({
75
+ sha: shaSchema,
76
+ tree: z.object({ sha: shaSchema }),
77
+ parents: z.array(z.object({ sha: shaSchema })).max(100),
78
+ })
79
+
80
+ export function decodeCommit(body: unknown): GitHubCommit {
81
+ const result = commitSchema.safeParse(body)
82
+ if (!result.success) throw responseError()
83
+ return { sha: result.data.sha, treeSha: result.data.tree.sha, parents: result.data.parents.map((parent) => parent.sha) }
84
+ }
85
+
86
+ const treeEntrySchema = z.union([
87
+ z.object({ path: z.string(), sha: shaSchema, type: z.literal('tree'), mode: z.literal('040000') }),
88
+ z.object({
89
+ path: z.string(),
90
+ sha: shaSchema,
91
+ type: z.literal('blob'),
92
+ mode: z.enum(['100644', '100755', '120000']),
93
+ size: z.number().int().nonnegative(),
94
+ }),
95
+ z.object({ path: z.string(), sha: shaSchema, type: z.literal('commit'), mode: z.literal('160000') }),
96
+ ])
97
+
98
+ const treeSchema = z.object({ sha: shaSchema, tree: z.array(treeEntrySchema), truncated: z.boolean() })
99
+
100
+ export interface DecodedTree {
101
+ readonly entries: readonly GitHubTreeEntry[]
102
+ readonly truncated: boolean
103
+ }
104
+
105
+ export function decodeTree(body: unknown, expectedSha: string): DecodedTree {
106
+ const result = treeSchema.safeParse(body)
107
+ if (!result.success || result.data.sha !== expectedSha) throw responseError()
108
+ return { entries: result.data.tree, truncated: result.data.truncated }
109
+ }
110
+
111
+ const createdTreeSchema = z.object({ sha: shaSchema })
112
+
113
+ export function decodeCreatedTreeSha(body: unknown): string {
114
+ const result = createdTreeSchema.safeParse(body)
115
+ if (!result.success) throw responseError()
116
+ return result.data.sha
117
+ }
118
+
119
+ const blobSchema = z.object({ sha: shaSchema, size: z.number().int().nonnegative(), encoding: z.literal('base64'), content: z.string() })
120
+
121
+ /** The blob's bytes as UTF-8 text, or null when they are not valid UTF-8. */
122
+ export function decodeTextBlob(body: unknown, expectedSha: string, expectedSize: number): string | null {
123
+ const result = blobSchema.safeParse(body)
124
+ if (!result.success || result.data.sha !== expectedSha || result.data.size !== expectedSize) throw responseError()
125
+ let binary: string
126
+ try {
127
+ binary = atob(result.data.content.replace(/\r?\n/g, ''))
128
+ } catch {
129
+ throw responseError()
130
+ }
131
+ if (binary.length !== expectedSize) throw responseError()
132
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0))
133
+ try {
134
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)
135
+ } catch {
136
+ return null
137
+ }
138
+ }
139
+
140
+ const pullRequestSchema = z.object({ number: z.number().int().positive(), html_url: z.string().url() })
141
+
142
+ export function decodePullRequest(body: unknown, created: boolean): GitHubPullRequestRef {
143
+ const result = pullRequestSchema.safeParse(body)
144
+ if (!result.success) throw responseError()
145
+ return { number: result.data.number, url: result.data.html_url, created }
146
+ }
147
+
148
+ export function decodePullRequestList(body: unknown): unknown[] {
149
+ const result = z.array(z.unknown()).max(100).safeParse(body)
150
+ if (!result.success) throw responseError()
151
+ return result.data
152
+ }
@@ -0,0 +1,363 @@
1
+ import { configurationError, GitHubBranchConflictError, GitHubNotFoundError, GitHubStaleHeadError, requestStatusError, responseError } from './errors'
2
+ import type {
3
+ GitHubCommit,
4
+ GitHubCommitFilesInput,
5
+ GitHubCreateBranchInput,
6
+ GitHubFileRead,
7
+ GitHubOpenPullRequestInput,
8
+ GitHubPullRequestRef,
9
+ GitHubRef,
10
+ GitHubRepositoryClient,
11
+ GitHubTextFile,
12
+ GitHubTreeEntry,
13
+ GitHubTreeListing,
14
+ } from './repository-types'
15
+ import {
16
+ decodeCommit,
17
+ decodeCreatedTreeSha,
18
+ decodePullRequest,
19
+ decodePullRequestList,
20
+ decodeRef,
21
+ decodeTextBlob,
22
+ decodeTree,
23
+ encodeBranch,
24
+ MAX_BLOB_RESPONSE_BYTES,
25
+ MAX_CHANGED_BYTES,
26
+ MAX_CHANGED_FILES,
27
+ MAX_COMMIT_MESSAGE_BYTES,
28
+ MAX_COMMIT_RESPONSE_BYTES,
29
+ MAX_FILE_BYTES,
30
+ MAX_PULL_REQUEST_BODY_BYTES,
31
+ MAX_PULL_REQUEST_RESPONSE_BYTES,
32
+ MAX_PULL_REQUEST_TITLE_BYTES,
33
+ MAX_READ_BYTES,
34
+ MAX_READ_PATHS,
35
+ MAX_TREE_ENTRIES,
36
+ MAX_TREE_RESPONSE_BYTES,
37
+ utf8Length,
38
+ validateBranch,
39
+ validatePath,
40
+ validateSha,
41
+ validateText,
42
+ } from './repository-validation'
43
+ import { createCancellation, GITHUB_ACCEPT, GITHUB_API_VERSION, GITHUB_USER_AGENT, readBoundedJson } from './transport'
44
+ import type { GitHubAppFetch, GitHubInstallationToken } from './types'
45
+ import { hasAsciiControl } from './validation'
46
+
47
+ export interface RepositoryClientConfig {
48
+ readonly owner: string
49
+ readonly repository: string
50
+ readonly token: GitHubInstallationToken
51
+ readonly now: () => number
52
+ readonly apiBaseUrl: string
53
+ readonly fetch: GitHubAppFetch
54
+ readonly timeoutMs: number
55
+ }
56
+
57
+ type RequestResult = { readonly ok: true; readonly body: unknown } | { readonly ok: false; readonly status: number }
58
+
59
+ interface RequestOptions {
60
+ readonly method?: 'GET' | 'POST' | 'PATCH'
61
+ readonly body?: unknown
62
+ readonly signal?: AbortSignal | undefined
63
+ readonly maxResponseBytes?: number
64
+ /** Statuses returned to the caller instead of thrown. */
65
+ readonly expectedFailures?: readonly number[]
66
+ }
67
+
68
+ interface TreeChange {
69
+ readonly path: string
70
+ readonly mode: '100644' | '100755'
71
+ readonly type: 'blob'
72
+ readonly content?: string
73
+ readonly sha?: null
74
+ }
75
+
76
+ export function createRepositoryClient(config: RepositoryClientConfig): GitHubRepositoryClient {
77
+ return new RepositoryClient(config)
78
+ }
79
+
80
+ class RepositoryClient implements GitHubRepositoryClient {
81
+ readonly #config: RepositoryClientConfig
82
+
83
+ constructor(config: RepositoryClientConfig) {
84
+ this.#config = config
85
+ }
86
+
87
+ async readRef(branch: string, signal?: AbortSignal): Promise<GitHubRef | null> {
88
+ validateBranch(branch)
89
+ const result = await this.#request(`/git/ref/heads/${encodeBranch(branch)}`, { signal, expectedFailures: [404] })
90
+ return result.ok ? decodeRef(result.body, branch) : null
91
+ }
92
+
93
+ async readTree(commitSha: string, directory = '', signal?: AbortSignal): Promise<GitHubTreeListing> {
94
+ validateSha(commitSha)
95
+ if (directory !== '') validatePath(directory)
96
+ const rootSha = (await this.#readCommit(commitSha, signal)).treeSha
97
+ let treeSha = rootSha
98
+ if (directory !== '') {
99
+ const entry = await this.#treeWalker(rootSha, signal).find(directory)
100
+ if (entry?.type !== 'tree') return { commitSha, directory, entries: [], truncated: false }
101
+ treeSha = entry.sha
102
+ }
103
+ const tree = decodeTree(await this.#readGitObject(`/git/trees/${treeSha}?recursive=1`, signal, MAX_TREE_RESPONSE_BYTES), treeSha)
104
+ const prefix = directory === '' ? '' : `${directory}/`
105
+ const entries = tree.entries.slice(0, MAX_TREE_ENTRIES).map((entry) => ({ ...entry, path: `${prefix}${entry.path}` }))
106
+ return { commitSha, directory, entries, truncated: tree.truncated || tree.entries.length > MAX_TREE_ENTRIES }
107
+ }
108
+
109
+ async readFiles(commitSha: string, paths: readonly string[], signal?: AbortSignal): Promise<GitHubFileRead> {
110
+ validateSha(commitSha)
111
+ if (paths.length === 0 || paths.length > MAX_READ_PATHS || new Set(paths).size !== paths.length) throw configurationError()
112
+ for (const path of paths) validatePath(path)
113
+ const directories = this.#treeWalker((await this.#readCommit(commitSha, signal)).treeSha, signal)
114
+ const files: GitHubTextFile[] = []
115
+ const missingPaths: string[] = []
116
+ let remainingBytes = MAX_READ_BYTES
117
+ for (const path of paths) {
118
+ const entry = await directories.find(path)
119
+ // Oversized files, and files past the total read budget, are reported missing like other unreadable paths.
120
+ if (entry?.type !== 'blob' || entry.mode === '120000' || entry.size > MAX_FILE_BYTES || entry.size > remainingBytes) {
121
+ missingPaths.push(path)
122
+ continue
123
+ }
124
+ const body = await this.#readGitObject(`/git/blobs/${entry.sha}`, signal, MAX_BLOB_RESPONSE_BYTES)
125
+ const content = decodeTextBlob(body, entry.sha, entry.size)
126
+ if (content === null) {
127
+ missingPaths.push(path)
128
+ continue
129
+ }
130
+ remainingBytes -= entry.size
131
+ files.push({ path, content })
132
+ }
133
+ return { commitSha, files, missingPaths }
134
+ }
135
+
136
+ async createBranch(input: GitHubCreateBranchInput): Promise<GitHubRef> {
137
+ validateBranch(input.branch)
138
+ validateSha(input.fromSha)
139
+ const existing = await this.readRef(input.branch, input.signal)
140
+ if (existing !== null) return requireBranchAt(existing, input.fromSha)
141
+ await this.#readCommit(input.fromSha, input.signal)
142
+ const result = await this.#request('/git/refs', {
143
+ method: 'POST',
144
+ body: { ref: `refs/heads/${input.branch}`, sha: input.fromSha },
145
+ signal: input.signal,
146
+ expectedFailures: [422],
147
+ })
148
+ if (result.ok) return decodeRef(result.body, input.branch)
149
+ // GitHub answers 422 both when the ref already exists (e.g. a concurrent create) and when `fromSha` is unknown.
150
+ const raced = await this.readRef(input.branch, input.signal)
151
+ if (raced === null) throw new GitHubNotFoundError()
152
+ return requireBranchAt(raced, input.fromSha)
153
+ }
154
+
155
+ async commitFiles(input: GitHubCommitFilesInput): Promise<GitHubCommit> {
156
+ validateBranch(input.branch)
157
+ validateSha(input.expectedHeadSha)
158
+ validateText(input.message, MAX_COMMIT_MESSAGE_BYTES, false)
159
+ validateText(input.author.name, 256, false)
160
+ validateText(input.author.email, 256, false)
161
+ if (hasAsciiControl(input.author.name) || !/^[^\s<>@]+@[^\s<>@]+$/.test(input.author.email)) throw configurationError()
162
+ const changes = treeChanges(input.changes)
163
+
164
+ // Known limit: REST has no compare-and-swap, so a concurrent reset to an ancestor still lets the non-force PATCH fast-forward.
165
+ const head = await this.readRef(input.branch, input.signal)
166
+ if (head?.sha !== input.expectedHeadSha) throw new GitHubStaleHeadError()
167
+ const parent = await this.#readCommit(input.expectedHeadSha, input.signal)
168
+ const tree = await this.#resolveModes(changes, parent.treeSha, input.signal)
169
+
170
+ const createdTree = await this.#request('/git/trees', {
171
+ method: 'POST',
172
+ body: { base_tree: parent.treeSha, tree },
173
+ signal: input.signal,
174
+ maxResponseBytes: MAX_TREE_RESPONSE_BYTES,
175
+ })
176
+ if (!createdTree.ok) throw requestStatusError(createdTree.status)
177
+ const treeSha = decodeCreatedTreeSha(createdTree.body)
178
+
179
+ const author = { name: input.author.name, email: input.author.email }
180
+ const created = await this.#request('/git/commits', {
181
+ method: 'POST',
182
+ body: { message: input.message, tree: treeSha, parents: [parent.sha], author, committer: author },
183
+ signal: input.signal,
184
+ maxResponseBytes: MAX_COMMIT_RESPONSE_BYTES,
185
+ })
186
+ if (!created.ok) throw requestStatusError(created.status)
187
+ const commit = decodeCommit(created.body)
188
+ if (commit.treeSha !== treeSha || commit.parents.length !== 1 || commit.parents[0] !== parent.sha) throw responseError()
189
+
190
+ const moved = await this.#request(`/git/refs/heads/${encodeBranch(input.branch)}`, {
191
+ method: 'PATCH',
192
+ body: { sha: commit.sha, force: false },
193
+ signal: input.signal,
194
+ expectedFailures: [422],
195
+ })
196
+ if (!moved.ok) {
197
+ // 422 is both "not a fast forward" and a refusal such as branch protection; only a moved head is stale.
198
+ const current = await this.readRef(input.branch, input.signal)
199
+ if (current?.sha !== input.expectedHeadSha) throw new GitHubStaleHeadError()
200
+ throw requestStatusError(moved.status)
201
+ }
202
+ if (decodeRef(moved.body, input.branch).sha !== commit.sha) throw responseError()
203
+ return commit
204
+ }
205
+
206
+ async openPullRequest(input: GitHubOpenPullRequestInput): Promise<GitHubPullRequestRef> {
207
+ validateBranch(input.head)
208
+ validateBranch(input.base)
209
+ if (input.head === input.base) throw configurationError()
210
+ validateText(input.title, MAX_PULL_REQUEST_TITLE_BYTES, false)
211
+ validateText(input.body, MAX_PULL_REQUEST_BODY_BYTES, true)
212
+ const created = await this.#request('/pulls', {
213
+ method: 'POST',
214
+ body: { title: input.title, body: input.body, head: input.head, base: input.base },
215
+ signal: input.signal,
216
+ maxResponseBytes: MAX_PULL_REQUEST_RESPONSE_BYTES,
217
+ expectedFailures: [422],
218
+ })
219
+ if (created.ok) return decodePullRequest(created.body, true)
220
+ // 422 covers "a pull request already exists" among other validation failures; only an open match recovers it.
221
+ const query = new URLSearchParams({ state: 'open', head: `${this.#config.owner}:${input.head}`, base: input.base, per_page: '1' })
222
+ const listed = await this.#request(`/pulls?${query}`, { signal: input.signal, maxResponseBytes: MAX_PULL_REQUEST_RESPONSE_BYTES })
223
+ if (!listed.ok) throw requestStatusError(listed.status)
224
+ const existing = decodePullRequestList(listed.body)[0]
225
+ if (existing === undefined) throw requestStatusError(created.status)
226
+ return decodePullRequest(existing, false)
227
+ }
228
+
229
+ /** Keeps an edited executable's mode, and refuses to delete anything but an existing file. */
230
+ async #resolveModes(changes: readonly TreeChange[], rootSha: string, signal: AbortSignal | undefined): Promise<TreeChange[]> {
231
+ const head = this.#treeWalker(rootSha, signal)
232
+ const result: TreeChange[] = []
233
+ for (const change of changes) {
234
+ const existing = await head.find(change.path)
235
+ const isFile = existing?.type === 'blob'
236
+ if (change.content === undefined && !isFile) throw configurationError()
237
+ result.push(isFile && existing.mode === '100755' ? { ...change, mode: '100755' } : change)
238
+ }
239
+ return result
240
+ }
241
+
242
+ #treeWalker(rootSha: string, signal: AbortSignal | undefined): TreeWalker {
243
+ return new TreeWalker(rootSha, (treeSha) => this.#readGitObject(`/git/trees/${treeSha}`, signal, MAX_TREE_RESPONSE_BYTES))
244
+ }
245
+
246
+ async #readCommit(sha: string, signal: AbortSignal | undefined): Promise<GitHubCommit> {
247
+ const commit = decodeCommit(await this.#readGitObject(`/git/commits/${sha}`, signal, MAX_COMMIT_RESPONSE_BYTES))
248
+ if (commit.sha !== sha) throw responseError()
249
+ return commit
250
+ }
251
+
252
+ /** Reads a commit, tree or blob by sha; GitHub answers 404 or 422 for an unknown one. */
253
+ async #readGitObject(path: string, signal: AbortSignal | undefined, maxResponseBytes?: number): Promise<unknown> {
254
+ const result = await this.#request(path, { signal, maxResponseBytes, expectedFailures: [404, 422] })
255
+ if (!result.ok) throw new GitHubNotFoundError()
256
+ return result.body
257
+ }
258
+
259
+ async #request(path: string, options: RequestOptions): Promise<RequestResult> {
260
+ const { token } = this.#config
261
+ if (token.expiresAt <= this.#config.now()) throw new Error('GitHub repository token expired')
262
+ const cancellation = createCancellation(options.signal, this.#config.timeoutMs)
263
+ try {
264
+ cancellation.throwIfCancelled()
265
+ const headers = new Headers({
266
+ authorization: `Bearer ${token.token}`,
267
+ accept: GITHUB_ACCEPT,
268
+ 'x-github-api-version': GITHUB_API_VERSION,
269
+ 'user-agent': GITHUB_USER_AGENT,
270
+ })
271
+ if (options.body !== undefined) headers.set('content-type', 'application/json')
272
+ let response: Response
273
+ try {
274
+ response = await this.#config.fetch(`${this.#config.apiBaseUrl}/repos/${this.#config.owner}/${this.#config.repository}${path}`, {
275
+ method: options.method ?? 'GET',
276
+ headers,
277
+ ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
278
+ redirect: 'error',
279
+ signal: cancellation.signal,
280
+ })
281
+ } catch {
282
+ cancellation.throwIfCancelled()
283
+ throw new Error('GitHub repository request failed')
284
+ }
285
+ cancellation.throwIfCancelled()
286
+ if (!response.ok) {
287
+ void response.body?.cancel().catch(() => {})
288
+ if (options.expectedFailures?.includes(response.status) === true) return { ok: false, status: response.status }
289
+ throw requestStatusError(response.status)
290
+ }
291
+ return { ok: true, body: await readBoundedJson(response, cancellation, options.maxResponseBytes) }
292
+ } finally {
293
+ cancellation.dispose()
294
+ }
295
+ }
296
+ }
297
+
298
+ /** Resolves repository paths through non-recursive tree reads, caching each directory once. */
299
+ class TreeWalker {
300
+ readonly #directories = new Map<string, Promise<ReadonlyMap<string, GitHubTreeEntry>>>()
301
+
302
+ constructor(
303
+ private readonly rootSha: string,
304
+ private readonly fetchTree: (treeSha: string) => Promise<unknown>,
305
+ ) {}
306
+
307
+ async find(path: string): Promise<GitHubTreeEntry | null> {
308
+ let treeSha = this.rootSha
309
+ const parts = path.split('/')
310
+ for (const [index, part] of parts.entries()) {
311
+ const entry = (await this.#read(treeSha)).get(part)
312
+ if (entry === undefined) return null
313
+ if (index === parts.length - 1) return entry
314
+ if (entry.type !== 'tree') return null
315
+ treeSha = entry.sha
316
+ }
317
+ return null
318
+ }
319
+
320
+ #read(treeSha: string): Promise<ReadonlyMap<string, GitHubTreeEntry>> {
321
+ let directory = this.#directories.get(treeSha)
322
+ if (directory === undefined) {
323
+ directory = this.#load(treeSha)
324
+ this.#directories.set(treeSha, directory)
325
+ }
326
+ return directory
327
+ }
328
+
329
+ async #load(treeSha: string): Promise<ReadonlyMap<string, GitHubTreeEntry>> {
330
+ const tree = decodeTree(await this.fetchTree(treeSha), treeSha)
331
+ // A truncated directory listing cannot prove a path is absent.
332
+ if (tree.truncated) throw responseError()
333
+ return new Map(tree.entries.map((entry) => [entry.path, entry]))
334
+ }
335
+ }
336
+
337
+ function requireBranchAt(ref: GitHubRef, sha: string): GitHubRef {
338
+ if (ref.sha !== sha) throw new GitHubBranchConflictError()
339
+ return ref
340
+ }
341
+
342
+ function treeChanges(changes: GitHubCommitFilesInput['changes']): TreeChange[] {
343
+ if (changes.length === 0 || changes.length > MAX_CHANGED_FILES) throw configurationError()
344
+ const paths = new Set<string>()
345
+ let bytes = 0
346
+ const tree = changes.map((change): TreeChange => {
347
+ validatePath(change.path)
348
+ if (paths.has(change.path)) throw configurationError()
349
+ paths.add(change.path)
350
+ if (change.content === null) return { path: change.path, mode: '100644', type: 'blob', sha: null }
351
+ validateText(change.content, MAX_FILE_BYTES, true)
352
+ bytes += utf8Length(change.content)
353
+ if (bytes > MAX_CHANGED_BYTES) throw configurationError()
354
+ return { path: change.path, mode: '100644', type: 'blob', content: change.content }
355
+ })
356
+ for (const path of paths) {
357
+ const parts = path.split('/')
358
+ for (let length = 1; length < parts.length; length++) {
359
+ if (paths.has(parts.slice(0, length).join('/'))) throw configurationError()
360
+ }
361
+ }
362
+ return tree
363
+ }
package/src/transport.ts CHANGED
@@ -2,6 +2,7 @@ import { responseError } from './errors'
2
2
 
3
3
  export const GITHUB_ACCEPT = 'application/vnd.github+json'
4
4
  export const GITHUB_API_VERSION = '2022-11-28'
5
+ export const GITHUB_USER_AGENT = 'vozka'
5
6
  const MAX_RESPONSE_BYTES = 64 * 1024
6
7
 
7
8
  interface RequestCancellation {
@@ -43,10 +44,15 @@ export function createCancellation(callerSignal: AbortSignal | undefined, timeou
43
44
  }
44
45
  }
45
46
 
46
- export async function readBoundedJson(response: Response, cancellation: RequestCancellation): Promise<unknown> {
47
+ export async function readBoundedJson(
48
+ response: Response,
49
+ cancellation: RequestCancellation,
50
+ maxResponseBytes = MAX_RESPONSE_BYTES,
51
+ ): Promise<unknown> {
47
52
  cancellation.throwIfCancelled()
48
53
  const contentLength = response.headers.get('content-length')
49
- if (contentLength !== null && /^[0-9]+$/.test(contentLength) && Number(contentLength) > MAX_RESPONSE_BYTES) {
54
+ if (contentLength !== null && /^[0-9]+$/.test(contentLength) && Number(contentLength) > maxResponseBytes) {
55
+ void response.body?.cancel().catch(() => {})
50
56
  throw responseError()
51
57
  }
52
58
  const reader = response.body?.getReader()
@@ -62,7 +68,7 @@ export async function readBoundedJson(response: Response, cancellation: RequestC
62
68
  break
63
69
  }
64
70
  total += result.value.byteLength
65
- if (total > MAX_RESPONSE_BYTES) {
71
+ if (total > maxResponseBytes) {
66
72
  throw responseError()
67
73
  }
68
74
  chunks.push(result.value)
package/src/types.ts CHANGED
@@ -31,7 +31,8 @@ export interface GitHubAppIdentity {
31
31
  readonly htmlUrl: string
32
32
  readonly public: boolean
33
33
  readonly permissions: {
34
- readonly contents: 'read'
34
+ readonly contents: 'read' | 'write'
35
+ readonly pull_requests?: 'read' | 'write'
35
36
  }
36
37
  readonly events: readonly string[]
37
38
  readonly owner: {
package/src/validation.ts CHANGED
@@ -12,8 +12,12 @@ export const appReferenceSchema = z.object({
12
12
  })
13
13
 
14
14
  const appIdentitySchema = appReferenceSchema.extend({
15
- // Strict for least privilege: an App granted any permission beyond read-only contents is refused.
16
- permissions: z.object({ contents: z.literal('read'), metadata: z.literal('read').optional() }).strict(),
15
+ // Strict for least privilege: anything beyond contents, pull requests and metadata is refused.
16
+ permissions: z.object({
17
+ contents: z.enum(['read', 'write']),
18
+ pull_requests: z.enum(['read', 'write']).optional(),
19
+ metadata: z.literal('read').optional(),
20
+ }).strict(),
17
21
  events: z.array(z.string().min(1).max(100)).max(100).refine((events) => events.includes('push')),
18
22
  owner: z.object({ login: z.string().min(1).max(100).regex(REPOSITORY_COMPONENT_PATTERN), type: z.enum(['Organization', 'User']) }),
19
23
  })
@@ -78,7 +82,7 @@ export function validateWebhookSecret(value: string): void {
78
82
  export function decodeAppIdentity(value: unknown): Omit<GitHubAppIdentity, 'public'> | null {
79
83
  const result = appIdentitySchema.safeParse(value)
80
84
  if (!result.success) return null
81
- const { id, slug, html_url: htmlUrl, permissions: { contents }, events, owner: { login, type } } = result.data
85
+ const { id, slug, html_url: htmlUrl, permissions: { contents, pull_requests: pullRequests }, events, owner: { login, type } } = result.data
82
86
  let parsedHtmlUrl: URL
83
87
  try {
84
88
  parsedHtmlUrl = new URL(htmlUrl)
@@ -92,7 +96,8 @@ export function decodeAppIdentity(value: unknown): Omit<GitHubAppIdentity, 'publ
92
96
  ) {
93
97
  return null
94
98
  }
95
- return { id, slug, htmlUrl, permissions: { contents }, events, owner: { login, type } }
99
+ const permissions = pullRequests === undefined ? { contents } : { contents, pull_requests: pullRequests }
100
+ return { id, slug, htmlUrl, permissions, events, owner: { login, type } }
96
101
  }
97
102
 
98
103
  export function sameAppIdentity(
@@ -101,6 +106,7 @@ export function sameAppIdentity(
101
106
  ): boolean {
102
107
  return left.id === right.id && left.slug === right.slug && left.htmlUrl === right.htmlUrl
103
108
  && left.owner.login === right.owner.login && left.owner.type === right.owner.type
109
+ && left.permissions.contents === right.permissions.contents && left.permissions.pull_requests === right.permissions.pull_requests
104
110
  && left.events.length === right.events.length && left.events.every((event, index) => event === right.events[index])
105
111
  }
106
112