Commit 95e0eb9679

95e0eb96792649c3544229bbe87c465cd126de30

parent: 41a6bcab5e

Unsigned

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

API run public for lib checks

Layout: unified · split

.github/workflows/ci-api.yml −1
@@ -5,7 +5,6 @@ on:
55 pull_request:
66 paths:
77 - 'api/**'
8 - 'awesome-privacy.yml'
98 - '.github/workflows/ci-api.yml'
109 workflow_dispatch:
1110
.github/zizmor.yml added +5
@@ -0,0 +1,5 @@
1rules:
2 unpinned-uses:
3 config:
4 policies:
5 '*': ref-pin
api/src/app.ts +23 −13
@@ -3,8 +3,8 @@ import { cors } from 'hono/cors'
33import { Scalar } from '@scalar/hono-api-reference'
44
55import { createStorage } from '@/lib/cache'
6import { errorHandler, notFound } from '@/lib/errors'
7import { requireBearer } from '@/lib/auth'
6import { ApiError, errorHandler, notFound } from '@/lib/errors'
7import { hasValidToken, authRequired } from '@/lib/auth'
88import { rateLimit } from '@/lib/ratelimit'
99import { newApp } from '@/lib/openapi'
1010import type { AppEnv } from '@/types'
@@ -37,9 +37,8 @@ const buildPublic = () => {
3737}
3838
3939const buildPrivate = () => {
40 // Private enrichment routes, bearer auth on every /enrich/* path
40 // Enrichment routes, public but rate-limited (see rate-limit wiring below)
4141 const priv = newApp()
42 priv.use('/enrich/*', requireBearer())
4342 priv.route('/', privacy)
4443 priv.route('/', github)
4544 priv.route('/', ios)
@@ -64,13 +63,21 @@ export const buildApp = () => {
6463 await next()
6564 })
6665
67 // CORS everywhere; rate limiting and edge caching are for public routes only,
68 // authenticated /enrich/* requests are exempt from both
66 // CORS everywhere. Public browse routes get the standard limit; enrich routes
67 // are public too, but anonymous callers hit a stricter limit while a valid
68 // bearer token bypasses it. Edge caching stays off for enrich (below).
6969 app.use('*', cors({ origin: '*' }))
70 const limiter = rateLimit()
71 app.use('/v1/*', (c, next) =>
72 c.req.path.startsWith('/v1/enrich') ? next() : limiter(c, next),
73 )
70 const publicLimiter = rateLimit()
71 const enrichLimiter = rateLimit((env) => env.ENRICH_RATE_LIMIT ?? env.RATE_LIMIT)
72 app.use('/v1/*', (c, next) => {
73 if (!c.req.path.startsWith('/v1/enrich')) return publicLimiter(c, next)
74 const authed = hasValidToken(c.env.API_TOKEN, c.req.header('authorization'))
75 if (authRequired(c.env.REQUIRE_AUTH) && !authed) {
76 throw new ApiError('UNAUTHORIZED', 'Invalid or missing bearer token', 401)
77 }
78 if (authed) return next()
79 return enrichLimiter(c, next)
80 })
7481 app.use('/v1/*', async (c, next) => {
7582 if (c.req.path.startsWith('/v1/enrich')) return next()
7683 await next()
@@ -100,9 +107,12 @@ export const buildApp = () => {
100107<details>
101108<summary>Authenticating</summary>
102109
103By default, no auth is needed.
104If you're self-hosting, you can enable auth by setting the \`API_TOKEN\` env var.
105Then, add the \`Authorization: Bearer <your-token>\` header when accessing the enrichment endpoints.
110The enrichment endpoints are public, but anonymous requests are rate-limited.
111On the hosted instance, sending a valid \`Authorization: Bearer <token>\` header
112exempts the request from rate limiting. Self-hosters can set the \`API_TOKEN\`
113env var to enable the same bypass for their own token.
114To lock the endpoints down entirely, set \`REQUIRE_AUTH\` (alongside \`API_TOKEN\`):
115requests without a valid token are then rejected with a 401.
106116</details>
107117
108118<details>
api/src/lib/auth.ts +19 −19
@@ -1,15 +1,12 @@
11/**
2 * Middleware to add basic bearer token auth to /enrich/* routes
3 * To prevent abuse of endpoints which make third-party requests
4 * It's off-by-default, and can be enabled by setting API_TOKEN
5 * Works by checking the "Authorization: Bearer $API_TOKEN" header
2 * Bearer token check for /enrich/* routes.
3 * The endpoints are public by default, but a request carrying the correct
4 * "Authorization: Bearer $API_TOKEN" header is exempt from rate limiting.
5 * When API_TOKEN is unset (e.g. self-hosted), no request is privileged.
6 * Setting REQUIRE_AUTH turns the token into a hard gate (see authRequired).
67 */
78
8import type { MiddlewareHandler } from 'hono'
9import { ApiError } from '@/lib/errors'
10import type { HonoEnv } from '@/types'
11
12// Compare specified token against expected, using constant time
9// Compare two strings in constant time
1310const constantTimeEqual = (left: string, right: string) => {
1411 if (left.length !== right.length) return false
1512 let diff = 0
@@ -19,14 +16,17 @@ const constantTimeEqual = (left: string, right: string) => {
1916 return diff === 0
2017}
2118
22// If auth enabled, check specified header matches env var, otherwise respond 401
23export const requireBearer = (): MiddlewareHandler<HonoEnv> => async (c, next) => {
24 const expected = c.env.API_TOKEN
25 if (!expected) return next()
26 const header = c.req.header('authorization') ?? ''
27 const match = /^Bearer\s+(\S+)$/i.exec(header)
28 if (!match || !constantTimeEqual(match[1], expected)) {
29 throw new ApiError('UNAUTHORIZED', 'Invalid or missing bearer token', 401)
30 }
31 await next()
19// True when a valid bearer token is present (auth must be configured)
20export const hasValidToken = (
21 expected: string | undefined,
22 header: string | undefined,
23): boolean => {
24 if (!expected) return false
25 const match = /^Bearer\s+(\S+)$/i.exec(header ?? '')
26 return !!match && constantTimeEqual(match[1], expected)
3227}
28
29// True when REQUIRE_AUTH is enabled, hard-gating enrich behind a valid token.
30// Off by default; needs API_TOKEN set too, else every request fails closed.
31export const authRequired = (value: string | undefined): boolean =>
32 /^(1|true|yes|on)$/i.test(value ?? '')
api/src/lib/env.ts +2
@@ -10,6 +10,7 @@ export const readEnv = (workersEnv?: Partial<AppEnv>): AppEnv => {
1010 const env = proc as Record<string, string | undefined>
1111 return {
1212 API_TOKEN: workersEnv?.API_TOKEN ?? env.API_TOKEN,
13 REQUIRE_AUTH: workersEnv?.REQUIRE_AUTH ?? env.REQUIRE_AUTH,
1314 DISCORD_BOT_TOKEN: workersEnv?.DISCORD_BOT_TOKEN ?? env.DISCORD_BOT_TOKEN,
1415 APIVOID_API_KEY: workersEnv?.APIVOID_API_KEY ?? env.APIVOID_API_KEY,
1516 EXODUS_TOKEN: workersEnv?.EXODUS_TOKEN ?? env.EXODUS_TOKEN,
@@ -17,6 +18,7 @@ export const readEnv = (workersEnv?: Partial<AppEnv>): AppEnv => {
1718 DOCKERHUB_TOKEN: workersEnv?.DOCKERHUB_TOKEN ?? env.DOCKERHUB_TOKEN,
1819 CACHE: workersEnv?.CACHE,
1920 RATE_LIMIT: workersEnv?.RATE_LIMIT,
21 ENRICH_RATE_LIMIT: workersEnv?.ENRICH_RATE_LIMIT,
2022 API_BASE: workersEnv?.API_BASE ?? env.API_BASE,
2123 }
2224}
api/src/lib/ratelimit/index.ts +15 −11
@@ -2,19 +2,23 @@
22 * Rate limit middleware factory
33 * Basic measure to prevent obvious abuse for public routes
44 * Uses CF's native rate-limiting API, configurable in wrangler.toml
5 * Only applies to unauthenticated requests on the public instance
5 * The binding is selectable, so different routes can use different limits
66 * By default, there's no rate-limiting on self-hosted/Bun versions
77 */
88import type { MiddlewareHandler } from 'hono'
99import { ApiError } from '@/lib/errors'
10import type { HonoEnv } from '@/types'
10import type { AppEnv, HonoEnv, RateLimiter } from '@/types'
1111
12export const rateLimit = (): MiddlewareHandler<HonoEnv> => async (c, next) => {
13 const limiter = c.env.RATE_LIMIT
14 if (!limiter) return next()
15 const key =
16 c.req.header('cf-connecting-ip') ?? c.req.header('x-forwarded-for') ?? 'anon'
17 const { success } = await limiter.limit({ key })
18 if (!success) throw new ApiError('RATE_LIMITED', 'Too many requests', 429)
19 return next()
20}
12export const rateLimit =
13 (
14 pick: (env: AppEnv) => RateLimiter | undefined = (env) => env.RATE_LIMIT,
15 ): MiddlewareHandler<HonoEnv> =>
16 async (c, next) => {
17 const limiter = pick(c.env)
18 if (!limiter) return next()
19 const key =
20 c.req.header('cf-connecting-ip') ?? c.req.header('x-forwarded-for') ?? 'anon'
21 const { success } = await limiter.limit({ key })
22 if (!success) throw new ApiError('RATE_LIMITED', 'Too many requests', 429)
23 return next()
24 }
api/src/types.ts +3
@@ -56,6 +56,8 @@ export interface RateLimiter {
5656// Unified environment seen by both Workers + Node
5757export interface AppEnv {
5858 API_TOKEN?: string
59 // When truthy, /enrich/* requires a valid bearer token (off by default)
60 REQUIRE_AUTH?: string
5961 DISCORD_BOT_TOKEN?: string
6062 APIVOID_API_KEY?: string
6163 EXODUS_TOKEN?: string
@@ -63,6 +65,7 @@ export interface AppEnv {
6365 DOCKERHUB_TOKEN?: string
6466 CACHE?: KVNamespace
6567 RATE_LIMIT?: RateLimiter
68 ENRICH_RATE_LIMIT?: RateLimiter
6669 API_BASE?: string
6770}
6871
api/tests/app.test.ts +76 −15
@@ -55,27 +55,80 @@ describe('public routes', () => {
5555 })
5656})
5757
58describe('auth', () => {
59 it('private route rejects missing token', async () => {
60 const res = await hit('/v1/enrich/privacy/1')
61 expect(res.status).toBe(401)
58describe('enrich rate limiting', () => {
59 // A limiter that always denies, recording how many times it was consulted
60 const denyLimiter = () => {
61 const calls = { n: 0 }
62 const limiter = {
63 limit: async () => {
64 calls.n++
65 return { success: false }
66 },
67 }
68 return { limiter, calls }
69 }
70 // A KV cache pre-seeded so handlers serve cached data without any upstream call
71 const seededCache = (value: unknown) => ({
72 get: async () => ({ value, cachedAt: Date.now() }),
73 put: async () => {},
6274 })
6375
64 it('private route rejects wrong token', async () => {
65 const res = await hit('/v1/enrich/privacy/1', {
66 headers: { authorization: 'Bearer wrong' },
76 it('anonymous enrich request is rate-limited', async () => {
77 const { limiter, calls } = denyLimiter()
78 const res = await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), {
79 API_TOKEN: 'test',
80 ENRICH_RATE_LIMIT: limiter,
6781 })
68 expect(res.status).toBe(401)
82 expect(res.status).toBe(429)
83 expect(calls.n).toBe(1)
6984 })
7085
71 it('security enrich route requires auth', async () => {
72 const res = await hit('/v1/enrich/security/jquery/jquery')
73 expect(res.status).toBe(401)
86 it('valid bearer token bypasses the enrich rate limit', async () => {
87 const { limiter, calls } = denyLimiter()
88 const res = await app.fetch(
89 new Request('http://localhost/v1/enrich/privacy/1', {
90 headers: { authorization: 'Bearer test' },
91 }),
92 { API_TOKEN: 'test', ENRICH_RATE_LIMIT: limiter, CACHE: seededCache({ id: 1 }) },
93 )
94 expect(res.status).toBe(200)
95 expect(calls.n).toBe(0)
96 })
97
98 it('wrong token does not bypass the enrich rate limit', async () => {
99 const { limiter, calls } = denyLimiter()
100 const res = await app.fetch(
101 new Request('http://localhost/v1/enrich/privacy/1', {
102 headers: { authorization: 'Bearer wrong' },
103 }),
104 { API_TOKEN: 'test', ENRICH_RATE_LIMIT: limiter },
105 )
106 expect(res.status).toBe(429)
107 expect(calls.n).toBe(1)
74108 })
75109
76 it('docker enrich route requires auth', async () => {
77 const res = await hit('/v1/enrich/docker/pihole')
78 expect(res.status).toBe(401)
110 it('REQUIRE_AUTH rejects missing/invalid token with 401', async () => {
111 const env = { API_TOKEN: 'test', REQUIRE_AUTH: 'true' }
112 expect(
113 (await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), env)).status,
114 ).toBe(401)
115 const wrong = await app.fetch(
116 new Request('http://localhost/v1/enrich/privacy/1', {
117 headers: { authorization: 'Bearer wrong' },
118 }),
119 env,
120 )
121 expect(wrong.status).toBe(401)
122 })
123
124 it('REQUIRE_AUTH still admits a valid token', async () => {
125 const res = await app.fetch(
126 new Request('http://localhost/v1/enrich/privacy/1', {
127 headers: { authorization: 'Bearer test' },
128 }),
129 { API_TOKEN: 'test', REQUIRE_AUTH: 'true', CACHE: seededCache({ id: 1 }) },
130 )
131 expect(res.status).toBe(200)
79132 })
80133})
81134
@@ -86,7 +139,15 @@ describe('middleware scoping', () => {
86139 })
87140
88141 it('enrich routes are not advertised as public cacheable', async () => {
89 const res = await hit('/v1/enrich/privacy/1')
142 // Seed the cache so the handler serves without an upstream call
143 const cache = {
144 get: async () => ({ value: { id: 1 }, cachedAt: Date.now() }),
145 put: async () => {},
146 }
147 const res = await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), {
148 API_TOKEN: 'test',
149 CACHE: cache,
150 })
90151 expect(res.headers.get('cache-control') ?? '').not.toContain('public')
91152 })
92153})
api/wrangler.toml +7
@@ -26,6 +26,13 @@ type = "ratelimit"
2626namespace_id = "1001"
2727simple = { limit = 60, period = 60 }
2828
29# Stricter limit for anonymous /enrich/* requests; a valid API_TOKEN bypasses it
30[[unsafe.bindings]]
31name = "ENRICH_RATE_LIMIT"
32type = "ratelimit"
33namespace_id = "1002"
34simple = { limit = 10, period = 60 }
35
2936# Scheduled cache warmer
3037[triggers]
3138crons = ["*/15 * * * *"]
lib/checks/check-project.py +8 −6
@@ -22,6 +22,8 @@ FINDINGS_PATH = "/tmp/findings-project.json"
2222
2323TIMEOUT = 10
2424USER_AGENT = "awesome-privacy-ci/1.0"
25# Reachable but blocking automated probes (bot-block/rate-limit), not a missing page.
26SOFT_HTTP = {401, 403, 405, 406, 429}
2527MIN_STARS = 100
2628INACTIVE_DAYS = 90
2729MIN_AGE_DAYS = 120
@@ -106,13 +108,13 @@ def load_diff(path):
106108
107109
108110def check_url(url):
109 """Return True if the URL is reachable. Transport errors are treated as reachable."""
111 """Return True if reachable. Transport errors and bot-block/rate-limit statuses
112 (SOFT_HTTP) count as reachable; only a real bad status (404, 5xx, ...) fails."""
110113 ok, status = utils.check_url(url, SESSION, TIMEOUT)
111 if not ok:
112 logger.warning("URL check failed for %s (HTTP %d)", url, status)
113 elif status is None:
114 logger.warning("URL check error for %s (unreachable)", url)
115 return ok
114 if ok or status is None or status in SOFT_HTTP:
115 return True
116 logger.warning("URL check failed for %s (HTTP %d)", url, status)
117 return False
116118
117119
118120def _gh_get(path, token, params=None, label=""):