api/src/app.ts

181 lines · 6303 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 { 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 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  // Enrichment routes, public but rate-limited (see rate-limit wiring below)
 41  const priv = newApp()
 42  priv.route('/', privacy)
 43  priv.route('/', github)
 44  priv.route('/', ios)
 45  priv.route('/', android)
 46  priv.route('/', discord)
 47  priv.route('/', reddit)
 48  priv.route('/', website)
 49  priv.route('/', security)
 50  priv.route('/', docker)
 51  return priv
 52}
 53
 54export const buildApp = () => {
 55  const app = newApp({ strict: false })
 56
 57  app.onError(errorHandler)
 58  app.notFound(notFound)
 59
 60  // Inject per-request storage backed by KV or in-memory
 61  app.use('*', async (c, next) => {
 62    c.set('storage', createStorage(c.env as AppEnv))
 63    await next()
 64  })
 65
 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).
 69  app.use('*', cors({ origin: '*' }))
 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  })
 81  app.use('/v1/*', async (c, next) => {
 82    if (c.req.path.startsWith('/v1/enrich')) return next()
 83    await next()
 84    c.header('Cache-Control', 'public, s-maxage=300')
 85  })
 86
 87  app.route('/v1', buildPublic())
 88  app.route('/v1', buildPrivate())
 89  app.route('/v1', mcp)
 90
 91  const description = `
 92  The API allows you to browse awesome-privacy's data programmatically.
 93  It also runs some lookups/checks on listings to surface useful insights
 94  to add additional context to listings, and save time when comparing software / services.
 95  <br>
 96  These endpoints are used by as part of the website generation,
 97  the PR review process and the scheduled listing audits.
 98  You're also free to use it for your own purposes.
 99  <br>
100  > [!IMPORTANT]
101  > It's very important not to rely on this data for any decision making,
102  > as it only gives a very narrow slice of the picture.
103  > There's also many real privacy issues which the automated lookups have no way of detecting,
104  > as well as the possibility for false positives/negatives.
105  > **Always do your own research**.
106
107<details>
108<summary>Authenticating</summary>
109
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.
116</details>
117
118<details>
119<summary>Caching</summary>
120
121Some responses are cached to reduce load on upstream services.
122When configured, successful enrichment results are cached in KV and served while fresh
123(from a week up to 90 days, depending on the endpoint). Stale entries are refreshed on
124demand, falling back to the cached copy if the upstream is unavailable.
125</details>
126
127<details>
128<summary>Self-Hosting</summary>
129
130See the [repo](https://github.com/lissy93/awesome-privacy/tree/main/api) for
131deployment and development guides, as well as instructions for self-hosting, contributing and usage.
132</details>
133
134  `
135
136  const publicDescription =
137    'Endpoints to browse the awesome-privacy dataset programatically'
138  const enrichDescription =
139    'Endpoints to fetch additional data about listings from external sources'
140
141  // OpenAPI document plus Scalar UI
142  app.doc('/openapi.json', {
143    openapi: '3.0.0',
144    info: {
145      title: 'Awesome Privacy API',
146      version: '1.0.0',
147      description,
148    },
149    servers: [{ url: '/' }],
150    tags: [
151      { name: 'Public', description: publicDescription },
152      { name: 'Enrichment', description: enrichDescription },
153    ],
154  })
155  const blurb = 'Browse awesome-privacy data and enrichment insights programmatically.'
156  app.get(
157    '/docs',
158    Scalar({
159      url: '/openapi.json',
160      theme: 'laserwave',
161      persistAuth: true,
162      favicon: 'https://awesome-privacy.xyz/favicon.svg',
163      operationTitleSource: 'summary',
164      operationsSorter: 'alpha',
165      orderRequiredPropertiesFirst: true,
166      mcp: { name: 'Awesome Privacy', url: '/v1/mcp' },
167      metaData: {
168        title: 'Awesome Privacy API',
169        description: blurb,
170        ogTitle: 'Awesome Privacy API',
171        ogDescription: blurb,
172        ogImage: 'https://awesome-privacy.xyz/banner.png',
173        twitterCard: 'summary_large_image',
174      },
175    }),
176  )
177
178  app.get('/', (c) => c.redirect('/docs'))
179
180  return app
181}