Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(notifications): validate the read and preference inputs at the boundary
nirholas7dfb92fc50ef
diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.jsindex 2542f92a5..e84d3c879 100644--- a/api/_lib/notify-prefs.js+++ b/api/_lib/notify-prefs.js@@ -153,18 +153,27 @@ export function defaultMatrix() {* sparse prefs onto DEFAULTS. Returns { categories, telegram_chat_id }.*/export async function resolvePrefs(userId) {- let stored = {};+ return mergeWithDefaults(await readStoredPrefs(userId));+}++/**+ * The caller's stored sparse override exactly as persisted, or `{}` when they+ * have never saved. A partial update merges onto this rather than onto the+ * resolved matrix, so a save never materialises today's defaults into the row+ * and freezes them there.+ */+export async function readStoredPrefs(userId) {try {const [row] = await sql`select prefs from notification_preferences where user_id = ${userId}`;- stored = row?.prefs && typeof row.prefs === 'object' ? row.prefs : {};+ return row?.prefs && typeof row.prefs === 'object' ? row.prefs : {};} catch (err) {- // A missing table or transient DB error must never block delivery — fall+ // A missing table or transient DB error must never block delivery. Fall// back to defaults (in_app + push on) rather than dropping the notice.console.error('[notify-prefs] resolve failed:', err.message);+ return {};}- return mergeWithDefaults(stored);}export function mergeWithDefaults(stored) {diff --git a/api/notifications/[id]/read.js b/api/notifications/[id]/read.jsindex d478df33f..90cb6a85e 100644--- a/api/notifications/[id]/read.js+++ b/api/notifications/[id]/read.js@@ -5,6 +5,11 @@ import { getRequestUser } from '../../_lib/auth.js';import { cors, json, method, wrap, error } from '../../_lib/http.js';import { requireCsrf } from '../../_lib/csrf.js';+// Matches the sibling DELETE handler: `user_notifications.id` is a uuid column,+// so a non-uuid id is a client mistake to reject at the boundary, not a query to+// send. Without this the cast failed inside Postgres and the caller got a 500.+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;@@ -15,7 +20,9 @@ export default wrap(async (req, res) => {if (!(await requireCsrf(req, res, user.id))) return;const id = req.query?.id;- if (!id) return error(res, 400, 'validation_error', 'id required');+ if (!id || !UUID_RE.test(String(id))) {+ return error(res, 400, 'validation_error', 'a notification id (uuid) is required');+ }const [row] = await sql`update user_notificationsdiff --git a/api/notifications/index.js b/api/notifications/index.jsindex 82aa35730..0dcbe6885 100644--- a/api/notifications/index.js+++ b/api/notifications/index.js@@ -16,7 +16,11 @@ export default wrap(async (req, res) => {if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;- const limit = Math.min(50, Math.max(1, parseInt(params.get('limit') || '20', 10)));+ // A non-numeric ?limit parses to NaN, and NaN survives both clamps — it then+ // reached Postgres as `limit NaN` and 500'd the whole list. Fall back to the+ // default instead, so a junk value degrades to the normal page.+ const limitRaw = Number.parseInt(params.get('limit') || '20', 10);+ const limit = Number.isFinite(limitRaw) ? Math.min(50, Math.max(1, limitRaw)) : 20;// Optional type filter (e.g. ?type=pump_alert). Validated against a strict// shape so the parameter can't smuggle anything unexpected into the query.const typeRaw = (params.get('type') || '').trim();diff --git a/api/notifications/preferences.js b/api/notifications/preferences.jsindex 2e2937673..8b15e3658 100644--- a/api/notifications/preferences.js+++ b/api/notifications/preferences.js@@ -4,7 +4,10 @@// → { categories: [...], channels: [...], prefs: {...}, push: {...} }// the full resolved matrix + metadata the UI renders from.// PUT /api/notifications/preferences { categories: {...}, telegram_chat_id }-// → persist a sanitised sparse override; unknown keys are dropped.+// → merge a sanitised sparse override onto what is already stored; unknown+// keys are dropped. A PUT carries only what the caller is changing, so+// omitting a key preserves it. Send telegram_chat_id: null (or '') to+// clear it deliberately.//// Defaults live in api/_lib/notify-prefs.js, so a user who has never saved gets// a sensible matrix and new categories appear automatically.@@ -15,16 +18,26 @@ import { getRequestUser } from '../_lib/auth.js';import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits } from '../_lib/rate-limit.js';+import { parse } from '../_lib/validate.js';import {CATEGORIES,CHANNELS,+ readStoredPrefs,resolvePrefs,sanitizePrefs,} from '../_lib/notify-prefs.js';const putBody = z.object({categories: z.record(z.record(z.boolean())).optional(),- telegram_chat_id: z.string().max(24).optional(),+ // Numeric Telegram chat id, or '' / null to disconnect. Rejecting a+ // malformed one here is what makes the difference visible: the sanitiser+ // silently drops it, which would read to the caller as a successful save.+ telegram_chat_id: z+ .string()+ .max(24)+ .regex(/^(-?\d{1,20})?$/, 'telegram_chat_id must be a numeric Telegram chat ID')+ .nullable()+ .optional(),});export default wrap(async (req, res) => {@@ -51,23 +64,33 @@ export default wrap(async (req, res) => {const rl = await limits.notifPrefsWrite(user.id);if (!rl.success) return rateLimited(res, rl);- const body = parseSafe(await readJson(req));- const clean = sanitizePrefs(body);+ const body = parse(putBody, await readJson(req));+ const next = mergeStored(await readStoredPrefs(user.id), sanitizePrefs(body), body);await sql`insert into notification_preferences (user_id, prefs, updated_at)- values (${user.id}, ${JSON.stringify(clean)}::jsonb, now())+ values (${user.id}, ${JSON.stringify(next)}::jsonb, now())on conflict (user_id) do update set- prefs = ${JSON.stringify(clean)}::jsonb,+ prefs = ${JSON.stringify(next)}::jsonb,updated_at = now()`;return json(res, 200, { ok: true, prefs: await resolvePrefs(user.id) });});-// Lenient parse: a malformed channel map shouldn't 400 the whole save — the-// sanitiser drops anything unrecognised. Validate only the coarse shape.-function parseSafe(raw) {- const out = putBody.safeParse(raw);- return out.success ? out.data : { categories: {} };+// The stored row is the whole preference state, so writing the request body over+// it drops everything the caller did not resend. The settings panel saves the+// category matrix alone, which used to wipe a connected Telegram chat id on+// every save and silently stop those alerts. Merge instead: each category the+// caller sent overlays the stored one, and a key nobody sent survives untouched.+function mergeStored(stored, clean, body) {+ const categories = { ...(stored?.categories || {}) };+ for (const [category, channels] of Object.entries(clean.categories)) {+ categories[category] = { ...(categories[category] || {}), ...channels };+ }+ const telegram =+ body.telegram_chat_id === undefined+ ? stored?.telegram_chat_id ?? null+ : clean.telegram_chat_id ?? null;+ return { categories, telegram_chat_id: telegram };}