Commit 3ecb71ee10
Unsigned
Layout: unified · split
api/src/app.ts +17 −8
| @@ -26,14 +26,8 @@ import security from '@/routes/private/security' | ||
| 26 | 26 | import mcp from '@/routes/mcp' |
| 27 | 27 | |
| 28 | 28 | const buildPublic = () => { |
| 29 | // Public routes, CORS open, rate limited, cacheable | |
| 29 | // Public browse routes, shared middleware is applied at the app level | |
| 30 | 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 | 31 | pub.route('/', services) |
| 38 | 32 | pub.route('/', categoriesRoute) |
| 39 | 33 | pub.route('/', searchRoute) |
| @@ -68,6 +62,19 @@ export const buildApp = () => { | ||
| 68 | 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 | 78 | app.route('/v1', buildPublic()) |
| 72 | 79 | app.route('/v1', buildPrivate()) |
| 73 | 80 | app.route('/v1', mcp) |
| @@ -100,7 +107,9 @@ Then, add the \`Authorization: Bearer <your-token>\` header when accessing the e | ||
| 100 | 107 | <summary>Caching</summary> |
| 101 | 108 | |
| 102 | 109 | Some responses are cached to reduce load on upstream services. |
| 103 | When configured, successful enrichment data results are put in KV for upto 7 days. | |
| 110 | When 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 | |
| 112 | demand, falling back to the cached copy if the upstream is unavailable. | |
| 104 | 113 | </details> |
| 105 | 114 | |
| 106 | 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 | ||
| 7 | export 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 | ||
| 18 | export type CacheRoute = keyof typeof CACHE_DAYS | |
| 19 | ||
| 20 | const DAY_SECONDS = 24 * 60 * 60 | |
| 21 | ||
| 22 | // Freshness window in seconds for a route, as passed to storage.fetch() | |
| 23 | export 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 | |
| 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. | |
| 5 | 6 | */ |
| 6 | 7 | |
| 7 | import { ApiError, type ErrorCode } from '@/lib/errors' | |
| 8 | import { ApiError } from '@/lib/errors' | |
| 8 | 9 | import type { AppEnv } from '@/types' |
| 9 | 10 | import { kvStorage } from '@/lib/cache/kv' |
| 10 | 11 | import { memoryStorage } from '@/lib/cache/memory' |
| 11 | 12 | |
| 13 | export interface StoredEntry<T = unknown> { | |
| 14 | value: T | |
| 15 | // Epoch milliseconds when this value was fetched | |
| 16 | cachedAt: number | |
| 17 | } | |
| 18 | ||
| 12 | 19 | export 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> | |
| 17 | 25 | } |
| 18 | 26 | |
| 19 | 27 | export const createStorage = (env: AppEnv): Storage => |
| 20 | 28 | env.CACHE ? kvStorage(env.CACHE) : memoryStorage() |
| 21 | 29 | |
| 22 | interface NegEntry { | |
| 23 | ok: false | |
| 24 | code: ErrorCode | |
| 25 | message: string | |
| 26 | status: number | |
| 27 | } | |
| 28 | interface 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. | |
| 34 | 32 | export const wrapFetch = |
| 35 | 33 | (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 | |
| 46 | 38 | } |
| 47 | 39 | try { |
| 48 | 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 | 45 | return value |
| 51 | 46 | } 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 | |
| 64 | 49 | } |
| 65 | 50 | } |
api/src/lib/cache/kv.ts +8 −7
| @@ -1,17 +1,18 @@ | ||
| 1 | 1 | /* Workers KV backed Storage */ |
| 2 | import type { Storage } from '@/lib/cache' | |
| 2 | import type { Storage, StoredEntry } from '@/lib/cache' | |
| 3 | 3 | import { wrapFetch } from '@/lib/cache' |
| 4 | 4 | |
| 5 | 5 | export const kvStorage = (kv: KVNamespace): Storage => { |
| 6 | 6 | const storage: Storage = { |
| 7 | 7 | 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 | |
| 10 | 9 | }, |
| 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 | ) | |
| 15 | 16 | }, |
| 16 | 17 | fetch: async () => { |
| 17 | 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 */ | |
| 2 | import type { Storage } from '@/lib/cache' | |
| 1 | /* In-process Map storage cache for Node/Bun */ | |
| 2 | import type { Storage, StoredEntry } from '@/lib/cache' | |
| 3 | 3 | import { wrapFetch } from '@/lib/cache' |
| 4 | 4 | |
| 5 | interface Entry { | |
| 6 | expires: number | |
| 7 | value: unknown | |
| 8 | } | |
| 9 | const store = new Map<string, Entry>() | |
| 5 | const store = new Map<string, StoredEntry>() | |
| 10 | 6 | |
| 11 | 7 | export const memoryStorage = (): Storage => { |
| 12 | 8 | const storage: Storage = { |
| 13 | 9 | 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 | |
| 21 | 11 | }, |
| 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() }) | |
| 24 | 15 | }, |
| 25 | 16 | fetch: async () => { |
| 26 | 17 | throw new Error('uninit') |
api/src/lib/fetch.ts +1
| @@ -17,6 +17,7 @@ const ALLOWED_HOSTS = new Set([ | ||
| 17 | 17 | 'endpoint.apivoid.com', |
| 18 | 18 | 'raw.githubusercontent.com', |
| 19 | 19 | 'api.deps.dev', |
| 20 | 'plexus.techlore.tech', | |
| 20 | 21 | ]) |
| 21 | 22 | |
| 22 | 23 | export 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 | ||
| 7 | export interface PlexusRating { | |
| 8 | rating_type?: string | |
| 9 | score?: { numerator?: number; denominator?: number } | |
| 10 | } | |
| 11 | ||
| 12 | const 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 | |
| 22 | const 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 | ||
| 46 | export 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 | |
| 2 | 2 | import { createRoute, z } from '@hono/zod-openapi' |
| 3 | 3 | import { fetchJson } from '@/lib/fetch' |
| 4 | 4 | import { ApiError } from '@/lib/errors' |
| 5 | import { freshSeconds } from '@/lib/cache/freshness' | |
| 5 | 6 | import { newApp } from '@/lib/openapi' |
| 7 | import { summarizeRatings, type PlexusRating } from '@/lib/plexus' | |
| 6 | 8 | import { AndroidReportSchema, ErrorResponse, Ok } from '@/schemas' |
| 7 | 9 | |
| 8 | 10 | const app = newApp() |
| 9 | 11 | |
| 10 | const SUCCESS_TTL = 7 * 24 * 60 * 60 | |
| 11 | const NEGATIVE_TTL = 6 * 60 * 60 | |
| 12 | const FRESH_TTL = freshSeconds('android') | |
| 12 | 13 | |
| 13 | 14 | interface AppDetails { |
| 14 | 15 | trackers: number[] |
| @@ -19,6 +20,39 @@ interface TrackerLookup { | ||
| 19 | 20 | } |
| 20 | 21 | |
| 21 | 22 | const EXODUS_BASE = 'https://reports.exodus-privacy.eu.org/api' |
| 23 | const PLEXUS_BASE = 'https://plexus.techlore.tech/api/v1' | |
| 24 | ||
| 25 | // Exodus apk details with tracker ids resolved to records, null if unavailable | |
| 26 | const 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 | |
| 46 | const 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 | |
| 23 | 57 | const route = createRoute({ |
| 24 | 58 | method: 'get', |
| @@ -31,40 +65,28 @@ const route = createRoute({ | ||
| 31 | 65 | 401: ErrorResponse, |
| 32 | 66 | 404: ErrorResponse, |
| 33 | 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 | |
| 39 | 72 | app.openapi(route, async (c) => { |
| 40 | 73 | const { pkg } = c.req.valid('param') |
| 41 | 74 | const token = c.env.EXODUS_TOKEN |
| 42 | 75 | 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 | }) | |
| 68 | 90 | return c.json(data, 200) |
| 69 | 91 | }) |
| 70 | 92 | |
api/src/routes/private/discord.ts +16 −21
| @@ -1,13 +1,13 @@ | ||
| 1 | 1 | // Discord invite info, projected to a compact response shape |
| 2 | 2 | import { createRoute, z } from '@hono/zod-openapi' |
| 3 | 3 | import { fetchJson } from '@/lib/fetch' |
| 4 | import { freshSeconds } from '@/lib/cache/freshness' | |
| 4 | 5 | import { newApp } from '@/lib/openapi' |
| 5 | 6 | import { DiscordInviteSchema, ErrorResponse, Ok } from '@/schemas' |
| 6 | 7 | |
| 7 | 8 | const app = newApp() |
| 8 | 9 | |
| 9 | const SUCCESS_TTL = 24 * 60 * 60 | |
| 10 | const NEGATIVE_TTL = 60 * 60 | |
| 10 | const FRESH_TTL = freshSeconds('discord') | |
| 11 | 11 | |
| 12 | 12 | interface Invite { |
| 13 | 13 | code?: string |
| @@ -51,25 +51,20 @@ app.openapi(route, async (c) => { | ||
| 51 | 51 | const upstream = |
| 52 | 52 | `https://discord.com/api/v9/invites/${encodeURIComponent(invite)}` + |
| 53 | 53 | '?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 | }) | |
| 73 | 68 | return c.json(data, 200) |
| 74 | 69 | }) |
| 75 | 70 | |
api/src/routes/private/github.ts +19 −24
| @@ -2,13 +2,13 @@ | ||
| 2 | 2 | import { createRoute, z } from '@hono/zod-openapi' |
| 3 | 3 | import { fetchJson } from '@/lib/fetch' |
| 4 | 4 | import { githubHeaders } from '@/lib/github' |
| 5 | import { freshSeconds } from '@/lib/cache/freshness' | |
| 5 | 6 | import { newApp } from '@/lib/openapi' |
| 6 | 7 | import { ErrorResponse, GithubRepoSchema, Ok } from '@/schemas' |
| 7 | 8 | |
| 8 | 9 | const app = newApp() |
| 9 | 10 | |
| 10 | const SUCCESS_TTL = 24 * 60 * 60 | |
| 11 | const NEGATIVE_TTL = 60 * 60 | |
| 11 | const FRESH_TTL = freshSeconds('github') | |
| 12 | 12 | |
| 13 | 13 | interface RepoInfo { |
| 14 | 14 | owner?: { login?: string; avatar_url?: string } |
| @@ -121,28 +121,23 @@ app.openapi(route, async (c) => { | ||
| 121 | 121 | const { owner, repo } = c.req.valid('param') |
| 122 | 122 | const slug = `${owner}/${repo}` |
| 123 | 123 | 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 | }) | |
| 146 | 141 | return c.json(data, 200) |
| 147 | 142 | }) |
| 148 | 143 | |
api/src/routes/private/ios.ts +10 −15
| @@ -2,13 +2,13 @@ | ||
| 2 | 2 | import { createRoute, z } from '@hono/zod-openapi' |
| 3 | 3 | import { fetchJson } from '@/lib/fetch' |
| 4 | 4 | import { ApiError } from '@/lib/errors' |
| 5 | import { freshSeconds } from '@/lib/cache/freshness' | |
| 5 | 6 | import { newApp } from '@/lib/openapi' |
| 6 | 7 | import { ErrorResponse, ItunesAppSchema, Ok } from '@/schemas' |
| 7 | 8 | |
| 8 | 9 | const app = newApp() |
| 9 | 10 | |
| 10 | const SUCCESS_TTL = 7 * 24 * 60 * 60 | |
| 11 | const NEGATIVE_TTL = 6 * 60 * 60 | |
| 11 | const FRESH_TTL = freshSeconds('ios') | |
| 12 | 12 | |
| 13 | 13 | interface ItunesResult { |
| 14 | 14 | resultCount: number |
| @@ -42,19 +42,14 @@ app.openapi(route, async (c) => { | ||
| 42 | 42 | const id = normalize(bundleId) |
| 43 | 43 | const idParam = /^\d+$/.test(id) ? `id=${id}` : `bundleId=${encodeURIComponent(id)}` |
| 44 | 44 | 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 | }) | |
| 58 | 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 | |
| 2 | 2 | import { createRoute, z } from '@hono/zod-openapi' |
| 3 | 3 | import { fetchJson } from '@/lib/fetch' |
| 4 | import { freshSeconds } from '@/lib/cache/freshness' | |
| 4 | 5 | import { newApp } from '@/lib/openapi' |
| 5 | 6 | import { ErrorResponse, Ok, TosdrServiceSchema } from '@/schemas' |
| 6 | 7 | |
| 7 | 8 | const app = newApp() |
| 8 | 9 | |
| 9 | const SUCCESS_TTL = 7 * 24 * 60 * 60 | |
| 10 | const NEGATIVE_TTL = 60 * 60 | |
| 10 | const FRESH_TTL = freshSeconds('privacy') | |
| 11 | 11 | |
| 12 | 12 | const route = createRoute({ |
| 13 | 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 | |
| 27 | 27 | app.openapi(route, async (c) => { |
| 28 | 28 | const { tosdrId } = c.req.valid('param') |
| 29 | 29 | 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 }), | |
| 35 | 32 | ) |
| 36 | 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 | 1 | // Subreddit info and top monthly posts |
| 2 | 2 | import { createRoute, z } from '@hono/zod-openapi' |
| 3 | 3 | import { fetchJson } from '@/lib/fetch' |
| 4 | import { freshSeconds } from '@/lib/cache/freshness' | |
| 4 | 5 | import { newApp } from '@/lib/openapi' |
| 5 | 6 | import { ErrorResponse, Ok, SubredditSchema } from '@/schemas' |
| 6 | 7 | |
| 7 | 8 | const app = newApp() |
| 8 | 9 | |
| 9 | const SUCCESS_TTL = 24 * 60 * 60 | |
| 10 | const NEGATIVE_TTL = 60 * 60 | |
| 10 | const FRESH_TTL = freshSeconds('reddit') | |
| 11 | 11 | |
| 12 | 12 | interface AboutData { |
| 13 | 13 | data?: { |
| @@ -91,18 +91,13 @@ app.openapi(route, async (c) => { | ||
| 91 | 91 | const { sub } = c.req.valid('param') |
| 92 | 92 | const aboutUrl = `https://www.reddit.com/r/${sub}/about.json` |
| 93 | 93 | 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 | }) | |
| 106 | 101 | return c.json(data, 200) |
| 107 | 102 | }) |
| 108 | 103 | |
api/src/routes/private/security.ts +14 −15
| @@ -2,13 +2,13 @@ | ||
| 2 | 2 | import { createRoute, z } from '@hono/zod-openapi' |
| 3 | 3 | import { fetchJson } from '@/lib/fetch' |
| 4 | 4 | import { githubHeaders } from '@/lib/github' |
| 5 | import { freshSeconds } from '@/lib/cache/freshness' | |
| 5 | 6 | import { newApp } from '@/lib/openapi' |
| 6 | 7 | import { ErrorResponse, Ok, SecurityReportSchema } from '@/schemas' |
| 7 | 8 | |
| 8 | 9 | const app = newApp() |
| 9 | 10 | |
| 10 | const SUCCESS_TTL = 7 * 24 * 60 * 60 | |
| 11 | const NEGATIVE_TTL = 60 * 60 | |
| 11 | const FRESH_TTL = freshSeconds('security') | |
| 12 | 12 | |
| 13 | 13 | interface Check { |
| 14 | 14 | name?: string |
| @@ -24,6 +24,8 @@ interface Project { | ||
| 24 | 24 | |
| 25 | 25 | interface Vuln { |
| 26 | 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 | 29 | first_patched_version?: { identifier?: string } | null |
| 28 | 30 | } |
| 29 | 31 | |
| @@ -63,7 +65,9 @@ const mapAdvisory = (a: Advisory) => { | ||
| 63 | 65 | ), |
| 64 | 66 | ] |
| 65 | 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 | 71 | const firstPatchedVersion = explicit ?? deriveFix(ranges) |
| 68 | 72 | return { |
| 69 | 73 | ghsaId: a.ghsa_id ?? '', |
| @@ -133,18 +137,13 @@ const route = createRoute({ | ||
| 133 | 137 | app.openapi(route, async (c) => { |
| 134 | 138 | const { owner, repo } = c.req.valid('param') |
| 135 | 139 | 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 | }) | |
| 148 | 147 | return c.json(data, 200) |
| 149 | 148 | }) |
| 150 | 149 | |
api/src/routes/private/website.ts +9 −14
| @@ -2,13 +2,13 @@ | ||
| 2 | 2 | import { createRoute, z } from '@hono/zod-openapi' |
| 3 | 3 | import { fetchJson } from '@/lib/fetch' |
| 4 | 4 | import { ApiError } from '@/lib/errors' |
| 5 | import { freshSeconds } from '@/lib/cache/freshness' | |
| 5 | 6 | import { newApp } from '@/lib/openapi' |
| 6 | 7 | import { ErrorResponse, Ok, WebsiteReportSchema } from '@/schemas' |
| 7 | 8 | |
| 8 | 9 | const app = newApp() |
| 9 | 10 | |
| 10 | const SUCCESS_TTL = 30 * 24 * 60 * 60 | |
| 11 | const NEGATIVE_TTL = 60 * 60 | |
| 11 | const FRESH_TTL = freshSeconds('website') | |
| 12 | 12 | |
| 13 | 13 | interface ApiVoidResp { |
| 14 | 14 | data?: { report?: unknown } |
| @@ -38,18 +38,13 @@ app.openapi(route, async (c) => { | ||
| 38 | 38 | const upstream = |
| 39 | 39 | 'https://endpoint.apivoid.com/urlrep/v1/pay-as-you-go/' + |
| 40 | 40 | `?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 | }) | |
| 53 | 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 | 136 | .openapi('ItunesApp', { description: 'iTunes lookup result, passthrough' }) |
| 137 | 137 | |
| 138 | 138 | export 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 | |
| 142 | 143 | export const WebsiteReportSchema = z |
api/tests/app.test.ts +12
| @@ -74,6 +74,18 @@ describe('auth', () => { | ||
| 74 | 74 | }) |
| 75 | 75 | }) |
| 76 | 76 | |
| 77 | describe('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 | ||
| 77 | 89 | describe('mcp', () => { |
| 78 | 90 | it('lists tools', async () => { |
| 79 | 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 | |
| 2 | import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' | |
| 3 | import { wrapFetch, type Storage, type StoredEntry } from '@/lib/cache' | |
| 4 | ||
| 5 | const FRESH = 60 // seconds | |
| 6 | ||
| 7 | // Minimal in-test storage that stamps the time on set, like the real backends | |
| 8 | const 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 | ||
| 25 | describe('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 | |
| 2 | import { describe, it, expect } from 'vitest' | |
| 3 | import { summarizeRatings, type PlexusRating } from '@/lib/plexus' | |
| 4 | ||
| 5 | const r = (type: string, num: number): PlexusRating => ({ | |
| 6 | rating_type: type, | |
| 7 | score: { numerator: num, denominator: 4 }, | |
| 8 | }) | |
| 9 | ||
| 10 | describe('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 | 163 | data["commit_count"] = None |
| 164 | 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 | 166 | languages = gh_get(f"/repos/{owner}/{repo}/languages", token) |
| 173 | 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 | 172 | return data |
| 176 | 173 | |
| 177 | 174 | |
| 175 | SECURITY_SEVERITIES = {"medium", "high", "critical"} | |
| 176 | ||
| 177 | ||
| 178 | def _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 | ||
| 178 | 190 | def grade_stats(data): |
| 179 | 191 | """Grade repo stats, returning list of (emoji, label, value_str) tuples.""" |
| 180 | 192 | stats = [] |
| @@ -255,13 +267,13 @@ def grade_stats(data): | ||
| 255 | 267 | else: |
| 256 | 268 | stats.append((RED if archived else GREEN, "Is Archived", "Yes" if archived else "No")) |
| 257 | 269 | |
| 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")) | |
| 263 | 275 | else: |
| 264 | stats.append((GREEN, "Security Alerts", "None")) | |
| 276 | stats.append((GREEN, "Security Advisories", "No unpatched active CVEs found")) | |
| 265 | 277 | |
| 266 | 278 | ai = data.get("ai_commit_count") |
| 267 | 279 | if ai is None: |