Skip to content

armgit / bygga

Public Imported from GitHub
0

IKEA assembly, step by step: animated, manual-style 3D guides. Scan any paper manual with Together AI.

TypeScript

Harden the API: own rate limit per route, key fallback

Youssefe732ca5cf3f1
diff --git a/.gitignore b/.gitignore
index eb96524..3c0c236 100644
--- a/.gitignore
+++ b/.gitignore
@@ -42,3 +42,4 @@ next-env.d.ts
# keep the example env file
!.env.example
+.env*.local
diff --git a/next.config.ts b/next.config.ts
index 6bcbe28..6de66ce 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -1,9 +1,21 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
- /* config options here */
cacheComponents: true,
partialPrefetching: true,
+ async headers() {
+ return [
+ {
+ // clips are named after their text, so a file only changes when it is re-recorded
+ source: "/voice/:path*",
+ headers: [{ key: "Cache-Control", value: "public, max-age=604800, stale-while-revalidate=2592000" }],
+ },
+ ];
+ },
+ async redirects() {
+ // the manual scanner is parked for v2: old links land on the search instead
+ return process.env.NEXT_PUBLIC_SCAN === "1" ? [] : [{ source: "/scan", destination: "/", permanent: false }];
+ },
};
export default nextConfig;
diff --git a/src/app/api/feedback/route.ts b/src/app/api/feedback/route.ts
new file mode 100644
index 0000000..4442f22
--- /dev/null
+++ b/src/app/api/feedback/route.ts
@@ -0,0 +1,23 @@
+import { ipOf, rateLimited } from "@/lib/together";
+
+/**
+ * "Did this match your box?" One line per answer in the server log
+ * (grep for [feedback]), so wrong guides can be found and fixed.
+ */
+export async function POST(req: Request) {
+ if (rateLimited(ipOf(req) + ":feedback", 12, 10 * 60_000)) return Response.json({ error: "slow down" }, { status: 429 });
+ const b = (await req.json().catch(() => ({}))) as Record<string, unknown>;
+ const str = (v: unknown, n: number) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim().slice(0, n) : undefined);
+ const entry = {
+ slug: str(b.slug, 80),
+ name: str(b.name, 60),
+ variant: str(b.variant, 80),
+ match: typeof b.match === "boolean" ? b.match : undefined,
+ step: typeof b.step === "number" && b.step > 0 && b.step < 200 ? Math.floor(b.step) : undefined,
+ note: str(b.note, 400),
+ via: str(b.via, 12),
+ };
+ if (!entry.slug || entry.match === undefined) return Response.json({ error: "bad" }, { status: 400 });
+ console.info("[feedback]", JSON.stringify(entry));
+ return Response.json({ ok: true });
+}
diff --git a/src/app/api/guide/route.ts b/src/app/api/guide/route.ts
index d644ad3..4a71780 100644
--- a/src/app/api/guide/route.ts
+++ b/src/app/api/guide/route.ts
@@ -22,7 +22,7 @@ export async function POST(req: Request) {
const own = userKey(req);
if (hasKey() || own) {
- if (rateLimited(ipOf(req), 12)) return Response.json({ error: "slow down" }, { status: 429 });
+ if (rateLimited(ipOf(req) + ":guide", 12)) return Response.json({ error: "slow down" }, { status: 429 });
try {
const { text, model } = await chatText({
key: own,
diff --git a/src/app/api/help/route.ts b/src/app/api/help/route.ts
index 75d90d0..0a55087 100644
--- a/src/app/api/help/route.ts
+++ b/src/app/api/help/route.ts
@@ -17,7 +17,7 @@ Never use em dashes or en dashes.`;
export async function POST(req: Request) {
const key = userKey(req);
if (!hasKey() && !key) return Response.json({ error: "ai-off" }, { status: 503 });
- if (rateLimited(ipOf(req), 20)) return Response.json({ error: "slow down" }, { status: 429 });
+ if (rateLimited(ipOf(req) + ":help", 20)) return Response.json({ error: "slow down" }, { status: 429 });
const b = (await req.json().catch(() => ({}))) as Body;
const question = (b.question ?? "").toString().slice(0, 600);
const context = (b.context ?? "").toString().slice(0, 3000);
diff --git a/src/app/api/identify/route.ts b/src/app/api/identify/route.ts
index 81b518a..d50f27c 100644
--- a/src/app/api/identify/route.ts
+++ b/src/app/api/identify/route.ts
@@ -7,7 +7,7 @@ The name is the word in capitals (it may contain Å, Ä or Ö). If you can't rea
export async function POST(req: Request) {
const key = userKey(req);
if (!hasKey() && !key) return Response.json({ error: "ai-off" }, { status: 503 });
- if (rateLimited(ipOf(req), 8)) return Response.json({ error: "slow down" }, { status: 429 });
+ if (rateLimited(ipOf(req) + ":identify", 8)) return Response.json({ error: "slow down" }, { status: 429 });
const { image } = (await req.json().catch(() => ({}))) as { image?: string };
if (!image || !image.startsWith("data:image/") || image.length > 6_000_000) return Response.json({ error: "bad image" }, { status: 400 });
try {
diff --git a/src/app/api/voice/route.ts b/src/app/api/voice/route.ts
index d2f2de2..1db970e 100644
--- a/src/app/api/voice/route.ts
+++ b/src/app/api/voice/route.ts
@@ -15,7 +15,7 @@ export async function GET(req: Request) {
if (site && site !== "same-origin") return Response.json({ error: "forbidden" }, { status: 403 });
const text = (new URL(req.url).searchParams.get("t") ?? "").replace(/\s+/g, " ").trim();
if (!text || text.length > 400) return Response.json({ error: "bad text" }, { status: 400 });
- if (rateLimited(ipOf(req), 40)) return Response.json({ error: "slow down" }, { status: 429 });
+ if (rateLimited(ipOf(req) + ":voice", 90)) return Response.json({ error: "slow down" }, { status: 429 });
try {
const audio = await speak(text, process.env.TOGETHER_API_KEY!.trim());
return new Response(audio, {
diff --git a/src/lib/together.ts b/src/lib/together.ts
index 329214e..93e5493 100644
--- a/src/lib/together.ts
+++ b/src/lib/together.ts
@@ -51,8 +51,22 @@ export class TogetherError extends Error {
/** Calls Together's chat completions, falling back through the model list when one is unavailable. */
export async function chat(o: ChatOpts): Promise<{ res: Response; model: string }> {
- const key = o.key?.trim() || process.env.TOGETHER_API_KEY?.trim();
- if (!key) throw new TogetherError("missing key", 401);
+ // a visitor's saved key can expire: the server key takes over when it is turned away
+ const keys = [...new Set([o.key?.trim(), process.env.TOGETHER_API_KEY?.trim()].filter((k): k is string => !!k))];
+ if (!keys.length) throw new TogetherError("missing key", 401);
+ let lastErr: TogetherError | null = null;
+ for (const key of keys) {
+ try {
+ return await chatWith(o, key);
+ } catch (e) {
+ lastErr = e as TogetherError;
+ if (!(e instanceof TogetherError) || (e.status !== 401 && e.status !== 403)) throw e;
+ }
+ }
+ throw lastErr!;
+}
+
+async function chatWith(o: ChatOpts, key: string): Promise<{ res: Response; model: string }> {
let lastErr: TogetherError | null = null;
for (const model of o.models.map((m) => m.trim()).filter(Boolean)) {
const reasoning = model.includes("gpt-oss") ? { reasoning_effort: o.reasoning ?? "low" } : {};
@@ -110,15 +124,23 @@ export function extractJson(text: string): unknown {
}
}
-/** Tiny in-memory rate limiter per IP. */
+/**
+ * Tiny in-memory rate limiter. Pass a bucket per route ("1.2.3.4:voice") so a
+ * chatty route can't use up another's allowance; refused calls don't count.
+ */
const hits = new Map<string, number[]>();
-export function rateLimited(ip: string, max = 20, windowMs = 60_000) {
+
+export function rateLimited(bucket: string, max = 20, windowMs = 60_000) {
const now = Date.now();
- const arr = (hits.get(ip) ?? []).filter((t) => now - t < windowMs);
+ const arr = (hits.get(bucket) ?? []).filter((t) => now - t < windowMs);
+ if (arr.length >= max) {
+ hits.set(bucket, arr);
+ return true;
+ }
arr.push(now);
- hits.set(ip, arr);
+ hits.set(bucket, arr);
if (hits.size > 5000) hits.clear();
- return arr.length > max;
+ return false;
}
/** A key the person pasted into the app, sent along with their request. Never stored or logged. */