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(push): refuse a push endpoint that points inside our own network
nirholas66385a5ca27c
diff --git a/api/_lib/web-push.js b/api/_lib/web-push.jsindex 0108a9d6e..629487a1c 100644--- a/api/_lib/web-push.js+++ b/api/_lib/web-push.js@@ -12,6 +12,26 @@// All sends are fire-and-forget — callers never await for correctness.import { sql } from './db.js';+import { validatePublicUrl, resolvePublicHost, SsrfError } from './ssrf.js';++// Endpoints are re-validated at send time, not just at registration: rows stored+// before the registration guard landed are untrusted, and a public host can+// re-point at an internal address between subscribe and send. A row that can+// never be a legal target (bad scheme, private address) is pruned like a dead+// endpoint; a transient resolver failure only skips this send.+const RETRYABLE_SSRF_CODES = new Set(['dns_timeout', 'dns_failed']);++async function endpointDeliverable(endpoint) {+ try {+ const url = validatePublicUrl(endpoint);+ await resolvePublicHost(url.hostname);+ return 'ok';+ } catch (err) {+ const code = err instanceof SsrfError ? err.code : 'invalid_url';+ console.error('[web-push] endpoint rejected:', code);+ return RETRYABLE_SSRF_CODES.has(code) ? 'skip' : 'prune';+ }+}let _configured = null; // null = not yet attempted, false = unavailable, true = readylet _webpush = null;@@ -76,6 +96,13 @@ export async function sendPushToUser(userId, payload) {await Promise.all(subs.map(async (s) => {+ const verdict = await endpointDeliverable(s.endpoint);+ if (verdict === 'prune') {+ dead.push(s.id);+ return;+ }+ if (verdict === 'skip') return;+const subscription = {endpoint: s.endpoint,keys: { p256dh: s.p256dh, auth: s.auth },diff --git a/api/push/subscribe.js b/api/push/subscribe.jsindex 9a3f98eca..e30fe24d9 100644--- a/api/push/subscribe.js+++ b/api/push/subscribe.js@@ -9,6 +9,12 @@// (`.toJSON()`): { endpoint, keys: { p256dh, auth } }. Endpoints are unique// globally, so a re-subscribe upserts: the latest owner wins and stale rows// from a previous account on the same device are reclaimed.+//+// The endpoint is a caller-supplied URL that api/_lib/web-push.js later fetches+// from our own network, so it is SSRF-guarded here at registration time, the+// same way developer-supplied webhook URLs are: https only, and the host must+// resolve to a public address. Without it, `javascript:`/`file:` schemes and+// `http://169.254.169.254/…`-style internal targets are storable.import { z } from 'zod';import { sql } from '../_lib/db.js';@@ -17,6 +23,7 @@ import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/import { requireCsrf } from '../_lib/csrf.js';import { limits } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';+import { assertPublicHttpsUrl, SsrfError } from '../_lib/ssrf.js';const subscriptionSchema = z.object({endpoint: z.string().url().max(2048),@@ -32,6 +39,28 @@ const deleteBody = z.object({subscription: subscriptionSchema.optional(),});+// Transient resolver trouble must not permanently reject a legitimate device:+// the client can retry a 503, while a blocked scheme or an internal target is a+// hard 400 no retry will ever turn into a stored row.+const RETRYABLE_SSRF_CODES = new Set(['dns_timeout', 'dns_failed']);++// Sends the response and returns false when the endpoint is not a public https+// URL; returns true when it is safe to store. Registration only: removing a row+// is safe, so an endpoint that stopped resolving can still be unsubscribed.+async function endpointIsPublic(res, endpoint) {+ try {+ await assertPublicHttpsUrl(endpoint);+ return true;+ } catch (err) {+ if (err instanceof SsrfError && RETRYABLE_SSRF_CODES.has(err.code)) {+ error(res, 503, 'endpoint_unverified', 'could not verify the push endpoint host, retry');+ return false;+ }+ error(res, 400, 'validation_error', 'endpoint must be a public https push service URL');+ return false;+ }+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,DELETE,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST', 'DELETE'])) return;@@ -55,6 +84,7 @@ export default wrap(async (req, res) => {}const { subscription } = parse(postBody, await readJson(req));+ if (!(await endpointIsPublic(res, subscription.endpoint))) return;const ua = String(req.headers['user-agent'] || '').slice(0, 400);await sql`diff --git a/data/changelog.json b/data/changelog.jsonindex 751a6bc64..6865b69aa 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,14 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-15",+ "title": "Push notification sign-up now only accepts a real push service address",+ "summary": "Turning on browser notifications hands the platform the address your browser wants alerts delivered to, and that address is one the platform later calls from its own servers. It was stored exactly as given, so a crafted sign-up could point it at an internal address instead of a push service and use the delivery job as a way to knock on doors inside our own network. Sign-up now checks the address before storing it: it has to be an ordinary secure web address on a genuinely public host, or it is refused with a clear reason. If the check cannot finish because name lookup is briefly down, the browser is told to try again rather than being turned away for good. Delivery re-checks every stored address at send time too, so anything registered before this landed can never be dialed, and an address that could never be legal is dropped from the list the way an expired one already was.",+ "tags": [+ "security"+ ]+ },{"date": "2026-08-15","title": "Daily usage caps stopped resetting themselves partway through the day",diff --git a/prompts/swarm-100/api-push-01.md b/prompts/swarm-100/api-push-01.mddeleted file mode 100644index 53239346f..000000000--- a/prompts/swarm-100/api-push-01.md+++ /dev/null@@ -1,101 +0,0 @@-# API audit: api/push batch 01 (1 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/push/subscribe.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-push-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/tests/native-launch-endpoint.test.js b/tests/native-launch-endpoint.test.jsindex 90e8fe3f9..b2e964fb6 100644--- a/tests/native-launch-endpoint.test.js+++ b/tests/native-launch-endpoint.test.js@@ -51,7 +51,12 @@ vi.mock('../api/_lib/db.js', () => ({return Promise.resolve([]);},}));-vi.mock('../api/_lib/r2.js', () => ({ publicUrl: (k) => `https://cdn.test/${k}` }));+vi.mock('../api/_lib/r2.js', () => ({+ publicUrl: (k) => `https://cdn.test/${k}`,+ // The launch row resolves avatar thumbnails through thumbnailUrl(), which+ // drops the legacy origin-pointing keys that publicUrl() would happily emit.+ thumbnailUrl: (k) => (k ? `https://cdn.test/${k}` : null),+}));vi.mock('../api/_lib/feed.js', () => ({ publishFeedEvent: vi.fn(async () => {}) }));vi.mock('../api/_lib/agent-identity.js', () => ({resolveOrCreateAgentForAvatar: vi.fn(async () => ({ id: 'agent-1' })),diff --git a/tests/push-subscribe-endpoint.test.js b/tests/push-subscribe-endpoint.test.jsindex 10b34e561..6bf0f73c6 100644--- a/tests/push-subscribe-endpoint.test.js+++ b/tests/push-subscribe-endpoint.test.js@@ -19,6 +19,15 @@ vi.mock('../api/_lib/rate-limit.js', () => ({limits: { pushSubscribe: (...a) => pushSubscribeLimitMock(...a) },}));+// The real SsrfError is kept so the handler's `instanceof` branch is exercised;+// only the resolver is faked, because a unit test must not hit live DNS.+const assertPublicHttpsUrlMock = vi.fn();+vi.mock('../api/_lib/ssrf.js', async (importOriginal) => ({+ ...(await importOriginal()),+ assertPublicHttpsUrl: (...a) => assertPublicHttpsUrlMock(...a),+}));+const { SsrfError } = await import('../api/_lib/ssrf.js');+const { default: handler } = await import('../api/push/subscribe.js');const USER = '28e98fb2-2a98-4500-b45a-5a9ad7b3f7a8';@@ -73,6 +82,7 @@ beforeEach(() => {getRequestUserMock.mockReset().mockResolvedValue({ id: USER });requireCsrfMock.mockReset().mockResolvedValue(true);pushSubscribeLimitMock.mockReset().mockResolvedValue({ success: true, limit: 30, remaining: 29, reset: 0 });+ assertPublicHttpsUrlMock.mockReset().mockResolvedValue(ENDPOINT);});describe('POST /api/push/subscribe', () => {@@ -124,6 +134,46 @@ describe('POST /api/push/subscribe', () => {});});+describe('POST /api/push/subscribe endpoint guard', () => {+ it('refuses a non-https scheme so a javascript: URL can never be stored', async () => {+ assertPublicHttpsUrlMock.mockRejectedValue(new SsrfError('scheme not allowed: javascript:', 'scheme_not_allowed'));+ const res = mkRes();+ const sub = { ...SUBSCRIPTION, endpoint: 'javascript:alert(1)' };+ await handler(mkReq({ body: { subscription: sub } }), res);++ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('validation_error');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('refuses an endpoint whose host resolves inside our network', async () => {+ assertPublicHttpsUrlMock.mockRejectedValue(new SsrfError('host resolves to private address: 169.254.169.254', 'private_address'));+ const res = mkRes();+ await handler(mkReq({ body: { subscription: SUBSCRIPTION } }), res);++ expect(res.statusCode).toBe(400);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('answers a resolver outage with a retryable 503 rather than a permanent rejection', async () => {+ assertPublicHttpsUrlMock.mockRejectedValue(new SsrfError('DNS lookup timed out', 'dns_timeout'));+ const res = mkRes();+ await handler(mkReq({ body: { subscription: SUBSCRIPTION } }), res);++ expect(res.statusCode).toBe(503);+ expect(parse(res).error).toBe('endpoint_unverified');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('checks the endpoint the caller sent, not a normalized one', async () => {+ const res = mkRes();+ await handler(mkReq({ body: { subscription: SUBSCRIPTION } }), res);++ expect(assertPublicHttpsUrlMock).toHaveBeenCalledWith(ENDPOINT);+ expect(res.statusCode).toBe(201);+ });+});+describe('DELETE /api/push/subscribe', () => {it('deletes the endpoint scoped to the signed-in user', async () => {const res = mkRes();@@ -145,6 +195,18 @@ describe('DELETE /api/push/subscribe', () => {expect(sqlMock.mock.calls[0].slice(1)).toEqual([USER, ENDPOINT]);});+ it('unsubscribes an endpoint that no longer resolves', async () => {+ // Removing a row is safe, so the registration-time host check must not+ // gate it: a browser rotating away from a dead push service still needs+ // its stale row cleared.+ assertPublicHttpsUrlMock.mockRejectedValue(new SsrfError('DNS lookup failed', 'dns_failed'));+ const res = mkRes();+ await handler(mkReq({ method: 'DELETE', body: { endpoint: ENDPOINT } }), res);++ expect(res.statusCode).toBe(200);+ expect(sqlMock.mock.calls[0].slice(1)).toEqual([USER, ENDPOINT]);+ });+it('rejects a body that names no endpoint at all', async () => {const res = mkRes();await handler(mkReq({ method: 'DELETE', body: {} }), res);