All files / src/evals scaffold.ts

79.38% Statements 77/97
67.94% Branches 53/78
100% Functions 12/12
79.38% Lines 77/97

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296                                                                                        1x 1x     5x 2x   3x       2x 2x 1x   1x       5x         6x 6x         6x       6x 6x 1x     5x 5x       5x       2x               2x       1x       2x 2x 2x 2x 2x                     2x 2x 2x                 3x 3x 1x   2x                             2x 2x             2x 2x       2x                                               1x                                   4x 4x 4x     4x 4x 4x         1x             1x 4x 4x 4x 4x 4x 4x   4x       1x 3x 3x 1x     2x 2x       2x 2x 2x 2x     2x 2x     1x       1x 1x   1x 2x 2x 2x             1x         2x             4x            
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join, posix } from 'node:path';
import { Octokit } from '@octokit/rest';
 
type PullRequestSide = 'base' | 'head';
 
export interface GitHubPullRequestRef {
  owner: string;
  repo: string;
  pullNumber: number;
}
 
export interface ScaffoldEvalOptions {
  url: string;
  category: string;
  side?: PullRequestSide;
  name?: string;
  evalsDir: string;
  force?: boolean;
}
 
export interface ScaffoldedEvalFile {
  sourcePath: string;
  fixturePath: string;
  ref: string;
}
 
export interface ScaffoldedEval {
  name: string;
  scenarioPath: string;
  files: ScaffoldedEvalFile[];
}
 
interface GitHubFileContent {
  content: string;
  ref: string;
}
 
interface PullFile {
  filename: string;
  status: string;
  previous_filename?: string;
}
 
const UNSAFE_FILENAME_CHARS = /[^a-zA-Z0-9._-]+/g;
const SAFE_PATH_SEGMENT = /^[a-zA-Z0-9._-]+$/;
 
function requireSafePathSegment(value: string, label: string): string {
  if (!SAFE_PATH_SEGMENT.test(value) || value === '.' || value === '..') {
    throw new Error(`Invalid ${label}: ${value}. Use only letters, numbers, ".", "_", or "-".`);
  }
  return value;
}
 
function requirePullRequestSide(value: PullRequestSide | undefined): PullRequestSide {
  const side = value ?? 'base';
  if (side !== 'base' && side !== 'head') {
    throw new Error(`Invalid pull request side: ${side}. Use "base" or "head".`);
  }
  return side;
}
 
function fromEvalsPath(evalsDir: string, relativePath: string): string {
  return join(evalsDir, ...relativePath.split('/'));
}
 
export function parseGitHubPullRequestUrl(url: string): GitHubPullRequestRef {
  let parsed: URL;
  try {
    parsed = new URL(url);
  } catch (error) {
    throw new Error(`Invalid GitHub URL: ${url}`, { cause: error });
  }
 
  Iif (parsed.hostname !== 'github.com') {
    throw new Error(`Expected github.com URL, got ${parsed.hostname}`);
  }
 
  const [owner, repo, kind, pullNumber] = parsed.pathname.split('/').filter(Boolean);
  if (!owner || !repo || kind !== 'pull' || !pullNumber) {
    throw new Error(`Expected GitHub pull request URL, got ${url}`);
  }
 
  const numericPullNumber = Number(pullNumber);
  Iif (!Number.isInteger(numericPullNumber) || numericPullNumber <= 0) {
    throw new Error(`Invalid pull request number in ${url}`);
  }
 
  return { owner, repo, pullNumber: numericPullNumber };
}
 
