|
| 1 | +import { spawnSync } from "node:child_process"; |
| 2 | + |
| 3 | +const MAX_REVIEW_FILES = 80; |
| 4 | +const MAX_GIT_OUTPUT_BYTES = 4 * 1024 * 1024; |
| 5 | +const MAX_REVIEW_BLOB_BYTES = 4 * 1024 * 1024; |
| 6 | +const GIT_OBJECT_ID = /^[0-9a-f]{40,64}$/i; |
| 7 | + |
| 8 | +type ReviewBlobFile = { |
| 9 | + filename?: unknown; |
| 10 | + previous_filename?: unknown; |
| 11 | + status?: unknown; |
| 12 | +}; |
| 13 | + |
| 14 | +export type ReviewBlobHydration = { |
| 15 | + hydrated: boolean; |
| 16 | + blobs: number; |
| 17 | +}; |
| 18 | + |
| 19 | +export function hydratePullRequestReviewBlobs({ |
| 20 | + targetDir, |
| 21 | + baseSha, |
| 22 | + headSha, |
| 23 | + files, |
| 24 | + resolveBlobSizes, |
| 25 | +}: { |
| 26 | + targetDir: string; |
| 27 | + baseSha: string; |
| 28 | + headSha: string; |
| 29 | + files: readonly unknown[]; |
| 30 | + resolveBlobSizes?: (objectIds: readonly string[]) => ReadonlyMap<string, number>; |
| 31 | +}): ReviewBlobHydration { |
| 32 | + if ( |
| 33 | + !GIT_OBJECT_ID.test(baseSha) || |
| 34 | + !GIT_OBJECT_ID.test(headSha) || |
| 35 | + files.length > MAX_REVIEW_FILES |
| 36 | + ) { |
| 37 | + return { hydrated: false, blobs: 0 }; |
| 38 | + } |
| 39 | + |
| 40 | + const basePaths = new Set<string>(); |
| 41 | + const headPaths = new Set<string>(); |
| 42 | + for (const value of files) { |
| 43 | + if (!value || typeof value !== "object") return { hydrated: false, blobs: 0 }; |
| 44 | + const file = value as ReviewBlobFile; |
| 45 | + const filename = safeReviewPath(file.filename); |
| 46 | + if (!filename) return { hydrated: false, blobs: 0 }; |
| 47 | + const previous = |
| 48 | + file.previous_filename === undefined ? filename : safeReviewPath(file.previous_filename); |
| 49 | + if (!previous) return { hydrated: false, blobs: 0 }; |
| 50 | + const status = typeof file.status === "string" ? file.status.toLowerCase() : ""; |
| 51 | + if (status !== "added" && status !== "a") basePaths.add(previous); |
| 52 | + if (status !== "removed" && status !== "deleted" && status !== "d") { |
| 53 | + headPaths.add(filename); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + const objectIds = new Set<string>(); |
| 58 | + for (const [sha, paths] of [ |
| 59 | + [baseSha, basePaths], |
| 60 | + [headSha, headPaths], |
| 61 | + ] as const) { |
| 62 | + if (paths.size === 0) continue; |
| 63 | + const tree = spawnSync("git", ["--literal-pathspecs", "ls-tree", "-z", sha, "--", ...paths], { |
| 64 | + cwd: targetDir, |
| 65 | + encoding: "utf8", |
| 66 | + env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, |
| 67 | + maxBuffer: MAX_GIT_OUTPUT_BYTES, |
| 68 | + }); |
| 69 | + if (tree.error || tree.status !== 0) return { hydrated: false, blobs: 0 }; |
| 70 | + for (const entry of tree.stdout.split("\0")) { |
| 71 | + if (!entry) continue; |
| 72 | + const match = entry.match(/^\d{6} (blob|commit) ([0-9a-f]{40,64})\t(.*)$/s); |
| 73 | + if (!match || !paths.has(match[3]!)) return { hydrated: false, blobs: 0 }; |
| 74 | + if (match[1] === "blob") objectIds.add(match[2]!); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + if (objectIds.size === 0) return { hydrated: true, blobs: 0 }; |
| 79 | + const objectInput = `${[...objectIds].join("\n")}\n`; |
| 80 | + const localObjects = spawnSync( |
| 81 | + "git", |
| 82 | + ["cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)"], |
| 83 | + { |
| 84 | + cwd: targetDir, |
| 85 | + encoding: "utf8", |
| 86 | + env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_NO_LAZY_FETCH: "1" }, |
| 87 | + input: objectInput, |
| 88 | + maxBuffer: MAX_GIT_OUTPUT_BYTES, |
| 89 | + }, |
| 90 | + ); |
| 91 | + if (localObjects.error || localObjects.status !== 0) return { hydrated: false, blobs: 0 }; |
| 92 | + const found = localObjects.stdout.trim().split("\n"); |
| 93 | + if (found.length !== objectIds.size) return { hydrated: false, blobs: 0 }; |
| 94 | + const sizes = new Map<string, number>(); |
| 95 | + const missing = new Set<string>(); |
| 96 | + for (const entry of found) { |
| 97 | + const [objectId, type, size] = entry.split(" "); |
| 98 | + if (!objectId || !objectIds.has(objectId) || (type !== "blob" && type !== "missing")) { |
| 99 | + return { hydrated: false, blobs: 0 }; |
| 100 | + } |
| 101 | + if (type === "missing") missing.add(objectId); |
| 102 | + else sizes.set(objectId, Number(size)); |
| 103 | + } |
| 104 | + if (missing.size > 0) { |
| 105 | + if (!resolveBlobSizes) return { hydrated: false, blobs: 0 }; |
| 106 | + let remoteSizes: ReadonlyMap<string, number>; |
| 107 | + try { |
| 108 | + remoteSizes = resolveBlobSizes([...missing]); |
| 109 | + } catch { |
| 110 | + return { hydrated: false, blobs: 0 }; |
| 111 | + } |
| 112 | + for (const objectId of missing) { |
| 113 | + const bytes = remoteSizes.get(objectId); |
| 114 | + if (bytes === undefined) return { hydrated: false, blobs: 0 }; |
| 115 | + sizes.set(objectId, bytes); |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + let objectBytes = 0; |
| 120 | + let skippedOversizedBlob = false; |
| 121 | + const bounded = new Set<string>(); |
| 122 | + for (const objectId of objectIds) { |
| 123 | + const bytes = sizes.get(objectId); |
| 124 | + if ( |
| 125 | + bytes === undefined || |
| 126 | + !Number.isSafeInteger(bytes) || |
| 127 | + bytes < 0 || |
| 128 | + bytes > MAX_REVIEW_BLOB_BYTES - objectBytes |
| 129 | + ) { |
| 130 | + skippedOversizedBlob = true; |
| 131 | + continue; |
| 132 | + } |
| 133 | + bounded.add(objectId); |
| 134 | + objectBytes += bytes; |
| 135 | + } |
| 136 | + |
| 137 | + const boundedMissing = [...missing].filter((objectId) => bounded.has(objectId)); |
| 138 | + if (boundedMissing.length > 0) { |
| 139 | + const fetched = spawnSync( |
| 140 | + "git", |
| 141 | + [ |
| 142 | + "-c", |
| 143 | + "fetch.negotiationAlgorithm=noop", |
| 144 | + "fetch", |
| 145 | + "origin", |
| 146 | + "--no-tags", |
| 147 | + "--no-write-fetch-head", |
| 148 | + "--recurse-submodules=no", |
| 149 | + "--filter=blob:none", |
| 150 | + "--stdin", |
| 151 | + ], |
| 152 | + { |
| 153 | + cwd: targetDir, |
| 154 | + encoding: "utf8", |
| 155 | + env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, |
| 156 | + input: `${boundedMissing.join("\n")}\n`, |
| 157 | + maxBuffer: MAX_GIT_OUTPUT_BYTES, |
| 158 | + }, |
| 159 | + ); |
| 160 | + if (fetched.error || fetched.status !== 0) return { hydrated: false, blobs: 0 }; |
| 161 | + } |
| 162 | + return { hydrated: !skippedOversizedBlob, blobs: bounded.size }; |
| 163 | +} |
| 164 | + |
| 165 | +export function githubReviewBlobSizes({ |
| 166 | + repository, |
| 167 | + objectIds, |
| 168 | + request, |
| 169 | +}: { |
| 170 | + repository: string; |
| 171 | + objectIds: readonly string[]; |
| 172 | + request: (query: string) => unknown; |
| 173 | +}): ReadonlyMap<string, number> { |
| 174 | + const match = repository.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/); |
| 175 | + if ( |
| 176 | + !match || |
| 177 | + match[1] === "." || |
| 178 | + match[1] === ".." || |
| 179 | + match[2] === "." || |
| 180 | + match[2] === ".." || |
| 181 | + objectIds.length > MAX_REVIEW_FILES * 2 |
| 182 | + ) { |
| 183 | + throw new Error("invalid bounded review blob metadata request"); |
| 184 | + } |
| 185 | + const objects = objectIds.map((objectId, index) => { |
| 186 | + if (!GIT_OBJECT_ID.test(objectId)) throw new Error("invalid review blob object ID"); |
| 187 | + return `b${index}: object(oid: "${objectId}") { ... on Blob { byteSize } }`; |
| 188 | + }); |
| 189 | + const query = `query { repository(owner: "${match[1]}", name: "${match[2]}") { ${objects.join(" ")} } }`; |
| 190 | + const response = request(query); |
| 191 | + if (!response || typeof response !== "object") throw new Error("invalid review blob response"); |
| 192 | + const data = (response as { data?: unknown }).data; |
| 193 | + if (!data || typeof data !== "object") throw new Error("missing review blob response data"); |
| 194 | + const values = (data as { repository?: unknown }).repository; |
| 195 | + if (!values || typeof values !== "object") throw new Error("missing review blob repository"); |
| 196 | + const result = new Map<string, number>(); |
| 197 | + for (const [index, objectId] of objectIds.entries()) { |
| 198 | + const object = (values as Record<string, unknown>)[`b${index}`]; |
| 199 | + const bytes = |
| 200 | + object && typeof object === "object" ? (object as { byteSize?: unknown }).byteSize : null; |
| 201 | + if (typeof bytes !== "number" || !Number.isSafeInteger(bytes) || bytes < 0) { |
| 202 | + throw new Error("invalid review blob size"); |
| 203 | + } |
| 204 | + result.set(objectId, bytes); |
| 205 | + } |
| 206 | + return result; |
| 207 | +} |
| 208 | + |
| 209 | +function safeReviewPath(value: unknown): string | null { |
| 210 | + if (typeof value !== "string" || !value || value.length > 4096) return null; |
| 211 | + if (value.startsWith("/") || value.includes("\\")) { |
| 212 | + return null; |
| 213 | + } |
| 214 | + for (let index = 0; index < value.length; index += 1) { |
| 215 | + const code = value.charCodeAt(index); |
| 216 | + if (code < 32 || code === 127) return null; |
| 217 | + } |
| 218 | + const parts = value.split("/"); |
| 219 | + if (parts.some((part) => !part || part === "." || part === ".." || part === ".git")) { |
| 220 | + return null; |
| 221 | + } |
| 222 | + return value; |
| 223 | +} |
0 commit comments