api/src/app.ts
188 lines · 6674 bytes
3 symbols in this file
1// Hono app assembler, the same instance runs on Workers and on Bun
2import { cors } from 'hono/cors'
3import { Scalar } from '@scalar/hono-api-reference'
4
5import { createStorage } from '@/lib/cache'
6import { ApiError, errorHandler, notFound } from '@/lib/errors'
7import { hasValidToken, authRequired } from '@/lib/auth'
8import { rateLimit } from '@/lib/ratelimit'
9import { newApp } from '@/lib/openapi'
10import type { AppEnv } from '@/types'
11
12import services from '@/routes/public/services'
13import categoriesRoute from '@/routes/public/categories'
14import searchRoute from '@/routes/public/search'
15import stats from '@/routes/public/stats'
16
17import privacy from '@/routes/private/privacy'
18import github from '@/routes/private/github'
19import ios from '@/routes/private/ios'
20import android from '@/routes/private/android'
21import discord from '@/routes/private/discord'
22import reddit from '@/routes/private/reddit'
23import website from '@/routes/private/website'
24import trackers from '@/routes/private/trackers'
25import security from '@/routes/private/security'
26import docker from '@/routes/private/docker'
27
28import mcp from '@/routes/mcp'
29
30const buildPublic = () => {
31 // Public browse routes, shared middleware is applied at the app level
32 const pub = newApp()
33 pub.route('/', services)
34 pub.route('/', categoriesRoute)
35 pub.route('/', searchRoute)
36 pub.route('/', stats)
37 return pub
38}
39
40const buildPrivate = () => {
41 // Enrichment routes, public but rate-limited (see rate-limit wiring below)
42 const priv = newApp()
43 priv.route('/', privacy)
44 priv.route('/', github)
45 priv.route('/', ios)
46 priv.route('/', android)
47 priv.route('/', discord)
48 priv.route('/', reddit)
49 priv.route('/', website)
50 priv.route('/', trackers)
51 priv.route('/', security)
52 priv.route('/', docker)
53 return priv
54}
55
56export const buildApp = () => {
57 const app = newApp({ strict: false })
58
59 app.onError(errorHandler)
60 app.notFound(notFound)
61
62 // Inject per-request storage backed by KV or in-memory
63 app.use('*', async (c, next) => {
64 c.set('storage', createStorage(c.env as AppEnv))
65 await next()
66 })
67
68 // CORS everywhere. Public browse routes get the standard limit; enrich routes
69 // are public too, but anonymous callers hit a stricter limit while a valid
70 // bearer token bypasses it. Edge caching stays off for enrich (below).
71 // Trackers has its own bucket, so its page fetches never starve the other lookups.
72 app.use('*', cors({ origin: '*' }))
73 const publicLimiter = rateLimit()
74 const enrichLimiter = rateLimit((env) => env.ENRICH_RATE_LIMIT ?? env.RATE_LIMIT)
75 const trackersLimiter = rateLimit(
76 (env) => env.TRACKERS_RATE_LIMIT ?? env.ENRICH_RATE_LIMIT ?? env.RATE_LIMIT,
77 )
78 app.use('/v1/*', (c, next) => {
79 if (!c.req.path.startsWith('/v1/enrich')) return publicLimiter(c, next)
80 const authed = hasValidToken(c.env.API_TOKEN, c.req.header('authorization'))
81 if (authRequired(c.env.REQUIRE_AUTH) && !authed) {
82 throw new ApiError('UNAUTHORIZED', 'Invalid or missing bearer token', 401)
83 }
84 if (authed) return next()
85 if (c.req.path.startsWith('/v1/enrich/trackers')) return trackersLimiter(c, next)
86 return enrichLimiter(c, next)
87 })
88 app.use('/v1/*', async (c, next) => {
89 if (c.req.path.startsWith('/v1/enrich')) return next()
90 await next()
91 c.header('Cache-Control', 'public, s-maxage=300')
92 })
93
94 app.route('/v1', buildPublic())
95 app.route('/v1', buildPrivate())
96 app.route('/v1', mcp)
97
98 const description = `
99 The API allows you to browse awesome-privacy's data programmatically.
100 It also runs some lookups/checks on listings to surface useful insights
101 to add additional context to listings, and save time when comparing software / services.
102 <br>
103 These endpoints are used by as part of the website generation,
104 the PR review process and the scheduled listing audits.
105 You're also free to use it for your own purposes.
106 <br>
107 > [!IMPORTANT]
108 > It's very important not to rely on this data for any decision making,
109 > as it only gives a very narrow slice of the picture.
110 > There's also many real privacy issues which the automated lookups have no way of detecting,
111 > as well as the possibility for false positives/negatives.
112 > **Always do your own research**.
113
114<details>
115<summary>Authenticating</summary>
116
117The enrichment endpoints are public, but anonymous requests are rate-limited.
118On the hosted instance, sending a valid \`Authorization: Bearer <token>\` header
119exempts the request from rate limiting. Self-hosters can set the \`API_TOKEN\`
120env var to enable the same bypass for their own token.
121To lock the endpoints down entirely, set \`REQUIRE_AUTH\` (alongside \`API_TOKEN\`):
122requests without a valid token are then rejected with a 401.
123</details>
124
125<details>
126<summary>Caching</summary>
127
128Some responses are cached to reduce load on upstream services.
129When configured, successful enrichment results are cached in KV and served while fresh
130(from a week up to 90 days, depending on the endpoint). Stale entries are refreshed on
131demand, falling back to the cached copy if the upstream is unavailable.
132</details>
133
134<details>
135<summary>Self-Hosting</summary>
136
137See the [repo](https://github.com/lissy93/awesome-privacy/tree/main/api) for
138deployment and development guides, as well as instructions for self-hosting, contributing and usage.
139</details>
140
141 `
142
143 const publicDescription =
144 'Endpoints to browse the awesome-privacy dataset programatically'
145 const enrichDescription =
146 'Endpoints to fetch additional data about listings from external sources'
147
148 // OpenAPI document plus Scalar UI
149 app.doc('/openapi.json', {
150 openapi: '3.0.0',
151 info: {
152 title: 'Awesome Privacy API',
153 version: '1.0.0',
154 description,
155 },
156 servers: [{ url: '/' }],
157 tags: [
158 { name: 'Public', description: publicDescription },
159 { name: 'Enrichment', description: enrichDescription },
160 ],
161 })
162 const blurb = 'Browse awesome-privacy data and enrichment insights programmatically.'
163 app.get(
164 '/docs',
165 Scalar({
166 url: '/openapi.json',
167 theme: 'laserwave',
168 persistAuth: true,
169 favicon: 'https://awesome-privacy.xyz/favicon.svg',
170 operationTitleSource: 'summary',
171 operationsSorter: 'alpha',
172 orderRequiredPropertiesFirst: true,
173 mcp: { name: 'Awesome Privacy', url: '/v1/mcp' },
174 metaData: {
175 title: 'Awesome Privacy API',
176 description: blurb,
177 ogTitle: 'Awesome Privacy API',
178 ogDescription: blurb,
179 ogImage: 'https://awesome-privacy.xyz/banner.png',
180 twitterCard: 'summary_large_image',
181 },
182 }),
183 )
184
185 app.get('/', (c) => c.redirect('/docs'))
186
187 return app
188}