Skip to content

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.

feat(ios): register iOS devices at /api/push/device and fan every push out to APNs

nirholas1806064d32da
diff --git a/api/_lib/apns.js b/api/_lib/apns.js
index 06cde5888..32ee30995 100644
--- a/api/_lib/apns.js
+++ b/api/_lib/apns.js
@@ -240,15 +240,15 @@ export async function sendApnsToUser(userId, payload) {
await Promise.all(
devices.map(async (device) => {
try {
- let env = device.environment in HOSTS ? device.environment : 'production';
- let result = await sendApns({ token: device.token, environment: env, body, collapseId });
+ let host = device.environment in HOSTS ? device.environment : 'production';
+ let result = await sendApns({ token: device.token, environment: host, body, collapseId });
// A sandbox token sent to production (or the reverse) answers
// BadDeviceToken. Try the other host once before calling it dead.
if (result.status === 400 && result.reason === 'BadDeviceToken') {
- env = OTHER[env];
- result = await sendApns({ token: device.token, environment: env, body, collapseId });
+ host = OTHER[host];
+ result = await sendApns({ token: device.token, environment: host, body, collapseId });
if (result.status === 200) {
- sql`update apns_devices set environment = ${env} where id = ${device.id}`.catch((e) =>
+ sql`update apns_devices set environment = ${host} where id = ${device.id}`.catch((e) =>
console.error('[apns] environment update failed:', e.message),
);
}
diff --git a/api/_lib/notify.js b/api/_lib/notify.js
index e0d9c8a4f..cd18ea2f4 100644
--- a/api/_lib/notify.js
+++ b/api/_lib/notify.js
@@ -7,7 +7,8 @@
* 2. inserts the durable in-app row (the bell inbox) when the category's
* `in_app` channel is on,
* 3. records a `sent` funnel event for in_app,
- * 4. fans out to Web Push for the categories the user left enabled,
+ * 4. fans out to Web Push and to the iOS app (APNs) for the categories the
+ * user left enabled,
* 5. records a `sent` event per push delivery,
* 6. queues Telegram and Discord delivery into the chats the owner paired
* through the chat gateways (api/_lib/gateway/notify.js).
@@ -33,6 +34,7 @@ import {
lockedChannelsFor,
} from './notify-prefs.js';
import { sendPushToUser } from './web-push.js';
+import { sendApnsToUser } from './apns.js';
import { queueChatNotifications } from './gateway/notify.js';
export function insertNotification(userId, type, payload = {}) {
@@ -81,8 +83,16 @@ async function deliver(userId, type, payload) {
// worker already tolerates (it only attributes funnel events when present).
try {
if (channelEnabled(prefs, type, 'push')) {
- const delivered = await sendPushToUser(userId, pushPayloadFor(type, payload, id));
- if (delivered > 0) recordEvent(id, userId, 'push', 'sent', { count: delivered });
+ // One payload, two transports: browsers and installed PWAs over Web
+ // Push, the iOS app over APNs (its WebView has no service worker).
+ // Either failing leaves the other to deliver.
+ const push = pushPayloadFor(type, payload, id);
+ const [web, ios] = await Promise.all([
+ sendPushToUser(userId, push).catch(() => 0),
+ sendApnsToUser(userId, push).catch(() => 0),
+ ]);
+ const delivered = web + ios;
+ if (delivered > 0) recordEvent(id, userId, 'push', 'sent', { count: delivered, web, ios });
}
} catch (err) {
console.error('[notify] push fan-out failed:', err.message);
diff --git a/api/config.js b/api/config.js
index 2cc2d79c8..22a112ad8 100644
--- a/api/config.js
+++ b/api/config.js
@@ -3,6 +3,7 @@
import { cors, json, method, wrap } from './_lib/http.js';
import { resolveProviderName, BYOK_REGEN_PROVIDERS } from './_lib/regen-provider.js';
import { vapidPublicKey, pushConfigured } from './_lib/web-push.js';
+import { apnsConfigured } from './_lib/apns.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;
@@ -44,6 +45,10 @@ export default wrap(async (req, res) => {
// enable-push affordance".
pushEnabled: pushConfigured(),
vapidPublicKey: vapidPublicKey(),
+ // Native push for the iOS app (APNs). Separate from pushEnabled because
+ // the two are configured independently: the app can receive push on a
+ // deploy that has no VAPID keys, and a browser on one that has no .p8.
+ nativePush: { ios: apnsConfigured() },
samlLabel: process.env.SAML_BUTTON_LABEL || 'Single sign-on (SSO)',
features: {
// avatarReconstruct is always true: BYOK providers (Meshy, Tripo) are
diff --git a/api/push/device.js b/api/push/device.js
new file mode 100644
index 000000000..d089ec37d
--- /dev/null
+++ b/api/push/device.js
@@ -0,0 +1,73 @@
+// Native device registry for push: the iOS app's APNs token.
+//
+// POST /api/push/device { token, platform: 'ios', app_version? }
+// → upsert this device for the signed-in user.
+// DELETE /api/push/device { token }
+// → remove it (the user turned push off in the app).
+//
+// The browser equivalent is /api/push/subscribe, which stores a Web Push
+// endpoint. The iOS app's WebView has no service worker and so no endpoint;
+// it registers with APNs natively and sends the device token here instead.
+// src/push-notifications.js picks the right one, so every "turn on push"
+// control on the site works unchanged inside the app.
+//
+// Unlike a Web Push endpoint, a device token is not a URL the server fetches,
+// so there is nothing to SSRF-guard: it is validated as hex and only ever
+// appears in a path on Apple's host.
+
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+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 { DEVICE_TOKEN_RE } from '../_lib/apns.js';
+
+// Capacitor reports the token as upper-case hex; APNs accepts either case.
+// Lower-casing on the way in is what keeps one device from becoming two rows.
+const token = z
+ .string()
+ .trim()
+ .transform((s) => s.toLowerCase())
+ .refine((s) => DEVICE_TOKEN_RE.test(s), 'token must be an APNs device token (hex)');
+
+const postBody = z.object({
+ token,
+ platform: z.literal('ios'),
+ app_version: z.string().trim().max(32).optional(),
+});
+const deleteBody = z.object({ token });
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST', 'DELETE'])) return;
+
+ const user = await getRequestUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const rl = await limits.pushSubscribe(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (req.method === 'DELETE') {
+ const body = parse(deleteBody, await readJson(req));
+ await sql`
+ delete from apns_devices
+ where user_id = ${user.id} and token = ${body.token}
+ `;
+ return json(res, 200, { ok: true });
+ }
+
+ const body = parse(postBody, await readJson(req));
+ await sql`
+ insert into apns_devices (user_id, token, app_version)
+ values (${user.id}, ${body.token}, ${body.app_version ?? null})
+ on conflict (token) do update set
+ user_id = excluded.user_id,
+ app_version = excluded.app_version,
+ last_seen_at = now()
+ `;
+
+ return json(res, 201, { ok: true });
+});
diff --git a/docs/api-reference.md b/docs/api-reference.md
index db23d2f74..c3e29ae9b 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -6689,6 +6689,91 @@ page strip (on-chain agents, attestations, forge models).
---
+## Platform Analytics API
+
+```
+GET /api/platform/analytics?window=30d|90d|all
+```
+
+Every platform total three.ws publishes about itself, in one read, each with a
+zero-filled daily series over the window and a `method` string that says
+exactly which rows were counted. This is the data behind the
+[analytics page](/analytics). No auth, CORS open to any origin, IP rate-limited.
+Cached 5 minutes in the shared cache and at the CDN
+(`public, s-maxage=300, stale-while-revalidate=600`).
+
+| Param | Values | Default |
+|---|---|---|
+| `window` | `30d`, `90d`, `all` (anything else falls back to `30d`) | `30d` |
+
+**Response** (one metric shown in full, the rest have the same shape)
+
+```json
+{
+ "window": "30d",
+ "window_days": 30,
+ "from": "2026-09-01",
+ "to": "2026-09-30",
+ "updated_at": "2026-09-30T08:14:03.151Z",
+ "metrics": {
+ "agents": {
+ "key": "agents",
+ "label": "Agents",
+ "unit": "count",
+ "method": "Every agent identity on three.ws that has not been deleted (table agent_identities, deleted_at is null), published or not. The daily series counts agents by the day they were created. Same rows /api/home-stats and /api/platform/stats count.",
+ "available": true,
+ "total": 4165,
+ "window_total": 724,
+ "daily": [{ "day": "2026-09-29", "value": 23 }, { "day": "2026-09-30", "value": 2 }]
+ },
+ "creator_fees": {
+ "key": "creator_fees",
+ "label": "Creator fees earned",
+ "unit": "usd",
+ "method": "coming with per-agent earnings",
+ "available": false,
+ "pending": true,
+ "total": null,
+ "window_total": null,
+ "daily": null
+ }
+ },
+ "errors": []
+}
+```
+
+| Metric key | Unit | Source |
+|---|---|---|
+| `agents` | count | `agent_identities`, not deleted (same rows as `/api/home-stats`) |
+| `agents_with_wallet` | count | agents above with a Solana address or a linked EVM wallet |
+| `coins_launched` | count | mainnet rows in `pump_agent_mints` plus `fixed_supply_launches` |
+| `models_generated` | count | finished, non-rejected `forge_creations` with a stored GLB |
+| `llm_tokens` | tokens | input plus output tokens of `usage_events` of kind `llm` (metered since 2026-06-08) |
+| `x402_settlements` | count | successful settles in `x402_self_facilitator_log` (includes the self-cycled ring, see `/api/x402-ring`) |
+| `x402_volume_usd` | usd | the USDC-paid share of those settlements, at face value |
+| `marketplace_sales` | count | `skill_purchases` confirmed with a paid kind (trials excluded) |
+| `marketplace_volume_three` | three | price of those sales paid in $THREE, in whole tokens |
+| `marketplace_volume_usd` | usd | price of those sales paid in USDC |
+| `hire_volume_usd` | usd | completed `agent_hires`, read through the same helper as `/api/agent-economy/volume` |
+| `creator_fees` | usd | pending (`pending: true`) until per-agent earnings ship |
+
+`total` is all time; `window_total` is the sum of `daily`; `daily` has one
+entry per UTC day from `from` to `to`, zeros included. For `window=all`,
+`from` is the first day any source recorded activity.
+
+**Partial failures.** A source that fails or times out sets its metrics to
+`available: false` with `null` figures and adds one entry per metric to
+`errors` (`{ metric, source, error: "query_failed" | "timeout", message }`).
+The response is still `200`, cached for 30 seconds only. Never read a `null`
+as zero.
+
+```bash
+curl -s "https://three.ws/api/platform/analytics?window=90d" \
+ | jq '.metrics | map_values(select(.available) | {total, window_total})'
+```
+
+---
+
## $THREE Fee Flow API
Two public reads behind the "Where every $100 goes" section of [/three-token](/three-token). No auth, CORS open.