export function slugifyEvalName(value: string): string {
  const slug = value
    .toLowerCase()
    .replace(/['"]/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 80)
    .replace(/-+$/g, '');
 
  return slug || 'github-pr-eval';
}
 
function getGitHubToken(): string | undefined {
  return process.env['GITHUB_TOKEN'] ?? process.env['GH_TOKEN'];
}
 
function fixtureFilename(path: string, seen: Set<string>): string {
  const base = path.split('/').pop() || 'fixture';
  let candidate = base.replace(UNSAFE_FILENAME_CHARS, '_');
  Eif (!seen.has(candidate)) {
    seen.add(candidate);
    return candidate;
  }
 
  const prefix = path
    .split('/')
    .slice(0, -1)
    .join('_')
    .replace(UNSAFE_FILENAME_CHARS, '_')
    .slice(-40)
    .replace(/^_+|_+$/g, '');
  candidate = prefix ? `${prefix}_${candidate}` : candidate;
  let deduped = candidate;
  let suffix = 2;
  while (seen.has(deduped)) {
    deduped = `${candidate}.${suffix}`;
    suffix++;
  }
  seen.add(deduped);
  return deduped;
}
 
function filePathForSide(file: PullFile, side: PullRequestSide): string | undefined {
  Eif (side === 'base') {
    if (file.status === 'added') {
      return undefined;
    }
    return file.previous_filename ?? file.filename;
  }
 
  if (file.status === 'removed') {
    return undefined;
  }
  return file.filename;
}
 
async function fetchFileContent(
  octokit: Octokit,
  pull: GitHubPullRequestRef,
  path: string,
  ref: string,
): Promise<GitHubFileContent | undefined> {
  try {
    const response = await octokit.rest.repos.getContent({
      owner: pull.owner,
      repo: pull.repo,
      path,
      ref,
    });
 
    const data = response.data;
    Iif (Array.isArray(data) || data.type !== 'file' || !('content' in data)) {
      return undefined;
    }
 
    return {
      ref,
      content: Buffer.from(data.content, 'base64').toString('utf-8'),
    };
  } catch (error) {
    if (
      error
      && typeof error === 'object'
      && 'status' in error
      && (error as { status?: unknown }).status === 404
    ) {
      return undefined;
    }
    throw error;
  }
}
 
function scenarioJson(args: {
  title: string;
  body?: string | null;
  files: string[];
  url: string;
  side: PullRequestSide;
}): string {
  return `${JSON.stringify({
    given: args.title,
    files: args.files,
    should_find: [{
      finding: `TODO: describe the vulnerability fixed by ${args.url}`,
    }],
    should_not_find: [],
    notes: {
      source: args.url,
      side: args.side,
      body: args.body || undefined,
    },
  }, null, 2)}\n`;
}
 
export async function scaffoldEvalFromGitHubPullRequest(
  options: ScaffoldEvalOptions
): Promise<ScaffoldedEval> {
  const pull = parseGitHubPullRequestUrl(options.url);
  const category = requireSafePathSegment(options.category, 'eval category');
  const requestedName = options.name
    ? requireSafePathSegment(options.name, 'eval name')
    : undefined;
  const side = requirePullRequestSide(options.side);
  const octokit = new Octokit({ auth: getGitHubToken() });
  const { data: pr } = await octokit.rest.pulls.get({
    owner: pull.owner,
    repo: pull.repo,
    pull_number: pull.pullNumber,
  });
  const files = await octokit.paginate(octokit.rest.pulls.listFiles, {
    owner: pull.owner,
    repo: pull.repo,
    pull_number: pull.pullNumber,
    per_page: 100,
  }) as PullFile[];
 
  const ref = side === 'base' ? pr.base.sha : pr.head.sha;
  const name = requestedName ?? slugifyEvalName(pr.title);
  const fixtureDir = fromEvalsPath(options.evalsDir, posix.join('fixtures', name));
  const scenarioPath = join(options.evalsDir, category, `${name}.json`);
  const seenFilenames = new Set<string>();
  const copiedFiles: ScaffoldedEvalFile[] = [];
  const contents: (ScaffoldedEvalFile & { content: string })[] = [];
 
  Iif (!options.force && existsSync(scenarioPath)) {
    throw new Error(`Eval scenario already exists: ${scenarioPath}`);
  }
 
  for (const file of files) {
    const sourcePath = filePathForSide(file, side);
    if (!sourcePath) {
      continue;
    }
 
    const content = await fetchFileContent(octokit, pull, sourcePath, ref);
    Iif (!content) {
      continue;
    }
 
    const filename = fixtureFilename(sourcePath, seenFilenames);
    const fixturePath = posix.join('fixtures', name, filename);
    const fullFixturePath = fromEvalsPath(options.evalsDir, fixturePath);
    Iif (!options.force && existsSync(fullFixturePath)) {
      throw new Error(`Eval fixture already exists: ${fullFixturePath}`);
    }
    contents.push({ sourcePath, fixturePath, ref: content.ref, content: content.content });
    copiedFiles.push({ sourcePath, fixturePath, ref: content.ref });
  }
 
  Iif (copiedFiles.length === 0) {
    throw new Error(`No ${side}-side files could be scaffolded from ${options.url}`);
  }
 
  mkdirSync(fixtureDir, { recursive: true });
  mkdirSync(join(options.evalsDir, category), { recursive: true });
 
  for (const content of contents) {
    const fullFixturePath = fromEvalsPath(options.evalsDir, content.fixturePath);
    mkdirSync(dirname(fullFixturePath), { recursive: true });
    writeFileSync(
      fullFixturePath,
      content.content,
      { flag: options.force ? 'w' : 'wx' },
    );
  }
 
  writeFileSync(
    scenarioPath,
    scenarioJson({
      title: pr.title,
      body: pr.body,
      files: copiedFiles.map((file) => file.fixturePath),
      url: options.url,
      side,
    }),
    { flag: options.force ? 'w' : 'wx' },
  );
 
  return {
    name,
    scenarioPath,
    files: copiedFiles,
  };
}