mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-03 01:23:31 +01:00
fix(viewers): keep authors out of PR commits, branches and gist binaries
- Commit messages lose sign-off and co-author trailers, e-mail addresses and the fork owner in merge headlines; without the origin option merge headlines lose branch names too. - Branch names are shown only with the origin option. - Gists keep only images (hidden unless images are displayed); other binaries are never stored or served. Images share an 8 MB budget so the gist document stays under MongoDB's limit, and an unreadable image no longer fails the whole gist. - Review threads match the diff side, and outdated comments go to the end of their file instead of an unrelated line. - The diff parser no longer reads a removed '-- ' line as a file header. - Each diff file renders as its own component from escaped HTML, so large diffs don't re-render on scroll or collapse. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
98bf382fa8
commit
023e3f9a51
16 files changed
+300
-128
No files matched your search
+46
-24
@@ -17,8 +17,13 @@ import config from "../config";
|
||||
import { octokit, ownerGitHubAccessRequired } from "./GitHubUtils";
|
||||
import { ContentAnonimizer, classifyByName } from "./anonymize-utils";
|
||||
|
||||
// Binary gist files above this size are listed but not stored.
|
||||
const GIST_BINARY_LIMIT = 10 * 1024 * 1024;
|
||||
// Images are the only binary gist files kept: other binaries (PDF, Office,
|
||||
// archives) carry metadata the text anonymizer cannot reach, so they are
|
||||
// listed but never stored or served. The whole gist is one MongoDB document
|
||||
// (16 MB max, base64 adds a third), so images share one budget.
|
||||
const GIST_IMAGE_LIMIT = 4 * 1024 * 1024;
|
||||
const GIST_IMAGE_BUDGET = 8 * 1024 * 1024;
|
||||
const GIST_RAW_ORIGIN = "https://gist.githubusercontent.com/";
|
||||
const isImageFile = (name: string) => /\.(png|jpe?g|gif|webp|bmp|ico|avif|tiff?)$/i.test(name || "");
|
||||
import { createLogger } from "./logger";
|
||||
|
||||
@@ -113,17 +118,31 @@ export default class Gist {
|
||||
}),
|
||||
]);
|
||||
|
||||
let imageBudget = GIST_IMAGE_BUDGET;
|
||||
const files = await Promise.all(Object.values(gistInfo.data.files || {})
|
||||
.filter((f): f is NonNullable<typeof f> => !!f)
|
||||
.map(async (f) => {
|
||||
// Binary files (images, PDF, media) are kept byte for byte as base64:
|
||||
// they cannot be anonymized as text, and UTF-8 decoding corrupts them.
|
||||
// Binary files cannot be anonymized as text, and UTF-8 decoding
|
||||
// corrupts them: images keep their bytes as base64, others none.
|
||||
if (f.filename && classifyByName(f.filename) === false) {
|
||||
const meta = { filename: f.filename, language: f.language || undefined, size: f.size || 0, type: f.type || undefined, encoding: "base64" as const };
|
||||
if ((f.size || 0) > GIST_BINARY_LIMIT || !f.raw_url) return { ...meta, content: "", tooLarge: (f.size || 0) > GIST_BINARY_LIMIT || undefined };
|
||||
const raw = await fetch(f.raw_url, { signal: AbortSignal.timeout(30000) });
|
||||
if (!raw.ok) throw new Error(`Gist file download failed (${raw.status})`);
|
||||
return { ...meta, content: Buffer.from(await raw.arrayBuffer()).toString("base64") };
|
||||
const size = f.size || 0;
|
||||
const meta = { filename: f.filename, language: f.language || undefined, size, type: f.type || undefined, encoding: "base64" as const, content: "" };
|
||||
if (!isImageFile(f.filename)) return meta;
|
||||
// Reserve before the await so concurrent downloads share the budget.
|
||||
if (size > GIST_IMAGE_LIMIT || size > imageBudget) return { ...meta, tooLarge: true };
|
||||
imageBudget -= size;
|
||||
if (!f.raw_url?.startsWith(GIST_RAW_ORIGIN)) return meta;
|
||||
try {
|
||||
const raw = await fetch(f.raw_url, { signal: AbortSignal.timeout(30000) });
|
||||
if (!raw.ok) throw new Error(`status ${raw.status}`);
|
||||
const bytes = Buffer.from(await raw.arrayBuffer());
|
||||
if (bytes.length > GIST_IMAGE_LIMIT) return { ...meta, tooLarge: true };
|
||||
return { ...meta, content: bytes.toString("base64") };
|
||||
} catch (error) {
|
||||
// One unreadable image must not make the whole gist unavailable.
|
||||
logger.warn("gist image unavailable", { code: "gist_file_unavailable", errorType: error instanceof Error ? error.name : undefined });
|
||||
return meta;
|
||||
}
|
||||
}
|
||||
let content = (f as typeof f & { encoding?: string }).encoding === "base64"
|
||||
? Buffer.from(f.content || "", "base64").toString("utf8")
|
||||
@@ -350,26 +369,29 @@ export default class Gist {
|
||||
output.ownerLogin = anonymizer.anonymize(g?.ownerLogin || "");
|
||||
}
|
||||
if (this.options.content) {
|
||||
output.files = (g?.files || []).map((f) => f.encoding === "base64"
|
||||
? {
|
||||
// Bytes pass through like a repository's binary files; images
|
||||
// follow the "Display images" option.
|
||||
filename: anonymizer.anonymize(f.filename),
|
||||
content: f.tooLarge || (this.options.image === false && isImageFile(f.filename)) ? undefined : f.content,
|
||||
language: f.language,
|
||||
size: f.size,
|
||||
type: f.type,
|
||||
encoding: "base64",
|
||||
tooLarge: f.tooLarge || undefined,
|
||||
hidden: this.options.image === false && isImageFile(f.filename) ? true : undefined,
|
||||
}
|
||||
: {
|
||||
output.files = (g?.files || []).map((f) => {
|
||||
if (f.encoding !== "base64") return {
|
||||
filename: anonymizer.anonymize(f.filename),
|
||||
content: anonymizer.anonymize(f.content),
|
||||
language: f.language,
|
||||
size: f.size,
|
||||
type: f.type,
|
||||
});
|
||||
};
|
||||
// Images follow "Display images" as in repositories (off unless set);
|
||||
// other binaries are never served, even if stored by an older version.
|
||||
const image = isImageFile(f.filename);
|
||||
const hidden = image && !this.options.image;
|
||||
return {
|
||||
filename: anonymizer.anonymize(f.filename),
|
||||
content: f.tooLarge || hidden || !image || !f.content ? undefined : f.content,
|
||||
language: f.language,
|
||||
size: f.size,
|
||||
type: f.type,
|
||||
encoding: "base64",
|
||||
tooLarge: f.tooLarge || undefined,
|
||||
hidden: hidden || undefined,
|
||||
};
|
||||
});
|
||||
}
|
||||
if (this.options.comments) {
|
||||
output.comments = g?.comments?.map((comment) => {
|
||||
|
||||
+37
-8
@@ -25,13 +25,13 @@ type ReviewComment = NonNullable<IAnonymizedPullRequestDocument["pullRequest"]["
|
||||
* comment ids never leave the server.
|
||||
*/
|
||||
export function reviewThreads(comments: ReviewComment[]) {
|
||||
const threads: { path: string; line?: number; comments: ReviewComment[] }[] = [];
|
||||
const threads: { path: string; line?: number; side?: "LEFT" | "RIGHT"; comments: ReviewComment[] }[] = [];
|
||||
const byId = new Map<number, (typeof threads)[number]>();
|
||||
const sorted = [...comments].sort((a, b) => new Date(a.creationDate).getTime() - new Date(b.creationDate).getTime());
|
||||
for (const comment of sorted) {
|
||||
let thread = comment.inReplyTo != null ? byId.get(comment.inReplyTo) : undefined;
|
||||
if (!thread) {
|
||||
thread = { path: comment.path, line: comment.line ?? undefined, comments: [] };
|
||||
thread = { path: comment.path, line: comment.line ?? undefined, side: comment.side, comments: [] };
|
||||
threads.push(thread);
|
||||
}
|
||||
thread.comments.push(comment);
|
||||
@@ -40,6 +40,25 @@ export function reviewThreads(comments: ReviewComment[]) {
|
||||
return threads;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove what identifies people from a commit message before the term
|
||||
* anonymizer runs: trailers (Signed-off-by, Co-authored-by, ...), e-mail
|
||||
* addresses, and the fork owner in merge headlines. Without the origin option,
|
||||
* merge headlines also lose their branch names.
|
||||
*/
|
||||
export function commitMessage(message: string, opts: { origin: boolean }) {
|
||||
const lines = message.split(/\r?\n/)
|
||||
.filter((line) => !/^\s*[A-Za-z][A-Za-z-]*-by\s*:/i.test(line))
|
||||
.map((line) => line.replace(/<?[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+>?/g, "").replace(/\s+$/, ""));
|
||||
const merge = lines[0]?.match(/^Merge pull request (#\d+) from (\S+)/);
|
||||
if (merge) lines[0] = opts.origin ? `Merge pull request ${merge[1]} from ${merge[2].replace(/^[^/]+\//, "")}` : `Merge pull request ${merge[1]}`;
|
||||
else if (/^Merge (remote-tracking )?branch/.test(lines[0] || "")) {
|
||||
lines[0] = opts.origin ? lines[0].replace(/ of \S+/, "") : "Merge branch";
|
||||
}
|
||||
while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export default class PullRequest {
|
||||
private _model: IAnonymizedPullRequestDocument;
|
||||
owner: User;
|
||||
@@ -146,7 +165,7 @@ export default class PullRequest {
|
||||
in_reply_to_id?: number;
|
||||
path?: string;
|
||||
line?: number | null;
|
||||
original_line?: number | null;
|
||||
side?: "LEFT" | "RIGHT" | null;
|
||||
body?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
@@ -185,7 +204,11 @@ export default class PullRequest {
|
||||
commentId: c.id,
|
||||
inReplyTo: c.in_reply_to_id,
|
||||
path: c.path || "",
|
||||
line: c.line ?? c.original_line ?? undefined,
|
||||
// An outdated comment has no line in the current diff; its
|
||||
// original_line would point at an unrelated line, so it goes at the
|
||||
// end of its file instead.
|
||||
line: c.line ?? undefined,
|
||||
side: c.line != null && c.side ? c.side : undefined,
|
||||
body: c.body || "",
|
||||
author: c.user?.login || "",
|
||||
creationDate: new Date(c.created_at),
|
||||
@@ -439,16 +462,21 @@ export default class PullRequest {
|
||||
if (this.options.username && this._model.pullRequest.author) {
|
||||
output.author = anonymizer.anonymize(this._model.pullRequest.author);
|
||||
}
|
||||
// Branch names are labels like the title: shown through the anonymizer.
|
||||
if (this._model.pullRequest.baseRef) output.baseRef = anonymizer.anonymize(this._model.pullRequest.baseRef);
|
||||
if (this._model.pullRequest.headRef) output.headRef = anonymizer.anonymize(this._model.pullRequest.headRef);
|
||||
// Branch names often carry a username or lab name ("asmith/fix"), so they
|
||||
// are part of the origin, like the repository names.
|
||||
if (this.options.origin) {
|
||||
if (this._model.pullRequest.baseRef) output.baseRef = anonymizer.anonymize(this._model.pullRequest.baseRef);
|
||||
if (this._model.pullRequest.headRef) output.headRef = anonymizer.anonymize(this._model.pullRequest.headRef);
|
||||
}
|
||||
if (this.options.diff) {
|
||||
output.diff = anonymizer.anonymize(this._model.pullRequest.diff);
|
||||
// Pull requests downloaded before commits were stored have none.
|
||||
if (this._model.pullRequest.commits?.length) {
|
||||
// No SHAs: a commit hash identifies the source repository.
|
||||
output.commits = this._model.pullRequest.commits.map((commit) => {
|
||||
const o: Record<string, unknown> = { message: anonymizer.anonymize(commit.message || "") };
|
||||
const o: Record<string, unknown> = {
|
||||
message: anonymizer.anonymize(commitMessage(commit.message || "", { origin: !!this.options.origin })),
|
||||
};
|
||||
if (this.options.username) o.author = anonymizer.anonymize(commit.author || "");
|
||||
if (this.options.date) o.date = commit.date;
|
||||
return o;
|
||||
@@ -459,6 +487,7 @@ export default class PullRequest {
|
||||
output.reviewComments = reviewThreads(this._model.pullRequest.reviewComments).map((thread) => ({
|
||||
path: anonymizer.anonymize(thread.path),
|
||||
line: thread.line,
|
||||
side: thread.side,
|
||||
comments: thread.comments.map((comment) => {
|
||||
const o: Record<string, unknown> = {};
|
||||
if (this.options.body) o.body = anonymizer.anonymize(comment.body);
|
||||
|
||||
@@ -60,7 +60,7 @@ const AnonymizedGistSchema = new Schema({
|
||||
// nested `{ type: String }` the whole object is compiled as an array
|
||||
// of strings and file objects are silently dropped on save.
|
||||
type: { type: String },
|
||||
// Binary files (images, PDF, media) keep their bytes as base64.
|
||||
// Binary files are listed; only images keep their bytes, as base64.
|
||||
encoding: String,
|
||||
tooLarge: Boolean,
|
||||
},
|
||||
|
||||
@@ -77,6 +77,8 @@ const AnonymizedPullRequestSchema = new Schema({
|
||||
inReplyTo: Number,
|
||||
path: String,
|
||||
line: Number,
|
||||
/** LEFT: a removed line (old numbering); RIGHT: an added or context line. */
|
||||
side: String,
|
||||
body: String,
|
||||
author: String,
|
||||
creationDate: Date,
|
||||
|
||||
@@ -58,6 +58,7 @@ export interface IAnonymizedPullRequest {
|
||||
inReplyTo?: number;
|
||||
path: string;
|
||||
line?: number;
|
||||
side?: "LEFT" | "RIGHT";
|
||||
body: string;
|
||||
author: string;
|
||||
creationDate: Date;
|
||||
|
||||
Reference in new issue
Block a user