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): open tapped push notifications in the app, refresh device tokens safely, and take shares from the share extension

nirholas5d0e1c54220b
diff --git a/api/push/device.js b/api/push/device.js
index d089ec37d..8e58a4d19 100644
--- a/api/push/device.js
+++ b/api/push/device.js
@@ -1,7 +1,8 @@
// 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.
+// POST /api/push/device { token, platform: 'ios', app_version?, previous? }
+// → upsert this device for the signed-in user. `previous` marks a
+// silent refresh (see below).
// DELETE /api/push/device { token }
// → remove it (the user turned push off in the app).
//
@@ -11,6 +12,13 @@
// src/push-notifications.js picks the right one, so every "turn on push"
// control on the site works unchanged inside the app.
//
+// A refresh is the app re-sending its token on launch without asking anyone,
+// so it must not be able to enrol a device for whoever happens to be signed in.
+// It carries the token the device registered last time, and succeeds only if
+// that token already belongs to the caller: someone else signing in on the
+// same phone gets 409 and the app forgets the token until they opt in
+// themselves. An explicit opt-in (no `previous`) claims the device outright.
+//
// 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.
@@ -36,6 +44,7 @@ const postBody = z.object({
token,
platform: z.literal('ios'),
app_version: z.string().trim().max(32).optional(),
+ previous: token.optional(),
});
const deleteBody = z.object({ token });
@@ -60,6 +69,16 @@ export default wrap(async (req, res) => {
}
const body = parse(postBody, await readJson(req));
+ if (body.previous) {
+ const [owned] = await sql`
+ select 1 from apns_devices
+ where token = ${body.previous} and user_id = ${user.id}
+ `;
+ if (!owned) return error(res, 409, 'not_owner', 'this device is not registered to the signed-in account');
+ if (body.previous !== body.token) {
+ await sql`delete from apns_devices where token = ${body.previous} and user_id = ${user.id}`;
+ }
+ }
await sql`
insert into apns_devices (user_id, token, app_version)
values (${user.id}, ${body.token}, ${body.app_version ?? null})
diff --git a/ios/src/native-bridge.js b/ios/src/native-bridge.js
index 028cea051..967850313 100644
--- a/ios/src/native-bridge.js
+++ b/ios/src/native-bridge.js
@@ -366,6 +366,86 @@ function installHaptics() {
);
}
+/**
+ * Opens the page a tapped push notification points at.
+ *
+ * The payload is built by api/_lib/apns.js from the same `pushPayloadFor` the
+ * Web Push service worker uses, so `url` is either a same-origin path or an
+ * absolute link (a transaction on an explorer). A path opens in the app with
+ * `?source=push&n=<id>`, which src/push-notifications.js turns into the
+ * `returned` funnel event exactly as it does after a service worker click; an
+ * absolute off-site link opens in the Safari sheet, never in the app WebView.
+ * The listener is registered on every page because Capacitor retains the tap
+ * until one is, which is what makes a tap on a cold start land correctly.
+ */
+export function pushTapTarget(data, current = location.href) {
+ const raw = typeof data?.url === 'string' ? data.url.trim() : '';
+ const id = typeof data?.notificationId === 'string' ? data.notificationId : '';
+ let url;
+ try {
+ url = new URL(raw || '/notifications', current);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;
+ if (!isInternalUrl(url.href)) return { external: url.href };
+ url.protocol = 'https:';
+ url.hostname = 'three.ws';
+ url.port = '';
+ url.searchParams.set('source', 'push');
+ if (id) url.searchParams.set('n', id);
+ else url.searchParams.delete('n');
+ return { internal: url.href };
+}
+
+function routePushTaps() {
+ const push = plugin('PushNotifications');
+ if (!push) return;
+ push.addListener('pushNotificationActionPerformed', (event) => {
+ if (event?.actionId === 'dismiss') return;
+ const data = event?.notification?.data || {};
+ // The funnel's `opened` step. The service worker records it for a
+ // browser; in the app this listener is the only thing that sees the tap.
+ if (typeof data.notificationId === 'string' && data.notificationId) {
+ fetch('/api/notifications/track', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ notification_id: data.notificationId, channel: 'push', event: 'opened' }),
+ keepalive: true,
+ }).catch(() => {});
+ }
+ const target = pushTapTarget(data);
+ if (!target) return;
+ if (target.external) {
+ plugin('Browser')?.open({ url: target.external, presentationStyle: 'popover' }).catch(() => {});
+ return;
+ }
+ if (target.internal !== location.href) location.assign(target.internal);
+ });
+}
+
+/**
+ * Keeps the home screen icon's badge equal to the inbox's unread count.
+ *
+ * APNs sets the badge when a notification arrives (api/_lib/apns.js sends the
+ * unread count with it); nothing but the app can bring it back down. The inbox
+ * in the nav (src/notifications.js) announces every count it learns as a
+ * `threews:unread` event, whether from its own fetch, the shared cache or
+ * another tab, so reading notifications anywhere in the app clears the icon.
+ */
+function syncBadge() {
+ const app = plugin('ThreeWsApp');
+ if (!app) return;
+ let last = null;
+ window.addEventListener('threews:unread', (event) => {
+ const count = Number(event?.detail?.count);
+ if (!Number.isInteger(count) || count < 0 || count === last) return;
+ last = count;
+ app.setBadge({ count }).catch(() => {});
+ });
+}
+
let booted = false;
/**
@@ -383,6 +463,8 @@ export function bootNativeIOS() {
installHaptics();
routeExternalLinks();
routeDeepLinks();
+ routePushTaps();
+ syncBadge();
hideSplashWhenPainted();
return true;
}
diff --git a/src/create.js b/src/create.js
index 034f321c7..132fa5ab9 100644
--- a/src/create.js
+++ b/src/create.js
@@ -476,9 +476,11 @@ function wireCard(id, handler) {
});
}
-// Android share-sheet handoff. public/share-target-sw.js intercepts the share
+// Share-sheet handoff. On Android public/share-target-sw.js intercepts the share
// POST to /create/share, stashes the files in the Cache API, and redirects here
-// with ?shared=glb (a .glb), ?shared=1 (anything else), or ?shared=error.
+// with ?shared=glb (a .glb), ?shared=1 (anything else), or ?shared=error. The
+// iOS app's share extension lands here with ?shared=glb&inbox=<id> instead,
+// and takeSharedFiles reads that share from the app.
async function ingestSharedFile() {
const intent = sharedIntent();
if (!intent) return;
@@ -496,13 +498,15 @@ async function ingestSharedFile() {
return;
}
if (intent === 'glb') {
- clearSharedIntent();
+ // Read before clearing: an iOS app share is addressed by the `inbox`
+ // param that clearSharedIntent strips.
let files = [];
try {
({ files } = await takeSharedFiles());
} catch (err) {
log.warn('[create] could not read shared file:', err);
}
+ clearSharedIntent();
const glb = files.find((f) => /\.glb$/i.test(f.name) || f.type === 'model/gltf-binary');
if (glb) await handleGlbFile(glb);
else showStatus('The shared file was not a .glb. Share a GLB avatar or a photo.', 'error');
diff --git a/src/notifications.js b/src/notifications.js
index bca73420e..578015cb2 100644
--- a/src/notifications.js
+++ b/src/notifications.js
@@ -387,6 +387,10 @@ class NotificationInbox {
}
_updateBadge() {
+ // Announced for anything outside the nav that mirrors the count; the iOS
+ // app uses it to keep its home screen icon badge in step
+ // (ios/src/native-bridge.js). Nothing listens in a browser.
+ window.dispatchEvent(new CustomEvent('threews:unread', { detail: { count: this._unread } }));
const badge = this._badge;
if (!badge) return;
if (this._unread > 0) {
diff --git a/src/push-notifications.js b/src/push-notifications.js
index 3563ae6d6..cea53f59a 100644
--- a/src/push-notifications.js
+++ b/src/push-notifications.js
@@ -6,17 +6,43 @@
// load — `enablePush()` is only ever called from a value moment (the inbox
// "turn on push" banner, or the preference center toggle).
//
+// Inside the three.ws iOS app the same API drives Apple Push Notification
+// service instead. The app's WKWebView runs no service worker, so Web Push is
+// impossible there; the PushNotifications Capacitor plugin registers with
+// APNs natively and the device token goes to /api/push/device. Every caller
+// (the inbox banner, the preference center, /companion) works unchanged.
+//
// Public API:
-// isPushSupported() → boolean (SW + PushManager + Notification)
+// isPushSupported() → boolean (SW + PushManager + Notification, or the iOS app)
// getPushConfig() → { pushEnabled, vapidPublicKey }
// getPushState() → { supported, permission, subscribed }
// enablePush() → subscribe + register; returns final state
// disablePush() → unsubscribe + deregister
// trackReturnedFromPush() → record `returned` when booted from a push click
+// refreshNativePushRegistration() → iOS app: re-send a changed APNs token
let _configPromise = null;
+// The APNs device token this app install last registered, so disabling push
+// can deregister exactly that device and a relaunch can detect a new token.
+const NATIVE_TOKEN_KEY = 'threews:apns-token';
+// Once per app session is enough to keep the server's copy of the token fresh.
+const NATIVE_REFRESH_KEY = 'threews:apns-refreshed';
+const NATIVE_REGISTER_TIMEOUT_MS = 15_000;
+
+/**
+ * The PushNotifications plugin when this page runs inside the three.ws iOS app,
+ * null everywhere else. Read off the Capacitor global rather than imported: the
+ * plugin package belongs to ios/package.json, not to the site bundle.
+ */
+function nativePushPlugin() {
+ const cap = globalThis.Capacitor;
+ if (!cap?.isNativePlatform?.() || cap.getPlatform?.() !== 'ios') return null;
+ return cap.Plugins?.PushNotifications ?? null;
+}
+
export function isPushSupported() {
+ if (nativePushPlugin()) return true;
return (
typeof navigator !== 'undefined' &&
'serviceWorker' in navigator &&
@@ -31,7 +57,9 @@ export async function getPushConfig() {
_configPromise = fetch('/api/config', { credentials: 'include' })
.then((r) => (r.ok ? r.json() : null))
.then((c) => ({
- pushEnabled: Boolean(c?.pushEnabled),
+ // In the app, "push is available" means APNs is configured on the
+ // server; VAPID keys are irrelevant to a WebView that cannot use them.
+ pushEnabled: nativePushPlugin() ? Boolean(c?.nativePush?.ios) : Boolean(c?.pushEnabled),
vapidPublicKey: c?.vapidPublicKey || '',
}))
.catch(() => ({ pushEnabled: false, vapidPublicKey: '' }));
@@ -40,6 +68,8 @@ export async function getPushConfig() {
}
export async function getPushState() {
+ const native = nativePushPlugin();
+ if (native) return nativePushState(native);
if (!isPushSupported()) {
return { supported: false, permission: 'unsupported', subscribed: false };
}
@@ -58,6 +88,8 @@ export async function getPushState() {
// Subscribe + register. Returns { ok, reason?, state }. `reason` is one of
// 'unsupported' | 'unconfigured' | 'denied' | 'error' on failure.
export async function enablePush() {
+ const native = nativePushPlugin();
+ if (native) return enableNativePush(native);
if (!isPushSupported()) return { ok: false, reason: 'unsupported', state: await getPushState() };
const { pushEnabled, vapidPublicKey } = await getPushConfig();
@@ -88,6 +120,8 @@ export async function enablePush() {
}
export async function disablePush() {
+ const native = nativePushPlugin();
+ if (native) return disableNativePush(native);
if (!isPushSupported()) return { ok: true };
try {
const reg = await navigator.serviceWorker.getRegistration();
@@ -132,6 +166,173 @@ export async function trackReturnedFromPush() {
}
}
+// ── iOS app (APNs) ───────────────────────────────────────────────────────────
+
+// Capacitor's permission vocabulary, mapped onto Notification.permission's so
+// callers need one set of branches.
+function toNotificationPermission(receive) {
+ if (receive === 'granted') return 'granted';
+ if (receive === 'denied') return 'denied';
+ return 'default';
+}
+
+function storedNativeToken() {
+ try {
+ return localStorage.getItem(NATIVE_TOKEN_KEY) || null;
+ } catch {
+ return null;
+ }
+}
+
+function storeNativeToken(token) {
+ try {
+ if (token) localStorage.setItem(NATIVE_TOKEN_KEY, token);
+ else localStorage.removeItem(NATIVE_TOKEN_KEY);
+ } catch {
+ /* storage disabled: the next enable simply re-registers */
+ }
+}
+
+async function nativePushState(plugin) {
+ let permission = 'default';
+ try {
+ permission = toNotificationPermission((await plugin.checkPermissions())?.receive);
+ } catch {
+ /* plugin not ready: report as not yet asked */
+ }
+ return { supported: true, permission, subscribed: permission === 'granted' && Boolean(storedNativeToken()) };
+}
+
+// register() answers through events, not its promise: the token arrives on
+// `registration` once APNs replies to the app delegate. Resolves with the hex
+// token, rejects on `registrationError` or when APNs never answers.
+async function nativeDeviceToken(plugin) {
+ const handles = [];
+ try {
+ const token = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('APNs did not answer')), NATIVE_REGISTER_TIMEOUT_MS);
+ const settle = (fn, value) => {
+ clearTimeout(timer);
+ fn(value);
+ };
+ Promise.all([
+ plugin.addListener('registration', (t) => settle(resolve, t?.value)),
+ plugin.addListener('registrationError', (e) => settle(reject, new Error(e?.error || 'registration failed'))),
+ ])
+ .then((hs) => {
+ handles.push(...hs);
+ return plugin.register();
+ })
+ .catch((err) => settle(reject, err));
+ });
+ if (!token) throw new Error('empty device token');
+ return String(token).toLowerCase();
+ } finally {
+ for (const h of handles) h?.remove?.();
+ }
+}
+
+// `previous` makes this a refresh the server only honours for the account that
+// opted in (api/push/device.js). Resolves with the HTTP status.
+async function registerNativeToken(token, previous = null) {
+ const csrf = await getCsrf();
+ const r = await fetch('/api/push/device', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', ...(csrf ? { 'x-csrf-token': csrf } : {}) },
+ body: JSON.stringify({ token, platform: 'ios', ...(previous ? { previous } : {}) }),
+ });
+ if (!r.ok && r.status !== 409) throw new Error(`device register failed: ${r.status}`);
+ return r.status;
+}
+
+async function deregisterNativeToken(token) {
+ const csrf = await getCsrf();
+ await fetch('/api/push/device', {
+ method: 'DELETE',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', ...(csrf ? { 'x-csrf-token': csrf } : {}) },
+ body: JSON.stringify({ token }),
+ }).catch(() => {});
+}
+
+async function enableNativePush(plugin) {
+ const { pushEnabled } = await getPushConfig();
+ if (!pushEnabled) return { ok: false, reason: 'unconfigured', state: await nativePushState(plugin) };
+
+ let receive;
+ try {
+ receive = (await plugin.requestPermissions())?.receive;
+ } catch (err) {
+ console.error('[push] native permission request failed', err);
+ return { ok: false, reason: 'error', state: await nativePushState(plugin) };
+ }
+ if (receive !== 'granted') {
+ return {
+ ok: false,
+ reason: receive === 'denied' ? 'denied' : 'dismissed',
+ state: await nativePushState(plugin),
+ };
+ }
+
+ try {
+ const token = await nativeDeviceToken(plugin);
+ await registerNativeToken(token);
+ storeNativeToken(token);
+ return { ok: true, state: await nativePushState(plugin) };
+ } catch (err) {
+ console.error('[push] native register failed', err);
+ return { ok: false, reason: 'error', state: await nativePushState(plugin) };
+ }
+}
+
+async function disableNativePush(plugin) {
+ const token = storedNativeToken();
+ try {
+ if (token) await deregisterNativeToken(token);
+ await plugin.unregister();
+ storeNativeToken(null);
+ return { ok: true };
+ } catch (err) {
+ console.error('[push] native unregister failed', err);
+ return { ok: false };
+ }
+}
+
+/**
+ * Keeps the server's copy of this device's APNs token current.
+ *
+ * Apple can issue a new token after a restore, a reinstall or an OS update,
+ * and the old one then answers 410. Re-registering once per app session, and
+ * only for a device that already opted in, means the server learns the new
+ * token before the next notification rather than losing the device silently.
+ * Never prompts: a device without permission is left alone.
+ */
+export async function refreshNativePushRegistration() {
+ const plugin = nativePushPlugin();
+ const previous = storedNativeToken();
+ if (!plugin || !previous) return;
+ try {
+ if (sessionStorage.getItem(NATIVE_REFRESH_KEY) === '1') return;
+ sessionStorage.setItem(NATIVE_REFRESH_KEY, '1');
+ } catch {
+ /* no session storage: refreshing once per page is still correct */
+ }
+ try {
+ if ((await plugin.checkPermissions())?.receive !== 'granted') {
+ storeNativeToken(null);
+ return;
+ }
+ const token = await nativeDeviceToken(plugin);
+ const status = await registerNativeToken(token, previous);
+ // Someone else is signed in on this phone now. Forget the device rather
+ // than enrol it for them; they can turn push on for themselves.
+ storeNativeToken(status === 409 ? null : token);
+ } catch (err) {
+ console.error('[push] native refresh failed', err);
+ }
+}
+
// ── backend register/deregister ──────────────────────────────────────────────
async function registerSubscription(sub) {
@@ -177,11 +378,16 @@ function urlBase64ToUint8Array(base64String) {
return out;
}
-// Auto-record a push-sourced return as soon as the module loads.
+// Auto-record a push-sourced return as soon as the module loads, and in the
+// iOS app keep the device's APNs registration fresh.
if (typeof window !== 'undefined') {
+ const boot = () => {
+ trackReturnedFromPush();
+ refreshNativePushRegistration();
+ };
if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', trackReturnedFromPush, { once: true });
+ document.addEventListener('DOMContentLoaded', boot, { once: true });
} else {
- trackReturnedFromPush();
+ boot();
}
}
diff --git a/src/selfie-capture.js b/src/selfie-capture.js
index bdb4467e6..e548f0b17 100644
--- a/src/selfie-capture.js
+++ b/src/selfie-capture.js
@@ -884,10 +884,12 @@ async function fileToScaledDataUrl(file) {
if (file) setSlot(REQUIRED_SLOT, file);
})();
-// ── Android share-sheet handoff ─────────────────────────────────────────────
+// ── Share-sheet handoff (Android and the iOS app) ───────────────────────────
// On the Seeker app (and any installed PWA) a photo shared into three.ws is
// POSTed to /create/share, parked in the Cache API by public/share-target-sw.js,
-// and the user lands here with ?shared=1. Fill frontal, then left and right,
+// and the user lands here with ?shared=1. The iOS app's share extension lands
+// here with ?shared=1&inbox=<id>, and takeSharedFiles reads those photos from
+// the app instead of the cache. Fill frontal, then left and right,
// with whatever images arrived; the read is one-shot, and the param is
// stripped so a reload does not look like a fresh share.
(async function ingestSharedPhotos() {
diff --git a/src/shared/share-target.js b/src/shared/share-target.js
index e56a66fb4..fb8055fb7 100644
--- a/src/shared/share-target.js
+++ b/src/shared/share-target.js
@@ -31,6 +31,8 @@ const SHARE_META_KEY = '/_share/meta';
*/
export async function takeSharedFiles({ maxAgeMs = 10 * 60 * 1000 } = {}) {
const empty = { files: [], meta: null };
+ const native = await takeNativeShare();
+ if (native) return native;
if (typeof caches === 'undefined' || !caches || typeof caches.open !== 'function') return empty;
let cache;
@@ -82,6 +84,46 @@ export async function takeSharedFiles({ maxAgeMs = 10 * 60 * 1000 } = {}) {
return { files, meta };
}
+/**
+ * The iOS app's half of the hand-off.
+ *
+ * The iOS WebView runs no service worker, so nothing can intercept a share
+ * POST. The app's share extension parks the files in its App Group instead and
+ * the app opens this page with `?inbox=<id>` (ios/native/App/ShareExtension/
+ * SharedInbox.swift); the `ThreeWsApp` plugin hands them over, once, as base64.
+ * Returns null when this is not an app share, so the caller falls through to
+ * the Cache API path.
+ *
+ * @returns {Promise<{ files: File[], meta: SharedMeta | null } | null>}
+ */
+async function takeNativeShare() {
+ if (typeof location === 'undefined') return null;
+ const id = new URLSearchParams(location.search).get('inbox');
+ const app = globalThis.Capacitor?.Plugins?.ThreeWsApp;
+ if (!id || !app || typeof app.takeShare !== 'function') return null;
+ let taken;
+ try {
+ taken = await app.takeShare({ id });
+ } catch {
+ // Expired, or already opened by an earlier load of this page.
+ return { files: [], meta: null };
+ }
+ const received = Number(taken?.createdAt) || Date.now();
+ const files = (Array.isArray(taken?.files) ? taken.files : []).map((f, i) => {
+ const bin = atob(String(f.data || ''));
+ const bytes = new Uint8Array(bin.length);
+ for (let j = 0; j < bin.length; j++) bytes[j] = bin.charCodeAt(j);
+ return new File([bytes], f.name || `shared-${i}`, {
+ type: f.type || 'application/octet-stream',
+ lastModified: received,
+ });
+ });
+ return {
+ files,
+ meta: { title: '', text: '', url: '', count: files.length, received },
+ };
+}
+
/**
* @param {string} url
* @returns {number | null}
@@ -116,7 +158,9 @@ export function sharedIntent() {
export function clearSharedIntent() {
if (typeof location === 'undefined' || typeof history === 'undefined') return;
const url = new URL(location.href);
- if (!url.searchParams.has('shared')) return;
+ if (!url.searchParams.has('shared') && !url.searchParams.has('inbox')) return;
url.searchParams.delete('shared');
+ // The iOS app's share id. Consumed already, and meaningless on a reload.
+ url.searchParams.delete('inbox');
history.replaceState(history.state, '', url.pathname + url.search + url.hash);
}