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'
2626import mcp from '@/routes/mcp'
2727
2828const buildPublic = () => {
29 // Public routes, CORS open, rate limited, cacheable
29 // Public browse routes, shared middleware is applied at the app level
3030 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 })
3731 pub.route('/', services)
3832 pub.route('/', categoriesRoute)
3933 pub.route('/', searchRoute)
@@ -68,6 +62,19 @@ export const buildApp = () => {
6862 await next()
6963 })
7064
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
7178 app.route('/v1', buildPublic())
7279 app.route('/v1', buildPrivate())
7380 app.route('/v1', mcp)
@@ -100,7 +107,9 @@ Then, add the \`Authorization: Bearer <your-token>\` header when accessing the e
100107<summary>Caching</summary>
101108
102109Some 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.
104113</details>
105114
106115<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 @@
11/**
2 * The storage interface
3 * Caches certain lookup results, so as to reduce load and improve perf
4 * Picks between in-mem store for Bun/Node or KV db for Cloudflare Workers
2 * Storage cache, an in-memory Map on Bun/Node or KV on Cloudflare Workers.
3 * Entries are kept indefinitely with their fetch time; a freshness window
4 * decides serve-as-is vs refresh. On a failed refresh the stale value is
5 * served, and failures are never cached.
56 */
67
7import { ApiError, type ErrorCode } from '@/lib/errors'
8import { ApiError } from '@/lib/errors'
89import type { AppEnv } from '@/types'
910import { kvStorage } from '@/lib/cache/kv'
1011import { memoryStorage } from '@/lib/cache/memory'
1112
13export interface StoredEntry<T = unknown> {
14 value: T
15 // Epoch milliseconds when this value was fetched
16 cachedAt: number
17}
18
1219export interface Storage {
13 get<T = unknown>(key: string): Promise<T | null>
14 set<T = unknown>(key: string, value: T, ttlSec: number): Promise<void>
15 // Run loader once, cache the result for ttl, cache negatives for negTtl
16 fetch<T>(key: string, ttl: number, negTtl: number, loader: () => Promise<T>): Promise<T>
20 get<T = unknown>(key: string): Promise<StoredEntry<T> | null>
21 // Store a value indefinitely, stamped with the current time
22 set<T = unknown>(key: string, value: T): Promise<void>
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>
1725}
1826
1927export const createStorage = (env: AppEnv): Storage =>
2028 env.CACHE ? kvStorage(env.CACHE) : memoryStorage()
2129
22interface NegEntry {
23 ok: false
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
30// Shared fetch wrapper, caches only successes and serves stale on failure.
31// Never resolves to undefined, a missing value yields an error not an empty body.
3432export const wrapFetch =
3533 (storage: Storage) =>
36 async <T>(
37 key: string,
38 ttl: number,
39 negTtl: number,
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)
34 async <T>(key: string, freshSec: number, loader: () => Promise<T>): Promise<T> => {
35 const cached = await storage.get<T>(key)
36 if (cached && cached.value !== undefined) {
37 if (Date.now() - cached.cachedAt < freshSec * 1000) return cached.value
4638 }
4739 try {
4840 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)
5045 return value
5146 } catch (caught) {
52 const error =
53 caught instanceof ApiError
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
47 if (cached && cached.value !== undefined) return cached.value
48 throw caught
6449 }
6550 }
api/src/lib/cache/kv.ts +8 −7
@@ -1,17 +1,18 @@
11/* Workers KV backed Storage */
2import type { Storage } from '@/lib/cache'
2import type { Storage, StoredEntry } from '@/lib/cache'
33import { wrapFetch } from '@/lib/cache'
44
55export const kvStorage = (kv: KVNamespace): Storage => {
66 const storage: Storage = {
77 async get<T>(key: string) {
8 const value = await kv.get(key, 'json')
9 return (value as T) ?? null
8 return (await kv.get<StoredEntry<T>>(key, 'json')) ?? null
109 },
11 async set<T>(key: string, value: T, ttlSec: number) {
12 await kv.put(key, JSON.stringify(value), {
13 expirationTtl: Math.max(ttlSec, 60),
14 })
10 async set<T>(key: string, value: T) {
11 // No expirationTtl, entries are kept indefinitely
12 await kv.put(
13 key,
14 JSON.stringify({ value, cachedAt: Date.now() } satisfies StoredEntry<T>),
15 )
1516 },
1617 fetch: async () => {
1718 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 */
2import type { Storage } from '@/lib/cache'
1/* In-process Map storage cache for Node/Bun */
2import type { Storage, StoredEntry } from '@/lib/cache'
33import { wrapFetch } from '@/lib/cache'
44
5interface Entry {
6 expires: number
7 value: unknown
8}
9const store = new Map<string, Entry>()
5const store = new Map<string, StoredEntry>()
106
117export const memoryStorage = (): Storage => {
128 const storage: Storage = {
139 async get<T>(key: string) {
14 const entry = store.get(key)
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
10 return (store.get(key) as StoredEntry<T>) ?? null
2111 },
22 async set<T>(key: string, value: T, ttlSec: number) {
23 store.set(key, { expires: Date.now() + ttlSec * 1000, value })
12 async set<T>(key: string, value: T) {
13 // Kept indefinitely, freshness is decided by the caller not by expiry
14 store.set(key, { value, cachedAt: Date.now() })
2415 },
2516 fetch: async () => {
2617 throw new Error('uninit')
api/src/lib/fetch.ts +1
@@ -17,6 +17,7 @@ const ALLOWED_HOSTS = new Set([
1717 'endpoint.apivoid.com',
1818 'raw.githubusercontent.com',
1919 'api.deps.dev',
20 'plexus.techlore.tech',
2021])
2122
2223export 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
22import { createRoute, z } from '@hono/zod-openapi'
33import { fetchJson } from '@/lib/fetch'
44import { ApiError } from '@/lib/errors'
5import { freshSeconds } from '@/lib/cache/freshness'
56import { newApp } from '@/lib/openapi'
7import { summarizeRatings, type PlexusRating } from '@/lib/plexus'
68import { AndroidReportSchema, ErrorResponse, Ok } from '@/schemas'
79
810const app = newApp()
911
10const SUCCESS_TTL = 7 * 24 * 60 * 60
11const NEGATIVE_TTL = 6 * 60 * 60
12const FRESH_TTL = freshSeconds('android')
1213
1314interface AppDetails {
1415 trackers: number[]
@@ -19,6 +20,39 @@ interface TrackerLookup {
1920}
2021
2122const 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}
2256
2357const route = createRoute({
2458 method: 'get',
@@ -31,40 +65,28 @@ const route = createRoute({
3165 401: ErrorResponse,
3266 404: ErrorResponse,
3367 500: ErrorResponse,
34 502: ErrorResponse,
3568 },
3669})
3770
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
3972app.openapi(route, async (c) => {
4073 const { pkg } = c.req.valid('param')
4174 const token = c.env.EXODUS_TOKEN
4275 if (!token) throw new ApiError('INTERNAL', 'EXODUS_TOKEN not configured', 500)
43 const headers = { Authorization: `Token ${token}` }
44 const data = await c.var.storage.fetch(
45 `android:${pkg}`,
46 SUCCESS_TTL,
47 NEGATIVE_TTL,
48 async () => {
49 const detailsUrl = `${EXODUS_BASE}/search/${encodeURIComponent(pkg)}/details`
50 const details = await fetchJson<AppDetails[]>(detailsUrl, {
51 headers,
52 timeoutMs: 10000,
53 })
54 const appInfo = details?.[0]
55 if (!appInfo) {
56 throw new ApiError('NOT_FOUND', `Package '${pkg}' not found on Exodus`, 404)
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 )
76 const data = await c.var.storage.fetch(`android:${pkg}`, FRESH_TTL, async () => {
77 const [exodus, degoogled] = await Promise.all([
78 getExodus(pkg, token),
79 getDegoogled(pkg),
80 ])
81 if (!exodus && !degoogled) {
82 throw new ApiError(
83 'NOT_FOUND',
84 `Package '${pkg}' not found on Exodus or Plexus`,
85 404,
86 )
87 }
88 return { ...exodus, degoogled: degoogled ?? null }
89 })
6890 return c.json(data, 200)
6991})
7092
api/src/routes/private/discord.ts +16 −21
@@ -1,13 +1,13 @@
11// Discord invite info, projected to a compact response shape
22import { createRoute, z } from '@hono/zod-openapi'
33import { fetchJson } from '@/lib/fetch'
4import { freshSeconds } from '@/lib/cache/freshness'
45import { newApp } from '@/lib/openapi'
56import { DiscordInviteSchema, ErrorResponse, Ok } from '@/schemas'
67
78const app = newApp()
89
9const SUCCESS_TTL = 24 * 60 * 60
10const NEGATIVE_TTL = 60 * 60
10const FRESH_TTL = freshSeconds('discord')
1111
1212interface Invite {
1313 code?: string
@@ -51,25 +51,20 @@ app.openapi(route, async (c) => {
5151 const upstream =
5252 `https://discord.com/api/v9/invites/${encodeURIComponent(invite)}` +
5353 '?with_counts=true&with_expiration=true'
54 const data = await c.var.storage.fetch(
55 `discord:${invite}`,
56 SUCCESS_TTL,
57 NEGATIVE_TTL,
58 async () => {
59 const raw = await fetchJson<Invite>(upstream, { headers })
60 const guild = raw.guild
61 return {
62 inviteCode: raw.code ?? null,
63 name: guild?.name ?? null,
64 memberCount: raw.approximate_member_count ?? null,
65 memberOnlineCount: raw.approximate_presence_count ?? null,
66 channel: raw.channel?.name ?? null,
67 icon: iconUrl(guild?.id, guild?.icon),
68 banner: bannerUrl(guild?.id, guild?.splash),
69 inviter: raw.inviter?.global_name ?? null,
70 }
71 },
72 )
54 const data = await c.var.storage.fetch(`discord:${invite}`, FRESH_TTL, async () => {
55 const raw = await fetchJson<Invite>(upstream, { headers })
56 const guild = raw.guild
57 return {
58 inviteCode: raw.code ?? null,
59 name: guild?.name ?? null,
60 memberCount: raw.approximate_member_count ?? null,
61 memberOnlineCount: raw.approximate_presence_count ?? null,
62 channel: raw.channel?.name ?? null,
63 icon: iconUrl(guild?.id, guild?.icon),
64 banner: bannerUrl(guild?.id, guild?.splash),
65 inviter: raw.inviter?.global_name ?? null,
66 }
67 })
7368 return c.json(data, 200)
7469})
7570
api/src/routes/private/github.ts +19 −24
@@ -2,13 +2,13 @@
22import { createRoute, z } from '@hono/zod-openapi'
33import { fetchJson } from '@/lib/fetch'
44import { githubHeaders } from '@/lib/github'
5import { freshSeconds } from '@/lib/cache/freshness'
56import { newApp } from '@/lib/openapi'
67import { ErrorResponse, GithubRepoSchema, Ok } from '@/schemas'
78
89const app = newApp()
910
10const SUCCESS_TTL = 24 * 60 * 60
11const NEGATIVE_TTL = 60 * 60
11const FRESH_TTL = freshSeconds('github')
1212
1313interface RepoInfo {
1414 owner?: { login?: string; avatar_url?: string }
@@ -121,28 +121,23 @@ app.openapi(route, async (c) => {
121121 const { owner, repo } = c.req.valid('param')
122122 const slug = `${owner}/${repo}`
123123 const headers = githubHeaders(c.env.GITHUB_TOKEN)
124 const data = await c.var.storage.fetch(
125 `gh:${slug}`,
126 SUCCESS_TTL,
127 NEGATIVE_TTL,
128 async () => {
129 const base = `https://api.github.com/repos/${slug}`
130 const [info, languages, tags, contributors, commits] = await Promise.all([
131 fetchJson<RepoInfo>(base, { headers }),
132 fetchJson<Record<string, number>>(`${base}/languages`, { headers }),
133 fetchJson<Tag[]>(`${base}/tags`, { headers }),
134 fetchJson<Contributor[]>(`${base}/contributors?per_page=100`, { headers }),
135 fetchJson<Commit[]>(`${base}/commits`, { headers }),
136 ])
137 return {
138 info: mapInfo(info),
139 languages: languages ?? {},
140 versions: tags.map(mapVersion),
141 contributors: contributors.map(mapContributor),
142 commits: commits.map(mapCommit),
143 }
144 },
145 )
124 const data = await c.var.storage.fetch(`gh:${slug}`, FRESH_TTL, async () => {
125 const base = `https://api.github.com/repos/${slug}`
126 const [info, languages, tags, contributors, commits] = await Promise.all([
127 fetchJson<RepoInfo>(base, { headers }),
128 fetchJson<Record<string, number>>(`${base}/languages`, { headers }),
129 fetchJson<Tag[]>(`${base}/tags`, { headers }),
130 fetchJson<Contributor[]>(`${base}/contributors?per_page=100`, { headers }),
131 fetchJson<Commit[]>(`${base}/commits`, { headers }),
132 ])
133 return {
134 info: mapInfo(info),
135 languages: languages ?? {},
136 versions: tags.map(mapVersion),
137 contributors: contributors.map(mapContributor),
138 commits: commits.map(mapCommit),
139 }
140 })
146141 return c.json(data, 200)
147142})
148143
api/src/routes/private/ios.ts +10 −15
@@ -2,13 +2,13 @@
22import { createRoute, z } from '@hono/zod-openapi'
33import { fetchJson } from '@/lib/fetch'
44import { ApiError } from '@/lib/errors'
5import { freshSeconds } from '@/lib/cache/freshness'
56import { newApp } from '@/lib/openapi'
67import { ErrorResponse, ItunesAppSchema, Ok } from '@/schemas'
78
89const app = newApp()
910
10const SUCCESS_TTL = 7 * 24 * 60 * 60
11const NEGATIVE_TTL = 6 * 60 * 60
11const FRESH_TTL = freshSeconds('ios')
1212
1313interface ItunesResult {
1414 resultCount: number
@@ -42,19 +42,14 @@ app.openapi(route, async (c) => {
4242 const id = normalize(bundleId)
4343 const idParam = /^\d+$/.test(id) ? `id=${id}` : `bundleId=${encodeURIComponent(id)}`
4444 const upstream = `https://itunes.apple.com/lookup?${idParam}&country=${country}`
45 const data = await c.var.storage.fetch(
46 `ios:${country}:${id}`,
47 SUCCESS_TTL,
48 NEGATIVE_TTL,
49 async () => {
50 const result = await fetchJson<ItunesResult>(upstream)
51 const first = result.results?.[0]
52 if (!result.resultCount || !first) {
53 throw new ApiError('NOT_FOUND', `No app found for '${id}'`, 404)
54 }
55 return first
56 },
57 )
45 const data = await c.var.storage.fetch(`ios:${country}:${id}`, FRESH_TTL, async () => {
46 const result = await fetchJson<ItunesResult>(upstream)
47 const first = result.results?.[0]
48 if (!result.resultCount || !first) {
49 throw new ApiError('NOT_FOUND', `No app found for '${id}'`, 404)
50 }
51 return first
52 })
5853 return c.json(data, 200)
5954})
6055
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
22import { createRoute, z } from '@hono/zod-openapi'
33import { fetchJson } from '@/lib/fetch'
4import { freshSeconds } from '@/lib/cache/freshness'
45import { newApp } from '@/lib/openapi'
56import { ErrorResponse, Ok, TosdrServiceSchema } from '@/schemas'
67
78const app = newApp()
89
9const SUCCESS_TTL = 7 * 24 * 60 * 60
10const NEGATIVE_TTL = 60 * 60
10const FRESH_TTL = freshSeconds('privacy')
1111
1212const route = createRoute({
1313 method: 'get',
@@ -23,15 +23,12 @@ const route = createRoute({
2323 },
2424})
2525
26// Pass through the ToS;DR v3 service shape, cached for a week
26// Pass through the ToS;DR v3 service shape
2727app.openapi(route, async (c) => {
2828 const { tosdrId } = c.req.valid('param')
2929 const upstream = `https://api.tosdr.org/service/v3?id=${encodeURIComponent(tosdrId)}`
30 const data = await c.var.storage.fetch(
31 `tosdr:${tosdrId}`,
32 SUCCESS_TTL,
33 NEGATIVE_TTL,
34 () => fetchJson(upstream, { timeoutMs: 8000 }),
30 const data = await c.var.storage.fetch(`tosdr:${tosdrId}`, FRESH_TTL, () =>
31 fetchJson(upstream, { timeoutMs: 8000 }),
3532 )
3633 return c.json(data as Record<string, unknown>, 200)
3734})
api/src/routes/private/reddit.ts +9 −14
@@ -1,13 +1,13 @@
11// Subreddit info and top monthly posts
22import { createRoute, z } from '@hono/zod-openapi'
33import { fetchJson } from '@/lib/fetch'
4import { freshSeconds } from '@/lib/cache/freshness'
45import { newApp } from '@/lib/openapi'
56import { ErrorResponse, Ok, SubredditSchema } from '@/schemas'
67
78const app = newApp()
89
9const SUCCESS_TTL = 24 * 60 * 60
10const NEGATIVE_TTL = 60 * 60
10const FRESH_TTL = freshSeconds('reddit')
1111
1212interface AboutData {
1313 data?: {
@@ -91,18 +91,13 @@ app.openapi(route, async (c) => {
9191 const { sub } = c.req.valid('param')
9292 const aboutUrl = `https://www.reddit.com/r/${sub}/about.json`
9393 const topUrl = `https://www.reddit.com/r/${sub}/top.json?t=month&limit=10`
94 const data = await c.var.storage.fetch(
95 `reddit:${sub}`,
96 SUCCESS_TTL,
97 NEGATIVE_TTL,
98 async () => {
99 const [about, top] = await Promise.all([
100 fetchJson<AboutData>(aboutUrl, { headers }),
101 fetchJson<PostListing>(topUrl, { headers }),
102 ])
103 return { info: mapInfo(about), posts: mapPosts(top) }
104 },
105 )
94 const data = await c.var.storage.fetch(`reddit:${sub}`, FRESH_TTL, async () => {
95 const [about, top] = await Promise.all([
96 fetchJson<AboutData>(aboutUrl, { headers }),
97 fetchJson<PostListing>(topUrl, { headers }),
98 ])
99 return { info: mapInfo(about), posts: mapPosts(top) }
100 })
106101 return c.json(data, 200)
107102})
108103
api/src/routes/private/security.ts +14 −15
@@ -2,13 +2,13 @@
22import { createRoute, z } from '@hono/zod-openapi'
33import { fetchJson } from '@/lib/fetch'
44import { githubHeaders } from '@/lib/github'
5import { freshSeconds } from '@/lib/cache/freshness'
56import { newApp } from '@/lib/openapi'
67import { ErrorResponse, Ok, SecurityReportSchema } from '@/schemas'
78
89const app = newApp()
910
10const SUCCESS_TTL = 7 * 24 * 60 * 60
11const NEGATIVE_TTL = 60 * 60
11const FRESH_TTL = freshSeconds('security')
1212
1313interface Check {
1414 name?: string
@@ -24,6 +24,8 @@ interface Project {
2424
2525interface Vuln {
2626 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
2729 first_patched_version?: { identifier?: string } | null
2830}
2931
@@ -63,7 +65,9 @@ const mapAdvisory = (a: Advisory) => {
6365 ),
6466 ]
6567 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)
6771 const firstPatchedVersion = explicit ?? deriveFix(ranges)
6872 return {
6973 ghsaId: a.ghsa_id ?? '',
@@ -133,18 +137,13 @@ const route = createRoute({
133137app.openapi(route, async (c) => {
134138 const { owner, repo } = c.req.valid('param')
135139 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 )
140 const data = await c.var.storage.fetch(`sec:${slug}`, FRESH_TTL, 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 })
148147 return c.json(data, 200)
149148})
150149
api/src/routes/private/website.ts +9 −14
@@ -2,13 +2,13 @@
22import { createRoute, z } from '@hono/zod-openapi'
33import { fetchJson } from '@/lib/fetch'
44import { ApiError } from '@/lib/errors'
5import { freshSeconds } from '@/lib/cache/freshness'
56import { newApp } from '@/lib/openapi'
67import { ErrorResponse, Ok, WebsiteReportSchema } from '@/schemas'
78
89const app = newApp()
910
10const SUCCESS_TTL = 30 * 24 * 60 * 60
11const NEGATIVE_TTL = 60 * 60
11const FRESH_TTL = freshSeconds('website')
1212
1313interface ApiVoidResp {
1414 data?: { report?: unknown }
@@ -38,18 +38,13 @@ app.openapi(route, async (c) => {
3838 const upstream =
3939 'https://endpoint.apivoid.com/urlrep/v1/pay-as-you-go/' +
4040 `?key=${key}&url=${encodeURIComponent(target)}`
41 const data = await c.var.storage.fetch(
42 `website:${host}`,
43 SUCCESS_TTL,
44 NEGATIVE_TTL,
45 async () => {
46 const result = await fetchJson<ApiVoidResp>(upstream, { timeoutMs: 15000 })
47 if (!result?.data?.report) {
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 )
41 const data = await c.var.storage.fetch(`website:${host}`, FRESH_TTL, async () => {
42 const result = await fetchJson<ApiVoidResp>(upstream, { timeoutMs: 15000 })
43 if (!result?.data?.report) {
44 throw new ApiError('UPSTREAM_ERROR', 'APIVoid did not return a report', 502)
45 }
46 return result.data.report as Record<string, unknown>
47 })
5348 return c.json(data as Record<string, unknown>, 200)
5449})
5550
api/src/schemas/index.ts +2 −1
@@ -136,7 +136,8 @@ export const ItunesAppSchema = z
136136 .openapi('ItunesApp', { description: 'iTunes lookup result, passthrough' })
137137
138138export 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)',
140141})
141142
142143export const WebsiteReportSchema = z
api/tests/app.test.ts +12
@@ -74,6 +74,18 @@ describe('auth', () => {
7474 })
7575})
7676
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
7789describe('mcp', () => {
7890 it('lists tools', async () => {
7991 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):
163163 data["commit_count"] = None
164164 data["ai_commit_count"] = None
165165
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
172166 languages = gh_get(f"/repos/{owner}/{repo}/languages", token)
173167 data["languages"] = list(languages.keys()) if languages is not None else None
174168
169 report = _enrich_get(f"security/{owner}/{repo}")
170 data["unpatched_advisories"] = _count_unpatched_advisories(report)
171
175172 return data
176173
177174
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
178190def grade_stats(data):
179191 """Grade repo stats, returning list of (emoji, label, value_str) tuples."""
180192 stats = []
@@ -255,13 +267,13 @@ def grade_stats(data):
255267 else:
256268 stats.append((RED if archived else GREEN, "Is Archived", "Yes" if archived else "No"))
257269
258 alerts = data.get("has_security_alerts")
259 if alerts is None:
260 stats.append((WHITE, "Security Alerts", "Unknown"))
261 elif alerts:
262 stats.append((RED, "Security Alerts", "Open critical/high alerts"))
270 adv = data.get("unpatched_advisories")
271 if adv is None:
272 stats.append((WHITE, "Security Advisories", "Unknown"))
273 elif adv > 0:
274 stats.append((ORANGE, "Security Advisories", f"{adv} unpatched CVEs"))
263275 else:
264 stats.append((GREEN, "Security Alerts", "None"))
276 stats.append((GREEN, "Security Advisories", "No unpatched active CVEs found"))
265277
266278 ai = data.get("ai_commit_count")
267279 if ai is None: