SPB Git

Repository Public

publicroutes.ts 4.5 KB 64 lines typescript

1import { z } from "zod";2import { ApiError, body } from "../http";3import { rateLimit } from "../ratelimit";4import { env } from "../env";5import { sql } from "../db";6import type { RouteDef } from "./router";7import { KINDS, LEVELS, LOCALES } from "@/schema";8import { allPublishedForFeeds, countView, getPublished, listPublished, listTopics } from "@/server/sheets";9import { getSettings } from "@/server/settings";1011interface Ctx { ip: string }12const q = (url: URL) => {13  const s = url.searchParams;14  const pick = <T extends readonly string[]>(name: string, allowed: T) => { const v = s.get(name); return v && (allowed as readonly string[]).includes(v) ? (v as T[number]) : undefined; };15  const slug = (name: string) => { const v = s.get(name); return v && /^[a-z0-9-]{1,96}$/.test(v) ? v : undefined; };16  return {17    locale: pick("locale", LOCALES), level: pick("level", LEVELS), kind: pick("kind", KINDS), topic: slug("topic"), tag: slug("tag"),18    q: s.get("q")?.slice(0, 120) || undefined, uiLocale: pick("ui", LOCALES) ?? "fr",19    limit: Math.min(50, Math.max(1, Number(s.get("limit") ?? 20) || 20)), offset: Math.min(5000, Math.max(0, Number(s.get("offset") ?? 0) || 0)),20  };21};22const cached = (data: unknown, seconds = 60) => Response.json(data, { headers: { "Cache-Control": `public, max-age=${seconds}, stale-while-revalidate=${seconds * 5}` } });2324/**25 * /api/public/* — read-only, anonymous, cacheable. Everything here reads published snapshots through26 * sheets.publication_id; a draft, an archived sheet or an unpublished revision cannot be reached from this file.27 */28export const publicRoutes: RouteDef<Ctx>[] = [29  ["GET", "sheets", async ({ url, ctx }) => { await rateLimit(`pub:${ctx.ip}`, 600, 600); return cached(await listPublished(q(url))); }],30  ["GET", "search", async ({ url, ctx }) => { await rateLimit(`pub:${ctx.ip}`, 600, 600); const p = q(url); if (!p.q) throw new ApiError(400, "invalid_input", "q is required"); return cached(await listPublished(p), 30); }],31  ["GET", "sheets/:slug", async ({ params, url, ctx }) => {32    await rateLimit(`pub:${ctx.ip}`, 600, 600);33    if (!/^[a-z0-9-]{1,96}$/.test(params.slug)) throw new ApiError(404, "not_found", "Sheet not found");34    const r = await getPublished(params.slug, q(url).locale ?? "fr");35    if (!r) throw new ApiError(404, "not_found", "Sheet not found");36    if ("redirect" in r) return Response.redirect(`${env.appUrl}/api/public/sheets/${r.redirect}${url.search}`, 301);37    const s = r.sheet;38    return cached({ slug: s.slug, locale: s.locale, title: s.title, summary: s.summary, author: s.doc.metadata.author, readingMinutes: s.readingMinutes, publishedAt: s.publishedAt, updatedAt: s.updatedAt,39      url: `${env.appUrl}/s/${s.slug}`, topics: s.topics.map((t) => t.slug), tags: s.tags.map((t) => t.slug), translations: s.translations, document: s.doc });40  }],41  ["GET", "topics", async ({ url, ctx }) => { await rateLimit(`pub:${ctx.ip}`, 600, 600); return cached({ topics: await listTopics(q(url).uiLocale) }, 300); }],42  ["GET", "feed", async ({ ctx }) => {43    await rateLimit(`pub:${ctx.ip}`, 600, 600);44    const items = await allPublishedForFeeds();45    return cached({46      version: "https://jsonfeed.org/version/1.1", title: "Sheet — by Simon-Pierre Boucher", home_page_url: env.appUrl, feed_url: `${env.appUrl}/api/public/feed`,47      authors: [{ name: "Simon-Pierre Boucher", url: `${env.appUrl}/about` }],48      items: items.slice(0, 100).map((i) => ({ id: `${env.appUrl}/s/${i.slug}`, url: `${env.appUrl}/s/${i.slug}`, title: i.title, summary: i.summary, language: i.locale, date_published: i.first_published_at.toISOString(), date_modified: i.published_at.toISOString() })),49    }, 300);50  }],51  // View counter: one increment per page view, no visitor data. Ignored when analytics are off or for bots.52  ["POST", "views", async ({ req, ctx }) => {53    await rateLimit(`view:${ctx.ip}`, 120, 600);54    const o = req.headers.get("origin");55    if (o && o !== new URL(env.appUrl).origin) throw new ApiError(403, "bad_origin", "Cross-origin request refused");56    const b = await body(req, z.object({ slug: z.string().regex(/^[a-z0-9-]{1,96}$/), locale: z.enum(LOCALES) }));57    if (/bot|crawl|spider|slurp|headless|preview|monitor|curl|wget/i.test(req.headers.get("user-agent") ?? "")) return { ok: true };58    if (!(await getSettings()).analyticsEnabled) return { ok: true };59    const [s] = await sql<{ id: string }[]>`SELECT id FROM sheets WHERE slug = ${b.slug} AND locale = ${b.locale} AND status = 'published' AND deleted_at IS NULL`;60    if (s) await countView(s.id);61    return { ok: true };62  }],63];64
Files main
Menu

Theme