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

Security: keep the paid endpoints to the app's own pages

Youssefc4cdbadec440
diff --git a/.gitignore b/.gitignore
index dd59600..ac0a9f1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -46,3 +46,6 @@ next-env.d.ts
# keep the example env file
!.env.example
.env*.local
+
+# local agent sessions and worktrees
+.claude/
diff --git a/next.config.ts b/next.config.ts
index a7402fb..ac8a608 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -1,5 +1,34 @@
import type { NextConfig } from "next";
+/*
+ * Everything the site loads comes from itself: scripts, fonts (next/font), the voice clips and analytics.
+ * Inline scripts stay allowed because the pages are prerendered and can't carry a per-request nonce.
+ */
+const CSP = [
+ "default-src 'self'",
+ // dev adds eval for fast refresh and Vercel Analytics' debug script, which production serves from the site itself
+ `script-src 'self' 'unsafe-inline'${process.env.NODE_ENV === "production" ? "" : " 'unsafe-eval' https://va.vercel-scripts.com"}`,
+ "style-src 'self' 'unsafe-inline'",
+ "img-src 'self' data: blob:",
+ "media-src 'self' blob: data:",
+ "font-src 'self' data:",
+ "connect-src 'self'",
+ "worker-src 'self' blob:",
+ "object-src 'none'",
+ "base-uri 'self'",
+ "form-action 'self'",
+ "frame-ancestors 'self'",
+].join("; ");
+
+const SECURITY = [
+ { key: "Content-Security-Policy", value: CSP },
+ { key: "X-Content-Type-Options", value: "nosniff" },
+ { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
+ { key: "X-Frame-Options", value: "SAMEORIGIN" },
+ // the camera reads box labels, the microphone hears "next"; nothing else
+ { key: "Permissions-Policy", value: "camera=(self), microphone=(self), geolocation=(), payment=(), usb=()" },
+];
+
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
@@ -12,6 +41,10 @@ const nextConfig: NextConfig = {
},
async headers() {
return [
+ {
+ source: "/:path*",
+ headers: SECURITY,
+ },
{
// share cards only change on deploy: let the CDN keep them, so a viral link renders each card once
source: "/:path(opengraph-image|twitter-image)",
diff --git a/src/app/api/feedback/route.ts b/src/app/api/feedback/route.ts
index 4442f22..17e0f0e 100644
--- a/src/app/api/feedback/route.ts
+++ b/src/app/api/feedback/route.ts
@@ -1,10 +1,11 @@
-import { ipOf, rateLimited } from "@/lib/together";
+import { fromApp, 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 (!fromApp(req)) return Response.json({ error: "forbidden" }, { status: 403 });
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);
diff --git a/src/app/api/guide/route.ts b/src/app/api/guide/route.ts
index 72d9fd5..937fc8d 100644
--- a/src/app/api/guide/route.ts
+++ b/src/app/api/guide/route.ts
@@ -3,12 +3,13 @@ import { categoryOf, fold, guessSpec, matchCatalog, searchCatalog } from "@/lib/
import { parseSpec, SPEC_PROMPT } from "@/lib/spec";
import { draft, type Draft } from "@/lib/draft";
import { ikeaType } from "@/lib/ikea";
-import { chatText, extractJson, hasKey, ipOf, MODELS, rateLimited, TogetherError, userKey } from "@/lib/together";
+import { chatText, extractJson, fromApp, hasKey, ipOf, MODELS, rateLimited, TogetherError, userKey } from "@/lib/together";
import type { ProductSpec } from "@/lib/types";
const cache = new Map<string, { spec: ProductSpec; model: string }>();
export async function POST(req: Request) {
+ if (!fromApp(req)) return Response.json({ error: "forbidden" }, { status: 403 });
const body = (await req.json().catch(() => ({}))) as { q?: string };
const q = (body.q ?? "").toString().slice(0, 80).trim();
if (!q) return Response.json({ error: "empty" }, { status: 400 });
@@ -43,6 +44,7 @@ export async function POST(req: Request) {
const known = PRODUCTS.find((c) => fold(c.name) === fold(spec.name) && c.archetype === spec.archetype && Math.abs(c.size.w - spec.size.w) < 6 && Math.abs(c.size.h - spec.size.h) < 6);
if (known) return Response.json({ spec: { ...toSpec(known), slug: known.slug }, via: "catalog" });
const out = { ...spec, slug: key.replace(/\s+/g, "-") };
+ if (cache.size > 1000) cache.clear();
cache.set(key, { spec: out, model });
return Response.json({ spec: out, via: "ai", model });
}
@@ -66,8 +68,19 @@ function drawable(type: string) {
/** The shared, cached draft on the server key; a visitor's own key is never cached under someone else's name. */
async function draftWith(own: string | undefined, key: string, q: string): Promise<Draft | null> {
if (!own && hasKey()) return draft(key, q);
+ try {
+ return await draftOwn(own!, q);
+ } catch (e) {
+ // a saved key that stopped working gets the shared, cached draft, not a fresh call on the server key
+ if (e instanceof TogetherError && (e.status === 401 || e.status === 403) && hasKey()) return draft(key, q);
+ throw e;
+ }
+}
+
+async function draftOwn(own: string, q: string): Promise<Draft | null> {
const { text, model } = await chatText({
key: own,
+ fallback: false,
models: MODELS.text,
json: true,
maxTokens: 1800,
diff --git a/src/app/api/help/route.ts b/src/app/api/help/route.ts
index 0a55087..11182aa 100644
--- a/src/app/api/help/route.ts
+++ b/src/app/api/help/route.ts
@@ -1,4 +1,4 @@
-import { chat, hasKey, ipOf, MODELS, rateLimited, userKey, type Msg } from "@/lib/together";
+import { chat, fromApp, hasKey, ipOf, MODELS, rateLimited, userKey, type Msg } from "@/lib/together";
interface Body {
context?: string;
@@ -15,14 +15,19 @@ If they send a photo of a part, say which part from the list it most likely is a
Never use em dashes or en dashes.`;
export async function POST(req: Request) {
+ if (!fromApp(req)) return Response.json({ error: "forbidden" }, { status: 403 });
const key = userKey(req);
if (!hasKey() && !key) return Response.json({ error: "ai-off" }, { status: 503 });
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);
- const history = (b.history ?? []).slice(-6).map((m) => ({ role: m.role, content: String(m.content).slice(0, 800) })) as Msg[];
- const image = b.image && b.image.startsWith("data:image/") && b.image.length < 6_000_000 ? b.image : undefined;
+ const history = (Array.isArray(b.history) ? b.history : [])
+ .filter((m) => m && (m.role === "user" || m.role === "assistant"))
+ .slice(-6)
+ .map((m) => ({ role: m.role, content: String(m.content).slice(0, 800) })) as Msg[];
+ // the app sends photos at 1024px, well under this
+ const image = typeof b.image === "string" && b.image.startsWith("data:image/") && b.image.length < 3_000_000 ? b.image : undefined;
const user: Msg = image
? { role: "user", content: [{ type: "text", text: question || "Which part is this?" }, { type: "image_url", image_url: { url: image } }] }
: { role: "user", content: question };
diff --git a/src/app/api/identify/route.ts b/src/app/api/identify/route.ts
index d50f27c..86b82e1 100644
--- a/src/app/api/identify/route.ts
+++ b/src/app/api/identify/route.ts
@@ -1,15 +1,16 @@
-import { chatText, extractJson, hasKey, ipOf, MODELS, rateLimited, userKey } from "@/lib/together";
+import { chatText, extractJson, fromApp, hasKey, ipOf, MODELS, rateLimited, userKey } from "@/lib/together";
const PROMPT = `This photo shows an IKEA product, its box, its label or its assembly manual cover. Read the product name.
Reply with JSON only: {"name": "KALLAX", "variant": "2x4 shelving unit", "confidence": 0.0-1.0}.
The name is the word in capitals (it may contain Å, Ä or Ö). If you can't read a name, guess the kind of furniture in "variant" and set name to "".`;
export async function POST(req: Request) {
+ if (!fromApp(req)) return Response.json({ error: "forbidden" }, { status: 403 });
const key = userKey(req);
if (!hasKey() && !key) return Response.json({ error: "ai-off" }, { status: 503 });
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 });
+ if (typeof image !== "string" || !image.startsWith("data:image/") || image.length > 3_000_000) return Response.json({ error: "bad image" }, { status: 400 });
try {
const { text } = await chatText({
key,
diff --git a/src/app/api/key/route.ts b/src/app/api/key/route.ts
index f8066d2..cd549d5 100644
--- a/src/app/api/key/route.ts
+++ b/src/app/api/key/route.ts
@@ -1,7 +1,10 @@
-import { userKey } from "@/lib/together";
+import { fromApp, ipOf, rateLimited, userKey } from "@/lib/together";
/** Checks that a pasted Together AI key works, without storing it. */
export async function POST(req: Request) {
+ // the scanner posts the key alone, with no body
+ if (!fromApp(req, false)) return Response.json({ ok: false, reason: "forbidden" }, { status: 403 });
+ if (rateLimited(ipOf(req) + ":key", 6, 10 * 60_000)) return Response.json({ ok: false, reason: "unavailable" }, { status: 429 });
const key = userKey(req);
if (!key) return Response.json({ ok: false, reason: "format" });
if (key === "bygga-dev-mock-key-000000" && process.env.NODE_ENV !== "production") return Response.json({ ok: true });
diff --git a/src/app/api/scan/route.ts b/src/app/api/scan/route.ts
index 364f8ab..6b911ba 100644
--- a/src/app/api/scan/route.ts
+++ b/src/app/api/scan/route.ts
@@ -2,7 +2,7 @@ import { buildPlan } from "@/lib/plan";
import { clean, fallbackSpec, parseScan } from "@/lib/scan/parse";
import { PAGE_PROMPT, PLAN_PROMPT, planInput, repairInput } from "@/lib/scan/prompts";
import { SAMPLE_SCAN } from "@/lib/scan/sample";
-import { chatText, extractJson, ipOf, MODELS, rateLimited, TogetherError, userKey, type Msg } from "@/lib/together";
+import { chatText, extractJson, fromApp, ipOf, MODELS, rateLimited, TogetherError, userKey, type Msg } from "@/lib/together";
import type { ProductSpec } from "@/lib/types";
import { SCAN_ENABLED } from "@/lib/site";
@@ -15,6 +15,7 @@ type Note = { kind?: string; product?: { name?: string; brand?: string; type?: s
export async function POST(req: Request) {
if (!SCAN_ENABLED) return Response.json({ error: "off" }, { status: 404 });
+ if (!fromApp(req)) return Response.json({ error: "forbidden" }, { status: 403 });
const key = userKey(req);
if (!key) return Response.json({ error: "key" }, { status: 401 });
if (rateLimited(ipOf(req) + ":scan", 6, 10 * 60_000)) return Response.json({ error: "busy" }, { status: 429 });
@@ -59,8 +60,10 @@ async function scan(key: string, pages: string[], hint: string, send: (o: object
while (next < pages.length) {
const i = next++;
try {
+ // scans only ever spend the person's own key, never the server's
const { text } = await chatText({
key,
+ fallback: false,
models: MODELS.read,
maxTokens: 2000,
temperature: 0,
@@ -87,7 +90,7 @@ async function scan(key: string, pages: string[], hint: string, send: (o: object
{ role: "user", content: planInput(notes, hint) },
];
const ask = async () => {
- const { text } = await chatText({ key, models: MODELS.plan, json: true, maxTokens: 16000, temperature: 0.2, reasoning: "medium", signal, messages: msgs });
+ const { text } = await chatText({ key, fallback: false, models: MODELS.plan, json: true, maxTokens: 16000, temperature: 0.2, reasoning: "medium", signal, messages: msgs });
return { text, raw: extractJson(text) };
};
let { text, raw } = await ask();
diff --git a/src/app/api/voice/route.ts b/src/app/api/voice/route.ts
index 0e08cb8..89c128d 100644
--- a/src/app/api/voice/route.ts
+++ b/src/app/api/voice/route.ts
@@ -5,21 +5,20 @@ import { forTTS, speak } from "@/lib/voice/tts";
/**
* Records a line live in the same voice as the pre-recorded clips, for text
* that has no clip yet: scanned guides and spoken help answers. Responses are
- * cached for good, so each line is only paid for once per edge.
+ * cached for good on the CDN too, so each line is only paid for once.
*/
export async function GET(req: Request) {
await connection();
if (!hasKey()) return Response.json({ error: "voice-off" }, { status: 404 });
- // only the app itself, not other sites hotlinking a free voice
- const site = req.headers.get("sec-fetch-site");
- if (site && site !== "same-origin") return Response.json({ error: "forbidden" }, { status: 403 });
+ // only the app's own pages, which always say so: not other sites or scripts using it as a free voice
+ if (req.headers.get("sec-fetch-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) + ":voice", 90)) return Response.json({ error: "slow down" }, { status: 429 });
+ if (rateLimited(ipOf(req) + ":voice", 40)) return Response.json({ error: "slow down" }, { status: 429 });
try {
const audio = await speak(forTTS(text), process.env.TOGETHER_API_KEY!.trim());
return new Response(audio, {
- headers: { "Content-Type": "audio/mpeg", "Cache-Control": "public, max-age=31536000, immutable" },
+ headers: { "Content-Type": "audio/mpeg", "Cache-Control": "public, max-age=31536000, immutable", "CDN-Cache-Control": "public, max-age=31536000, immutable" },
});
} catch (e) {
console.error("[voice]", (e as Error).message);
diff --git a/src/engine/stage.ts b/src/engine/stage.ts
index b5de218..a299dad 100644
--- a/src/engine/stage.ts
+++ b/src/engine/stage.ts
@@ -4,6 +4,9 @@ import { POSE_EULER } from "@/lib/plan/math";
import { Drawable, hwDrawable, partDrawable, wallDrawable } from "./drawable";
import { INK, INK_OLD } from "./materials";
+/** Part names can come from a shared scan link: never let them through as markup. */
+const esc = (t: string) => String(t).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
+
export type StageMode =
| { kind: "intro"; dims?: boolean }
| { kind: "assembled"; turntable?: boolean; dims?: boolean; view?: { az: number; el: number }; frame?: Vec3[] }
@@ -1087,7 +1090,7 @@ export class Stage {
this.labelLayer.appendChild(el);
this.labels.set(id, el);
}
- const html = `<b>${l.text}</b>${l.sub ? `<span>${l.sub}</span>` : ""}`;
+ const html = `<b>${esc(l.text)}</b>${l.sub ? `<span>${esc(l.sub)}</span>` : ""}`;
if (el.innerHTML !== html) el.innerHTML = html;
el.style.transform = `translate(${l.x}px, ${l.y}px) translate(-50%, -50%) scale(${0.7 + 0.3 * l.o})`;
el.style.opacity = String(l.o);
@@ -1334,7 +1337,7 @@ export class Stage {
if (this.tooltip) {
const type = ref ? this.plan.parts.find((p) => p.id === ref) : null;
if (type && !type.extra) {
- this.tooltip.innerHTML = `<b>${type.label}</b>${type.name}`;
+ this.tooltip.innerHTML = `<b>${esc(type.label)}</b>${esc(type.name)}`;
this.tooltip.style.transform = `translate(${x - r.left + 14}px, ${y - r.top + 16}px)`;
this.tooltip.style.opacity = "1";
} else this.tooltip.style.opacity = "0";
diff --git a/src/lib/scan/parse.ts b/src/lib/scan/parse.ts
index 6491a01..90db041 100644
--- a/src/lib/scan/parse.ts
+++ b/src/lib/scan/parse.ts
@@ -59,6 +59,7 @@ const Root = z.object({
export function clean(s: string) {
return s
+ .replace(/[<>]/g, "")
.replace(/\s*[‒-―]\s*/g, ", ")
.replace(/\s+,/g, ",")
.replace(/\s+/g, " ")
diff --git a/src/lib/together.ts b/src/lib/together.ts
index 93e5493..285dec5 100644
--- a/src/lib/together.ts
+++ b/src/lib/together.ts
@@ -35,8 +35,10 @@ interface ChatOpts {
temperature?: number;
stream?: boolean;
signal?: AbortSignal;
- /** The person's own key. Falls back to the server key. */
+ /** The person's own key. Falls back to the server key, unless `fallback` is false. */
key?: string;
+ /** False for calls that must only ever spend the person's own credit. */
+ fallback?: boolean;
reasoning?: "low" | "medium" | "high";
}
@@ -52,7 +54,7 @@ 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 }> {
// 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))];
+ const keys = [...new Set([o.key?.trim(), o.fallback === false ? undefined : 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) {
@@ -149,6 +151,24 @@ export function userKey(req: Request) {
return k.length >= 20 && k.length <= 200 && /^[\w.-]+$/.test(k) ? k : undefined;
}
+/**
+ * True for requests from this site's own pages. Other sites can't make their visitors'
+ * browsers spend the key: browsers say where a request came from, and a JSON body
+ * can't be sent across sites without a preflight we never answer.
+ */
+export function fromApp(req: Request, json = true) {
+ if (json && !(req.headers.get("content-type") ?? "").includes("application/json")) return false;
+ const site = req.headers.get("sec-fetch-site");
+ if (site) return site === "same-origin";
+ const origin = req.headers.get("origin");
+ if (!origin) return true;
+ try {
+ return new URL(origin).host === req.headers.get("host");
+ } catch {
+ return false;
+ }
+}
+
export function ipOf(req: Request) {
return req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || req.headers.get("x-real-ip") || "local";
}