Commit 3ecb71ee10

3ecb71ee10024c21371347d22d95517c5bb45738

parent: 8adf0e15ec

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-06-09 13:42 UTC

Cache controls, de-googled compatibility and advisory reporting

Layout: unified · split

api/src/app.ts +17 −8
@@ -26,14 +26,8 @@ import security from '@/routes/private/security'
26import mcp from '@/routes/mcp' 26import mcp from '@/routes/mcp'
27 27
28const buildPublic = () => { 28const buildPublic = () => {
29 // Public routes, CORS open, rate limited, cacheable 29 // Public browse routes, shared middleware is applied at the app level
30 const pub = newApp() 30 const pub = newApp()
31 pub.use('*', cors({ origin: '*' }))
32 pub.use('*', rateLimit())
33 pub.use('*', async (c, next) => {
34 await next()
35 c.header('Cache-Control', 'public, s-maxage=300')
36 })
37 pub.route('/', services) 31 pub.route('/', services)
38 pub.route('/', categoriesRoute) 32 pub.route('/', categoriesRoute)
39 pub.route('/', searchRoute) 33 pub.route('/', searchRoute)
@@ -68,6 +62,19 @@ export const buildApp = () => {
68 await next() 62 await next()
69 }) 63 })
70 64
65 // CORS everywhere; rate limiting and edge caching are for public routes only,
66 // authenticated /enrich/* requests are exempt from both
67 app.use('*', cors({ origin: '*' }))
68 const limiter = rateLimit()
69 app.use('/v1/*', (c, next) =>
70 c.req.path.startsWith('/v1/enrich') ? next() : limiter(c, next),
71 )
72 app.use('/v1/*', async (c, next) => {
73 if (c.req.path.startsWith('/v1/enrich')) return next()
74 await next()
75 c.header('Cache-Control', 'public, s-maxage=300')
76 })
77
71 app.route('/v1', buildPublic()) 78 app.route('/v1', buildPublic())
72 app.route('/v1', buildPrivate()) 79 app.route('/v1', buildPrivate())
73 app.route('/v1', mcp) 80 app.route('/v1', mcp)
@@ -100,7 +107,9 @@ Then, add the \`Authorization: Bearer <your-token>\` header when accessing the e
100<summary>Caching</summary> 107<summary>Caching</summary>
101 108
102Some responses are cached to reduce load on upstream services. 109Some responses are cached to reduce load on upstream services.
103When configured, successful enrichment data results are put in KV for upto 7 days. 110When configured, successful enrichment results are cached in KV and served while fresh
111(from a week up to 90 days, depending on the endpoint). Stale entries are refreshed on
112demand, falling back to the cached copy if the upstream is unavailable.
104</details> 113</details>
105 114
106<details> 115<details>
api/src/lib/cache/freshness.ts added +23
@@ -0,0 +1,23 @@
1/**
2 * Central cache freshness windows, in days, per enrichment route.
3 * A cached response is served as-is until it is this many days old, then a
4 * refresh is attempted. To change how long a route caches, edit one number here.
5 */
6
7export const CACHE_DAYS = {
8 privacy: 90,
9 security: 14,
10 android: 60,
11 website: 60,
12 ios: 60,
13 github: 7,
14 discord: 14,
15 reddit: 14,
16} as const
17
18export type CacheRoute = keyof typeof CACHE_DAYS
19
20const DAY_SECONDS = 24 * 60 * 60
21
22// Freshness window in seconds for a route, as passed to storage.fetch()
23export const freshSeconds = (route: CacheRoute): number => CACHE_DAYS[route] * DAY_SECONDS
api/src/lib/cache/index.ts +28 −43
@@ -1,65 +1,50 @@
1/** 1/**
2 * The storage interface 2 * Storage cache, an in-memory Map on Bun/Node or KV on Cloudflare Workers.
3 * Caches certain lookup results, so as to reduce load and improve perf 3 * Entries are kept indefinitely with their fetch time; a freshness window
4 * Picks between in-mem store for Bun/Node or KV db for Cloudflare Workers 4 * decides serve-as-is vs refresh. On a failed refresh the stale value is
5 * served, and failures are never cached.
5 */ 6 */
6 7
7import { ApiError, type ErrorCode } from '@/lib/errors' 8import { ApiError } from '@/lib/errors'
8import type { AppEnv } from '@/types' 9import type { AppEnv } from '@/types'
9import { kvStorage } from '@/lib/cache/kv' 10import { kvStorage } from '@/lib/cache/kv'
10import { memoryStorage } from '@/lib/cache/memory' 11import { memoryStorage } from '@/lib/cache/memory'
11 12
13export interface StoredEntry<T = unknown> {
14 value: T
15 // Epoch milliseconds when this value was fetched
16 cachedAt: number
17}
18
12export interface Storage { 19export interface Storage {
13 get<T = unknown>(key: string): Promise<T | null> 20 get<T = unknown>(key: string): Promise<StoredEntry<T> | null>
14 set<T = unknown>(key: string, value: T, ttlSec: number): Promise<void> 21 // Store a value indefinitely, stamped with the current time
15 // Run loader once, cache the result for ttl, cache negatives for negTtl 22 set<T = unknown>(key: string, value: T): Promise<void>
16 fetch<T>(key: string, ttl: number, negTtl: number, loader: () => Promise<T>): Promise<T> 23 // Serve a fresh cache, else refresh; on refresh failure fall back to stale
24 fetch<T>(key: string, freshSec: number, loader: () => Promise<T>): Promise<T>
17} 25}
18 26
19export const createStorage = (env: AppEnv): Storage => 27export const createStorage = (env: AppEnv): Storage =>
20 env.CACHE ? kvStorage(env.CACHE) : memoryStorage() 28 env.CACHE ? kvStorage(env.CACHE) : memoryStorage()
21 29
22interface NegEntry { 30// Shared fetch wrapper, caches only successes and serves stale on failure.
23 ok: false 31// Never resolves to undefined, a missing value yields an error not an empty body.
24 code: ErrorCode
25 message: string
26 status: number
27}
28interface PosEntry<T> {
29 ok: true
30 value: T
31}
32
33// Shared fetch wrapper, caches successes and replays typed negatives
34export const wrapFetch = 32export const wrapFetch =
35 (storage: Storage) => 33 (storage: Storage) =>
36 async <T>( 34 async <T>(key: string, freshSec: number, loader: () => Promise<T>): Promise<T> => {
37 key: string, 35 const cached = await storage.get<T>(key)
38 ttl: number, 36 if (cached && cached.value !== undefined) {
39 negTtl: number, 37 if (Date.now() - cached.cachedAt < freshSec * 1000) return cached.value
40 loader: () => Promise<T>,
41 ): Promise<T> => {
42 const cached = await storage.get<PosEntry<T> | NegEntry>(key)
43 if (cached) {
44 if (cached.ok) return cached.value
45 throw new ApiError(cached.code, cached.message, cached.status)
46 } 38 }
47 try { 39 try {
48 const value = await loader() 40 const value = await loader()
49 await storage.set(key, { ok: true, value } satisfies PosEntry<T>, ttl) 41 if (value === undefined) {
42 throw new ApiError('UPSTREAM_ERROR', 'Upstream returned no data', 502)
43 }
44 await storage.set(key, value)
50 return value 45 return value
51 } catch (caught) { 46 } catch (caught) {
52 const error = 47 if (cached && cached.value !== undefined) return cached.value
53 caught instanceof ApiError 48 throw caught
54 ? caught
55 : new ApiError('UPSTREAM_ERROR', (caught as Error).message, 502)
56 const negative: NegEntry = {
57 ok: false,
58 code: error.code,
59 message: error.message,
60 status: error.status,
61 }
62 await storage.set(key, negative, negTtl)
63 throw error
64 } 49 }
65 } 50 }
api/src/lib/cache/kv.ts +8 −7
@@ -1,17 +1,18 @@
1/* Workers KV backed Storage */ 1/* Workers KV backed Storage */
2import type { Storage } from '@/lib/cache' 2import type { Storage, StoredEntry } from '@/lib/cache'
3import { wrapFetch } from '@/lib/cache' 3import { wrapFetch } from '@/lib/cache'
4 4
5export const kvStorage = (kv: KVNamespace): Storage => { 5export const kvStorage = (kv: KVNamespace): Storage => {
6 const storage: Storage = { 6 const storage: Storage = {
7 async get<T>(key: string) { 7 async get<T>(key: string) {
8 const value = await kv.get(key, 'json') 8 return (await kv.get<StoredEntry<T>>(key, 'json')) ?? null
9 return (value as T) ?? null
10 }, 9 },
11 async set<T>(key: string, value: T, ttlSec: number) { 10 async set<T>(key: string, value: T) {
12 await kv.put(key, JSON.stringify(value), { 11 // No expirationTtl, entries are kept indefinitely
13 expirationTtl: Math.max(ttlSec, 60), 12 await kv.put(
14 }) 13 key,
14 JSON.stringify({ value, cachedAt: Date.now() } satisfies StoredEntry<T>),
15 )
15 }, 16 },
16 fetch: async () => { 17 fetch: async () => {
17 throw new Error('uninit') 18 throw new Error('uninit')
api/src/lib/cache/memory.ts +7 −16
@@ -1,26 +1,17 @@
1/* In-process Map with TTL, storage cache for Node/Bun */ 1/* In-process Map storage cache for Node/Bun */
2import type { Storage } from '@/lib/cache' 2import type { Storage, StoredEntry } from '@/lib/cache'
3import { wrapFetch } from '@/lib/cache' 3import { wrapFetch } from '@/lib/cache'
4 4
5interface Entry { 5const store = new Map<string, StoredEntry>()
6 expires: number
7 value: unknown
8}
9const store = new Map<string, Entry>()
10 6
11export const memoryStorage = (): Storage => { 7export const memoryStorage = (): Storage => {
12 const storage: Storage = { 8 const storage: Storage = {
13 async get<T>(key: string) { 9 async get<T>(key: string) {
14 const entry = store.get(key) 10 return (store.get(key) as StoredEntry<T>) ?? null
15 if (!entry) return null
16 if (entry.expires < Date.now()) {
17 store.delete(key)
18 return null
19 }
20 return entry.value as T
21 }, 11 },
22 async set<T>(key: string, value: T, ttlSec: number) { 12 async set<T>(key: string, value: T) {
23 store.set(key, { expires: Date.now() + ttlSec * 1000, value }) 13 // Kept indefinitely, freshness is decided by the caller not by expiry
14 store.set(key, { value, cachedAt: Date.now() })
24 }, 15 },
25 fetch: async () => { 16 fetch: async () => {
26 throw new Error('uninit') 17 throw new Error('uninit')
api/src/lib/fetch.ts +1
@@ -17,6 +17,7 @@ const ALLOWED_HOSTS = new Set([
17 'endpoint.apivoid.com', 17 'endpoint.apivoid.com',
18 'raw.githubusercontent.com', 18 'raw.githubusercontent.com',
19 'api.deps.dev', 19 'api.deps.dev',
20 'plexus.techlore.tech',
20]) 21])
21 22
22export interface FetchOpts { 23export interface FetchOpts {
api/src/lib/plexus.ts added +49
@@ -0,0 +1,49 @@
1/**
2 * Aggregates Plexus crowdsourced ratings into de-Googled compatibility status.
3 * Each rating scores an app out of 4, native is no-microG and micro_g is with it.
4 * Scores map to gold (flawless), silver, bronze (limited) and broken.
5 */
6
7export interface PlexusRating {
8 rating_type?: string
9 score?: { numerator?: number; denominator?: number }
10}
11
12const statusFor = (ratio: number) =>
13 ratio >= 0.875
14 ? 'gold'
15 : ratio >= 0.625
16 ? 'silver'
17 : ratio >= 0.375
18 ? 'bronze'
19 : 'broken'
20
21// Mean the matching scores into a status summary, or mark the type unavailable
22const summarize = (ratings: PlexusRating[], type: string) => {
23 const ratios: number[] = []
24 for (const r of ratings) {
25 const num = r.score?.numerator
26 const den = r.score?.denominator
27 if (
28 r.rating_type === type &&
29 typeof num === 'number' &&
30 typeof den === 'number' &&
31 den > 0
32 ) {
33 ratios.push(num / den)
34 }
35 }
36 if (ratios.length === 0) return { available: false as const }
37 const ratio = ratios.reduce((sum, x) => sum + x, 0) / ratios.length
38 return {
39 available: true as const,
40 status: statusFor(ratio),
41 score: Math.round(ratio * 40) / 10,
42 ratings: ratios.length,
43 }
44}
45
46export const summarizeRatings = (ratings: PlexusRating[]) => ({
47 native: summarize(ratings, 'native'),
48 microg: summarize(ratings, 'micro_g'),
49})
api/src/routes/private/android.ts +52 −30
@@ -1,14 +1,15 @@
1// Exodus Privacy app lookup, joined with the tracker dictionary 1// Exodus tracker analysis merged with Plexus de-Googled compatibility
2import { createRoute, z } from '@hono/zod-openapi' 2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch' 3import { fetchJson } from '@/lib/fetch'
4import { ApiError } from '@/lib/errors' 4import { ApiError } from '@/lib/errors'
5import { freshSeconds } from '@/lib/cache/freshness'
5import { newApp } from '@/lib/openapi' 6import { newApp } from '@/lib/openapi'
7import { summarizeRatings, type PlexusRating } from '@/lib/plexus'
6import { AndroidReportSchema, ErrorResponse, Ok } from '@/schemas' 8import { AndroidReportSchema, ErrorResponse, Ok } from '@/schemas'
7 9
8const app = newApp() 10const app = newApp()
9 11
10const SUCCESS_TTL = 7 * 24 * 60 * 60 12const FRESH_TTL = freshSeconds('android')
11const NEGATIVE_TTL = 6 * 60 * 60
12 13
13interface AppDetails { 14interface AppDetails {
14 trackers: number[] 15 trackers: number[]
@@ -19,6 +20,39 @@ interface TrackerLookup {
19} 20}
20 21
21const EXODUS_BASE = 'https://reports.exodus-privacy.eu.org/api' 22const EXODUS_BASE = 'https://reports.exodus-privacy.eu.org/api'
23const PLEXUS_BASE = 'https://plexus.techlore.tech/api/v1'
24
25// Exodus apk details with tracker ids resolved to records, null if unavailable
26const getExodus = async (pkg: string, token: string) => {
27 try {
28 const headers = { Authorization: `Token ${token}` }
29 const details = await fetchJson<AppDetails[]>(
30 `${EXODUS_BASE}/search/${encodeURIComponent(pkg)}/details`,
31 { headers, timeoutMs: 10000 },
32 )
33 const appInfo = details?.[0]
34 if (!appInfo) return null
35 const { trackers } = await fetchJson<TrackerLookup>(`${EXODUS_BASE}/trackers`, {
36 headers,
37 timeoutMs: 10000,
38 })
39 return { ...appInfo, trackers: appInfo.trackers.map((id) => trackers[String(id)]) }
40 } catch {
41 return null
42 }
43}
44
45// Plexus crowdsourced de-Googled compatibility, null if the app has no ratings
46const getDegoogled = async (pkg: string) => {
47 try {
48 const { data } = await fetchJson<{ data: PlexusRating[] }>(
49 `${PLEXUS_BASE}/apps/${encodeURIComponent(pkg)}/ratings`,
50 )
51 return data?.length ? summarizeRatings(data) : null
52 } catch {
53 return null
54 }
55}
22 56
23const route = createRoute({ 57const route = createRoute({
24 method: 'get', 58 method: 'get',
@@ -31,40 +65,28 @@ const route = createRoute({
31 401: ErrorResponse, 65 401: ErrorResponse,
32 404: ErrorResponse, 66 404: ErrorResponse,
33 500: ErrorResponse, 67 500: ErrorResponse,
34 502: ErrorResponse,
35 }, 68 },
36}) 69})
37 70
38// Resolve the apk then replace tracker ids with their detail records 71// Merge Exodus trackers with Plexus de-Googled status, 404 only if both miss
39app.openapi(route, async (c) => { 72app.openapi(route, async (c) => {
40 const { pkg } = c.req.valid('param') 73 const { pkg } = c.req.valid('param')
41 const token = c.env.EXODUS_TOKEN 74 const token = c.env.EXODUS_TOKEN
42 if (!token) throw new ApiError('INTERNAL', 'EXODUS_TOKEN not configured', 500) 75 if (!token) throw new ApiError('INTERNAL', 'EXODUS_TOKEN not configured', 500)
43 const headers = { Authorization: `Token ${token}` } 76 const data = await c.var.storage.fetch(`android:${pkg}`, FRESH_TTL, async () => {
44 const data = await c.var.storage.fetch( 77 const [exodus, degoogled] = await Promise.all([
45 `android:${pkg}`, 78 getExodus(pkg, token),
46 SUCCESS_TTL, 79 getDegoogled(pkg),
47 NEGATIVE_TTL, 80 ])
48 async () => { 81 if (!exodus && !degoogled) {
49 const detailsUrl = `${EXODUS_BASE}/search/${encodeURIComponent(pkg)}/details` 82 throw new ApiError(
50 const details = await fetchJson<AppDetails[]>(detailsUrl, { 83 'NOT_FOUND',
51 headers, 84 `Package '${pkg}' not found on Exodus or Plexus`,
52 timeoutMs: 10000, 85 404,
53 }) 86 )
54 const appInfo = details?.[0] 87 }
55 if (!appInfo) { 88 return { ...exodus, degoogled: degoogled ?? null }
56 throw new ApiError('NOT_FOUND', `Package '${pkg}' not found on Exodus`, 404) 89 })
57 }
58 const { trackers } = await fetchJson<TrackerLookup>(`${EXODUS_BASE}/trackers`, {
59 headers,
60 timeoutMs: 10000,
61 })
62 return {
63 ...appInfo,
64 trackers: appInfo.trackers.map((id) => trackers[String(id)]),
65 }
66 },
67 )
68 return c.json(data, 200) 90 return c.json(data, 200)
69}) 91})
70 92
api/src/routes/private/discord.ts +16 −21
@@ -1,13 +1,13 @@
1// Discord invite info, projected to a compact response shape 1// Discord invite info, projected to a compact response shape
2import { createRoute, z } from '@hono/zod-openapi' 2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch' 3import { fetchJson } from '@/lib/fetch'
4import { freshSeconds } from '@/lib/cache/freshness'
4import { newApp } from '@/lib/openapi' 5import { newApp } from '@/lib/openapi'
5import { DiscordInviteSchema, ErrorResponse, Ok } from '@/schemas' 6import { DiscordInviteSchema, ErrorResponse, Ok } from '@/schemas'
6 7
7const app = newApp() 8const app = newApp()
8 9
9const SUCCESS_TTL = 24 * 60 * 60 10const FRESH_TTL = freshSeconds('discord')
10const NEGATIVE_TTL = 60 * 60
11 11
12interface Invite { 12interface Invite {
13 code?: string 13 code?: string
@@ -51,25 +51,20 @@ app.openapi(route, async (c) => {
51 const upstream = 51 const upstream =
52 `https://discord.com/api/v9/invites/${encodeURIComponent(invite)}` + 52 `https://discord.com/api/v9/invites/${encodeURIComponent(invite)}` +
53 '?with_counts=true&with_expiration=true' 53 '?with_counts=true&with_expiration=true'
54 const data = await c.var.storage.fetch( 54 const data = await c.var.storage.fetch(`discord:${invite}`, FRESH_TTL, async () => {
55 `discord:${invite}`, 55 const raw = await fetchJson<Invite>(upstream, { headers })
56 SUCCESS_TTL, 56 const guild = raw.guild
57 NEGATIVE_TTL, 57 return {
58 async () => { 58 inviteCode: raw.code ?? null,
59 const raw = await fetchJson<Invite>(upstream, { headers }) 59 name: guild?.name ?? null,
60 const guild = raw.guild 60 memberCount: raw.approximate_member_count ?? null,
61 return { 61 memberOnlineCount: raw.approximate_presence_count ?? null,
62 inviteCode: raw.code ?? null, 62 channel: raw.channel?.name ?? null,
63 name: guild?.name ?? null, 63 icon: iconUrl(guild?.id, guild?.icon),
64 memberCount: raw.approximate_member_count ?? null, 64 banner: bannerUrl(guild?.id, guild?.splash),
65 memberOnlineCount: raw.approximate_presence_count ?? null, 65 inviter: raw.inviter?.global_name ?? null,
66 channel: raw.channel?.name ?? null, 66 }
67 icon: iconUrl(guild?.id, guild?.icon), 67 })
68 banner: bannerUrl(guild?.id, guild?.splash),
69 inviter: raw.inviter?.global_name ?? null,
70 }
71 },
72 )
73 return c.json(data, 200) 68 return c.json(data, 200)
74}) 69})
75 70
api/src/routes/private/github.ts +19 −24
@@ -2,13 +2,13 @@
2import { createRoute, z } from '@hono/zod-openapi' 2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch' 3import { fetchJson } from '@/lib/fetch'
4import { githubHeaders } from '@/lib/github' 4import { githubHeaders } from '@/lib/github'
5import { freshSeconds } from '@/lib/cache/freshness'
5import { newApp } from '@/lib/openapi' 6import { newApp } from '@/lib/openapi'
6import { ErrorResponse, GithubRepoSchema, Ok } from '@/schemas' 7import { ErrorResponse, GithubRepoSchema, Ok } from '@/schemas'
7 8
8const app = newApp() 9const app = newApp()
9 10
10const SUCCESS_TTL = 24 * 60 * 60 11const FRESH_TTL = freshSeconds('github')
11const NEGATIVE_TTL = 60 * 60
12 12
13interface RepoInfo { 13interface RepoInfo {
14 owner?: { login?: string; avatar_url?: string } 14 owner?: { login?: string; avatar_url?: string }
@@ -121,28 +121,23 @@ app.openapi(route, async (c) => {
121 const { owner, repo } = c.req.valid('param') 121 const { owner, repo } = c.req.valid('param')
122 const slug = `${owner}/${repo}` 122 const slug = `${owner}/${repo}`
123 const headers = githubHeaders(c.env.GITHUB_TOKEN) 123 const headers = githubHeaders(c.env.GITHUB_TOKEN)
124 const data = await c.var.storage.fetch( 124 const data = await c.var.storage.fetch(`gh:${slug}`, FRESH_TTL, async () => {
125 `gh:${slug}`, 125 const base = `https://api.github.com/repos/${slug}`
126 SUCCESS_TTL, 126 const [info, languages, tags, contributors, commits] = await Promise.all([
127 NEGATIVE_TTL, 127 fetchJson<RepoInfo>(base, { headers }),
128 async () => { 128 fetchJson<Record<string, number>>(`${base}/languages`, { headers }),
129 const base = `https://api.github.com/repos/${slug}` 129 fetchJson<Tag[]>(`${base}/tags`, { headers }),
130 const [info, languages, tags, contributors, commits] = await Promise.all([ 130 fetchJson<Contributor[]>(`${base}/contributors?per_page=100`, { headers }),
131 fetchJson<RepoInfo>(base, { headers }), 131 fetchJson<Commit[]>(`${base}/commits`, { headers }),
132 fetchJson<Record<string, number>>(`${base}/languages`, { headers }), 132 ])
133 fetchJson<Tag[]>(`${base}/tags`, { headers }), 133 return {
134 fetchJson<Contributor[]>(`${base}/contributors?per_page=100`, { headers }), 134 info: mapInfo(info),
135 fetchJson<Commit[]>(`${base}/commits`, { headers }), 135 languages: languages ?? {},
136 ]) 136 versions: tags.map(mapVersion),
137 return { 137 contributors: contributors.map(mapContributor),
138 info: mapInfo(info), 138 commits: commits.map(mapCommit),
139 languages: languages ?? {}, 139 }
140 versions: tags.map(mapVersion), 140 })
141 contributors: contributors.map(mapContributor),
142 commits: commits.map(mapCommit),
143 }
144 },
145 )
146 return c.json(data, 200) 141 return c.json(data, 200)
147}) 142})
148 143
api/src/routes/private/ios.ts +10 −15
@@ -2,13 +2,13 @@
2import { createRoute, z } from '@hono/zod-openapi' 2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch' 3import { fetchJson } from '@/lib/fetch'
4import { ApiError } from '@/lib/errors' 4import { ApiError } from '@/lib/errors'
5import { freshSeconds } from '@/lib/cache/freshness'
5import { newApp } from '@/lib/openapi' 6import { newApp } from '@/lib/openapi'
6import { ErrorResponse, ItunesAppSchema, Ok } from '@/schemas' 7import { ErrorResponse, ItunesAppSchema, Ok } from '@/schemas'
7 8
8const app = newApp() 9const app = newApp()
9 10
10const SUCCESS_TTL = 7 * 24 * 60 * 60 11const FRESH_TTL = freshSeconds('ios')
11const NEGATIVE_TTL = 6 * 60 * 60
12 12
13interface ItunesResult { 13interface ItunesResult {
14 resultCount: number 14 resultCount: number
@@ -42,19 +42,14 @@ app.openapi(route, async (c) => {
42 const id = normalize(bundleId) 42 const id = normalize(bundleId)
43 const idParam = /^\d+$/.test(id) ? `id=${id}` : `bundleId=${encodeURIComponent(id)}` 43 const idParam = /^\d+$/.test(id) ? `id=${id}` : `bundleId=${encodeURIComponent(id)}`
44 const upstream = `https://itunes.apple.com/lookup?${idParam}&country=${country}` 44 const upstream = `https://itunes.apple.com/lookup?${idParam}&country=${country}`
45 const data = await c.var.storage.fetch( 45 const data = await c.var.storage.fetch(`ios:${country}:${id}`, FRESH_TTL, async () => {
46 `ios:${country}:${id}`, 46 const result = await fetchJson<ItunesResult>(upstream)
47 SUCCESS_TTL, 47 const first = result.results?.[0]
48 NEGATIVE_TTL, 48 if (!result.resultCount || !first) {
49 async () => { 49 throw new ApiError('NOT_FOUND', `No app found for '${id}'`, 404)
50 const result = await fetchJson<ItunesResult>(upstream) 50 }
51 const first = result.results?.[0] 51 return first
52 if (!result.resultCount || !first) { 52 })
53 throw new ApiError('NOT_FOUND', `No app found for '${id}'`, 404)
54 }
55 return first
56 },
57 )
58 return c.json(data, 200) 53 return c.json(data, 200)
59}) 54})
60 55
api/src/routes/private/privacy.ts +6 −9
@@ -1,13 +1,13 @@
1// ToS;DR v3 lookup by service id, cached weekly 1// ToS;DR v3 lookup by service id
2import { createRoute, z } from '@hono/zod-openapi' 2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch' 3import { fetchJson } from '@/lib/fetch'
4import { freshSeconds } from '@/lib/cache/freshness'
4import { newApp } from '@/lib/openapi' 5import { newApp } from '@/lib/openapi'
5import { ErrorResponse, Ok, TosdrServiceSchema } from '@/schemas' 6import { ErrorResponse, Ok, TosdrServiceSchema } from '@/schemas'
6 7
7const app = newApp() 8const app = newApp()
8 9
9const SUCCESS_TTL = 7 * 24 * 60 * 60 10const FRESH_TTL = freshSeconds('privacy')
10const NEGATIVE_TTL = 60 * 60
11 11
12const route = createRoute({ 12const route = createRoute({
13 method: 'get', 13 method: 'get',
@@ -23,15 +23,12 @@ const route = createRoute({
23 }, 23 },
24}) 24})
25 25
26// Pass through the ToS;DR v3 service shape, cached for a week 26// Pass through the ToS;DR v3 service shape
27app.openapi(route, async (c) => { 27app.openapi(route, async (c) => {
28 const { tosdrId } = c.req.valid('param') 28 const { tosdrId } = c.req.valid('param')
29 const upstream = `https://api.tosdr.org/service/v3?id=${encodeURIComponent(tosdrId)}` 29 const upstream = `https://api.tosdr.org/service/v3?id=${encodeURIComponent(tosdrId)}`
30 const data = await c.var.storage.fetch( 30 const data = await c.var.storage.fetch(`tosdr:${tosdrId}`, FRESH_TTL, () =>
31 `tosdr:${tosdrId}`, 31 fetchJson(upstream, { timeoutMs: 8000 }),
32 SUCCESS_TTL,
33 NEGATIVE_TTL,
34 () => fetchJson(upstream, { timeoutMs: 8000 }),
35 ) 32 )
36 return c.json(data as Record<string, unknown>, 200) 33 return c.json(data as Record<string, unknown>, 200)
37}) 34})
api/src/routes/private/reddit.ts +9 −14
@@ -1,13 +1,13 @@
1// Subreddit info and top monthly posts 1// Subreddit info and top monthly posts
2import { createRoute, z } from '@hono/zod-openapi' 2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch' 3import { fetchJson } from '@/lib/fetch'
4import { freshSeconds } from '@/lib/cache/freshness'
4import { newApp } from '@/lib/openapi' 5import { newApp } from '@/lib/openapi'
5import { ErrorResponse, Ok, SubredditSchema } from '@/schemas' 6import { ErrorResponse, Ok, SubredditSchema } from '@/schemas'
6 7
7const app = newApp() 8const app = newApp()
8 9
9const SUCCESS_TTL = 24 * 60 * 60 10const FRESH_TTL = freshSeconds('reddit')
10const NEGATIVE_TTL = 60 * 60
11 11
12interface AboutData { 12interface AboutData {
13 data?: { 13 data?: {
@@ -91,18 +91,13 @@ app.openapi(route, async (c) => {
91 const { sub } = c.req.valid('param') 91 const { sub } = c.req.valid('param')
92 const aboutUrl = `https://www.reddit.com/r/${sub}/about.json` 92 const aboutUrl = `https://www.reddit.com/r/${sub}/about.json`
93 const topUrl = `https://www.reddit.com/r/${sub}/top.json?t=month&limit=10` 93 const topUrl = `https://www.reddit.com/r/${sub}/top.json?t=month&limit=10`
94 const data = await c.var.storage.fetch( 94 const data = await c.var.storage.fetch(`reddit:${sub}`, FRESH_TTL, async () => {
95 `reddit:${sub}`, 95 const [about, top] = await Promise.all([
96 SUCCESS_TTL, 96 fetchJson<AboutData>(aboutUrl, { headers }),
97 NEGATIVE_TTL, 97 fetchJson<PostListing>(topUrl, { headers }),
98 async () => { 98 ])
99 const [about, top] = await Promise.all([ 99 return { info: mapInfo(about), posts: mapPosts(top) }
100 fetchJson<AboutData>(aboutUrl, { headers }), 100 })
101 fetchJson<PostListing>(topUrl, { headers }),
102 ])
103 return { info: mapInfo(about), posts: mapPosts(top) }
104 },
105 )
106 return c.json(data, 200) 101 return c.json(data, 200)
107}) 102})
108 103
api/src/routes/private/security.ts +14 −15
@@ -2,13 +2,13 @@
2import { createRoute, z } from '@hono/zod-openapi' 2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch' 3import { fetchJson } from '@/lib/fetch'
4import { githubHeaders } from '@/lib/github' 4import { githubHeaders } from '@/lib/github'
5import { freshSeconds } from '@/lib/cache/freshness'
5import { newApp } from '@/lib/openapi' 6import { newApp } from '@/lib/openapi'
6import { ErrorResponse, Ok, SecurityReportSchema } from '@/schemas' 7import { ErrorResponse, Ok, SecurityReportSchema } from '@/schemas'
7 8
8const app = newApp() 9const app = newApp()
9 10
10const SUCCESS_TTL = 7 * 24 * 60 * 60 11const FRESH_TTL = freshSeconds('security')
11const NEGATIVE_TTL = 60 * 60
12 12
13interface Check { 13interface Check {
14 name?: string 14 name?: string
@@ -24,6 +24,8 @@ interface Project {
24 24
25interface Vuln { 25interface Vuln {
26 vulnerable_version_range?: string | null 26 vulnerable_version_range?: string | null
27 // Repo advisories carry the fix here, the global advisory db uses first_patched_version
28 patched_versions?: string | null
27 first_patched_version?: { identifier?: string } | null 29 first_patched_version?: { identifier?: string } | null
28} 30}
29 31
@@ -63,7 +65,9 @@ const mapAdvisory = (a: Advisory) => {
63 ), 65 ),
64 ] 66 ]
65 const vulnerableRange = ranges.join('; ') 67 const vulnerableRange = ranges.join('; ')
66 const explicit = vulns.map((v) => v.first_patched_version?.identifier).find(Boolean) 68 const explicit = vulns
69 .map((v) => v.patched_versions?.trim() || v.first_patched_version?.identifier)
70 .find(Boolean)
67 const firstPatchedVersion = explicit ?? deriveFix(ranges) 71 const firstPatchedVersion = explicit ?? deriveFix(ranges)
68 return { 72 return {
69 ghsaId: a.ghsa_id ?? '', 73 ghsaId: a.ghsa_id ?? '',
@@ -133,18 +137,13 @@ const route = createRoute({
133app.openapi(route, async (c) => { 137app.openapi(route, async (c) => {
134 const { owner, repo } = c.req.valid('param') 138 const { owner, repo } = c.req.valid('param')
135 const slug = `${owner}/${repo}` 139 const slug = `${owner}/${repo}`
136 const data = await c.var.storage.fetch( 140 const data = await c.var.storage.fetch(`sec:${slug}`, FRESH_TTL, async () => {
137 `sec:${slug}`, 141 const [posture, advisories] = await Promise.all([
138 SUCCESS_TTL, 142 getPosture(slug),
139 NEGATIVE_TTL, 143 getAdvisories(slug, c.env.GITHUB_TOKEN),
140 async () => { 144 ])
141 const [posture, advisories] = await Promise.all([ 145 return { repo: slug, ...posture, advisories }
142 getPosture(slug), 146 })
143 getAdvisories(slug, c.env.GITHUB_TOKEN),
144 ])
145 return { repo: slug, ...posture, advisories }
146 },
147 )
148 return c.json(data, 200) 147 return c.json(data, 200)
149}) 148})
150 149
api/src/routes/private/website.ts +9 −14
@@ -2,13 +2,13 @@
2import { createRoute, z } from '@hono/zod-openapi' 2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch' 3import { fetchJson } from '@/lib/fetch'
4import { ApiError } from '@/lib/errors' 4import { ApiError } from '@/lib/errors'
5import { freshSeconds } from '@/lib/cache/freshness'
5import { newApp } from '@/lib/openapi' 6import { newApp } from '@/lib/openapi'
6import { ErrorResponse, Ok, WebsiteReportSchema } from '@/schemas' 7import { ErrorResponse, Ok, WebsiteReportSchema } from '@/schemas'
7 8
8const app = newApp() 9const app = newApp()
9 10
10const SUCCESS_TTL = 30 * 24 * 60 * 60 11const FRESH_TTL = freshSeconds('website')
11const NEGATIVE_TTL = 60 * 60
12 12
13interface ApiVoidResp { 13interface ApiVoidResp {
14 data?: { report?: unknown } 14 data?: { report?: unknown }
@@ -38,18 +38,13 @@ app.openapi(route, async (c) => {
38 const upstream = 38 const upstream =
39 'https://endpoint.apivoid.com/urlrep/v1/pay-as-you-go/' + 39 'https://endpoint.apivoid.com/urlrep/v1/pay-as-you-go/' +
40 `?key=${key}&url=${encodeURIComponent(target)}` 40 `?key=${key}&url=${encodeURIComponent(target)}`
41 const data = await c.var.storage.fetch( 41 const data = await c.var.storage.fetch(`website:${host}`, FRESH_TTL, async () => {
42 `website:${host}`, 42 const result = await fetchJson<ApiVoidResp>(upstream, { timeoutMs: 15000 })
43 SUCCESS_TTL, 43 if (!result?.data?.report) {
44 NEGATIVE_TTL, 44 throw new ApiError('UPSTREAM_ERROR', 'APIVoid did not return a report', 502)
45 async () => { 45 }
46 const result = await fetchJson<ApiVoidResp>(upstream, { timeoutMs: 15000 }) 46 return result.data.report as Record<string, unknown>
47 if (!result?.data?.report) { 47 })
48 throw new ApiError('UPSTREAM_ERROR', 'APIVoid did not return a report', 502)
49 }
50 return result.data.report as Record<string, unknown>
51 },
52 )
53 return c.json(data as Record<string, unknown>, 200) 48 return c.json(data as Record<string, unknown>, 200)
54}) 49})
55 50
api/src/schemas/index.ts +2 −1
@@ -136,7 +136,8 @@ export const ItunesAppSchema = z
136 .openapi('ItunesApp', { description: 'iTunes lookup result, passthrough' }) 136 .openapi('ItunesApp', { description: 'iTunes lookup result, passthrough' })
137 137
138export const AndroidReportSchema = z.object({}).openapi('AndroidReport', { 138export const AndroidReportSchema = z.object({}).openapi('AndroidReport', {
139 description: 'Exodus Privacy report with resolved trackers', 139 description:
140 'Exodus Privacy trackers merged with Plexus de-Googled compatibility (degoogled)',
140}) 141})
141 142
142export const WebsiteReportSchema = z 143export const WebsiteReportSchema = z
api/tests/app.test.ts +12
@@ -74,6 +74,18 @@ describe('auth', () => {
74 }) 74 })
75}) 75})
76 76
77describe('middleware scoping', () => {
78 it('public routes are edge cacheable', async () => {
79 const res = await hit('/v1/stats')
80 expect(res.headers.get('cache-control')).toBe('public, s-maxage=300')
81 })
82
83 it('enrich routes are not advertised as public cacheable', async () => {
84 const res = await hit('/v1/enrich/privacy/1')
85 expect(res.headers.get('cache-control') ?? '').not.toContain('public')
86 })
87})
88
77describe('mcp', () => { 89describe('mcp', () => {
78 it('lists tools', async () => { 90 it('lists tools', async () => {
79 const res = await hit('/v1/mcp', { 91 const res = await hit('/v1/mcp', {
api/tests/cache.test.ts added +94
@@ -0,0 +1,94 @@
1// Unit tests for the cache freshness + serve-stale-on-failure behaviour
2import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
3import { wrapFetch, type Storage, type StoredEntry } from '@/lib/cache'
4
5const FRESH = 60 // seconds
6
7// Minimal in-test storage that stamps the time on set, like the real backends
8const makeStorage = () => {
9 const map = new Map<string, StoredEntry>()
10 const storage: Storage = {
11 async get<T>(key: string) {
12 return (map.get(key) as StoredEntry<T>) ?? null
13 },
14 async set<T>(key: string, value: T) {
15 map.set(key, { value, cachedAt: Date.now() })
16 },
17 fetch: async () => {
18 throw new Error('uninit')
19 },
20 }
21 storage.fetch = wrapFetch(storage)
22 return { storage, map }
23}
24
25describe('cache wrapFetch', () => {
26 beforeEach(() => vi.useFakeTimers())
27 afterEach(() => vi.useRealTimers())
28
29 it('miss runs the loader, stores, and returns the value', async () => {
30 const { storage, map } = makeStorage()
31 const loader = vi.fn().mockResolvedValue('v1')
32 expect(await storage.fetch('k', FRESH, loader)).toBe('v1')
33 expect(loader).toHaveBeenCalledTimes(1)
34 expect(map.get('k')).toMatchObject({ value: 'v1' })
35 })
36
37 it('fresh cache is served without touching the loader', async () => {
38 const { storage } = makeStorage()
39 await storage.fetch('k', FRESH, vi.fn().mockResolvedValue('v1'))
40 vi.advanceTimersByTime(30_000) // still inside the window
41 const loader = vi.fn().mockResolvedValue('v2')
42 expect(await storage.fetch('k', FRESH, loader)).toBe('v1')
43 expect(loader).not.toHaveBeenCalled()
44 })
45
46 it('stale cache refreshes and re-stores on success', async () => {
47 const { storage, map } = makeStorage()
48 await storage.fetch('k', FRESH, vi.fn().mockResolvedValue('v1'))
49 vi.advanceTimersByTime(61_000) // past the window
50 const loader = vi.fn().mockResolvedValue('v2')
51 expect(await storage.fetch('k', FRESH, loader)).toBe('v2')
52 expect(loader).toHaveBeenCalledTimes(1)
53 expect(map.get('k')).toMatchObject({ value: 'v2' })
54 })
55
56 it('stale cache falls back to the stale value on failure, without overwriting', async () => {
57 const { storage, map } = makeStorage()
58 await storage.fetch('k', FRESH, vi.fn().mockResolvedValue('v1'))
59 vi.advanceTimersByTime(61_000)
60 const failing = vi.fn().mockRejectedValue(new Error('upstream down'))
61 expect(await storage.fetch('k', FRESH, failing)).toBe('v1')
62 expect(map.get('k')).toMatchObject({ value: 'v1' })
63 })
64
65 it('miss with a failing loader throws and caches nothing', async () => {
66 const { storage, map } = makeStorage()
67 const failing = vi.fn().mockRejectedValue(new Error('boom'))
68 await expect(storage.fetch('k', FRESH, failing)).rejects.toThrow('boom')
69 expect(map.has('k')).toBe(false)
70 })
71
72 it('entries never expire, a year-old value still serves when upstream fails', async () => {
73 const { storage } = makeStorage()
74 await storage.fetch('k', FRESH, vi.fn().mockResolvedValue('v1'))
75 vi.advanceTimersByTime(365 * 24 * 60 * 60 * 1000)
76 const failing = vi.fn().mockRejectedValue(new Error('down'))
77 expect(await storage.fetch('k', FRESH, failing)).toBe('v1')
78 })
79
80 it('an undefined loader result throws instead of caching an empty body', async () => {
81 const { storage, map } = makeStorage()
82 const loader = vi.fn().mockResolvedValue(undefined)
83 await expect(storage.fetch('k', FRESH, loader)).rejects.toThrow()
84 expect(map.has('k')).toBe(false)
85 })
86
87 it('a corrupted undefined cached value is treated as a miss, not served empty', async () => {
88 const { storage, map } = makeStorage()
89 map.set('k', { value: undefined, cachedAt: Date.now() })
90 expect(await storage.fetch('k', FRESH, vi.fn().mockResolvedValue('fresh'))).toBe(
91 'fresh',
92 )
93 })
94})
api/tests/plexus.test.ts added +45
@@ -0,0 +1,45 @@
1// Unit tests for Plexus de-Googled rating aggregation
2import { describe, it, expect } from 'vitest'
3import { summarizeRatings, type PlexusRating } from '@/lib/plexus'
4
5const r = (type: string, num: number): PlexusRating => ({
6 rating_type: type,
7 score: { numerator: num, denominator: 4 },
8})
9
10describe('summarizeRatings', () => {
11 it('maps perfect native scores to gold', () => {
12 const out = summarizeRatings([r('native', 4), r('native', 4)])
13 expect(out.native).toMatchObject({
14 available: true,
15 status: 'gold',
16 score: 4,
17 ratings: 2,
18 })
19 expect(out.microg).toEqual({ available: false })
20 })
21
22 it('grades silver, bronze and broken by average score', () => {
23 expect(summarizeRatings([r('native', 3)]).native).toMatchObject({ status: 'silver' })
24 expect(summarizeRatings([r('native', 2)]).native).toMatchObject({ status: 'bronze' })
25 expect(summarizeRatings([r('native', 1)]).native).toMatchObject({ status: 'broken' })
26 })
27
28 it('separates native from micro_g ratings', () => {
29 const out = summarizeRatings([r('native', 4), r('micro_g', 2)])
30 expect(out.native).toMatchObject({ status: 'gold', ratings: 1 })
31 expect(out.microg).toMatchObject({ status: 'bronze', ratings: 1 })
32 })
33
34 it('marks a type unavailable when it has no ratings', () => {
35 expect(summarizeRatings([]).native).toEqual({ available: false })
36 })
37
38 it('ignores ratings with a missing or zero score', () => {
39 const bad = [
40 { rating_type: 'native' },
41 { rating_type: 'native', score: { denominator: 0 } },
42 ]
43 expect(summarizeRatings(bad as PlexusRating[]).native).toEqual({ available: false })
44 })
45})
lib/checks/make-info-stats.py +24 −12
@@ -163,18 +163,30 @@ def fetch_all_data(owner, repo, token):
163 data["commit_count"] = None 163 data["commit_count"] = None
164 data["ai_commit_count"] = None 164 data["ai_commit_count"] = None
165 165
166 alerts = gh_get(
167 f"/repos/{owner}/{repo}/dependabot/alerts", token,
168 {"state": "open", "severity": "critical,high", "per_page": 1},
169 )
170 data["has_security_alerts"] = bool(alerts) if alerts is not None else None
171
172 languages = gh_get(f"/repos/{owner}/{repo}/languages", token) 166 languages = gh_get(f"/repos/{owner}/{repo}/languages", token)
173 data["languages"] = list(languages.keys()) if languages is not None else None 167 data["languages"] = list(languages.keys()) if languages is not None else None
174 168
169 report = _enrich_get(f"security/{owner}/{repo}")
170 data["unpatched_advisories"] = _count_unpatched_advisories(report)
171
175 return data 172 return data
176 173
177 174
175SECURITY_SEVERITIES = {"medium", "high", "critical"}
176
177
178def _count_unpatched_advisories(report):
179 """Count open advisories of medium severity or above that are unpatched, or None."""
180 if not report:
181 return None
182 items = (report.get("advisories") or {}).get("items") or []
183 return sum(
184 1 for a in items
185 if not a.get("isPatched")
186 and str(a.get("severity", "")).lower() in SECURITY_SEVERITIES
187 )
188
189
178def grade_stats(data): 190def grade_stats(data):
179 """Grade repo stats, returning list of (emoji, label, value_str) tuples.""" 191 """Grade repo stats, returning list of (emoji, label, value_str) tuples."""
180 stats = [] 192 stats = []
@@ -255,13 +267,13 @@ def grade_stats(data):
255 else: 267 else:
256 stats.append((RED if archived else GREEN, "Is Archived", "Yes" if archived else "No")) 268 stats.append((RED if archived else GREEN, "Is Archived", "Yes" if archived else "No"))
257 269
258 alerts = data.get("has_security_alerts") 270 adv = data.get("unpatched_advisories")
259 if alerts is None: 271 if adv is None:
260 stats.append((WHITE, "Security Alerts", "Unknown")) 272 stats.append((WHITE, "Security Advisories", "Unknown"))
261 elif alerts: 273 elif adv > 0:
262 stats.append((RED, "Security Alerts", "Open critical/high alerts")) 274 stats.append((ORANGE, "Security Advisories", f"{adv} unpatched CVEs"))
263 else: 275 else:
264 stats.append((GREEN, "Security Alerts", "None")) 276 stats.append((GREEN, "Security Advisories", "No unpatched active CVEs found"))
265 277
266 ai = data.get("ai_commit_count") 278 ai = data.get("ai_commit_count")
267 if ai is None: 279 if ai is None: