|
| 1 | +import { getServiceChildLogger } from '@crowd/logging' |
| 2 | + |
| 3 | +import { parseGithubUrl } from '../../enricher/fetchLightRepo' |
| 4 | +import { ExtractorDeps, ProvenanceEntry, RawContact, RepoTarget } from '../types' |
| 5 | + |
| 6 | +import { isEmail } from './http' |
| 7 | + |
| 8 | +const log = getServiceChildLogger('security-contacts:top-committers') |
| 9 | + |
| 10 | +const SOURCE = 'github-commits' |
| 11 | +const SINCE_DAYS = 90 |
| 12 | +const TOP_N = 3 |
| 13 | +// GitHub computes /stats/contributors asynchronously and returns 202 while it's not ready yet — |
| 14 | +// poll a few times with a short backoff before giving up for this pass. |
| 15 | +const STATS_POLL_ATTEMPTS = 3 |
| 16 | +const STATS_POLL_DELAY_MS = 2000 |
| 17 | + |
| 18 | +interface WeekStat { |
| 19 | + w?: unknown |
| 20 | + c?: unknown |
| 21 | +} |
| 22 | + |
| 23 | +interface ContributorStat { |
| 24 | + author?: { login?: unknown; type?: unknown } | null |
| 25 | + weeks?: WeekStat[] |
| 26 | +} |
| 27 | + |
| 28 | +interface AggregatedAuthor { |
| 29 | + login: string |
| 30 | + count: number |
| 31 | +} |
| 32 | + |
| 33 | +const BOT_TOKENS = [ |
| 34 | + 'dependabot', |
| 35 | + 'renovate', |
| 36 | + 'github-actions', |
| 37 | + 'claude', |
| 38 | + 'anthropic', |
| 39 | + 'copilot', |
| 40 | + 'chatgpt', |
| 41 | + 'openai', |
| 42 | +] |
| 43 | + |
| 44 | +function matchesBotToken(value: string): boolean { |
| 45 | + const lower = value.toLowerCase() |
| 46 | + return BOT_TOKENS.some((token) => lower.includes(token)) |
| 47 | +} |
| 48 | + |
| 49 | +function isBotLogin(login: string): boolean { |
| 50 | + const lower = login.toLowerCase() |
| 51 | + if (lower.endsWith('[bot]')) return true |
| 52 | + return matchesBotToken(lower) |
| 53 | +} |
| 54 | + |
| 55 | +export function aggregateTopCommitters( |
| 56 | + stats: ContributorStat[], |
| 57 | + sinceUnixSeconds: number, |
| 58 | + topN: number = TOP_N, |
| 59 | +): AggregatedAuthor[] { |
| 60 | + const authors: AggregatedAuthor[] = [] |
| 61 | + |
| 62 | + for (const stat of stats) { |
| 63 | + if (stat.author?.type === 'Bot') continue |
| 64 | + const login = typeof stat.author?.login === 'string' ? stat.author.login : undefined |
| 65 | + if (!login || isBotLogin(login)) continue |
| 66 | + |
| 67 | + const count = (stat.weeks ?? []).reduce((sum, week) => { |
| 68 | + const w = typeof week.w === 'number' ? week.w : 0 |
| 69 | + const c = typeof week.c === 'number' ? week.c : 0 |
| 70 | + return w >= sinceUnixSeconds ? sum + c : sum |
| 71 | + }, 0) |
| 72 | + if (count > 0) authors.push({ login, count }) |
| 73 | + } |
| 74 | + |
| 75 | + return authors.sort((a, b) => b.count - a.count || a.login.localeCompare(b.login)).slice(0, topN) |
| 76 | +} |
| 77 | + |
| 78 | +async function resolvePublicEmail( |
| 79 | + login: string, |
| 80 | + githubGet: ExtractorDeps['githubGet'], |
| 81 | +): Promise<string | null> { |
| 82 | + try { |
| 83 | + const { text } = await githubGet(`/users/${login}`) |
| 84 | + const email = (text ? (JSON.parse(text) as { email?: unknown }) : null)?.email |
| 85 | + if (typeof email !== 'string' || !isEmail(email) || matchesBotToken(email)) return null |
| 86 | + return email |
| 87 | + } catch (err) { |
| 88 | + log.warn({ login, errMsg: (err as Error).message }, 'Committer email resolution failed') |
| 89 | + return null |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +export async function mapCommittersToContacts( |
| 94 | + authors: AggregatedAuthor[], |
| 95 | + fetchedAt: string, |
| 96 | + apiPath: string, |
| 97 | + githubGet: ExtractorDeps['githubGet'], |
| 98 | +): Promise<RawContact[]> { |
| 99 | + const contacts: RawContact[] = [] |
| 100 | + |
| 101 | + for (const author of authors) { |
| 102 | + const provenance: ProvenanceEntry[] = [ |
| 103 | + { source: SOURCE, sourceTier: 'D', path: apiPath, fetchedAt }, |
| 104 | + ] |
| 105 | + |
| 106 | + contacts.push({ |
| 107 | + channel: 'github-handle', |
| 108 | + value: author.login, |
| 109 | + handle: author.login, |
| 110 | + role: 'committer', |
| 111 | + tier: 'D', |
| 112 | + provenance, |
| 113 | + }) |
| 114 | + |
| 115 | + const email = await resolvePublicEmail(author.login, githubGet) |
| 116 | + if (email) { |
| 117 | + contacts.push({ |
| 118 | + channel: 'email', |
| 119 | + value: email, |
| 120 | + handle: author.login, |
| 121 | + role: 'committer', |
| 122 | + tier: 'D', |
| 123 | + provenance, |
| 124 | + }) |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + return contacts |
| 129 | +} |
| 130 | + |
| 131 | +async function fetchContributorStats( |
| 132 | + path: string, |
| 133 | + target: RepoTarget, |
| 134 | + owner: string, |
| 135 | + name: string, |
| 136 | + githubGet: ExtractorDeps['githubGet'], |
| 137 | + sleep: (ms: number) => Promise<void>, |
| 138 | +): Promise<ContributorStat[] | null> { |
| 139 | + for (let attempt = 1; attempt <= STATS_POLL_ATTEMPTS; attempt++) { |
| 140 | + let status: number |
| 141 | + let text: string | null |
| 142 | + try { |
| 143 | + ;({ status, text } = await githubGet(path, { extraOkStatuses: [202] })) |
| 144 | + } catch (err) { |
| 145 | + log.warn( |
| 146 | + { repoId: target.repoId, owner, name, errMsg: (err as Error).message }, |
| 147 | + 'Contributor stats lookup failed', |
| 148 | + ) |
| 149 | + return null |
| 150 | + } |
| 151 | + |
| 152 | + if (status === 202) { |
| 153 | + if (attempt < STATS_POLL_ATTEMPTS) await sleep(STATS_POLL_DELAY_MS) |
| 154 | + continue |
| 155 | + } |
| 156 | + |
| 157 | + if (!text) return null |
| 158 | + try { |
| 159 | + const parsed = JSON.parse(text) |
| 160 | + return Array.isArray(parsed) ? (parsed as ContributorStat[]) : null |
| 161 | + } catch (err) { |
| 162 | + log.warn( |
| 163 | + { repoId: target.repoId, owner, name, errMsg: (err as Error).message }, |
| 164 | + 'Contributor stats lookup failed', |
| 165 | + ) |
| 166 | + return null |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + log.info( |
| 171 | + { repoId: target.repoId, owner, name }, |
| 172 | + 'Contributor stats still computing after polling — skipping this pass', |
| 173 | + ) |
| 174 | + return null |
| 175 | +} |
| 176 | + |
| 177 | +export async function fetchTopCommitters( |
| 178 | + target: RepoTarget, |
| 179 | + deps: Pick<ExtractorDeps, 'githubGet'>, |
| 180 | + now: () => Date = () => new Date(), |
| 181 | + sleep: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)), |
| 182 | +): Promise<RawContact[]> { |
| 183 | + let owner: string |
| 184 | + let name: string |
| 185 | + try { |
| 186 | + ;({ owner, name } = parseGithubUrl(target.url)) |
| 187 | + } catch { |
| 188 | + return [] |
| 189 | + } |
| 190 | + |
| 191 | + const path = `/repos/${owner}/${name}/stats/contributors` |
| 192 | + const stats = await fetchContributorStats(path, target, owner, name, deps.githubGet, sleep) |
| 193 | + if (!stats) return [] |
| 194 | + |
| 195 | + const sinceUnixSeconds = Math.floor(now().getTime() / 1000) - SINCE_DAYS * 24 * 60 * 60 |
| 196 | + const authors = aggregateTopCommitters(stats, sinceUnixSeconds) |
| 197 | + const fetchedAt = new Date().toISOString() |
| 198 | + return mapCommittersToContacts( |
| 199 | + authors, |
| 200 | + fetchedAt, |
| 201 | + `https://api.github.com${path}`, |
| 202 | + deps.githubGet, |
| 203 | + ) |
| 204 | +} |
0 commit comments