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
test(ios): hold the app's native layer to its web callers and cover APNs delivery end to end
nirholasee65c4019a1e
diff --git a/package.json b/package.jsonindex 3879609ee..102bbe9a6 100644--- a/package.json+++ b/package.json@@ -250,7 +250,7 @@"audit:route-shadowing": "node scripts/audit-route-shadowing.mjs","audit:handlers": "node scripts/audit-empty-handlers.mjs","audit:x402-catalog": "node scripts/audit-x402-catalog.mjs",- "gate": "npm run check:conflicts && npm run check:claude && npm run check:vendored && npm run check:model-viewer && npm run check:gcloudignore && npm run check:fetch-timeouts && npm run check:tdz-bootstrap && npm run check:event && npm run check:cron-syntax && npm run check:home-matrix && npm run check:studio-openapi && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-safety && npm run audit:mcp-catalog && npm run check:mcp-catalog && npm run audit:mcp-listing && npm run audit:mcp-surfaces && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:links && npm run check:awesome && npm run check:prompt-library && npm run audit:docs && npm run check:docs-freshness && npm run audit:upstreams && npm run check:tutorials && npm run audit:hidden-guard && npm run audit:inline-handlers && npm run audit:x402-catalog && npm run audit:tokens && npm run audit:states && npm run audit:motion-tokens && npm run audit:guards && npm run audit:tour-atlas && npm run check:ios-icons && npm run check:macos-icon && npm run check:apple-widget && npm run check:windows-widget && npm run check:announce && npm run i18n:home && npm run check:skills-seed && npm run check:openai-skills && npm run check:skills-pack && npm run check:skill-repos && npm run check:openai-fields && npm run audit:motion && npm run audit:tour-global && npm run check:doc-media && npm run check:images && npm run audit:route-shadowing",+ "gate": "npm run check:conflicts && npm run check:claude && npm run check:vendored && npm run check:model-viewer && npm run check:gcloudignore && npm run check:fetch-timeouts && npm run check:tdz-bootstrap && npm run check:event && npm run check:cron-syntax && npm run check:home-matrix && npm run check:studio-openapi && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-safety && npm run audit:mcp-catalog && npm run check:mcp-catalog && npm run audit:mcp-listing && npm run audit:mcp-surfaces && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:links && npm run check:awesome && npm run check:prompt-library && npm run audit:docs && npm run check:docs-freshness && npm run audit:upstreams && npm run check:tutorials && npm run audit:hidden-guard && npm run audit:inline-handlers && npm run audit:x402-catalog && npm run audit:tokens && npm run audit:states && npm run audit:motion-tokens && npm run audit:guards && npm run audit:tour-atlas && npm run check:ios-icons && npm run check:macos-icon && npm run check:apple-widget && npm run check:ios-app && npm run check:windows-widget && npm run check:announce && npm run i18n:home && npm run check:skills-seed && npm run check:openai-skills && npm run check:skills-pack && npm run check:skill-repos && npm run check:openai-fields && npm run audit:motion && npm run audit:tour-global && npm run check:doc-media && npm run check:images && npm run audit:route-shadowing","test:gate-3d": "vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js","audit:mcp-golden": "node scripts/audit-mcp-golden.mjs","audit:mcp-safety": "node scripts/audit-mcp-safety.mjs",@@ -483,6 +483,7 @@"macos:icon": "node apple/scripts/make-macos-icon.mjs","check:macos-icon": "node apple/scripts/make-macos-icon.mjs --check","check:apple-widget": "node scripts/check-apple-widget.mjs",+ "check:ios-app": "node scripts/check-ios-app.mjs","check:windows-widget": "node scripts/check-windows-widget.mjs","check:windows-widget:live": "node scripts/check-windows-widget.mjs --live","ios:open": "npm --prefix ios run open",diff --git a/scripts/check-ios-app.mjs b/scripts/check-ios-app.mjsnew file mode 100644index 000000000..860369dc4--- /dev/null+++ b/scripts/check-ios-app.mjs@@ -0,0 +1,198 @@+#!/usr/bin/env node+/**+ * Verifies the iOS app's native layer against the web code it talks to.+ *+ * node scripts/check-ios-app.mjs+ *+ * Why this exists. Nothing on a Linux build machine can compile Swift, and the+ * iOS app is two halves that only meet on a phone: Swift in ios/native/App and+ * JavaScript that ships with the site. Every failure this catches has the same+ * shape, a name that changed on one side and not the other, and every one of+ * them is silent on device: a quick action whose type no longer matches a+ * route opens nothing, a share extension that is not embedded never appears in+ * the share sheet, a plugin method renamed in Swift makes the page's call+ * reject, and a SceneDelegate that roots the stock Capacitor controller quietly+ * drops swipe-back, the CarPlay channel and the app's own plugin.+ *+ * It is a structural check, not a build. Green means the halves agree; it does+ * not mean the Swift compiles. The Agent glance widget has its own check,+ * scripts/check-apple-widget.mjs.+ */++import { readFileSync, readdirSync, existsSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const read = (rel) => readFileSync(join(REPO, rel), 'utf8');++const problems = [];+const fail = (msg) => problems.push(msg);+let checks = 0;+const pass = (msg) => {+ checks++;+ console.log(`[ios-app] ok ${msg}`);+};+const section = (fn) => {+ const before = problems.length;+ const label = fn();+ if (problems.length === before) pass(label);+};++const pbx = read('ios/native/App/App.xcodeproj/project.pbxproj');+const appPlist = read('ios/native/App/App/Info.plist');+const sharePlist = read('ios/native/App/ShareExtension/Info.plist');+const pages = JSON.parse(read('data/pages.json'));+const pagePaths = new Set(pages.sections.flatMap((s) => s.pages || []).map((p) => p.path));++/** Build files for `file` in the pbxproj, one per target that compiles it. */+const buildFileCount = (file) => (pbx.match(new RegExp(`/\\* ${file.replace('.', '\\.')} in Sources \\*/ = `, 'g')) || []).length;++// ------------------------------------------------------------- sources ---++section(() => {+ for (const dir of ['ios/native/App/App', 'ios/native/App/ShareExtension']) {+ for (const file of readdirSync(join(REPO, dir)).filter((f) => f.endsWith('.swift'))) {+ if (!buildFileCount(file)) fail(`${dir}/${file} is on disk but no target compiles it`);+ }+ }+ // The inbox is written by the extension and read by the app.+ if (buildFileCount('SharedInbox.swift') !== 2) fail('SharedInbox.swift must be compiled by both the app and the share extension');+ return 'every Swift source under ios/native/App is a member of a target';+});++// ----------------------------------------------------- the share extension ---++section(() => {+ const required = [+ ['/* ShareExtension */ = {\n\t\t\tisa = PBXNativeTarget;', 'the ShareExtension target'],+ ['ShareExtension.appex in Embed Foundation Extensions', 'the extension embedded in the app'],+ ['PRODUCT_BUNDLE_IDENTIFIER = ws.three.app.share;', 'the extension bundle id under the app id'],+ ['INFOPLIST_FILE = ShareExtension/Info.plist;', 'the extension Info.plist'],+ ['CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements;', 'the extension entitlements'],+ ['APPLICATION_EXTENSION_API_ONLY = YES;', 'the extension-safe API flag'],+ ];+ for (const [needle, what] of required) if (!pbx.includes(needle)) fail(`project.pbxproj is missing ${what}`);+ for (const file of ['ShareViewController.swift', 'SharedInbox.swift', 'Info.plist', 'ShareExtension.entitlements']) {+ if (!existsSync(join(REPO, 'ios/native/App/ShareExtension', file))) fail(`ios/native/App/ShareExtension/${file} is missing`);+ }+ // App Store Connect rejects an upload whose extension version differs from+ // the app's, so every MARKETING_VERSION in the project has to agree.+ const versions = new Set([...pbx.matchAll(/MARKETING_VERSION = ([^;]+);/g)].map((m) => m[1]));+ if (versions.size !== 1) fail(`MARKETING_VERSION differs between targets: ${[...versions].join(', ')}`);+ return 'the share extension target is wired, embedded and versioned with the app';+});++section(() => {+ if (!sharePlist.includes('com.apple.share-services')) fail('the share extension is not a share-services extension');+ if (!sharePlist.includes('$(PRODUCT_MODULE_NAME).ShareViewController')) fail('the share extension principal class is not ShareViewController');+ if (!sharePlist.includes('<key>GlanceAppGroup</key>')) fail('the share extension Info.plist does not carry GlanceAppGroup, which SharedInbox.swift reads');+ for (const file of ['ios/native/App/ShareExtension/ShareExtension.entitlements', 'ios/native/App/App/App.entitlements']) {+ if (!read(file).includes('$(GLANCE_APP_GROUP)')) fail(`${file} does not join the shared App Group`);+ }+ // The activation rule names the .glb type; only the app's import gives a+ // file that type, so the two have to agree on the identifier.+ const glb = 'org.khronos.glb';+ if (!sharePlist.includes(`"${glb}"`)) fail(`the share extension activation rule does not accept ${glb}`);+ if (!/UTImportedTypeDeclarations[\s\S]*org\.khronos\.glb[\s\S]*<string>glb<\/string>/.test(appPlist)) {+ fail(`the app does not import ${glb} for the .glb extension, so a model in Files never matches the activation rule`);+ }+ if (!read('ios/native/App/ShareExtension/ShareViewController.swift').includes(`"${glb}"`)) {+ fail(`ShareViewController.swift does not load ${glb}`);+ }+ return 'the share extension and the app agree on the App Group and the .glb type';+});++section(() => {+ const inbox = read('ios/native/App/ShareExtension/SharedInbox.swift');+ const landings = [...inbox.matchAll(/return "(\/[^"?]*)\?([^"]*)inbox=/g)];+ if (landings.length !== 2) fail(`SharedInbox.swift should land photos and models on two pages, found ${landings.length}`);+ for (const [, path, query] of landings) {+ if (!pagePaths.has(path)) fail(`SharedInbox.swift lands a share on ${path}, which is not in data/pages.json`);+ if (!query.includes('shared=')) fail(`SharedInbox.swift lands on ${path} without the shared= intent the page checks`);+ }+ const shareTarget = read('src/shared/share-target.js');+ if (!shareTarget.includes(".get('inbox')")) fail('src/shared/share-target.js no longer reads the inbox param');+ if (!shareTarget.includes('takeShare')) fail('src/shared/share-target.js no longer calls ThreeWsApp.takeShare');+ return 'a shared file lands on a real page that reads it from the app';+});++// ------------------------------------------------------- app controller ---++section(() => {+ const scene = read('ios/native/App/App/SceneDelegate.swift');+ if (/rootViewController = CAPBridgeViewController\(\)/.test(scene)) {+ fail('SceneDelegate roots the stock CAPBridgeViewController, which drops MainViewController and everything it installs');+ }+ if (!/MainViewController\(\)/.test(scene)) fail('SceneDelegate does not create MainViewController');+ if (!scene.includes('sceneDidBecomeActive') || !scene.includes('SharedInbox.claimPending')) {+ fail('SceneDelegate never collects a pending share');+ }+ const main = read('ios/native/App/App/MainViewController.swift');+ if (!main.includes('registerPluginInstance(ThreeWsAppPlugin())')) fail('MainViewController does not register the ThreeWsApp plugin');+ return 'the scene is rooted in MainViewController, which registers the app plugin';+});++section(() => {+ const swift = read('ios/native/App/App/ThreeWsAppPlugin.swift');+ if (!swift.includes('jsName = "ThreeWsApp"')) fail('ThreeWsAppPlugin is not exposed to the web as ThreeWsApp');+ const methods = [...swift.matchAll(/CAPPluginMethod\(name: "(\w+)"/g)].map((m) => m[1]);+ for (const m of methods) {+ if (!new RegExp(`@objc func ${m}\\(`).test(swift)) fail(`ThreeWsAppPlugin declares ${m} but does not implement it`);+ }+ const callers = {+ takeShare: read('src/shared/share-target.js'),+ setBadge: read('ios/src/native-bridge.js'),+ };+ for (const [m, js] of Object.entries(callers)) {+ if (!methods.includes(m)) fail(`the web calls ThreeWsApp.${m}, which the plugin does not declare`);+ if (!js.includes(`.${m}(`)) fail(`nothing on the web calls ThreeWsApp.${m} any more`);+ }+ return `the ThreeWsApp plugin's ${methods.length} methods match their web callers`;+});++// -------------------------------------------------------------- push ---++section(() => {+ const app = read('ios/native/App/App/AppDelegate.swift');+ for (const [hook, name] of [+ ['didRegisterForRemoteNotificationsWithDeviceToken', '.capacitorDidRegisterForRemoteNotifications'],+ ['didFailToRegisterForRemoteNotificationsWithError', '.capacitorDidFailToRegisterForRemoteNotifications'],+ ]) {+ if (!app.includes(hook) || !app.includes(name)) fail(`AppDelegate does not forward ${hook} to Capacitor, so register() never resolves`);+ }+ if (!read('ios/native/App/App/App.entitlements').includes('aps-environment')) fail('App.entitlements has no aps-environment');+ if (!appPlist.includes('remote-notification')) fail('Info.plist does not declare the remote-notification background mode');+ const client = read('src/push-notifications.js');+ if (!client.includes("'/api/push/device'")) fail('src/push-notifications.js does not register the device with /api/push/device');+ if (!existsSync(join(REPO, 'api/push/device.js'))) fail('api/push/device.js is missing');+ if (!read('api/_lib/notify.js').includes('sendApnsToUser')) fail('api/_lib/notify.js does not fan out to APNs');+ if (!read('ios/src/native-bridge.js').includes('pushNotificationActionPerformed')) fail('the bridge does not route a tapped push');+ return 'push is wired from the app delegate through the device endpoint to the notification fan-out';+});++// ------------------------------------------------------- quick actions ---++section(() => {+ const swift = read('ios/native/App/App/QuickActions.swift');+ const routes = Object.fromEntries([...swift.matchAll(/"(ws\.three\.app\.[\w.]+)": "([^"]+)"/g)].map((m) => [m[1], m[2]]));+ const declared = [...appPlist.matchAll(/<key>UIApplicationShortcutItemType<\/key>\s*<string>([^<]+)<\/string>/g)].map((m) => m[1]);+ if (!declared.length) fail('Info.plist declares no quick actions');+ for (const type of declared) {+ if (!routes[type]) fail(`Info.plist declares quick action ${type}, which QuickActions.swift does not route`);+ }+ for (const [type, target] of Object.entries(routes)) {+ if (!declared.includes(type)) fail(`QuickActions.swift routes ${type}, which Info.plist never declares`);+ const path = target.split('?')[0];+ if (!pagePaths.has(path)) fail(`quick action ${type} opens ${path}, which is not in data/pages.json`);+ }+ return `${declared.length} quick actions are declared, routed and land on live pages`;+});++if (problems.length) {+ console.error('');+ for (const p of problems) console.error(`[ios-app] FAIL ${p}`);+ console.error(`\n[ios-app] ${problems.length} problem(s). See ios/README.md.`);+ process.exit(1);+}+console.log(`\n[ios-app] ${checks} checks passed.`);diff --git a/tests/apns.test.js b/tests/apns.test.jsnew file mode 100644index 000000000..b4156a1c8--- /dev/null+++ b/tests/apns.test.js@@ -0,0 +1,208 @@+// api/_lib/apns.js: push delivery to the iOS app.+//+// The transport is faked at node:http2 so the test never reaches Apple, but+// the provider token is signed with a real ES256 key and verified back, so the+// auth header is exactly what APNs would receive. What is pinned:+// - an unconfigured deploy sends nothing and reads nothing;+// - the request carries the topic, the provider token and the device path;+// - the badge is the recipient's unread count;+// - a sandbox token answered BadDeviceToken by production is retried on the+// sandbox host and the row's environment is corrected;+// - a token APNs says is gone is pruned.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'node:events';+import { generateKeyPairSync } from 'node:crypto';+import { jwtVerify, importSPKI } from 'jose';++const sqlMock = vi.fn();+vi.mock('../api/_lib/db.js', () => ({ sql: sqlMock }));++// Scripted APNs: each request pops the next { status, reason } for its host.+const sent = [];+const script = { production: [], sandbox: [] };+vi.mock('node:http2', () => {+ const connect = (host) => {+ const session = new EventEmitter();+ session.closed = false;+ session.destroyed = false;+ session.unref = () => {};+ session.destroy = () => {+ session.destroyed = true;+ };+ session.request = (headers) => {+ const stream = new EventEmitter();+ stream.setEncoding = () => {};+ stream.setTimeout = () => {};+ stream.close = () => {};+ stream.end = (body) => {+ const env = host.includes('sandbox') ? 'sandbox' : 'production';+ sent.push({ host, env, headers, body: JSON.parse(body) });+ const next = script[env].shift() || { status: 200 };+ queueMicrotask(() => {+ stream.emit('response', { ':status': next.status });+ if (next.reason) stream.emit('data', JSON.stringify({ reason: next.reason }));+ stream.emit('end');+ });+ };+ return stream;+ };+ return session;+ };+ return { default: { connect, constants: { NGHTTP2_CANCEL: 8 } }, connect };+});++const apns = await import('../api/_lib/apns.js');++const USER = '28e98fb2-2a98-4500-b45a-5a9ad7b3f7a8';+const TOKEN = 'a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90';+const PAYLOAD = {+ title: 'Skill sold',+ body: 'Someone bought Weather from your agent',+ url: '/dashboard/',+ notificationId: '2b1f4c1e-7d0a-4a55-9b8e-1f2d3c4b5a69',+ category: 'sales',+ tag: 'skill_purchased',+};++const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });+const PEM = privateKey.export({ type: 'pkcs8', format: 'pem' });+const SPKI = publicKey.export({ type: 'spki', format: 'pem' });++// Routes the handful of queries the sender makes to canned answers.+function database({ devices, unread = 2 }) {+ sqlMock.mockImplementation((strings) => {+ const q = strings.join(' ');+ if (q.includes('from apns_devices')) return Promise.resolve(devices);+ if (q.includes('from user_notifications')) return Promise.resolve([{ n: unread }]);+ return Promise.resolve([]);+ });+}+const writes = () =>+ sqlMock.mock.calls+ .map(([strings, ...values]) => ({ q: strings.join(' '), values }))+ .filter(({ q }) => q.startsWith('update') || q.trim().startsWith('delete'));++beforeEach(() => {+ apns._resetApnsForTests();+ sent.length = 0;+ script.production.length = 0;+ script.sandbox.length = 0;+ sqlMock.mockReset();+ vi.stubEnv('APNS_KEY_ID', 'ABC123DEFG');+ vi.stubEnv('APNS_TEAM_ID', 'TEAM123456');+ // Stored the way a multi-line secret survives an env var.+ vi.stubEnv('APNS_AUTH_KEY', PEM.replace(/\n/g, '\\n'));+ vi.stubEnv('APNS_BUNDLE_ID', '');+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('apnsConfigured', () => {+ it('needs the key id, the key and a team id', () => {+ expect(apns.apnsConfigured()).toBe(true);+ vi.stubEnv('APNS_AUTH_KEY', '');+ expect(apns.apnsConfigured()).toBe(false);+ });++ it('takes the team id the app association already uses', () => {+ vi.stubEnv('APNS_TEAM_ID', '');+ vi.stubEnv('APPLE_TEAM_ID', 'TEAM123456');+ expect(apns.apnsConfigured()).toBe(true);+ });+});++describe('buildApnsPayload', () => {+ it('puts the alert under aps and the tap target beside it', () => {+ expect(apns.buildApnsPayload(PAYLOAD, 4)).toEqual({+ aps: {+ alert: { title: 'Skill sold', body: 'Someone bought Weather from your agent' },+ sound: 'default',+ 'thread-id': 'sales',+ badge: 4,+ },+ url: '/dashboard/',+ notificationId: PAYLOAD.notificationId,+ category: 'sales',+ });+ });++ it('leaves the badge alone when the count is unknown', () => {+ expect(apns.buildApnsPayload(PAYLOAD, null).aps).not.toHaveProperty('badge');+ });++ it('opens the inbox when the notification links nowhere', () => {+ expect(apns.buildApnsPayload({ title: 't', body: 'b' }).url).toBe('/notifications');+ });+});++describe('sendApnsToUser', () => {+ it('sends nothing and reads nothing when APNs is not configured', async () => {+ vi.stubEnv('APNS_KEY_ID', '');+ expect(await apns.sendApnsToUser(USER, PAYLOAD)).toBe(0);+ expect(sqlMock).not.toHaveBeenCalled();+ expect(sent).toHaveLength(0);+ });++ it('delivers with a verifiable provider token, the app topic and the unread badge', async () => {+ database({ devices: [{ id: 'd1', token: TOKEN, environment: 'production' }], unread: 3 });++ expect(await apns.sendApnsToUser(USER, PAYLOAD)).toBe(1);+ const [req] = sent;+ expect(req.env).toBe('production');+ expect(req.headers[':path']).toBe(`/3/device/${TOKEN}`);+ expect(req.headers['apns-topic']).toBe('ws.three.app');+ expect(req.headers['apns-push-type']).toBe('alert');+ expect(req.headers['apns-collapse-id']).toBe(PAYLOAD.notificationId);+ expect(req.body.aps.badge).toBe(3);++ const jwt = req.headers.authorization.replace(/^bearer /, '');+ const { payload, protectedHeader } = await jwtVerify(jwt, await importSPKI(SPKI, 'ES256'));+ expect(protectedHeader).toMatchObject({ alg: 'ES256', kid: 'ABC123DEFG' });+ expect(payload.iss).toBe('TEAM123456');+ });++ it('reuses one provider token across sends, as Apple requires', async () => {+ database({ devices: [{ id: 'd1', token: TOKEN, environment: 'production' }] });+ await apns.sendApnsToUser(USER, PAYLOAD);+ await apns.sendApnsToUser(USER, PAYLOAD);+ expect(sent[0].headers.authorization).toBe(sent[1].headers.authorization);+ });++ it('retries a development token on the sandbox host and records where it lives', async () => {+ database({ devices: [{ id: 'd1', token: TOKEN, environment: 'production' }] });+ script.production.push({ status: 400, reason: 'BadDeviceToken' });++ expect(await apns.sendApnsToUser(USER, PAYLOAD)).toBe(1);+ expect(sent.map((r) => r.env)).toEqual(['production', 'sandbox']);+ await new Promise((r) => setTimeout(r, 0));+ const update = writes().find(({ q }) => q.includes('update apns_devices'));+ expect(update.values).toEqual(['sandbox', 'd1']);+ });++ it('prunes a device APNs says is gone', async () => {+ database({+ devices: [+ { id: 'gone', token: TOKEN, environment: 'production' },+ { id: 'live', token: TOKEN.replace('a1', 'b2'), environment: 'production' },+ ],+ });+ script.production.push({ status: 410, reason: 'Unregistered' });++ expect(await apns.sendApnsToUser(USER, PAYLOAD)).toBe(1);+ await new Promise((r) => setTimeout(r, 0));+ const prune = writes().find(({ q }) => q.includes('delete from apns_devices'));+ expect(prune.values).toEqual([['gone']]);+ });++ it('keeps a device through a transient APNs error', async () => {+ database({ devices: [{ id: 'd1', token: TOKEN, environment: 'production' }] });+ script.production.push({ status: 503, reason: 'ServiceUnavailable' });++ expect(await apns.sendApnsToUser(USER, PAYLOAD)).toBe(0);+ await new Promise((r) => setTimeout(r, 0));+ expect(writes()).toHaveLength(0);+ });+});diff --git a/tests/ios-native-app-mode.test.js b/tests/ios-native-app-mode.test.jsindex 0dc3882ed..6ea80ac7e 100644--- a/tests/ios-native-app-mode.test.js+++ b/tests/ios-native-app-mode.test.js@@ -21,6 +21,7 @@ import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vites/** Minimal stand-in for the plugins Capacitor registers natively. */function fakeCapacitor() {+ fakeCapacitor.pushHandlers = {};const calls = [];const record =(name) =>@@ -47,6 +48,14 @@ function fakeCapacitor() {},},Haptics: { impact: record('Haptics.impact') },+ ThreeWsApp: { setBadge: record('ThreeWsApp.setBadge') },+ PushNotifications: {+ addListener: (event, handler) => {+ calls.push(['PushNotifications.addListener', event]);+ fakeCapacitor.pushHandlers[event] = handler;+ return Promise.resolve({ remove() {} });+ },+ },App: {addListener: (event, handler) => {calls.push(['App.addListener', event]);@@ -70,9 +79,16 @@ describe('ios native bridge, running inside the app', () => {let mod;let bootCalls;+ let fetchCalls;+beforeAll(async () => {cap = fakeCapacitor();vi.stubGlobal('Capacitor', cap);+ fetchCalls = [];+ vi.stubGlobal('fetch', (url, init) => {+ fetchCalls.push([url, init]);+ return Promise.resolve(new Response('{}', { status: 200 }));+ });mod = await import('../ios/src/native-bridge.js');mod.bootNativeIOS();// The splash hide is deferred behind a double requestAnimationFrame, so@@ -202,6 +218,73 @@ describe('ios native bridge, running inside the app', () => {});});+ describe('push notifications', () => {+ it('listens for taps from boot, so a tap on a cold start is not lost', () => {+ expect(+ bootCalls.some((c) => c[0] === 'PushNotifications.addListener' && c[1] === 'pushNotificationActionPerformed'),+ ).toBe(true);+ });++ it('opens an explorer link from a push in the Safari sheet and records the open', () => {+ fetchCalls.length = 0;+ fakeCapacitor.pushHandlers.pushNotificationActionPerformed({+ actionId: 'tap',+ notification: {+ data: {+ url: 'https://solscan.io/tx/abc',+ notificationId: '2b1f4c1e-7d0a-4a55-9b8e-1f2d3c4b5a69',+ },+ },+ });+ expect(cap.calls.find((c) => c[0] === 'Browser.open')[1].url).toBe('https://solscan.io/tx/abc');+ const [url, init] = fetchCalls.find(([u]) => u === '/api/notifications/track');+ expect(url).toBe('/api/notifications/track');+ expect(JSON.parse(init.body)).toEqual({+ notification_id: '2b1f4c1e-7d0a-4a55-9b8e-1f2d3c4b5a69',+ channel: 'push',+ event: 'opened',+ });+ });++ it('ignores a dismissed notification', () => {+ fetchCalls.length = 0;+ fakeCapacitor.pushHandlers.pushNotificationActionPerformed({+ actionId: 'dismiss',+ notification: { data: { url: 'https://solscan.io/tx/abc', notificationId: 'x' } },+ });+ expect(cap.calls.some((c) => c[0] === 'Browser.open')).toBe(false);+ expect(fetchCalls).toHaveLength(0);+ });+ });++ describe('icon badge', () => {+ const announce = (count) =>+ window.dispatchEvent(new CustomEvent('threews:unread', { detail: { count } }));+ const badgeCalls = () => cap.calls.filter((c) => c[0] === 'ThreeWsApp.setBadge');++ it('mirrors the inbox unread count onto the home screen icon', () => {+ announce(3);+ expect(badgeCalls().at(-1)[1]).toEqual({ count: 3 });+ });++ it('clears the badge when the inbox is read', () => {+ announce(0);+ expect(badgeCalls().at(-1)[1]).toEqual({ count: 0 });+ });++ it('does not call native again for a count it already set', () => {+ announce(5);+ announce(5);+ expect(badgeCalls()).toHaveLength(1);+ });++ it('ignores a malformed count rather than zeroing the badge', () => {+ announce('lots');+ announce(-1);+ expect(badgeCalls()).toHaveLength(0);+ });+ });+it('hides the launch screen rather than holding it forever', () => {// Two independent triggers, so a page that never paints still reveals// itself: a double rAF, and a hard ceiling. jsdom runs rAF, so thediff --git a/tests/ios-native-bridge.test.js b/tests/ios-native-bridge.test.jsindex 388fcc0d6..1bc9c3f5d 100644--- a/tests/ios-native-bridge.test.js+++ b/tests/ios-native-bridge.test.js@@ -79,4 +79,41 @@ describe('ios native bridge', () => {});}});++ describe('pushTapTarget', () => {+ const ID = '2b1f4c1e-7d0a-4a55-9b8e-1f2d3c4b5a69';++ it('opens a same-origin path in the app, marked as a push return', () => {+ expect(mod.pushTapTarget({ url: '/agents/7', notificationId: ID })).toEqual({+ internal: `https://three.ws/agents/7?source=push&n=${ID}`,+ });+ });++ it('keeps the query the notification already carried', () => {+ const { internal } = mod.pushTapTarget({ url: '/dashboard/?tab=sales', notificationId: ID });+ const url = new URL(internal);+ expect(url.searchParams.get('tab')).toBe('sales');+ expect(url.searchParams.get('source')).toBe('push');+ });++ it('pins a www link to the app origin', () => {+ expect(mod.pushTapTarget({ url: 'https://www.three.ws/create' }).internal).toBe(+ 'https://three.ws/create?source=push',+ );+ });++ it('sends an off-site link out of the app', () => {+ expect(mod.pushTapTarget({ url: 'https://solscan.io/tx/abc' })).toEqual({+ external: 'https://solscan.io/tx/abc',+ });+ });++ it('falls back to the inbox when the payload has no link', () => {+ expect(new URL(mod.pushTapTarget({}).internal).pathname).toBe('/notifications');+ });++ it('refuses a script URL outright', () => {+ expect(mod.pushTapTarget({ url: 'javascript:alert(1)' })).toBeNull();+ });+ });});diff --git a/tests/push-device-endpoint.test.js b/tests/push-device-endpoint.test.jsnew file mode 100644index 000000000..25ee11801--- /dev/null+++ b/tests/push-device-endpoint.test.js@@ -0,0 +1,177 @@+// /api/push/device: the iOS app's APNs token registry. The browser twin is+// /api/push/subscribe (tests/push-subscribe-endpoint.test.js). The rule most+// worth pinning is the refresh guard: the app re-sends its token on every+// launch without asking anyone, and that must never enrol the phone for a+// different account that happens to be signed in now.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const sqlMock = vi.fn();+vi.mock('../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: () => false,+}));++const getRequestUserMock = vi.fn();+vi.mock('../api/_lib/auth.js', () => ({ getRequestUser: (...a) => getRequestUserMock(...a) }));++const requireCsrfMock = vi.fn();+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: (...a) => requireCsrfMock(...a) }));++const pushSubscribeLimitMock = vi.fn();+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { pushSubscribe: (...a) => pushSubscribeLimitMock(...a) },+}));++const { default: handler } = await import('../api/push/device.js');++const USER = '28e98fb2-2a98-4500-b45a-5a9ad7b3f7a8';+// Capacitor reports tokens in upper case; the table stores lower case.+const TOKEN = 'A1B2C3D4E5F60718293A4B5C6D7E8F90A1B2C3D4E5F60718293A4B5C6D7E8F90';+const NEW_TOKEN = 'ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100';++function mkReq({ method = 'POST', headers = {}, body = null } = {}) {+ const hdrs = { 'content-type': 'application/json', ...headers };+ return {+ method,+ url: '/api/push/device',+ headers: hdrs,+ on(event, cb) {+ if (event === 'data' && body != null) {+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));+ queueMicrotask(() => {+ cb(buf);+ this._endCb?.();+ });+ } else if (event === 'end') {+ this._endCb = cb;+ if (body == null) queueMicrotask(() => cb());+ }+ },+ destroy() {},+ };+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(b) {+ this.body = b;+ this.writableEnded = true;+ },+ };+}++const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);+const queries = () => sqlMock.mock.calls.map(([strings]) => strings.join(' '));++beforeEach(() => {+ sqlMock.mockReset().mockResolvedValue([]);+ getRequestUserMock.mockReset().mockResolvedValue({ id: USER });+ requireCsrfMock.mockReset().mockResolvedValue(true);+ pushSubscribeLimitMock.mockReset().mockResolvedValue({ success: true, limit: 30, remaining: 29, reset: 0 });+});++describe('POST /api/push/device', () => {+ it('registers the device for the signed-in user, lower-casing the token', async () => {+ const res = mkRes();+ await handler(mkReq({ body: { token: TOKEN, platform: 'ios', app_version: '1.0' } }), res);++ expect(res.statusCode).toBe(201);+ expect(parse(res)).toEqual({ ok: true });+ const [strings, ...values] = sqlMock.mock.calls[0];+ expect(strings.join(' ')).toContain('insert into apns_devices');+ // Latest owner wins, the same rule the Web Push table uses.+ expect(strings.join(' ')).toContain('on conflict (token) do update');+ expect(values).toEqual([USER, TOKEN.toLowerCase(), '1.0']);+ });++ it('rejects a token that is not hex before touching the database', async () => {+ const res = mkRes();+ await handler(mkReq({ body: { token: 'not-a-token', platform: 'ios' } }), res);+ expect(res.statusCode).toBe(400);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('rejects a platform it does not deliver to', async () => {+ const res = mkRes();+ await handler(mkReq({ body: { token: TOKEN, platform: 'android' } }), res);+ expect(res.statusCode).toBe(400);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('refuses an anonymous caller before CSRF, the limiter or the database', async () => {+ getRequestUserMock.mockResolvedValue(null);+ const res = mkRes();+ await handler(mkReq({ body: { token: TOKEN, platform: 'ios' } }), res);+ expect(res.statusCode).toBe(401);+ expect(requireCsrfMock).not.toHaveBeenCalled();+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('stops at the rate limiter', async () => {+ pushSubscribeLimitMock.mockResolvedValue({ success: false, limit: 30, remaining: 0, reset: Date.now() + 1000 });+ const res = mkRes();+ await handler(mkReq({ body: { token: TOKEN, platform: 'ios' } }), res);+ expect(res.statusCode).toBe(429);+ expect(sqlMock).not.toHaveBeenCalled();+ });+});++describe('POST /api/push/device refresh', () => {+ it('refuses to move a device to a different account that is signed in now', async () => {+ // The ownership lookup finds no row for this caller.+ sqlMock.mockResolvedValueOnce([]);+ const res = mkRes();+ await handler(mkReq({ body: { token: TOKEN, platform: 'ios', previous: TOKEN } }), res);++ expect(res.statusCode).toBe(409);+ expect(parse(res).error).toBe('not_owner');+ expect(queries().some((q) => q.includes('insert into apns_devices'))).toBe(false);+ });++ it('bumps the same token for its owner', async () => {+ sqlMock.mockResolvedValueOnce([{ '?column?': 1 }]);+ const res = mkRes();+ await handler(mkReq({ body: { token: TOKEN, platform: 'ios', previous: TOKEN } }), res);++ expect(res.statusCode).toBe(201);+ expect(queries().some((q) => q.includes('delete from apns_devices'))).toBe(false);+ expect(queries().some((q) => q.includes('insert into apns_devices'))).toBe(true);+ });++ it('swaps a rotated token for its owner, dropping the old one', async () => {+ sqlMock.mockResolvedValueOnce([{ '?column?': 1 }]);+ const res = mkRes();+ await handler(mkReq({ body: { token: NEW_TOKEN, platform: 'ios', previous: TOKEN } }), res);++ expect(res.statusCode).toBe(201);+ const del = sqlMock.mock.calls.find(([s]) => s.join(' ').includes('delete from apns_devices'));+ expect(del.slice(1)).toEqual([TOKEN.toLowerCase(), USER]);+ const ins = sqlMock.mock.calls.find(([s]) => s.join(' ').includes('insert into apns_devices'));+ expect(ins[2]).toBe(NEW_TOKEN);+ });+});++describe('DELETE /api/push/device', () => {+ it("removes only the caller's own row for that token", async () => {+ const res = mkRes();+ await handler(mkReq({ method: 'DELETE', body: { token: TOKEN } }), res);++ expect(res.statusCode).toBe(200);+ const [strings, ...values] = sqlMock.mock.calls[0];+ expect(strings.join(' ')).toContain('delete from apns_devices');+ expect(values).toEqual([USER, TOKEN.toLowerCase()]);+ });+});diff --git a/tests/push-notifications-native.test.js b/tests/push-notifications-native.test.jsnew file mode 100644index 000000000..8539c02bd--- /dev/null+++ b/tests/push-notifications-native.test.js@@ -0,0 +1,180 @@+// @vitest-environment jsdom+// @vitest-environment-options { "url": "https://three.ws/notifications" }+//+// src/push-notifications.js inside the iOS app. The WebView there has no+// service worker, so the same public API has to enrol the device with APNs+// through the PushNotifications plugin and register the token at+// /api/push/device. Every "turn on push" control on the site calls this+// module, so if this path breaks, push silently never works on iPhone.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const TOKEN = 'A1B2C3D4E5F60718293A4B5C6D7E8F90A1B2C3D4E5F60718293A4B5C6D7E8F90';++function fakePushPlugin({ receive = 'granted', token = TOKEN, fail = null } = {}) {+ const listeners = {};+ const calls = [];+ return {+ calls,+ checkPermissions: async () => ({ receive }),+ requestPermissions: async () => {+ calls.push('requestPermissions');+ return { receive };+ },+ addListener: async (event, fn) => {+ listeners[event] = fn;+ return { remove: () => delete listeners[event] };+ },+ register: async () => {+ calls.push('register');+ // APNs answers the app delegate asynchronously, after register resolves.+ setTimeout(() => {+ if (fail) listeners.registrationError?.({ error: fail });+ else listeners.registration?.({ value: token });+ }, 0);+ },+ unregister: async () => {+ calls.push('unregister');+ },+ };+}++let fetchCalls;+function stubFetch({ nativeIos = true, deviceStatus = 201 } = {}) {+ fetchCalls = [];+ vi.stubGlobal('fetch', async (url, init = {}) => {+ fetchCalls.push({ url, init });+ if (url === '/api/config') return new Response(JSON.stringify({ pushEnabled: false, nativePush: { ios: nativeIos } }));+ if (url === '/api/csrf-token') return new Response(JSON.stringify({ data: { token: 'csrf-1' } }));+ if (url === '/api/push/device') return new Response('{}', { status: init.method === 'DELETE' ? 200 : deviceStatus });+ return new Response('{}');+ });+}++async function load(plugin) {+ vi.resetModules();+ vi.stubGlobal('Capacitor', {+ isNativePlatform: () => true,+ getPlatform: () => 'ios',+ Plugins: { PushNotifications: plugin },+ });+ return import('../src/push-notifications.js');+}++const deviceCalls = () => fetchCalls.filter((c) => c.url === '/api/push/device');++beforeEach(() => {+ localStorage.clear();+ sessionStorage.clear();+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('push in the iOS app', () => {+ it('reports push as supported although the WebView has no service worker', async () => {+ stubFetch();+ const mod = await load(fakePushPlugin());+ expect(mod.isPushSupported()).toBe(true);+ });++ it('offers push when the server has APNs configured, whatever VAPID says', async () => {+ stubFetch({ nativeIos: true });+ const mod = await load(fakePushPlugin());+ expect((await mod.getPushConfig()).pushEnabled).toBe(true);+ });++ it('hides push when the server cannot deliver to iPhone', async () => {+ stubFetch({ nativeIos: false });+ const plugin = fakePushPlugin();+ const mod = await load(plugin);+ const result = await mod.enablePush();+ expect(result).toMatchObject({ ok: false, reason: 'unconfigured' });+ expect(plugin.calls).not.toContain('requestPermissions');+ });++ it('asks permission, registers with APNs and sends the token to the device endpoint', async () => {+ stubFetch();+ const plugin = fakePushPlugin();+ const mod = await load(plugin);++ const result = await mod.enablePush();++ expect(result.ok).toBe(true);+ expect(result.state).toEqual({ supported: true, permission: 'granted', subscribed: true });+ expect(plugin.calls).toEqual(['requestPermissions', 'register']);+ const [post] = deviceCalls();+ expect(post.init.method).toBe('POST');+ expect(post.init.headers['x-csrf-token']).toBe('csrf-1');+ expect(JSON.parse(post.init.body)).toEqual({ token: TOKEN.toLowerCase(), platform: 'ios' });+ });++ it('reports a refusal as denied and registers nothing', async () => {+ stubFetch();+ const mod = await load(fakePushPlugin({ receive: 'denied' }));+ const result = await mod.enablePush();+ expect(result).toMatchObject({ ok: false, reason: 'denied' });+ expect(result.state.permission).toBe('denied');+ expect(deviceCalls()).toHaveLength(0);+ });++ it('surfaces an APNs registration failure instead of claiming success', async () => {+ stubFetch();+ const mod = await load(fakePushPlugin({ fail: 'no valid aps-environment entitlement' }));+ const result = await mod.enablePush();+ expect(result).toMatchObject({ ok: false, reason: 'error' });+ expect(result.state.subscribed).toBe(false);+ expect(deviceCalls()).toHaveLength(0);+ });++ it('deregisters exactly this device when push is turned off', async () => {+ stubFetch();+ const plugin = fakePushPlugin();+ const mod = await load(plugin);+ await mod.enablePush();+ fetchCalls.length = 0;++ expect(await mod.disablePush()).toEqual({ ok: true });+ const [del] = deviceCalls();+ expect(del.init.method).toBe('DELETE');+ expect(JSON.parse(del.init.body)).toEqual({ token: TOKEN.toLowerCase() });+ expect(plugin.calls).toContain('unregister');+ expect((await mod.getPushState()).subscribed).toBe(false);+ });+});++describe('refreshNativePushRegistration', () => {+ it('does nothing for a device that never opted in', async () => {+ stubFetch();+ const plugin = fakePushPlugin();+ const mod = await load(plugin);+ await mod.refreshNativePushRegistration();+ expect(plugin.calls).not.toContain('register');+ expect(deviceCalls()).toHaveLength(0);+ });++ it('re-sends the token as a refresh, proving the device was already this account', async () => {+ localStorage.setItem('threews:apns-token', TOKEN.toLowerCase());+ stubFetch();+ const mod = await load(fakePushPlugin());+ // The module refreshes once on load; wait for that pass.+ await vi.waitFor(() => expect(deviceCalls()).toHaveLength(1));+ expect(JSON.parse(deviceCalls()[0].init.body)).toEqual({+ token: TOKEN.toLowerCase(),+ platform: 'ios',+ previous: TOKEN.toLowerCase(),+ });+ // Once per app session.+ await mod.refreshNativePushRegistration();+ expect(deviceCalls()).toHaveLength(1);+ });++ it('forgets the device when a different account is signed in now', async () => {+ localStorage.setItem('threews:apns-token', TOKEN.toLowerCase());+ stubFetch({ deviceStatus: 409 });+ await load(fakePushPlugin());+ await vi.waitFor(() => expect(deviceCalls()).toHaveLength(1));+ await vi.waitFor(() => expect(localStorage.getItem('threews:apns-token')).toBeNull());+ });+});diff --git a/tests/share-target.test.js b/tests/share-target.test.jsindex ef72d8fcf..f9a10133d 100644--- a/tests/share-target.test.js+++ b/tests/share-target.test.js@@ -275,3 +275,54 @@ describe('sharedIntent', () => {expect(sharedIntent()).toBeNull();});});++// ── The iOS app: shares arrive from the share extension, not a service worker ──+describe('takeSharedFiles in the iOS app', () => {+ const ID = '6f1c2b3a-4d5e-4f60-8a7b-9c0d1e2f3a4b';++ afterEach(() => {+ delete globalThis.Capacitor;+ history.replaceState(null, '', '/');+ });++ function app(takeShare) {+ globalThis.Capacitor = { Plugins: { ThreeWsApp: { takeShare } } };+ }++ it('reads the share the extension parked, as real File objects', async () => {+ history.replaceState(null, '', `/create/selfie?shared=1&inbox=${ID}`);+ const calls = [];+ app(async (args) => {+ calls.push(args);+ return {+ kind: 'photo',+ createdAt: 1767225600000,+ files: [{ name: 'shared-photo-1.jpg', type: 'image/jpeg', data: btoa('jpeg-bytes') }],+ };+ });++ const { files, meta } = await takeSharedFiles();++ expect(calls).toEqual([{ id: ID }]);+ expect(files).toHaveLength(1);+ expect(files[0].name).toBe('shared-photo-1.jpg');+ expect(files[0].type).toBe('image/jpeg');+ expect(await files[0].text()).toBe('jpeg-bytes');+ expect(meta).toMatchObject({ count: 1, received: 1767225600000 });+ });++ it('returns nothing for a share that expired or was already opened', async () => {+ history.replaceState(null, '', `/create?shared=glb&inbox=${ID}`);+ app(async () => {+ throw new Error('not_found');+ });+ expect(await takeSharedFiles()).toEqual({ files: [], meta: null });+ });++ it('strips the inbox id so a reload is not a second share', () => {+ history.replaceState(null, '', `/create?shared=glb&inbox=${ID}&tab=upload`);+ clearSharedIntent();+ expect(location.search).toBe('?tab=upload');+ });+});+