Commit 8ba5d765ad

8ba5d765ad183d5ecb9c368e47bf69babedb484f

parent: 0c6cf335b1

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-06-07 21:36 UTC

Repo security API endpoint

Layout: unified · split

api/src/app.ts +2
@@ -21,6 +21,7 @@ import android from '@/routes/private/android'
2121import discord from '@/routes/private/discord'
2222import reddit from '@/routes/private/reddit'
2323import website from '@/routes/private/website'
24import security from '@/routes/private/security'
2425
2526import mcp from '@/routes/mcp'
2627
@@ -51,6 +52,7 @@ const buildPrivate = () => {
5152 priv.route('/', discord)
5253 priv.route('/', reddit)
5354 priv.route('/', website)
55 priv.route('/', security)
5456 return priv
5557}
5658
api/src/lib/fetch.ts +1
@@ -16,6 +16,7 @@ const ALLOWED_HOSTS = new Set([
1616 'www.reddit.com',
1717 'endpoint.apivoid.com',
1818 'raw.githubusercontent.com',
19 'api.deps.dev',
1920])
2021
2122export interface FetchOpts {
api/src/lib/github.ts added +9
@@ -0,0 +1,9 @@
1// Shared GitHub REST request headers, adds auth when a token is present
2export const githubHeaders = (token?: string): Record<string, string> => {
3 const headers: Record<string, string> = {
4 'User-Agent': 'awesome-privacy-api',
5 Accept: 'application/vnd.github+json',
6 }
7 if (token) headers.Authorization = `token ${token}`
8 return headers
9}
api/src/routes/private/github.ts +13 −12
@@ -1,6 +1,7 @@
11// GitHub repo info, aggregates info, languages, tags, contributors, commits
22import { createRoute, z } from '@hono/zod-openapi'
33import { fetchJson } from '@/lib/fetch'
4import { githubHeaders } from '@/lib/github'
45import { newApp } from '@/lib/openapi'
56import { ErrorResponse, GithubRepoSchema, Ok } from '@/schemas'
67
@@ -16,15 +17,18 @@ interface RepoInfo {
1617 homepage?: string
1718 language?: string
1819 topics?: string[]
19 license?: { spdx_id?: string }
20 license?: { spdx_id?: string; name?: string }
2021 fork?: boolean
2122 archived?: boolean
23 parent?: { full_name?: string }
2224 created_at?: string
2325 updated_at?: string
26 pushed_at?: string
2427 size?: number
2528 stargazers_count?: number
2629 forks_count?: number
2730 watchers_count?: number
31 open_issues_count?: number
2832}
2933
3034interface Tag {
@@ -37,6 +41,7 @@ interface Tag {
3741interface Contributor {
3842 login?: string
3943 avatar_url?: string
44 html_url?: string
4045 contributions?: number
4146}
4247
@@ -60,14 +65,18 @@ const mapInfo = (info: RepoInfo) => ({
6065 language: info.language ?? '',
6166 topics: info.topics ?? [],
6267 license: info.license?.spdx_id ?? '',
68 licenseName: info.license?.name ?? '',
6369 isFork: info.fork ?? false,
6470 isArchived: info.archived ?? false,
71 forkParent: info.parent?.full_name ?? '',
6572 createdAt: info.created_at ?? '',
6673 updatedAt: info.updated_at ?? '',
74 pushedAt: info.pushed_at ?? '',
6775 size: info.size ?? 0,
6876 starCount: info.stargazers_count ?? 0,
6977 forksCount: info.forks_count ?? 0,
7078 watchersCount: info.watchers_count ?? 0,
79 openIssues: info.open_issues_count ?? 0,
7180})
7281
7382const mapVersion = (tag: Tag) => ({
@@ -80,6 +89,7 @@ const mapVersion = (tag: Tag) => ({
8089const mapContributor = (person: Contributor) => ({
8190 username: person.login ?? '',
8291 avatar: person.avatar_url ?? '',
92 url: person.html_url ?? '',
8393 contributions: person.contributions ?? 0,
8494})
8595
@@ -92,15 +102,6 @@ const mapCommit = (commit: Commit) => ({
92102 authorAvatar: commit.author?.avatar_url ?? '',
93103})
94104
95const buildHeaders = (token?: string) => {
96 const headers: Record<string, string> = {
97 'User-Agent': 'awesome-privacy-api',
98 Accept: 'application/vnd.github.v3+json',
99 }
100 if (token) headers.Authorization = `token ${token}`
101 return headers
102}
103
104105const route = createRoute({
105106 method: 'get',
106107 path: '/enrich/github/{owner}/{repo}',
@@ -119,7 +120,7 @@ const route = createRoute({
119120app.openapi(route, async (c) => {
120121 const { owner, repo } = c.req.valid('param')
121122 const slug = `${owner}/${repo}`
122 const headers = buildHeaders(c.env.GITHUB_TOKEN)
123 const headers = githubHeaders(c.env.GITHUB_TOKEN)
123124 const data = await c.var.storage.fetch(
124125 `gh:${slug}`,
125126 SUCCESS_TTL,
@@ -130,7 +131,7 @@ app.openapi(route, async (c) => {
130131 fetchJson<RepoInfo>(base, { headers }),
131132 fetchJson<Record<string, number>>(`${base}/languages`, { headers }),
132133 fetchJson<Tag[]>(`${base}/tags`, { headers }),
133 fetchJson<Contributor[]>(`${base}/contributors`, { headers }),
134 fetchJson<Contributor[]>(`${base}/contributors?per_page=100`, { headers }),
134135 fetchJson<Commit[]>(`${base}/commits`, { headers }),
135136 ])
136137 return {
api/src/routes/private/security.ts added +151
@@ -0,0 +1,151 @@
1// Repo security report: deps.dev scorecard + OSS-Fuzz + GitHub advisories
2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch'
4import { githubHeaders } from '@/lib/github'
5import { newApp } from '@/lib/openapi'
6import { ErrorResponse, Ok, SecurityReportSchema } from '@/schemas'
7
8const app = newApp()
9
10const SUCCESS_TTL = 7 * 24 * 60 * 60
11const NEGATIVE_TTL = 60 * 60
12
13interface Check {
14 name?: string
15 score?: number
16 reason?: string
17 documentation?: { url?: string }
18}
19
20interface Project {
21 scorecard?: { date?: string; overallScore?: number; checks?: Check[] }
22 ossFuzz?: unknown
23}
24
25interface Vuln {
26 vulnerable_version_range?: string | null
27 first_patched_version?: { identifier?: string } | null
28}
29
30interface Advisory {
31 ghsa_id?: string
32 cve_id?: string | null
33 summary?: string
34 severity?: string
35 cvss?: { score?: number | null }
36 published_at?: string
37 withdrawn_at?: string | null
38 state?: string
39 html_url?: string
40 vulnerabilities?: Vuln[] | null
41}
42
43const mapCheck = (check: Check) => ({
44 name: check.name ?? '',
45 score: check.score ?? -1,
46 reason: check.reason ?? '',
47 url: check.documentation?.url ?? '',
48})
49
50// A lone strict "< x" range names the fix version, otherwise unknown
51const deriveFix = (ranges: string[]) => {
52 const match = ranges.length === 1 ? ranges[0].match(/^<\s*([\w.+-]+)$/) : null
53 return match ? match[1] : null
54}
55
56const mapAdvisory = (a: Advisory) => {
57 const vulns = a.vulnerabilities ?? []
58 const ranges = [
59 ...new Set(
60 vulns
61 .map((v) => v.vulnerable_version_range?.trim())
62 .filter((r): r is string => !!r),
63 ),
64 ]
65 const vulnerableRange = ranges.join('; ')
66 const explicit = vulns.map((v) => v.first_patched_version?.identifier).find(Boolean)
67 const firstPatchedVersion = explicit ?? deriveFix(ranges)
68 return {
69 ghsaId: a.ghsa_id ?? '',
70 cveId: a.cve_id ?? null,
71 summary: a.summary ?? '',
72 severity: a.severity ?? '',
73 cvssScore: a.cvss?.score ?? null,
74 publishedAt: a.published_at ?? '',
75 url: a.html_url ?? '',
76 firstPatchedVersion,
77 vulnerableRange,
78 // an upper bound means later versions are safe, so a fix exists
79 isPatched: Boolean(firstPatchedVersion) || vulnerableRange.includes('<'),
80 }
81}
82
83// OpenSSF Scorecard + fuzzing signal from deps.dev, degrades to empty
84const getPosture = async (slug: string) => {
85 try {
86 const key = encodeURIComponent(`github.com/${slug}`)
87 const project = await fetchJson<Project>(`https://api.deps.dev/v3/projects/${key}`)
88 const card = project.scorecard
89 return {
90 scorecard: {
91 available: Boolean(card),
92 overallScore: card?.overallScore ?? null,
93 generatedAt: card?.date ?? '',
94 checks: (card?.checks ?? []).map(mapCheck),
95 },
96 fuzzed: Boolean(project.ossFuzz),
97 }
98 } catch {
99 return {
100 scorecard: { available: false, overallScore: null, generatedAt: '', checks: [] },
101 fuzzed: false,
102 }
103 }
104}
105
106// Maintainer-published GitHub security advisories, degrades to empty
107const getAdvisories = async (slug: string, token?: string) => {
108 try {
109 const list = await fetchJson<Advisory[]>(
110 `https://api.github.com/repos/${slug}/security-advisories?per_page=100&state=published`,
111 { headers: githubHeaders(token) },
112 )
113 const items = list.filter((a) => !a.withdrawn_at).map(mapAdvisory)
114 return { count: items.length, items }
115 } catch {
116 return { count: 0, items: [] }
117 }
118}
119
120const route = createRoute({
121 method: 'get',
122 path: '/enrich/security/{owner}/{repo}',
123 tags: ['Enrichment'],
124 summary: 'Repo security',
125 request: { params: z.object({ owner: z.string(), repo: z.string() }) },
126 responses: {
127 200: Ok(SecurityReportSchema),
128 401: ErrorResponse,
129 500: ErrorResponse,
130 },
131})
132
133app.openapi(route, async (c) => {
134 const { owner, repo } = c.req.valid('param')
135 const slug = `${owner}/${repo}`
136 const data = await c.var.storage.fetch(
137 `sec:${slug}`,
138 SUCCESS_TTL,
139 NEGATIVE_TTL,
140 async () => {
141 const [posture, advisories] = await Promise.all([
142 getPosture(slug),
143 getAdvisories(slug, c.env.GITHUB_TOKEN),
144 ])
145 return { repo: slug, ...posture, advisories }
146 },
147 )
148 return c.json(data, 200)
149})
150
151export default app
api/src/schemas/index.ts +43
@@ -155,14 +155,18 @@ export const GithubRepoSchema = z
155155 language: z.string(),
156156 topics: z.array(z.string()),
157157 license: z.string(),
158 licenseName: z.string(),
158159 isFork: z.boolean(),
159160 isArchived: z.boolean(),
161 forkParent: z.string(),
160162 createdAt: z.string(),
161163 updatedAt: z.string(),
164 pushedAt: z.string(),
162165 size: z.number(),
163166 starCount: z.number(),
164167 forksCount: z.number(),
165168 watchersCount: z.number(),
169 openIssues: z.number(),
166170 }),
167171 languages: z.record(z.number()),
168172 versions: z.array(
@@ -177,6 +181,7 @@ export const GithubRepoSchema = z
177181 z.object({
178182 username: z.string(),
179183 avatar: z.string(),
184 url: z.string(),
180185 contributions: z.number(),
181186 }),
182187 ),
@@ -193,6 +198,44 @@ export const GithubRepoSchema = z
193198 })
194199 .openapi('GithubRepo')
195200
201// Repo security report, merges deps.dev scorecard with GitHub advisories
202export const SecurityReportSchema = z
203 .object({
204 repo: z.string(),
205 scorecard: z.object({
206 available: z.boolean(),
207 overallScore: z.number().nullable(),
208 generatedAt: z.string(),
209 checks: z.array(
210 z.object({
211 name: z.string(),
212 score: z.number(),
213 reason: z.string(),
214 url: z.string(),
215 }),
216 ),
217 }),
218 advisories: z.object({
219 count: z.number(),
220 items: z.array(
221 z.object({
222 ghsaId: z.string(),
223 cveId: z.string().nullable(),
224 summary: z.string(),
225 severity: z.string(),
226 cvssScore: z.number().nullable(),
227 publishedAt: z.string(),
228 url: z.string(),
229 firstPatchedVersion: z.string().nullable(),
230 vulnerableRange: z.string(),
231 isPatched: z.boolean(),
232 }),
233 ),
234 }),
235 fuzzed: z.boolean(),
236 })
237 .openapi('SecurityReport')
238
196239export const DiscordInviteSchema = z
197240 .object({
198241 inviteCode: z.string().nullable(),
api/tests/app.test.ts +5
@@ -67,6 +67,11 @@ describe('auth', () => {
6767 })
6868 expect(res.status).toBe(401)
6969 })
70
71 it('security enrich route requires auth', async () => {
72 const res = await hit('/v1/enrich/security/jquery/jquery')
73 expect(res.status).toBe(401)
74 })
7075})
7176
7277describe('mcp', () => {