api/src/app.ts
171 lines · 5605 bytes
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 { errorHandler, notFound } from '@/lib/errors'
7import { requireBearer } 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 security from '@/routes/private/security'
25import docker from '@/routes/private/docker'
26
27import mcp from '@/routes/mcp'
28
29const buildPublic = () => {
30 // Public browse routes, shared middleware is applied at the app level
31 const pub = newApp()
32 pub.route('/', services)
33 pub.route('/', categoriesRoute)
34 pub.route('/', searchRoute)
35 pub.route('/', stats)
36 return pub
37}
38
39const buildPrivate = () => {
40 // Private enrichment routes, bearer auth on every /enrich/* path
41 const priv = newApp()
42 priv.use('/enrich/*', requireBearer())
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('/', security)
51 priv.route('/', docker)
52 return priv
53}
54
55export const buildApp = () => {
56 const app = newApp({ strict: false })
57
58 app.onError(errorHandler)
59 app.notFound(notFound)
60
61 // Inject per-request storage backed by KV or in-memory
62 app.use('*', async (c, next) => {
63 c.set('storage', createStorage(c.env as AppEnv))
64 await next()
65 })
66
67 // CORS everywhere; rate limiting and edge caching are for public routes only,
68 // authenticated /enrich/* requests are exempt from both
69 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 )
74 app.use('/v1/*', async (c, next) => {
75 if (c.req.path.startsWith('/v1/enrich')) return next()
76 await next()
77 c.header('Cache-Control', 'public, s-maxage=300')
78 })
79
80 app.route('/v1', buildPublic())
81 app.route('/v1', buildPrivate())
82 app.route('/v1', mcp)
83
84 const description = `
85 The API allows you to browse awesome-privacy's data programmatically.
86 It also runs some lookups/checks on listings to surface useful insights
87 to add additional context to listings, and save time when comparing software / services.
88 <br>
89 These endpoints are used by as part of the website generation,
90 the PR review process and the scheduled listing audits.
91 You're also free to use it for your own purposes.
92 <br>
93 > [!IMPORTANT]
94 > It's very important not to rely on this data for any decision making,
95 > as it only gives a very narrow slice of the picture.
96 > There's also many real privacy issues which the automated lookups have no way of detecting,
97 > as well as the possibility for false positives/negatives.
98 > **Always do your own research**.
99
100<details>
101<summary>Authenticating</summary>
102
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.
106</details>
107
108<details>
109<summary>Caching</summary>
110
111Some responses are cached to reduce load on upstream services.
112When configured, successful enrichment results are cached in KV and served while fresh
113(from a week up to 90 days, depending on the endpoint). Stale entries are refreshed on
114demand, falling back to the cached copy if the upstream is unavailable.
115</details>
116
117<details>
118<summary>Self-Hosting</summary>
119
120See the [repo](https://github.com/lissy93/awesome-privacy/tree/main/api) for
121deployment and development guides, as well as instructions for self-hosting, contributing and usage.
122</details>
123
124 `
125
126 const publicDescription =
127 'Endpoints to browse the awesome-privacy dataset programatically'
128 const enrichDescription =
129 'Endpoints to fetch additional data about listings from external sources'
130
131 // OpenAPI document plus Scalar UI
132 app.doc('/openapi.json', {
133 openapi: '3.0.0',
134 info: {
135 title: 'Awesome Privacy API',
136 version: '1.0.0',
137 description,
138 },
139 servers: [{ url: '/' }],
140 tags: [
141 { name: 'Public', description: publicDescription },
142 { name: 'Enrichment', description: enrichDescription },
143 ],
144 })
145 const blurb = 'Browse awesome-privacy data and enrichment insights programmatically.'
146 app.get(
147 '/docs',
148 Scalar({
149 url: '/openapi.json',
150 theme: 'laserwave',
151 persistAuth: true,
152 favicon: 'https://awesome-privacy.xyz/favicon.svg',
153 operationTitleSource: 'summary',
154 operationsSorter: 'alpha',
155 orderRequiredPropertiesFirst: true,
156 mcp: { name: 'Awesome Privacy', url: '/v1/mcp' },
157 metaData: {
158 title: 'Awesome Privacy API',
159 description: blurb,
160 ogTitle: 'Awesome Privacy API',
161 ogDescription: blurb,
162 ogImage: 'https://awesome-privacy.xyz/banner.png',
163 twitterCard: 'summary_large_image',
164 },
165 }),
166 )
167
168 app.get('/', (c) => c.redirect('/docs'))
169
170 return app
171}