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
feat(ios): send in-app payments to Safari through a one-time session handoff, and script the App Store release
nirholaseee6c2b332a0
diff --git a/api/_lib/migrations/20261009233000_session_handoffs.sql b/api/_lib/migrations/20261009233000_session_handoffs.sqlnew file mode 100644index 000000000..d0beb2d4a--- /dev/null+++ b/api/_lib/migrations/20261009233000_session_handoffs.sql@@ -0,0 +1,33 @@+-- Migration: single-use codes that carry a signed-in session from the iOS app+-- into Safari.+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261009233000_session_handoffs.sql+-- Idempotent.+--+-- The iOS app sends payments, token launches and trading out to Safari (App+-- Review guidelines 3.1.1 and 3.1.5, ios/docs/REVIEW-RISK.md). Safari has its own+-- cookie jar, so without a handoff the visitor would arrive signed out on a page+-- that exists to spend their money. The app's WebView, which holds the session+-- cookie, asks api/auth/handoff.js for a code; Safari opens+-- /api/auth/handoff?code=... and the code is exchanged for a fresh session+-- there, exactly once, within a minute.+--+-- code_hash sha256 of the code. The plaintext only ever exists in the URL+-- handed to Safari, so a read of this table cannot be replayed.+-- next_path the same-origin path the visitor lands on after the exchange,+-- validated when the code is minted.+-- consumed_at set by the exchange in the same statement that checks it, so+-- two concurrent opens of one URL cannot both get a session.+--+-- Rows are tiny and expire in sixty seconds; the exchange deletes anything more+-- than a day old as it goes, so the table never grows past a day of handoffs.++create table if not exists session_handoffs (+ code_hash text primary key,+ user_id uuid not null references users(id) on delete cascade,+ next_path text not null check (left(next_path, 1) = '/' and left(next_path, 2) <> '//'),+ created_at timestamptz not null default now(),+ expires_at timestamptz not null,+ consumed_at timestamptz+);++create index if not exists session_handoffs_created_at_idx on session_handoffs (created_at);diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 3107288d7..51968a879 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -639,6 +639,12 @@ export const limits = {// code; anything faster is answered `slow_down` by the handler first.cliLinkIp: (ip) =>getLimiter('cli:link:ip', { limit: 20, window: '10 m', critical: true, degradeToMemory: true }).limit(ip),+ // iOS app to Safari session handoff (api/auth/handoff.js). Minting is one+ // tap on a payment, launch or trade surface, so 30 per 10 min per user is+ // far above a real person and keeps a hijacked WebView from filling the+ // table with live codes.+ sessionHandoffUser: (userId) =>+ getLimiter('auth:handoff:user', { limit: 30, window: '10 m', critical: true, degradeToMemory: true }).limit(userId),cliPoll: (deviceHash) =>getLimiter('cli:poll', { limit: 240, window: '10 m', local: true }).limit(deviceHash),// Open inference network (api/nodes/*). Node registration is an idempotentdiff --git a/api/auth/handoff.js b/api/auth/handoff.jsnew file mode 100644index 000000000..47977fdba--- /dev/null+++ b/api/auth/handoff.js@@ -0,0 +1,136 @@+// /api/auth/handoff: carry a signed-in session from the iOS app into Safari.+//+// POST { next } (app WebView, session cookie) -> { url, expires_at }+// GET ?code=&next= (Safari) -> 302 to next with a fresh session cookie+// GET ?next= (Safari) -> 302 to next, signed out (no session to carry)+//+// Why this exists: the iOS app sends payments, token launches and trading out+// to Safari (App Review guidelines 3.1.1 and 3.1.5; ios/docs/REVIEW-RISK.md).+// Safari keeps its own cookie jar, so the __Host-sid cookie the app's WebView+// holds never reaches it, and without a handoff the visitor would land signed+// out on the one page that exists to spend their money. The WebView mints a+// code here, same-origin, and the app opens the returned URL in Safari, which+// exchanges it for a session of its own.+//+// The code is the credential, so it is treated like one: 32 random bytes,+// stored only as a sha256, valid for sixty seconds, and consumed by the same+// statement that checks it, so a URL that leaks (history, a screenshot, a+// shoulder) is dead by the time anyone could reuse it. Minting requires the+// request to come from three.ws itself, the same posture as extension-token.js.+// The landing path is validated as same-origin at both ends, so the endpoint+// can never be turned into an open redirect.+//+// Every app-to-Safari hop goes through this path, signed in or not, because+// /api/* is the one part of three.ws the apple-app-site-association file+// (api/wk.js) keeps out of universal links. Opening https://three.ws/launch+// directly from the app would be claimed by the app again and never reach+// Safari; /api/auth/handoff?next=/launch always does.++import { createSession, destroySession, getSessionUser, isSameSiteOrigin, sessionCookie } from '../_lib/auth.js';+import { logAudit } from '../_lib/audit.js';+import { randomToken, sha256 } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';+import { env } from '../_lib/env.js';+import { cors, error, json, method, rateLimited, readJson, redirect, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';++export const HANDOFF_TTL_SEC = 60;+const MAX_NEXT_LENGTH = 2048;++/**+ * A same-origin path, or null. Rejects protocol-relative (`//host`) and+ * backslash (`/\host`, which browsers normalise to `//host`) forms, control+ * characters, and anything that is not a path at all.+ */+export function safeHandoffPath(next) {+ if (typeof next !== 'string' || next.length === 0 || next.length > MAX_NEXT_LENGTH) return null;+ if (!next.startsWith('/') || next.startsWith('//') || next.includes('\\')) return null;+ // eslint-disable-next-line no-control-regex+ if (/[\u0000-\u001f\u007f]/.test(next)) return null;+ try {+ const url = new URL(next, 'https://three.ws');+ if (url.origin !== 'https://three.ws') return null;+ return `${url.pathname}${url.search}${url.hash}`;+ } catch {+ return null;+ }+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;+ if (req.method === 'POST') return mint(req, res);+ return exchange(req, res);+});++async function mint(req, res) {+ // Only three.ws itself may mint. A foreign page cannot read the response+ // anyway (CORS), but refusing it outright keeps the surface to one origin.+ if (!isSameSiteOrigin(req)) return error(res, 403, 'forbidden', 'handoff codes are minted from three.ws only');++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in first');++ const rl = await limits.sessionHandoffUser(session.id);+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req, 8_192);+ const next = safeHandoffPath(body?.next);+ if (!next) return error(res, 400, 'invalid_next', 'next must be a path on three.ws');++ const code = randomToken(32);+ const expiresAt = new Date(Date.now() + HANDOFF_TTL_SEC * 1000);+ await sql`+ insert into session_handoffs (code_hash, user_id, next_path, expires_at)+ values (${await sha256(code)}, ${session.id}, ${next}, ${expiresAt.toISOString()})+ `;++ const url = new URL('/api/auth/handoff', env.APP_ORIGIN);+ url.searchParams.set('code', code);+ // Carried in the clear only so an expired code can still send the visitor+ // to sign in with their destination intact; the code's own row is what+ // decides where a successful exchange lands.+ url.searchParams.set('next', next);+ res.setHeader('cache-control', 'no-store');+ return json(res, 200, { url: url.href, expires_at: expiresAt.toISOString() });+}++async function exchange(req, res) {+ const url = new URL(req.url, env.APP_ORIGIN);+ const code = url.searchParams.get('code') || '';+ const fallbackNext = safeHandoffPath(url.searchParams.get('next')) || '/';+ const toLogin = (reason) => redirect(res, `${env.APP_ORIGIN}/login?error=${reason}&next=${encodeURIComponent(fallbackNext)}`);+ // The landing page must not see this URL as its referrer, consumed or not.+ res.setHeader('referrer-policy', 'no-referrer');++ // No code: a signed-out visitor leaving the app. Nothing to exchange, just+ // land them on the page they asked for.+ if (!url.searchParams.has('code')) return redirect(res, `${env.APP_ORIGIN}${fallbackNext}`);++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return toLogin('rate_limited');+ if (!/^[A-Za-z0-9_-]{32,128}$/.test(code)) return toLogin('handoff_expired');++ const [row] = await sql`+ update session_handoffs h+ set consumed_at = now()+ from users u+ where h.code_hash = ${await sha256(code)}+ and h.consumed_at is null+ and h.expires_at > now()+ and u.id = h.user_id+ and u.deleted_at is null+ returning h.user_id, h.next_path+ `;+ // Housekeeping rides along with real traffic instead of needing a cron.+ sql`delete from session_handoffs where created_at < now() - interval '1 day'`.catch(() => {});+ if (!row) return toLogin('handoff_expired');++ // Whoever this browser was signed in as before, it is now the app's user:+ // the visitor asked the app to continue here as themselves.+ await destroySession(req);+ const token = await createSession({ userId: row.user_id, userAgent: req.headers['user-agent'], ip: clientIp(req) });+ res.setHeader('set-cookie', sessionCookie(token));+ logAudit({ userId: row.user_id, action: 'login', req, meta: { method: 'ios_handoff' } });+ return redirect(res, `${env.APP_ORIGIN}${safeHandoffPath(row.next_path) || '/'}`);+}diff --git a/ios/docs/SUBMISSION.md b/ios/docs/SUBMISSION.mdindex 3fb15cec5..54896311a 100644--- a/ios/docs/SUBMISSION.md+++ b/ios/docs/SUBMISSION.md@@ -106,47 +106,98 @@ cd ios && npm install && npm run sync## 5. On a Mac: archive, sign, upload+### Once per Mac: signing+```bash-cd ios && npm run open # opens native/App/App.xcodeproj+cd ios && npm install && npm run open # opens native/App/App.xcodeproj```-In Xcode:+Capacitor 8 resolves its plugins through Swift Package Manager, so there is no+`.xcworkspace` and no CocoaPods step: `App.xcodeproj` is the whole project.1. Select the **App** target, Signing & Capabilities, choose the team. ConfirmAssociated Domains lists `applinks:three.ws` and Push Notifications ispresent; both come from `App/App.entitlements`. App Groups should list`group.ws.three.app` and Keychain Sharing `ws.three.shared`, which are whatthe Agent glance widget reads.-1b. Select the **GlanceWidgetExtension** target and choose the same team. It+2. Select the **GlanceWidgetExtension** target and choose the same team. Itneeds the same App Group and Keychain Sharing entries; both expand from`DEVELOPMENT_TEAM`, so nothing else has to be typed. A build with no team onthis target fails to sign the .appex and the archive is rejected.-1c. Select the **ShareExtension** target and choose the same team. It needs+3. Select the **ShareExtension** target and choose the same team. It needsonly the App Group, which is where it parks shared photos and models for theapp. Without the group the extension still appears in the share sheet butthe app never finds what was shared.-2. Set the marketing version and build number. `MARKETING_VERSION` is `1.0`- and `CURRENT_PROJECT_VERSION` is `1` in the project file; the build number- must increase on every upload.-3. Replace the placeholder app icon in `App/Assets.xcassets` per- [`ASSETS.md`](ASSETS.md). Xcode rejects an archive with a missing icon.-4. Product > Archive, then Distribute App > App Store Connect > Upload.+4. Check the app icon per [`ASSETS.md`](ASSETS.md); `npm run check:ios-icons`+ at the repo root confirms the catalog is complete. Xcode rejects an archive+ with a missing icon.-Capacitor 8 resolves its plugins through Swift Package Manager, so there is no-`.xcworkspace` and no CocoaPods step: `App.xcodeproj` is the whole project.+Skip all four on a build Mac with no Xcode account by using an App Store+Connect API key instead (below): automatic signing then creates and fetches+the profiles itself.++### Every upload: one command-Headless alternative once signing is configured, for a Mac build machine or-Xcode Cloud:+From the repo root:```bash-xcodebuild -project native/App/App.xcodeproj -scheme App \- -configuration Release -archivePath build/App.xcarchive archive-xcodebuild -exportArchive -archivePath build/App.xcarchive \- -exportOptionsPlist ExportOptions.plist -exportPath build/export+APPLE_TEAM_ID=<team id> npm run ios:release```-`ExportOptions.plist` does not exist yet; it needs the real team ID and-provisioning profile name, so it is written at the same time as step 1.+That is [`../scripts/release.mjs`](../scripts/release.mjs), and it runs, in+order:++1. `scripts/check-ios-app.mjs`, the structural check (targets, plugins, privacy+ manifests, entitlements, build settings). A red one is a build Apple would+ reject or a feature that is silently dead on device.+2. `npm ci` and `npx cap sync ios` in `ios/`, which write the gitignored+ `capacitor.config.json`, `config.xml` and shell bundle the archive copies.+ An archive made without them launches to a blank screen.+3. `xcodebuild archive`, Release, automatic signing for `APPLE_TEAM_ID`.+4. `xcodebuild -exportArchive` with an `ExportOptions.plist` it writes itself+ (method `app-store-connect`, destination `upload`), which sends the build+ straight to App Store Connect. No Transporter step.++The build number is the UTC time of the run, `YYMMDD.HMM` (for example+`261009.1907`), so it rises on every upload without anyone tracking the last+one. All three targets read it from the same build setting, which App Store+Connect requires of an app and its extensions.++| Flag | Effect |+|---|---|+| `--dry-run` | Validates everything, writes `ExportOptions.plist`, prints every command. Runs on Linux too: `APPLE_TEAM_ID=<team id> npm run ios:release:dry` |+| `--marketing-version 1.1` | Sets `CFBundleShortVersionString` for this build. Bump it for each App Store release; TestFlight builds can share one. |+| `--build-number N` | Overrides the timestamp build number. |+| `--export-only` | Writes the `.ipa` to `ios/native/App/build/export` instead of uploading. |+| `--skip-sync` | Skips `npm ci` and `cap sync`, for a rerun right after a sync. |+| `--carplay` | Signs with `App/App-CarPlay.entitlements`. Only after Apple grants the entitlement; see [`CARPLAY.md`](CARPLAY.md). |++For a build Mac with no Xcode account, create an App Store Connect API key+(Users and Access, Integrations, App Store Connect API, role **App Manager**),+download its `.p8` once, and set all three alongside the team id. They can live+in the repo-root `.env.local`, which the script reads and git ignores:++```bash+APPLE_TEAM_ID=<team id>+ASC_KEY_ID=<key id>+ASC_ISSUER_ID=<issuer id>+ASC_KEY_PATH=/path/to/AuthKey_<key id>.p8+```++Setting only some of the three fails before anything builds.++### Or: Xcode Cloud++The project is ready for it as checked in: the **App** scheme is shared+(`App.xcodeproj/xcshareddata`), so Xcode Cloud can see it, and+[`../native/App/ci_scripts/ci_post_clone.sh`](../native/App/ci_scripts/ci_post_clone.sh)+installs Node, runs the structural check and `cap sync` before the build.++In Xcode, Integrate, Create Workflow: product **App**, start condition on+`main` (or a `release/*` branch), action **Archive** for iOS, post-action+**TestFlight Internal Testing**. Xcode Cloud numbers builds itself. To sign a+cloud build with CarPlay once the grant exists, add the environment variable+`THREEWS_CARPLAY=1` to the workflow.## 6. TestFlight, then review@@ -170,4 +221,6 @@ provisioning profile name, so it is written at the same time as step 1.- [ ] An off-site link opens the Safari sheet and returns to the app- [ ] Account deletion is reachable in-app (guideline 5.1.1)- [ ] No white flash between launch screen and first paint-- [ ] Value-moving surfaces open in Safari, per `REVIEW-RISK.md`+- [ ] Value-moving surfaces open in Safari, signed in, per `REVIEW-RISK.md`: tap Launch on `/create` or Buy credits on `/credits`, choose Open in Safari, and Safari lands on the same page under the same account+- [ ] Privacy answers in App Store Connect match `App/PrivacyInfo.xcprivacy` (see `../publish/listing.md`)+- [ ] `/api/auth/handoff` is live: `curl -sI 'https://three.ws/api/auth/handoff?next=%2Flaunch'` answers `302` with `location: https://three.ws/launch`diff --git a/ios/native/App/App.xcodeproj/project.pbxproj b/ios/native/App/App.xcodeproj/project.pbxprojindex a187facae..fd87cd219 100644--- a/ios/native/App/App.xcodeproj/project.pbxproj+++ b/ios/native/App/App.xcodeproj/project.pbxproj@@ -42,6 +42,8 @@C4A11E0330C1001400000000 /* SharedInbox.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A11E0330C1000300000000 /* SharedInbox.swift */; };C4A11E0330C1001500000000 /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A11E0330C1000400000000 /* ShareViewController.swift */; };C4A11E0330C1001600000000 /* ShareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = C4A11E0330C1000700000000 /* ShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };+ C4A11E0440D1000200000000 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = C4A11E0440D1000100000000 /* PrivacyInfo.xcprivacy */; };+ C4A11E0440D1000400000000 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = C4A11E0440D1000300000000 /* PrivacyInfo.xcprivacy */; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */@@ -112,6 +114,10 @@C4A11E0330C1000500000000 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };C4A11E0330C1000600000000 /* ShareExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = ShareExtension.entitlements; sourceTree = "<group>"; };C4A11E0330C1000700000000 /* ShareExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = ShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };+ C4A11E0440D1000100000000 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };+ C4A11E0440D1000300000000 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };+ C4A11E0440D1000600000000 /* App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = App.entitlements; sourceTree = "<group>"; };+ C4A11E0440D1000700000000 /* App-CarPlay.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "App-CarPlay.entitlements"; sourceTree = "<group>"; };/* End PBXFileReference section *//* Begin PBXFrameworksBuildPhase section */@@ -176,6 +182,9 @@504EC30E1FED79650016851F /* Assets.xcassets */,504EC3101FED79650016851F /* LaunchScreen.storyboard */,504EC3131FED79650016851F /* Info.plist */,+ C4A11E0440D1000100000000 /* PrivacyInfo.xcprivacy */,+ C4A11E0440D1000600000000 /* App.entitlements */,+ C4A11E0440D1000700000000 /* App-CarPlay.entitlements */,2FAD9762203C412B000D30F8 /* config.xml */,50B271D01FEDC1A000F3C39B /* public */,);@@ -226,6 +235,7 @@C4A11E0330C1000400000000 /* ShareViewController.swift */,C4A11E0330C1000300000000 /* SharedInbox.swift */,C4A11E0330C1000500000000 /* Info.plist */,+ C4A11E0440D1000300000000 /* PrivacyInfo.xcprivacy */,C4A11E0330C1000600000000 /* ShareExtension.entitlements */,);path = ShareExtension;@@ -279,6 +289,7 @@buildPhases = (C4A11E0330C1006100000000 /* Sources */,C4A11E0330C1006200000000 /* Frameworks */,+ C4A11E0440D1000500000000 /* Resources */,);buildRules = ();@@ -347,6 +358,15 @@50379B232058CBB4000EE86E /* capacitor.config.json in Resources */,504EC30D1FED79650016851F /* Main.storyboard in Resources */,2FAD9763203C412B000D30F8 /* config.xml in Resources */,+ C4A11E0440D1000200000000 /* PrivacyInfo.xcprivacy in Resources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ C4A11E0440D1000500000000 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ C4A11E0440D1000400000000 /* PrivacyInfo.xcprivacy in Resources */,);runOnlyForDeploymentPostprocessing = 0;};@@ -550,7 +570,7 @@buildSettings = {ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;CODE_SIGN_STYLE = Automatic;- CODE_SIGN_ENTITLEMENTS = App/App.entitlements;+ CODE_SIGN_ENTITLEMENTS = "$(THREEWS_APP_ENTITLEMENTS)";CURRENT_PROJECT_VERSION = 1;GLANCE_APP_GROUP = group.ws.three.app;GLANCE_KEYCHAIN_GROUP = "$(DEVELOPMENT_TEAM).ws.three.shared";@@ -565,6 +585,7 @@OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";PRODUCT_BUNDLE_IDENTIFIER = ws.three.app;PRODUCT_NAME = "$(TARGET_NAME)";+ THREEWS_APP_ENTITLEMENTS = App/App.entitlements;SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";@@ -576,7 +597,7 @@buildSettings = {ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;CODE_SIGN_STYLE = Automatic;- CODE_SIGN_ENTITLEMENTS = App/App.entitlements;+ CODE_SIGN_ENTITLEMENTS = "$(THREEWS_APP_ENTITLEMENTS)";CURRENT_PROJECT_VERSION = 1;GLANCE_APP_GROUP = group.ws.three.app;GLANCE_KEYCHAIN_GROUP = "$(DEVELOPMENT_TEAM).ws.three.shared";@@ -590,6 +611,7 @@MARKETING_VERSION = 1.0;PRODUCT_BUNDLE_IDENTIFIER = ws.three.app;PRODUCT_NAME = "$(TARGET_NAME)";+ THREEWS_APP_ENTITLEMENTS = App/App.entitlements;SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";diff --git a/ios/native/App/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme b/ios/native/App/App.xcodeproj/xcshareddata/xcschemes/App.xcschemenew file mode 100644index 000000000..b53010b0a--- /dev/null+++ b/ios/native/App/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme@@ -0,0 +1,77 @@+<?xml version="1.0" encoding="UTF-8"?>+<Scheme+ LastUpgradeVersion = "1600"+ version = "1.7">+ <BuildAction+ parallelizeBuildables = "YES"+ buildImplicitDependencies = "YES">+ <BuildActionEntries>+ <BuildActionEntry+ buildForTesting = "YES"+ buildForRunning = "YES"+ buildForProfiling = "YES"+ buildForArchiving = "YES"+ buildForAnalyzing = "YES">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "504EC3031FED79650016851F"+ BuildableName = "App.app"+ BlueprintName = "App"+ ReferencedContainer = "container:App.xcodeproj">+ </BuildableReference>+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ shouldUseLaunchSchemeArgsEnv = "YES"+ shouldAutocreateTestPlan = "YES">+ </TestAction>+ <LaunchAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ launchStyle = "0"+ useCustomWorkingDirectory = "NO"+ ignoresPersistentStateOnLaunch = "NO"+ debugDocumentVersioning = "YES"+ debugServiceExtension = "internal"+ allowLocationSimulation = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "504EC3031FED79650016851F"+ BuildableName = "App.app"+ BlueprintName = "App"+ ReferencedContainer = "container:App.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </LaunchAction>+ <ProfileAction+ buildConfiguration = "Release"+ shouldUseLaunchSchemeArgsEnv = "YES"+ savedToolIdentifier = ""+ useCustomWorkingDirectory = "NO"+ debugDocumentVersioning = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "504EC3031FED79650016851F"+ BuildableName = "App.app"+ BlueprintName = "App"+ ReferencedContainer = "container:App.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction+ buildConfiguration = "Debug">+ </AnalyzeAction>+ <ArchiveAction+ buildConfiguration = "Release"+ revealArchiveInOrganizer = "YES">+ </ArchiveAction>+</Scheme>diff --git a/ios/native/App/App/App-CarPlay.entitlements b/ios/native/App/App/App-CarPlay.entitlementsnew file mode 100644index 000000000..e2fbc8300--- /dev/null+++ b/ios/native/App/App/App-CarPlay.entitlements@@ -0,0 +1,60 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <!--+ App.entitlements plus the CarPlay grant. Selected through the+ THREEWS_APP_ENTITLEMENTS build setting once Apple has granted CarPlay;+ every other key must match App.entitlements exactly, which+ scripts/check-ios-app.mjs enforces.+ -->++ <!--+ Universal links. Every https://three.ws link the app can handle opens in+ the app instead of Safari, which is what makes a shared /viewer, /irl/s/+ or /avatars/ link land on an installed app. Paired with+ public/.well-known/apple-app-site-association, which Apple's CDN fetches+ over TLS with no redirects; if that file 404s or is served with the wrong+ content type, links silently keep opening in Safari and nothing errors.+ -->+ <key>com.apple.developer.associated-domains</key>+ <array>+ <string>applinks:three.ws</string>+ <string>applinks:www.three.ws</string>+ <!-- Password AutoFill for the three.ws login form inside the WebView. -->+ <string>webcredentials:three.ws</string>+ </array>++ <!--+ APNs. Xcode rewrites this to "production" on an App Store / TestFlight+ archive; "development" is what a device build off a personal team needs.+ -->+ <key>aps-environment</key>+ <string>development</string>++ <!--+ CarPlay, voice-based conversational category (iOS 26.4 and later). This+ is what puts three.ws Drive on the car screen. Apple grants it per app+ on request (https://developer.apple.com/carplay/). Sign with this file+ only once the grant is on the App ID and in the provisioning profile:+ the carplay flag of ios/scripts/release.mjs. See ios/docs/CARPLAY.md.+ -->+ <key>com.apple.developer.carplay-voice-based-conversation</key>+ <true/>+ <!--+ The Agent glance home screen widget. The App Group holds the last card+ the widget downloaded, so it keeps painting when the phone is offline,+ and the keychain group holds the widget token this app claims from+ threews://glance/link. Both are read-only reads of one endpoint; see+ docs/native-widgets.md.+ -->+ <key>com.apple.security.application-groups</key>+ <array>+ <string>$(GLANCE_APP_GROUP)</string>+ </array>+ <key>keychain-access-groups</key>+ <array>+ <string>$(GLANCE_KEYCHAIN_GROUP)</string>+ </array>+</dict>+</plist>diff --git a/ios/native/App/App/App.entitlements b/ios/native/App/App/App.entitlementsindex 8d3a90a76..186a47aa6 100644--- a/ios/native/App/App/App.entitlements+++ b/ios/native/App/App/App.entitlements@@ -2,6 +2,16 @@<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>+ <!--+ The entitlements every build signs with. CarPlay is NOT here: Apple grants+ it per app, and codesign refuses to sign an archive whose entitlements+ name a capability its provisioning profile lacks, so carrying the key+ before the grant breaks every TestFlight upload. App-CarPlay.entitlements+ is this file plus the CarPlay key; the THREEWS_APP_ENTITLEMENTS build+ setting picks between them (the carplay flag of ios/scripts/release.mjs), and+ scripts/check-ios-app.mjs keeps the two files identical apart from it.+ -->+<!--Universal links. Every https://three.ws link the app can handle opens inthe app instead of Safari, which is what makes a shared /viewer, /irl/s/@@ -25,16 +35,6 @@<key>aps-environment</key><string>development</string>- <!--- CarPlay, voice-based conversational category (iOS 26.4 and later). This- is what puts three.ws Drive on the car screen. Apple grants it per app- on request (https://developer.apple.com/carplay/), and a build signed- without the grant simply never sees a CarPlay scene: the phone app is- unaffected either way, so this key is safe to carry before approval- lands. See ios/docs/CARPLAY.md for the request and the review notes.- -->- <key>com.apple.developer.carplay-voice-based-conversation</key>- <true/><!--The Agent glance home screen widget. The App Group holds the last cardthe widget downloaded, so it keeps painting when the phone is offline,diff --git a/ios/native/App/App/PrivacyInfo.xcprivacy b/ios/native/App/App/PrivacyInfo.xcprivacynew file mode 100644index 000000000..267d55697--- /dev/null+++ b/ios/native/App/App/PrivacyInfo.xcprivacy@@ -0,0 +1,174 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<!--+ The app's privacy manifest. App Store Connect reads it at upload time and+ refuses a build whose binary calls a "required reason" API that no manifest+ in the bundle explains (ITMS-91053). Capacitor core and Cordova ship their+ own manifests; the twelve Capacitor plugins do not, and Swift Package Manager+ links them straight into this binary, so their reasons are declared here.++ Required reason APIs, and who calls them:+ UserDefaults @capacitor/preferences stores the app's own key/value data.+ CA92.1: read and written only by this app.+ FileTimestamp SharedInbox.swift sweeps day-old shares by creation date in+ the App Group container; @capacitor/filesystem stat() returns+ ctime/mtime for files in the app container.+ C617.1: timestamps of files inside the app or group container.++ Collected data mirrors the App Privacy answers in ios/publish/listing.md.+ Change one, change both: Apple compares them, and a reviewer reads the+ listing. three.ws does not track in Apple's sense (no third-party ad data,+ no data brokers), so NSPrivacyTracking is false and there are no tracking+ domains. PostHog is first-party product analytics, declared as such below.+ scripts/check-ios-app.mjs verifies the API reasons stay declared.+-->+<plist version="1.0">+<dict>+ <key>NSPrivacyTracking</key>+ <false/>+ <key>NSPrivacyTrackingDomains</key>+ <array/>+ <key>NSPrivacyAccessedAPITypes</key>+ <array>+ <dict>+ <key>NSPrivacyAccessedAPIType</key>+ <string>NSPrivacyAccessedAPICategoryUserDefaults</string>+ <key>NSPrivacyAccessedAPITypeReasons</key>+ <array>+ <string>CA92.1</string>+ </array>+ </dict>+ <dict>+ <key>NSPrivacyAccessedAPIType</key>+ <string>NSPrivacyAccessedAPICategoryFileTimestamp</string>+ <key>NSPrivacyAccessedAPITypeReasons</key>+ <array>+ <string>C617.1</string>+ </array>+ </dict>+ </array>+ <key>NSPrivacyCollectedDataTypes</key>+ <array>+ <!-- Account sign-in (email code or password). -->+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypeEmailAddress</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ </array>+ </dict>+ <!-- The account id every request carries, and analytics identity. -->+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypeUserID</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ <string>NSPrivacyCollectedDataTypePurposeAnalytics</string>+ </array>+ </dict>+ <!-- A selfie or reference photo turned into an avatar. -->+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypePhotosorVideos</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ </array>+ </dict>+ <!-- Talk mode: speech is transcribed so the agent can answer. -->+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypeAudioData</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ </array>+ </dict>+ <!-- Prompts, generated models, agent personas, chat. -->+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypeOtherUserContent</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ </array>+ </dict>+ <!-- IRL drops are pinned at the exact coordinates the owner chose. -->+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypePreciseLocation</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ </array>+ </dict>+ <!-- Skill purchases and their receipts, shown back to the buyer. -->+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypePurchaseHistory</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ </array>+ </dict>+ <!-- PostHog pageviews, clicks and session replays. -->+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypeProductInteraction</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAnalytics</string>+ <string>NSPrivacyCollectedDataTypePurposeProductPersonalization</string>+ </array>+ </dict>+ <!-- Handled errors reported with context (src/analytics.js trackError). -->+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypeOtherDiagnosticData</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ <string>NSPrivacyCollectedDataTypePurposeAnalytics</string>+ </array>+ </dict>+ </array>+</dict>+</plist>diff --git a/ios/native/App/App/ThreeWsAppPlugin.swift b/ios/native/App/App/ThreeWsAppPlugin.swiftindex 92887221d..9d1e27e27 100644--- a/ios/native/App/App/ThreeWsAppPlugin.swift+++ b/ios/native/App/App/ThreeWsAppPlugin.swift@@ -1,8 +1,9 @@import Foundationimport Capacitor+import UIKitimport UserNotifications-/// The app's own Capacitor plugin, for the two things no packaged plugin does.+/// The app's own Capacitor plugin, for the things no packaged plugin does.////// - `takeShare({ id })` hands the page the files the share extension parked in/// the App Group (see SharedInbox.swift). src/shared/share-target.js calls it@@ -10,6 +11,13 @@ import UserNotifications/// - `setBadge({ count })` keeps the home screen icon's badge equal to the/// inbox's unread count. APNs sets it when a push arrives; this is what/// brings it back down when the notifications are read in the app.+/// - `openInSafari({ url })` hands a page to the real Safari app. Payments,+/// token launches and trading leave the app this way (ios/docs/REVIEW-RISK.md),+/// and it has to be Safari itself: @capacitor/browser opens an in-app+/// SFSafariViewController, which App Review treats as still inside the app.+/// Only https://three.ws/api/auth/handoff is accepted. That endpoint carries+/// the session across (api/auth/handoff.js), and /api/* is excluded from+/// universal links, so iOS cannot route the URL straight back into this app.////// Registered in MainViewController.capacitorDidLoad, and reached from the web/// as `Capacitor.Plugins.ThreeWsApp`.@@ -20,8 +28,12 @@ public class ThreeWsAppPlugin: CAPPlugin, CAPBridgedPlugin {public let pluginMethods: [CAPPluginMethod] = [CAPPluginMethod(name: "takeShare", returnType: CAPPluginReturnPromise),CAPPluginMethod(name: "setBadge", returnType: CAPPluginReturnPromise),+ CAPPluginMethod(name: "openInSafari", returnType: CAPPluginReturnPromise),]+ static let handoffHosts: Set<String> = ["three.ws", "www.three.ws"]+ static let handoffPath = "/api/auth/handoff"+@objc func takeShare(_ call: CAPPluginCall) {guard let id = call.getString("id"), SharedInbox.isValidId(id) else {call.reject("A share id is required", "invalid_id")@@ -55,4 +67,26 @@ public class ThreeWsAppPlugin: CAPPlugin, CAPBridgedPlugin {}}}++ @objc func openInSafari(_ call: CAPPluginCall) {+ guard let raw = call.getString("url"),+ let url = URL(string: raw),+ url.scheme == "https",+ let host = url.host?.lowercased(),+ Self.handoffHosts.contains(host),+ url.path == Self.handoffPath+ else {+ call.reject("Only three.ws handoff links open in Safari", "invalid_url")+ return+ }+ DispatchQueue.main.async {+ UIApplication.shared.open(url, options: [:]) { opened in+ if opened {+ call.resolve()+ } else {+ call.reject("Safari could not be opened", "open_failed")+ }+ }+ }+ }}diff --git a/ios/native/App/ShareExtension/PrivacyInfo.xcprivacy b/ios/native/App/ShareExtension/PrivacyInfo.xcprivacynew file mode 100644index 000000000..952a895f8--- /dev/null+++ b/ios/native/App/ShareExtension/PrivacyInfo.xcprivacy@@ -0,0 +1,31 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<!--+ The share extension's privacy manifest. An extension is its own binary and+ App Store Connect checks it on its own, so the app's manifest does not cover+ it. SharedInbox.swift, compiled into both, reads creation dates to sweep+ day-old shares out of the App Group container (C617.1). The extension sends+ nothing anywhere: it copies the shared files into the group and the app+ uploads them, so collected data is declared once, in the app's manifest.+-->+<plist version="1.0">+<dict>+ <key>NSPrivacyTracking</key>+ <false/>+ <key>NSPrivacyTrackingDomains</key>+ <array/>+ <key>NSPrivacyCollectedDataTypes</key>+ <array/>+ <key>NSPrivacyAccessedAPITypes</key>+ <array>+ <dict>+ <key>NSPrivacyAccessedAPIType</key>+ <string>NSPrivacyAccessedAPICategoryFileTimestamp</string>+ <key>NSPrivacyAccessedAPITypeReasons</key>+ <array>+ <string>C617.1</string>+ </array>+ </dict>+ </array>+</dict>+</plist>diff --git a/ios/native/App/ci_scripts/ci_post_clone.sh b/ios/native/App/ci_scripts/ci_post_clone.shnew file mode 100755index 000000000..1cdbd93a0--- /dev/null+++ b/ios/native/App/ci_scripts/ci_post_clone.sh@@ -0,0 +1,34 @@+#!/bin/sh+# Xcode Cloud runs this right after it clones the repo, before it resolves+# Swift packages or builds. Xcode Cloud finds it because ci_scripts/ sits next+# to App.xcodeproj.+#+# The clone alone cannot build: CapApp-SPM resolves every Capacitor plugin from+# ios/node_modules, and cap sync writes the gitignored capacitor.config.json,+# config.xml and shell bundle the app target copies. Xcode Cloud images ship+# Homebrew but not Node, so Node comes first.+#+# Xcode Cloud assigns its own rising build number to every archive, so this+# does not touch CURRENT_PROJECT_VERSION. CarPlay stays off unless the workflow+# sets the environment variable THREEWS_CARPLAY=1, which only makes sense once+# Apple has granted the entitlement. A target-level build setting outranks an+# environment variable, so the switch is made in this clone's project file.+set -eu++export HOMEBREW_NO_INSTALL_CLEANUP=1+export HOMEBREW_NO_AUTO_UPDATE=1+brew install node++cd "$CI_PRIMARY_REPOSITORY_PATH"+node scripts/check-ios-app.mjs++if [ "${THREEWS_CARPLAY:-0}" = "1" ]; then+ sed -i '' 's#THREEWS_APP_ENTITLEMENTS = App/App.entitlements;#THREEWS_APP_ENTITLEMENTS = App/App-CarPlay.entitlements;#' \+ ios/native/App/App.xcodeproj/project.pbxproj+ echo "CarPlay entitlement on for this build"+fi++cd ios+npm ci --no-audit --no-fund+npx cap sync ios+test -f native/App/App/capacitor.config.jsondiff --git a/ios/scripts/release.mjs b/ios/scripts/release.mjsnew file mode 100644index 000000000..1491be2cc--- /dev/null+++ b/ios/scripts/release.mjs@@ -0,0 +1,230 @@+#!/usr/bin/env node+/**+ * Archives the iOS app and uploads it to App Store Connect for TestFlight.+ *+ * node ios/scripts/release.mjs [--dry-run] [--carplay] [--export-only]+ * [--build-number N] [--marketing-version X.Y.Z]+ * [--skip-sync]+ *+ * One command from a clean checkout to a build processing in TestFlight. Every+ * upload is otherwise a dozen clicks in Xcode, and the two mistakes that cost a+ * day each, a build number App Store Connect has already seen and an archive+ * made before `cap sync` wrote capacitor.config.json, are both mechanical, so+ * the script owns them.+ *+ * Steps, in order:+ * 1. scripts/check-ios-app.mjs, the structural check. A red one here is a+ * build Apple would reject or a feature that is silently dead on device.+ * 2. npm ci + cap sync in ios/, which writes the gitignored+ * capacitor.config.json, config.xml and shell bundle the archive copies.+ * 3. xcodebuild archive, Release, signed by $APPLE_TEAM_ID with automatic+ * signing. The build number is a UTC timestamp (YYMMDD.HMM), so it rises+ * on every run without anyone tracking the last one.+ * 4. xcodebuild -exportArchive with destination=upload, which sends the+ * build straight to App Store Connect. --export-only writes the .ipa to+ * ios/native/App/build/export instead.+ *+ * Environment (read from the shell, then .env.local and .env at the repo root):+ * APPLE_TEAM_ID required. The 10-character team id from the Developer portal.+ * ASC_KEY_ID, ASC_ISSUER_ID, ASC_KEY_PATH+ * an App Store Connect API key (Users and Access, Integrations,+ * role App Manager). With all three, signing and upload run+ * with no Xcode account signed in, which is what a CI Mac needs.+ * Without them xcodebuild uses the account in Xcode > Settings.+ *+ * --carplay signs with App/App-CarPlay.entitlements. Use it only once Apple has+ * granted the CarPlay entitlement to ws.three.app: codesign refuses an archive+ * whose entitlements name a capability the provisioning profile lacks.+ *+ * --dry-run runs everywhere, Linux included: it validates the inputs, writes+ * ExportOptions.plist, and prints every command it would run.+ */++import { spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, writeFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const HERE = dirname(fileURLToPath(import.meta.url));+export const IOS = resolve(HERE, '..');+const REPO = resolve(IOS, '..');+const PROJECT_DIR = join(IOS, 'native/App');+const BUILD_DIR = join(PROJECT_DIR, 'build');++export const BASE_ENTITLEMENTS = 'App/App.entitlements';+export const CARPLAY_ENTITLEMENTS = 'App/App-CarPlay.entitlements';++/**+ * A CFBundleVersion that rises monotonically with wall-clock time: YYMMDD.HMM+ * in UTC. App Store Connect compares each dot-separated part as an integer, so+ * the minutes part is written without leading zeros (00:05 is "5", 12:00 is+ * "1200") and still orders correctly within a day.+ */+export function buildNumberFor(date = new Date()) {+ const pad = (n) => String(n).padStart(2, '0');+ const day = `${pad(date.getUTCFullYear() % 100)}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}`;+ return `${Number(day)}.${date.getUTCHours() * 100 + date.getUTCMinutes()}`;+}++/** CFBundleVersion and CFBundleShortVersionString: one to three integers. */+export const isBundleVersion = (v) => /^\d+(\.\d+){0,2}$/.test(String(v));++export function parseArgs(argv) {+ const opts = { dryRun: false, carplay: false, exportOnly: false, skipSync: false, buildNumber: null, marketingVersion: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ const value = () => {+ const v = argv[++i];+ if (v === undefined || v.startsWith('--')) throw new Error(`${arg} needs a value`);+ return v;+ };+ if (arg === '--dry-run') opts.dryRun = true;+ else if (arg === '--carplay') opts.carplay = true;+ else if (arg === '--export-only') opts.exportOnly = true;+ else if (arg === '--skip-sync') opts.skipSync = true;+ else if (arg === '--build-number') opts.buildNumber = value();+ else if (arg === '--marketing-version') opts.marketingVersion = value();+ else throw new Error(`unknown option ${arg}`);+ }+ if (opts.buildNumber !== null && !isBundleVersion(opts.buildNumber)) throw new Error(`--build-number ${opts.buildNumber} is not one to three dot-separated integers`);+ if (opts.marketingVersion !== null && !isBundleVersion(opts.marketingVersion)) throw new Error(`--marketing-version ${opts.marketingVersion} is not one to three dot-separated integers`);+ return opts;+}++const escapeXml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');++/** The ExportOptions.plist xcodebuild -exportArchive reads. */+export function exportOptionsPlist({ teamId, upload }) {+ const entries = [+ ['method', 'string', 'app-store-connect'],+ ['destination', 'string', upload ? 'upload' : 'export'],+ ['teamID', 'string', teamId],+ ['signingStyle', 'string', 'automatic'],+ ['uploadSymbols', 'bool', true],+ // The script sets the build number itself; letting Xcode rewrite it+ // would make the archive and the uploaded build disagree.+ ['manageAppVersionAndBuildNumber', 'bool', false],+ ];+ const body = entries+ .map(([key, type, v]) => `\t<key>${key}</key>\n\t${type === 'bool' ? `<${v}/>` : `<string>${escapeXml(v)}</string>`}`)+ .join('\n');+ return `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+${body}+</dict>+</plist>+`;+}++/** xcodebuild flags for an App Store Connect API key, or none without one. */+export function authArgs(env) {+ const { ASC_KEY_ID, ASC_ISSUER_ID, ASC_KEY_PATH } = env;+ const set = [ASC_KEY_ID, ASC_ISSUER_ID, ASC_KEY_PATH].filter(Boolean).length;+ if (set === 0) return [];+ if (set !== 3) throw new Error('ASC_KEY_ID, ASC_ISSUER_ID and ASC_KEY_PATH go together; set all three or none');+ return ['-authenticationKeyPath', resolve(ASC_KEY_PATH), '-authenticationKeyID', ASC_KEY_ID, '-authenticationKeyIssuerID', ASC_ISSUER_ID];+}++/** Every command the release runs, in order, as [cmd, args, cwd]. */+export function releasePlan(opts, env) {+ const teamId = env.APPLE_TEAM_ID;+ const buildNumber = opts.buildNumber ?? buildNumberFor(opts.now);+ const archivePath = join(BUILD_DIR, `App-${buildNumber}.xcarchive`);+ const exportPath = join(BUILD_DIR, 'export');+ const exportOptions = join(BUILD_DIR, 'ExportOptions.plist');+ const auth = authArgs(env);+ const settings = [+ `DEVELOPMENT_TEAM=${teamId}`,+ `CURRENT_PROJECT_VERSION=${buildNumber}`,+ ...(opts.marketingVersion ? [`MARKETING_VERSION=${opts.marketingVersion}`] : []),+ `THREEWS_APP_ENTITLEMENTS=${opts.carplay ? CARPLAY_ENTITLEMENTS : BASE_ENTITLEMENTS}`,+ ];+ const steps = [['node', ['scripts/check-ios-app.mjs'], REPO]];+ if (!opts.skipSync) steps.push(['npm', ['ci', '--no-audit', '--no-fund'], IOS], ['npx', ['cap', 'sync', 'ios'], IOS]);+ steps.push(+ [+ 'xcodebuild',+ ['archive', '-project', 'App.xcodeproj', '-scheme', 'App', '-configuration', 'Release', '-destination', 'generic/platform=iOS', '-archivePath', archivePath, '-allowProvisioningUpdates', ...auth, ...settings],+ PROJECT_DIR,+ ],+ ['xcodebuild', ['-exportArchive', '-archivePath', archivePath, '-exportOptionsPlist', exportOptions, '-exportPath', exportPath, '-allowProvisioningUpdates', ...auth], PROJECT_DIR],+ );+ return { buildNumber, archivePath, exportPath, exportOptions, steps, plist: exportOptionsPlist({ teamId, upload: !opts.exportOnly }) };+}++function loadRepoEnv() {+ for (const file of ['.env.local', '.env']) {+ const path = join(REPO, file);+ // loadEnvFile never overrides a variable the shell already set.+ if (existsSync(path)) process.loadEnvFile(path);+ }+}++function preflight(opts, env) {+ const problems = [];+ if (!/^[A-Z0-9]{10}$/.test(env.APPLE_TEAM_ID || '')) {+ problems.push('APPLE_TEAM_ID is not set to a 10-character team id (Developer portal, Membership details)');+ }+ authArgs(env);+ if (env.ASC_KEY_PATH && !existsSync(resolve(env.ASC_KEY_PATH))) problems.push(`ASC_KEY_PATH ${env.ASC_KEY_PATH} does not exist`);+ if (opts.carplay && !existsSync(join(PROJECT_DIR, CARPLAY_ENTITLEMENTS))) problems.push(`${CARPLAY_ENTITLEMENTS} is missing`);+ if (!opts.dryRun) {+ if (process.platform !== 'darwin') problems.push('archiving needs macOS with Xcode; use --dry-run to check the plan here');+ else if (spawnSync('xcodebuild', ['-version']).status !== 0) problems.push('xcodebuild is not available; install Xcode and run xcode-select -s');+ }+ return problems;+}++function run([cmd, args, cwd]) {+ console.log(`\n[ios-release] $ (cd ${cwd.replace(REPO, '.') || '.'} && ${cmd} ${args.join(' ')})`);+ const res = spawnSync(cmd, args, { cwd, stdio: 'inherit' });+ if (res.status !== 0) throw new Error(`${cmd} ${args[0]} exited with ${res.status ?? res.signal}`);+}++function main() {+ const opts = parseArgs(process.argv.slice(2));+ loadRepoEnv();+ const env = { ...process.env };+ const problems = preflight(opts, env);+ if (problems.length && !(opts.dryRun && problems.every((p) => p.startsWith('APPLE_TEAM_ID')))) {+ for (const p of problems) console.error(`[ios-release] ${p}`);+ process.exit(1);+ }+ if (opts.dryRun && !env.APPLE_TEAM_ID) {+ console.warn('[ios-release] APPLE_TEAM_ID is not set; the plan below uses TEAMID0000 in its place');+ env.APPLE_TEAM_ID = 'TEAMID0000';+ }+ const plan = releasePlan(opts, env);+ mkdirSync(BUILD_DIR, { recursive: true });+ writeFileSync(plan.exportOptions, plan.plist);+ console.log(`[ios-release] build ${plan.buildNumber}${opts.marketingVersion ? `, version ${opts.marketingVersion}` : ''}, ${opts.carplay ? 'with' : 'without'} CarPlay, ${opts.exportOnly ? 'export only' : 'upload to App Store Connect'}`);+ console.log(`[ios-release] wrote ${plan.exportOptions.replace(REPO + '/', '')}`);+ if (opts.dryRun) {+ for (const [cmd, args, cwd] of plan.steps) console.log(` (cd ${cwd.replace(REPO, '.') || '.'} && ${cmd} ${args.join(' ')})`);+ return;+ }+ for (const step of plan.steps) {+ // capacitor.config.json is gitignored and written by cap sync. An+ // archive without it boots to a blank WebView with no server URL.+ if (step[1][0] === 'archive' && !existsSync(join(PROJECT_DIR, 'App/capacitor.config.json'))) {+ throw new Error('App/capacitor.config.json is missing; run without --skip-sync so cap sync writes it');+ }+ run(step);+ }+ console.log(+ opts.exportOnly+ ? `\n[ios-release] exported to ${plan.exportPath}`+ : `\n[ios-release] build ${plan.buildNumber} uploaded. App Store Connect emails when processing finishes (usually 5 to 30 minutes); it then appears under TestFlight.`,+ );+}++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ try {+ main();+ } catch (err) {+ console.error(`[ios-release] ${err.message}`);+ process.exit(1);+ }+}diff --git a/ios/src/native-bridge.js b/ios/src/native-bridge.jsindex 967850313..f3dd6143f 100644--- a/ios/src/native-bridge.js+++ b/ios/src/native-bridge.js@@ -93,6 +93,100 @@ html.ios-app select,html.ios-app textarea {font-size: max(16px, 1em);}+/* The Safari handoff sheet (requireSafari below). */+.tw-handoff {+ position: fixed;+ inset: 0;+ z-index: 2147483000;+ display: flex;+ align-items: flex-end;+ justify-content: center;+ padding: 16px 16px max(16px, env(safe-area-inset-bottom, 0px));+ background: rgba(4, 4, 8, 0.72);+ -webkit-backdrop-filter: blur(10px);+ backdrop-filter: blur(10px);+ opacity: 0;+ transition: opacity 180ms ease;+}+.tw-handoff[data-open] {+ opacity: 1;+}+.tw-handoff__card {+ width: 100%;+ max-width: 420px;+ padding: 24px 20px 20px;+ border-radius: 20px;+ border: 1px solid rgba(255, 255, 255, 0.1);+ background: var(--surface-1, #12121a);+ color: var(--text, #f2f2f5);+ font: 400 15px/1.5 var(--font-sans, -apple-system, system-ui, sans-serif);+ box-shadow: 0 24px 64px rgba(0, 0, 0, 0.5);+ transform: translateY(24px);+ transition: transform 220ms cubic-bezier(0.2, 0.8, 0.2, 1);+ will-change: transform;+}+.tw-handoff[data-open] .tw-handoff__card {+ transform: none;+}+.tw-handoff__title {+ margin: 0 0 8px;+ font-size: 19px;+ font-weight: 650;+ line-height: 1.3;+}+.tw-handoff__body {+ margin: 0 0 20px;+ color: var(--text-muted, #a6a6b4);+}+.tw-handoff__actions {+ display: grid;+ gap: 10px;+}+.tw-handoff__btn {+ min-height: 48px;+ border-radius: 12px;+ border: 1px solid rgba(255, 255, 255, 0.14);+ background: transparent;+ color: inherit;+ font: inherit;+ font-weight: 600;+ cursor: pointer;+ transition: background-color 120ms ease, transform 120ms ease, opacity 120ms ease;+}+.tw-handoff__btn--primary {+ border-color: transparent;+ background: var(--accent, #7c5cff);+ color: #fff;+}+.tw-handoff__btn:hover {+ background-color: rgba(255, 255, 255, 0.06);+}+.tw-handoff__btn--primary:hover {+ background-color: var(--accent-hover, #6b4cf0);+}+.tw-handoff__btn:active {+ transform: scale(0.98);+}+.tw-handoff__btn:focus-visible {+ outline: 2px solid var(--focus-ring, #b8a6ff);+ outline-offset: 2px;+}+.tw-handoff__btn[aria-busy='true'] {+ opacity: 0.7;+ cursor: progress;+}+.tw-handoff__error {+ margin: -8px 0 16px;+ color: var(--danger, #ff7a8a);+ font-size: 14px;+}+@media (prefers-reduced-motion: reduce) {+ .tw-handoff,+ .tw-handoff__card,+ .tw-handoff__btn {+ transition: none;+ }+}`;/**@@ -211,6 +305,243 @@ function routeExternalLinks() {);}+// Pages whose whole purpose is moving money: paying, buying credits, launching+// or trading a coin, funding a vault. App Review does not allow those inside an+// iOS app outside In-App Purchase (guidelines 3.1.1 and 3.1.5), so in the app+// they open in Safari instead, signed in, through api/auth/handoff.js. Wallets,+// balances, profiles and everything else that only shows value stay in the app.+// ios/docs/REVIEW-RISK.md has the reasoning; purchase buttons on pages that are+// NOT in this list reach the same sheet through window.threeWsNative.+const HANDOFF_EXACT = new Set([+ '/autopilot',+ '/credits',+ '/launch-studio',+ '/launcher',+ '/launchpad',+ '/markets/robinhood/desk',+ '/pay',+ '/payments',+ '/three-launchpad',+ '/vault',+ '/vaults',+]);+// The launchpad and its sub-flows (/launch/paired, /launch/robinhood).+const HANDOFF_SUBTREES = ['/launch'];++/**+ * The same-origin path to hand to Safari for `href`, or null when the link+ * stays in the app.+ *+ * @param {string} href+ * @param {string} [base]+ * @returns {string|null}+ */+export function handoffPathFor(href, base = 'https://three.ws/') {+ let url;+ try {+ url = new URL(href, base);+ } catch {+ return null;+ }+ if (!INTERNAL_HOSTS.has(url.hostname)) return null;+ const path = url.pathname.replace(/\.html$/, '').replace(/\/+$/, '') || '/';+ const matches = HANDOFF_EXACT.has(path) || HANDOFF_SUBTREES.some((root) => path === root || path.startsWith(`${root}/`));+ return matches ? `${url.pathname}${url.search}${url.hash}` : null;+}++/**+ * Opens `path` in Safari with this session carried across.+ *+ * Asks api/auth/handoff.js for a single-use code first; signed out, or if that+ * fails, Safari still goes through the same endpoint without one, because+ * /api/* is the only part of three.ws universal links leave alone and a bare+ * https://three.ws/launch would open straight back into this app.+ *+ * @param {string} path same-origin path, e.g. '/launch?mint=...'+ */+export async function openInSafari(path) {+ let url = `https://three.ws/api/auth/handoff?next=${encodeURIComponent(path)}`;+ try {+ const res = await fetch('/api/auth/handoff', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ next: path }),+ });+ if (res.ok) {+ const data = await res.json();+ if (typeof data?.url === 'string') url = data.url;+ }+ } catch {+ // Offline or the API is down: Safari can still open the page signed out,+ // and the login there brings them back to it.+ }+ const app = plugin('ThreeWsApp');+ if (typeof app?.openInSafari === 'function') {+ await app.openInSafari({ url });+ return;+ }+ // A dev build without the native method: the Safari sheet is the closest+ // thing, and still leaves the WebView where it was.+ const browser = plugin('Browser');+ if (!browser) throw new Error('Safari is not available');+ await browser.open({ url });+}++let handoffSheet = null;++/**+ * The full-screen sheet that explains why this step leaves the app and opens+ * it in Safari. One instance at a time; a second call retargets it.+ *+ * @param {string} path what Safari should open+ * @param {{ dismiss: 'close'|'back' }} options `back` when the page underneath+ * is itself a handoff page, so dismissing has to leave it too.+ */+function showHandoffSheet(path, { dismiss }) {+ if (handoffSheet) {+ handoffSheet.retarget(path, dismiss);+ return;+ }+ const previousFocus = document.activeElement;+ const root = document.createElement('div');+ root.className = 'tw-handoff';+ root.setAttribute('role', 'dialog');+ root.setAttribute('aria-modal', 'true');+ root.setAttribute('aria-labelledby', 'tw-handoff-title');+ root.setAttribute('aria-describedby', 'tw-handoff-body');+ root.innerHTML = `+ <div class="tw-handoff__card">+ <h2 class="tw-handoff__title" id="tw-handoff-title">Continue in Safari</h2>+ <p class="tw-handoff__body" id="tw-handoff-body">Payments, coin launches and trading happen on three.ws in Safari. You stay signed in, and everything you do there shows up here.</p>+ <p class="tw-handoff__error" role="alert" hidden></p>+ <div class="tw-handoff__actions">+ <button type="button" class="tw-handoff__btn tw-handoff__btn--primary" data-handoff-open>Open in Safari</button>+ <button type="button" class="tw-handoff__btn" data-handoff-dismiss></button>+ </div>+ </div>`;+ const openBtn = root.querySelector('[data-handoff-open]');+ const dismissBtn = root.querySelector('[data-handoff-dismiss]');+ const errorEl = root.querySelector('.tw-handoff__error');+ let target = path;+ let mode = dismiss;++ const close = () => {+ document.removeEventListener('keydown', onKey, true);+ root.removeAttribute('data-open');+ setTimeout(() => root.remove(), 200);+ handoffSheet = null;+ if (previousFocus?.focus) previousFocus.focus();+ };+ const leave = () => {+ if (mode === 'close') return close();+ // Landed straight on a payment page: going back means leaving it.+ if (history.length > 1) history.back();+ else location.replace('/');+ };+ function onKey(ev) {+ if (ev.key === 'Escape') {+ ev.preventDefault();+ leave();+ } else if (ev.key === 'Tab') {+ // Two buttons; keep focus between them while the sheet is up.+ const order = [openBtn, dismissBtn];+ const i = order.indexOf(document.activeElement);+ ev.preventDefault();+ order[(i + (ev.shiftKey ? order.length - 1 : 1)) % order.length].focus();+ }+ }+ openBtn.addEventListener('click', async () => {+ if (openBtn.getAttribute('aria-busy') === 'true') return;+ openBtn.setAttribute('aria-busy', 'true');+ errorEl.hidden = true;+ try {+ await openInSafari(target);+ if (mode === 'close') close();+ } catch {+ errorEl.textContent = 'Safari could not be opened. Check your connection and try again.';+ errorEl.hidden = false;+ } finally {+ openBtn.removeAttribute('aria-busy');+ }+ });+ dismissBtn.addEventListener('click', leave);++ const retarget = (nextPath, nextDismiss) => {+ target = nextPath;+ mode = nextDismiss;+ dismissBtn.textContent = mode === 'back' ? 'Go back' : 'Not now';+ };+ retarget(path, dismiss);+ handoffSheet = { retarget };++ document.addEventListener('keydown', onKey, true);+ document.body.appendChild(root);+ requestAnimationFrame(() => root.setAttribute('data-open', ''));+ openBtn.focus();+}++// Real-funds steps that DO stay in the app, by the context slug they pass to the+// agreements gate (public/risk-ack.js). Each one moves the visitor's own crypto+// between their own wallets, or out to an address they chose, which is wallet+// functionality App Review permits (guideline 3.1.5(i)). Everything else that+// reaches the gate (trades, launches, swaps, purchases, x402, onramp, top-ups,+// donations) opens in Safari, including any context added later and not listed+// here: an unknown money step defaults to leaving the app.+const IN_APP_CONTEXTS = new Set([+ 'agreements-page',+ 'claim',+ 'deposit',+ 'fund-agent',+ 'master-send',+ 'withdraw',+]);++/**+ * Sends a money-moving step to Safari. The public half of the handoff, exposed+ * as `window.threeWsNative.requireSafari` so purchase flows anywhere on the+ * site can call it without importing app code (src/shared/native-handoff.js+ * wraps it for modules, and the agreements gate calls it with its context).+ *+ * @param {string} [path] where Safari should land; defaults to this page.+ * @param {{ context?: string }} [opts] the agreements-gate context, when the+ * caller is the gate; a context in IN_APP_CONTEXTS stays in the app.+ * @returns {boolean} true when the app took over and the caller must stop.+ */+export function requireSafari(path, { context } = {}) {+ if (!isNativeIOS()) return false;+ if (context && IN_APP_CONTEXTS.has(context)) return false;+ const here = `${location.pathname}${location.search}${location.hash}`;+ const target = typeof path === 'string' && path.startsWith('/') && !path.startsWith('//') ? path : here;+ showHandoffSheet(target, { dismiss: 'close' });+ return true;+}++/**+ * Routes the app's handoff pages to Safari: links to them open the sheet in+ * place, and arriving on one directly (a push, a universal link, a redirect)+ * covers it with the sheet, since nothing on that page can be used in the app.+ */+function routeHandoffPages() {+ if (!isNativeIOS()) return;+ globalThis.threeWsNative = Object.freeze({ requireSafari, openInSafari });+ document.addEventListener(+ 'click',+ (ev) => {+ if (ev.defaultPrevented || ev.button !== 0 || ev.metaKey || ev.ctrlKey) return;+ const anchor = ev.target?.closest?.('a[href]');+ if (!anchor || anchor.hasAttribute('download')) return;+ const path = handoffPathFor(anchor.getAttribute('href') || '', location.href);+ if (!path) return;+ ev.preventDefault();+ showHandoffSheet(path, { dismiss: 'close' });+ },+ true,+ );+ const here = handoffPathFor(location.href);+ if (here) showHandoffSheet(here, { dismiss: 'back' });+}+/*** Gives the app a working `navigator.share`.*@@ -462,6 +793,7 @@ export function bootNativeIOS() {installShare();installHaptics();routeExternalLinks();+ routeHandoffPages();routeDeepLinks();routePushTaps();syncBadge();diff --git a/package.json b/package.jsonindex acfd52031..807dc8299 100644--- a/package.json+++ b/package.json@@ -509,6 +509,8 @@"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",+ "ios:release": "node ios/scripts/release.mjs",+ "ios:release:dry": "node ios/scripts/release.mjs --dry-run","clean:worktrees": "node scripts/clean-deploy-worktrees.mjs","prep:worktree": "node scripts/prepare-deploy-worktree.mjs","check:browser-graph": "node scripts/check-browser-graph.mjs",diff --git a/pages/pricing.html b/pages/pricing.htmlindex 6b8950990..42cd06018 100644--- a/pages/pricing.html+++ b/pages/pricing.html@@ -1411,6 +1411,8 @@// Signed out (or already upgraded) → let the link navigate.if (!user || ['pro', 'team', 'enterprise'].includes(user.plan)) return;e.preventDefault();+ // In the iOS app, plans are bought on three.ws in Safari.+ if (window.threeWsNative?.requireSafari?.() === true) return;openModal();});diff --git a/pages/x-pricing.html b/pages/x-pricing.htmlindex 562008c5e..937980f42 100644--- a/pages/x-pricing.html+++ b/pages/x-pricing.html@@ -155,6 +155,8 @@} catch {}async function createCheckout() {+ // In the iOS app, plans are bought on three.ws in Safari.+ if (window.threeWsNative?.requireSafari?.() === true) return;$('upgrade-btn').disabled = true;$('upgrade-btn').textContent = 'Creating checkout…';setStatus('');diff --git a/public/login.html b/public/login.htmlindex fbdcca934..9f948cd90 100644--- a/public/login.html+++ b/public/login.html@@ -806,6 +806,8 @@saml_error: 'Something went wrong completing single sign-on.',account_deleted: 'This account has been deleted.',rate_limited: 'Too many attempts. Please try again in a moment.',+ handoff_expired:+ 'That link from the three.ws app has expired. Sign in here to continue where you left off.',};const errCode = params.get('error');if (errEl && errCode && SSO_MESSAGES[errCode]) {diff --git a/public/risk-ack.js b/public/risk-ack.jsindex 87740848d..c738ce481 100644Binary files a/public/risk-ack.js and b/public/risk-ack.js differdiff --git a/public/x402-pay-core.js b/public/x402-pay-core.jsindex af527b0bf..e8f12219d 100644--- a/public/x402-pay-core.js+++ b/public/x402-pay-core.js@@ -704,6 +704,11 @@ export async function payEvm({ accept, resourceUrl, walletName, onStatus, reques// Single entry point for the paywall controller. Routes a wallet button to the// correct chain-specific payer based on the network of the matching `accept`.export async function pay({ accept, resourceUrl, walletName, onStatus, origin, request }) {+ // Inside the three.ws iOS app, payments open in Safari (ios/src/native-bridge.js+ // shows the sheet that takes the visitor there).+ if (globalThis.threeWsNative?.requireSafari?.() === true) {+ throw Object.assign(new Error('Payments continue in Safari.'), { code: 'native_handoff' });+ }if (isSolanaNetwork(accept?.network)) {return paySolana({ accept, resourceUrl, walletName, onStatus, origin, request });}diff --git a/scripts/check-ios-app.mjs b/scripts/check-ios-app.mjsindex f2ae5e4d0..82d0781bf 100644--- a/scripts/check-ios-app.mjs+++ b/scripts/check-ios-app.mjs@@ -153,6 +153,7 @@ section(() => {const callers = {takeShare: read('src/shared/share-target.js'),setBadge: read('ios/src/native-bridge.js'),+ openInSafari: 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`);@@ -181,6 +182,92 @@ section(() => {return 'push is wired from the app delegate through the device endpoint to the notification fan-out';});+// ------------------------------------------------- upload readiness ---++// Required reason APIs (ITMS-91053). App Store Connect refuses a build whose+// binary calls one of these without a manifest naming the category. Each row+// maps a call to its category; the plugin rows cover Capacitor plugins that+// Swift Package Manager links straight into the app and that ship no manifest.+const REASON_APIS = [+ { category: 'NSPrivacyAccessedAPICategoryFileTimestamp', swift: /creationDate|contentModificationDate|modificationDate|attributesOfItem|\bstat\(/ },+ { category: 'NSPrivacyAccessedAPICategoryUserDefaults', swift: /UserDefaults/ },+ { category: 'NSPrivacyAccessedAPICategorySystemBootTime', swift: /systemUptime|mach_absolute_time/ },+ { category: 'NSPrivacyAccessedAPICategoryDiskSpace', swift: /volumeAvailableCapacity|systemFreeSize|systemSize\b/ },+ { category: 'NSPrivacyAccessedAPICategoryActiveKeyboards', swift: /activeInputModes/ },+];+const PLUGIN_REASONS = {+ '@capacitor/preferences': 'NSPrivacyAccessedAPICategoryUserDefaults',+ '@capacitor/filesystem': 'NSPrivacyAccessedAPICategoryFileTimestamp',+};++section(() => {+ const targets = [+ { name: 'App', dir: 'ios/native/App/App', group: 'App' },+ { name: 'ShareExtension', dir: 'ios/native/App/ShareExtension', group: 'ShareExtension' },+ ];+ const iosDeps = Object.keys(JSON.parse(read('ios/package.json') || '{}').dependencies || {});+ for (const t of targets) {+ const manifest = read(`${t.dir}/PrivacyInfo.xcprivacy`);+ if (!manifest) continue;+ // Membership in the target's Resources phase is what puts the file in+ // the bundle; a manifest on disk that no phase copies is not uploaded.+ const targetBlock = pbx.match(new RegExp(`/\\* ${t.name} \\*/ = \\{\\n\\t\\t\\tisa = PBXNativeTarget;[\\s\\S]*?\\n\\t\\t\\};`))?.[0] || '';+ const resId = targetBlock.match(/(\w{24}) \/\* Resources \*\//)?.[1];+ const phase = resId && pbx.match(new RegExp(`${resId} /\\* Resources \\*/ = \\{\\n\\t\\t\\tisa = PBXResourcesBuildPhase;[\\s\\S]*?\\n\\t\\t\\};`))?.[0];+ if (!phase?.includes('PrivacyInfo.xcprivacy in Resources')) fail(`${t.dir}/PrivacyInfo.xcprivacy is not in the ${t.name} target's Resources phase`);+ if (!/<key>NSPrivacyTracking<\/key>\s*<(true|false)\/>/.test(manifest)) fail(`${t.dir}/PrivacyInfo.xcprivacy does not declare NSPrivacyTracking`);++ const sources = readdirSync(join(REPO, t.dir)).filter((f) => f.endsWith('.swift'));+ // SharedInbox.swift lives with the extension but is compiled into both binaries.+ if (!sources.includes('SharedInbox.swift')) sources.push('../ShareExtension/SharedInbox.swift');+ const swift = sources.map((f) => read(`${t.dir}/${f}`).replace(/^\s*\/\/.*$/gm, '')).join('\n');+ const needed = new Set(REASON_APIS.filter((r) => r.swift.test(swift)).map((r) => r.category));+ if (t.name === 'App') for (const [dep, category] of Object.entries(PLUGIN_REASONS)) if (iosDeps.includes(dep)) needed.add(category);+ for (const category of needed) {+ const entry = manifest.match(new RegExp(`<string>${category}</string>\\s*<key>NSPrivacyAccessedAPITypeReasons</key>\\s*<array>\\s*<string>[0-9A-F]{4}\\.\\d</string>`));+ if (!entry) fail(`${t.name} calls a ${category.replace('NSPrivacyAccessedAPICategory', '')} API but ${t.dir}/PrivacyInfo.xcprivacy gives no reason for it (ITMS-91053)`);+ }+ }+ return 'the app and the share extension each bundle a privacy manifest covering every required reason API they call';+});++section(() => {+ // CarPlay is granted per app. codesign refuses an archive whose entitlements+ // name a capability its provisioning profile lacks, so the key lives in an+ // opt-in file and the default one must never carry it.+ const key = 'com.apple.developer.carplay-voice-based-conversation';+ const keys = (xml) => [...xml.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<key>([^<]+)<\/key>\s*(<[\s\S]*?)(?=\s*<key>|\s*<\/dict>\s*<\/plist>)/g)].map((m) => [m[1], m[2].replace(/\s+/g, '')]);+ const base = keys(read('ios/native/App/App/App.entitlements'));+ const carplay = keys(read('ios/native/App/App/App-CarPlay.entitlements'));+ if (base.some(([k]) => k === key)) fail(`App.entitlements carries ${key}; an archive signed before Apple grants it fails codesign`);+ if (!carplay.some(([k]) => k === key)) fail(`App-CarPlay.entitlements does not carry ${key}`);+ const rest = JSON.stringify(carplay.filter(([k]) => k !== key));+ if (rest !== JSON.stringify(base)) fail('App-CarPlay.entitlements has drifted from App.entitlements; apart from the CarPlay key they must be identical');+ const selectors = [...pbx.matchAll(/THREEWS_APP_ENTITLEMENTS = ([^;]+);/g)].map((m) => m[1]);+ if (selectors.length !== 2 || selectors.some((s) => s !== 'App/App.entitlements')) {+ fail('the App target must default THREEWS_APP_ENTITLEMENTS to App/App.entitlements in Debug and Release');+ }+ if ((pbx.match(/CODE_SIGN_ENTITLEMENTS = "\$\(THREEWS_APP_ENTITLEMENTS\)";/g) || []).length !== 2) {+ fail('the App target does not sign with $(THREEWS_APP_ENTITLEMENTS), so the release script cannot opt into CarPlay');+ }+ if (!read('ios/scripts/release.mjs').includes('App/App-CarPlay.entitlements')) fail('ios/scripts/release.mjs has no way to sign with App-CarPlay.entitlements');+ return 'CarPlay is opt-in at signing time, so a build without the grant still archives';+});++section(() => {+ // The app and every extension it embeds must carry the same build number,+ // or App Store Connect rejects the upload (ITMS-90473).+ const builds = new Set([...pbx.matchAll(/CURRENT_PROJECT_VERSION = ([^;]+);/g)].map((m) => m[1]));+ if (builds.size !== 1) fail(`CURRENT_PROJECT_VERSION differs between targets: ${[...builds].join(', ')}`);+ for (const plist of ['ios/native/App/App/Info.plist', 'ios/native/App/ShareExtension/Info.plist', 'apple/GlanceWidget/Info.plist']) {+ const xml = read(plist);+ if (!/<key>CFBundleVersion<\/key>\s*<string>\$\(CURRENT_PROJECT_VERSION\)<\/string>/.test(xml)) fail(`${plist} hardcodes CFBundleVersion instead of $(CURRENT_PROJECT_VERSION), so the release script cannot bump it`);+ if (!/<key>CFBundleShortVersionString<\/key>\s*<string>\$\(MARKETING_VERSION\)<\/string>/.test(xml)) fail(`${plist} hardcodes CFBundleShortVersionString instead of $(MARKETING_VERSION)`);+ }+ if (!/<key>ITSAppUsesNonExemptEncryption<\/key>\s*<false\/>/.test(appPlist)) fail('Info.plist does not answer ITSAppUsesNonExemptEncryption, so every TestFlight build waits on the export compliance question');+ return 'every target shares one build number and version, set from the build settings the release script overrides';+});+// ------------------------------------------------------- quick actions ---section(() => {diff --git a/src/credits.js b/src/credits.jsindex 88c24aea4..72a54abd8 100644--- a/src/credits.js+++ b/src/credits.js@@ -11,6 +11,7 @@import { getAdapter } from './onchain/adapters/index.js';import { resolveTokenProgramId } from './shared/spl-token-program.js';import { solToUsd, getTokenPriceUsd } from './shared/usd-price.js';+import { leaveAppForPayment } from './shared/native-handoff.js';const SOL_MINT = 'So11111111111111111111111111111111111111112';@@ -431,6 +432,7 @@ async function buildThreeTransfer({ web3, spl, conn, from, to, amount, mintStr,}async function doDeposit() {+ if (leaveAppForPayment()) return;const btn = $('deposit-btn');const amount = Number($('amount').value);if (!(amount > 0)) return setStatus('Enter an amount greater than zero.', 'err');diff --git a/src/forge-studio/forge-pay.js b/src/forge-studio/forge-pay.jsindex cd686bf9a..07490664a 100644--- a/src/forge-studio/forge-pay.js+++ b/src/forge-studio/forge-pay.js@@ -17,6 +17,7 @@// { ok:true, paymentId, refId } on a verified on-chain payment.import { payWithToken } from '../token-pay.js';+import { leaveAppForPayment } from '../shared/native-handoff.js';const ECONOMY_URL = '/three-token';const SIGN_IN_URL = '/login';@@ -163,6 +164,7 @@ export function payForConsumption({successText = 'Payment confirmed — continuing…',refPrefix = 'forge',} = {}) {+ if (leaveAppForPayment()) return Promise.resolve({ ok: false, cancelled: true });injectStyles();return new Promise((resolve) => {const refId = clientNonce(refPrefix);diff --git a/src/game/coin-buy.js b/src/game/coin-buy.jsindex b76b1b499..cb8a14315 100644--- a/src/game/coin-buy.js+++ b/src/game/coin-buy.js@@ -23,6 +23,7 @@ import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/import { createSafetyPanel } from '../shared/safety-panel.js';import { createSmartMoneyPanel } from '../shared/smart-money-panel.js';import { proxiedImageURL } from '../ipfs.js';+import { leaveAppForPayment } from '../shared/native-handoff.js';const WSOL = 'So11111111111111111111111111111111111111112';const USDC_MINT = {@@ -134,6 +135,7 @@ function friendlyTradeError(err, mode = 'buy') {*/export function openBuyModal(coin, opts = {}) {if (!coin?.mint) return;+ if (leaveAppForPayment()) return;if (_open) {if (_open.coin?.mint === coin.mint) { _open.focus(); return; }_open.close();diff --git a/src/marketplace.js b/src/marketplace.jsindex a500167fa..bbb2fe632 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -29,6 +29,7 @@ import { debounce, syncStateToUrl } from './shared/list-controls.js';import { log } from './shared/log.js';import { track, trackError, ANALYTICS_EVENTS } from './analytics.js';import { resizedImageUrl } from './shared/image-url.js';+import { leaveAppForPayment } from './shared/native-handoff.js';ensureStateKitStyles();const API = '/api';@@ -2025,6 +2026,7 @@ function renderSubscriptionTiers(agent) {}async function initiateSubscription(planId, btn) {+ if (leaveAppForPayment()) return;if (!currentUserId) {location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;return;@@ -7221,6 +7223,7 @@ function shortMintLabel(mint) {async function openTimePassFlow(agentId, skill, durationHours, btn) {+ if (leaveAppForPayment()) return;if (!detailState?.agent || detailState.agent.id !== agentId) {alert('Agent not loaded; refresh and try again.');return;@@ -7297,6 +7300,7 @@ async function openTrialFlow(agentId, skill, btn) {}async function openPurchaseFlow(agentId, skill) {+ if (leaveAppForPayment()) return;if (!detailState?.agent || detailState.agent.id !== agentId) {alert('Agent not loaded; refresh and try again.');return;@@ -7372,6 +7376,7 @@ async function createPendingPurchase(agentId, skill, durationHours = null) {let pendingAssetPurchase = null; // { item_type, item_id, label, price }function openAssetPurchaseFlow(asset) {+ if (leaveAppForPayment()) return;const confirmBtn = $('payment-confirm-btn');const skillName = $('payment-skill-name');const agentName = $('payment-agent-name');diff --git a/src/shared/agent-tip.js b/src/shared/agent-tip.jsindex fff5b8016..a7fa1e22e 100644--- a/src/shared/agent-tip.js+++ b/src/shared/agent-tip.js@@ -38,6 +38,7 @@ import {} from '@solana/spl-token';import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';import { resolveTokenProgramId } from './spl-token-program.js';+import { leaveAppForPayment } from './native-handoff.js';const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -98,6 +99,9 @@ async function waitForConfirmation(conn, signature, timeoutMs = 60_000) {export async function tipAgent({ toAddress, token = 'SOL', amount, mint: splMint, decimals: splDecimals, noBalanceMsg, network = 'mainnet', onStage } = {}) {const stage = (s) => { try { onStage?.(s); } catch { /* listener best-effort */ } };+ // In the iOS app this opens the Safari sheet; the caller's error copy then+ // says where the tip continues.+ if (leaveAppForPayment()) throw new TipError('Tips are sent from three.ws in Safari.', 'native_handoff');if (!toAddress || !BASE58_RE.test(String(toAddress))) {throw new TipError('This agent has no valid wallet address to tip.', 'no_address');}diff --git a/src/shared/native-handoff.js b/src/shared/native-handoff.jsnew file mode 100644index 000000000..f7035f543--- /dev/null+++ b/src/shared/native-handoff.js@@ -0,0 +1,24 @@+// In the three.ws iOS app, steps that move money open in Safari instead of+// running in the app's WebView (App Review guidelines 3.1.1 and 3.1.5; see+// ios/docs/REVIEW-RISK.md). The app installs `window.threeWsNative` from+// ios/src/native-bridge.js; everywhere else it is absent and this is a no-op.+//+// Call it first thing in any flow that pays, buys, deposits, tips, swaps or+// launches, and stop when it returns true:+//+// if (leaveAppForPayment()) return null;+//+// The visitor sees a sheet that explains the hop and opens this page in Safari,+// still signed in, where the same flow runs normally.++/**+ * @param {string} [path] same-origin path Safari should land on; defaults to+ * the current page, which is where the flow the visitor just started lives.+ * @returns {boolean} true when the app took over and the caller must not+ * continue the payment here.+ */+export function leaveAppForPayment(path) {+ const native = globalThis.threeWsNative;+ if (typeof native?.requireSafari !== 'function') return false;+ return native.requireSafari(path) === true;+}diff --git a/src/shared/risk-ack.js b/src/shared/risk-ack.jsindex a61c1f83c..5d95ab44e 100644--- a/src/shared/risk-ack.js+++ b/src/shared/risk-ack.js@@ -73,6 +73,9 @@ function _degradedConfirm() {* @returns {Promise<boolean>}*/export async function ensureRiskAck(opts) {+ // Checked here as well as in public/risk-ack.js so the degraded confirm()+ // path below cannot run a payment inside the iOS app either.+ if (globalThis.threeWsNative?.requireSafari?.(undefined, { context: opts?.context ?? 'real-funds' }) === true) return false;let m;try {m = await _mod();diff --git a/src/shared/skill-purchase.js b/src/shared/skill-purchase.jsindex b21ad5a9b..b98ecc72b 100644--- a/src/shared/skill-purchase.js+++ b/src/shared/skill-purchase.js@@ -24,6 +24,7 @@import { log } from './log.js';import { showToast } from '../ui-helpers.js';+import { leaveAppForPayment } from './native-handoff.js';export const USDC_MAINNET_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';@@ -702,6 +703,7 @@ async function pollConfirm(reference, windowMs = 60_000) {// ── Skill purchase flows ────────────────────────────────────────────────────export async function openPurchaseFlow(agentId, skill) {+ if (leaveAppForPayment()) return;ensureModal();const agent = cfg.getAgent();if (!agent || agent.id !== agentId) { alert('Agent not loaded; refresh and try again.'); return; }@@ -742,6 +744,7 @@ export async function openPurchaseFlow(agentId, skill) {}export async function openTimePassFlow(agentId, skill, durationHours, btn) {+ if (leaveAppForPayment()) return;ensureModal();const agent = cfg.getAgent();if (!agent || agent.id !== agentId) { alert('Agent not loaded; refresh and try again.'); return; }@@ -816,6 +819,7 @@ export async function openTrialFlow(agentId, skill, btn) {let pendingAssetPurchase = null;export function openAssetPurchaseFlow(asset) {+ if (leaveAppForPayment()) return;ensureModal();const confirmBtn = $('payment-confirm-btn');const skillName = $('payment-skill-name');@@ -1228,6 +1232,7 @@ let pendingSubscription = null;* @param {{ id: string, name: string, price_usd: number, interval: string, perks?: string[] }} tier*/export async function openSubscribeFlow(agentId, tier) {+ if (leaveAppForPayment()) return;ensureModal();const agent = cfg.getAgent();if (!agent || agent.id !== agentId) { alert('Agent not loaded; refresh and try again.'); return; }diff --git a/tests/auth-handoff.test.js b/tests/auth-handoff.test.jsnew file mode 100644index 000000000..ccefeae57--- /dev/null+++ b/tests/auth-handoff.test.js@@ -0,0 +1,225 @@+// /api/auth/handoff: the session hop from the iOS app into Safari.+//+// The code in the URL is a bearer credential for a whole account, so what these+// tests pin is everything that keeps it from being one for long: it is minted+// only from three.ws for a signed-in session, it lands only on a three.ws path,+// and the exchange consumes it in the same statement that checks it. They also+// pin the signed-out bounce, the one form of the URL that carries no code,+// because it is what keeps a bare three.ws link from being claimed straight+// back by the app through universal links.++import { beforeEach, describe, expect, it, vi } from 'vitest';++const state = { user: null, consumeRow: null, queries: [], limited: false };++vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => state.user),+ isSameSiteOrigin: (req) => req.headers.origin === 'https://three.ws',+ createSession: vi.fn(async () => 'fresh-session-token'),+ destroySession: vi.fn(async () => {}),+ sessionCookie: (token) => `__Host-sid=${token}; Path=/; HttpOnly; Secure; SameSite=Lax`,+}));++vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ sessionHandoffUser: vi.fn(async () => ({ success: !state.limited })),+ authIp: vi.fn(async () => ({ success: !state.limited })),+ },+ clientIp: () => '203.0.113.7',+}));++vi.mock('../api/_lib/db.js', () => {+ const sql = vi.fn((strings, ...values) => {+ const text = strings.join('?').replace(/\s+/g, ' ').trim().toLowerCase();+ state.queries.push({ text, values });+ if (text.startsWith('update session_handoffs')) return Promise.resolve(state.consumeRow ? [state.consumeRow] : []);+ return Promise.resolve([]);+ });+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };+});++const { default: handler, safeHandoffPath, HANDOFF_TTL_SEC } = await import('../api/auth/handoff.js');+const { createSession, destroySession } = await import('../api/_lib/auth.js');+const { sha256 } = await import('../api/_lib/crypto.js');++function makeRes() {+ return {+ statusCode: 200,+ payload: null,+ headers: {},+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ removeHeader(k) { delete this.headers[String(k).toLowerCase()]; },+ writeHead(code) { this.statusCode = code; return this; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ end(chunk) {+ if (chunk) { try { this.payload = JSON.parse(String(chunk)); } catch { this.payload = String(chunk); } }+ return this;+ },+ };+}++async function mint(body, { origin = 'https://three.ws' } = {}) {+ const raw = Buffer.from(JSON.stringify(body));+ const req = {+ method: 'POST',+ url: '/api/auth/handoff',+ headers: { 'content-type': 'application/json', origin },+ body,+ rawBody: raw,+ };+ const res = makeRes();+ await handler(req, res);+ return res;+}++async function open(query) {+ const req = { method: 'GET', url: `/api/auth/handoff?${query}`, headers: { 'user-agent': 'Safari' } };+ const res = makeRes();+ await handler(req, res);+ return res;+}++const USER = { id: '11111111-1111-4111-8111-111111111111', email: '[email protected]' };++beforeEach(() => {+ state.user = null;+ state.consumeRow = null;+ state.queries = [];+ state.limited = false;+ vi.clearAllMocks();+});++describe('safeHandoffPath', () => {+ it('keeps a same-origin path with its query and hash', () => {+ expect(safeHandoffPath('/launch?mint=abc#top')).toBe('/launch?mint=abc#top');+ });++ it.each([+ ['protocol-relative', '//evil.example/launch'],+ ['backslash that browsers read as //', '/\\evil.example'],+ ['absolute URL', 'https://evil.example/'],+ ['scheme', 'javascript:alert(1)'],+ ['relative path', 'launch'],+ ['control character', '/launch\nSet-Cookie: x'],+ ['empty', ''],+ ['non-string', 42],+ ['over 2048 characters', `/${'a'.repeat(2048)}`],+ ])('refuses a %s', (_label, value) => {+ expect(safeHandoffPath(value)).toBeNull();+ });+});++describe('POST /api/auth/handoff (mint)', () => {+ it('refuses a request that is not from three.ws', async () => {+ state.user = USER;+ const res = await mint({ next: '/launch' }, { origin: 'https://evil.example' });+ expect(res.statusCode).toBe(403);+ expect(state.queries).toHaveLength(0);+ });++ it('requires a signed-in session', async () => {+ const res = await mint({ next: '/launch' });+ expect(res.statusCode).toBe(401);+ expect(state.queries).toHaveLength(0);+ });++ it('refuses a landing path off three.ws', async () => {+ state.user = USER;+ const res = await mint({ next: '//evil.example' });+ expect(res.statusCode).toBe(400);+ expect(res.payload.error).toBe('invalid_next');+ });++ it('is rate limited per user', async () => {+ state.user = USER;+ state.limited = true;+ const res = await mint({ next: '/launch' });+ expect(res.statusCode).toBe(429);+ });++ it('stores only the hash of a short-lived code and returns the Safari URL', async () => {+ state.user = USER;+ const before = Date.now();+ const res = await mint({ next: '/launch/paired?x=1' });+ expect(res.statusCode).toBe(200);+ expect(res.headers['cache-control']).toBe('no-store');++ const url = new URL(res.payload.url);+ expect(url.origin).toBe('https://three.ws');+ expect(url.pathname).toBe('/api/auth/handoff');+ expect(url.searchParams.get('next')).toBe('/launch/paired?x=1');+ const code = url.searchParams.get('code');+ expect(code).toMatch(/^[A-Za-z0-9_-]{40,}$/);++ const insert = state.queries.find((q) => q.text.startsWith('insert into session_handoffs'));+ expect(insert).toBeTruthy();+ const [codeHash, userId, next, expiresAt] = insert.values;+ expect(codeHash).toBe(await sha256(code));+ expect(insert.values).not.toContain(code);+ expect(userId).toBe(USER.id);+ expect(next).toBe('/launch/paired?x=1');+ const ttl = new Date(expiresAt).getTime() - before;+ expect(ttl).toBeGreaterThan(0);+ expect(ttl).toBeLessThanOrEqual(HANDOFF_TTL_SEC * 1000 + 1000);+ });+});++describe('GET /api/auth/handoff (exchange)', () => {+ it('signs Safari in and lands on the stored path', async () => {+ state.consumeRow = { user_id: USER.id, next_path: '/launch' };+ const res = await open('code=' + 'a'.repeat(43) + '&next=%2Fpricing');+ expect(res.statusCode).toBe(302);+ // The stored path wins over the one in the URL, which only serves the+ // expired-code fallback.+ expect(res.headers.location).toBe('https://three.ws/launch');+ expect(res.headers['set-cookie']).toContain('fresh-session-token');+ expect(res.headers['referrer-policy']).toBe('no-referrer');+ expect(destroySession).toHaveBeenCalledOnce();+ expect(createSession).toHaveBeenCalledWith(expect.objectContaining({ userId: USER.id }));+ });++ it('consumes the code in the same statement that checks it', async () => {+ state.consumeRow = { user_id: USER.id, next_path: '/launch' };+ const code = 'b'.repeat(43);+ await open(`code=${code}`);+ const update = state.queries.find((q) => q.text.startsWith('update session_handoffs'));+ expect(update.text).toContain('consumed_at = now()');+ expect(update.text).toContain('consumed_at is null');+ expect(update.text).toContain('expires_at > now()');+ expect(update.text).toContain('deleted_at is null');+ expect(update.values).toContain(await sha256(code));+ });++ it('sends a used or expired code to sign in, keeping the destination', async () => {+ const res = await open('code=' + 'c'.repeat(43) + '&next=%2Flaunch');+ expect(res.statusCode).toBe(302);+ expect(res.headers.location).toBe('https://three.ws/login?error=handoff_expired&next=%2Flaunch');+ expect(res.headers['set-cookie']).toBeUndefined();+ expect(createSession).not.toHaveBeenCalled();+ });++ it('never redirects off three.ws, even for a hostile next', async () => {+ const res = await open('code=short&next=%2F%2Fevil.example');+ expect(res.headers.location).toBe('https://three.ws/login?error=handoff_expired&next=%2F');+ });++ it('bounces a signed-out visitor straight to the page, with no session change', async () => {+ const res = await open('next=%2Flaunch%3Fmint%3Dabc');+ expect(res.statusCode).toBe(302);+ expect(res.headers.location).toBe('https://three.ws/launch?mint=abc');+ expect(res.headers['set-cookie']).toBeUndefined();+ expect(state.queries).toHaveLength(0);+ });++ it('refuses to exchange while rate limited', async () => {+ state.limited = true;+ state.consumeRow = { user_id: USER.id, next_path: '/launch' };+ const res = await open('code=' + 'd'.repeat(43));+ expect(res.headers.location).toMatch(/^https:\/\/three\.ws\/login\?error=rate_limited/);+ expect(createSession).not.toHaveBeenCalled();+ });+});diff --git a/tests/ios-release.test.js b/tests/ios-release.test.jsnew file mode 100644index 000000000..c2be4f512--- /dev/null+++ b/tests/ios-release.test.js@@ -0,0 +1,142 @@+// ios/scripts/release.mjs: the archive-and-upload pipeline for TestFlight.+//+// It only runs on a Mac, so the parts a Linux CI box can check are the ones+// that decide what Xcode is told: the build number App Store Connect will+// accept, the export options, the API key flags and the CarPlay switch. A+// wrong value in any of them fails as an upload rejection minutes into a+// build on someone's laptop, which is the slowest possible place to find it.++import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';++import {+ BASE_ENTITLEMENTS,+ CARPLAY_ENTITLEMENTS,+ IOS,+ authArgs,+ buildNumberFor,+ exportOptionsPlist,+ isBundleVersion,+ parseArgs,+ releasePlan,+} from '../ios/scripts/release.mjs';++const TEAM = { APPLE_TEAM_ID: 'ABCDE12345' };++describe('buildNumberFor', () => {+ it('is the UTC date and minute as a CFBundleVersion', () => {+ expect(buildNumberFor(new Date('2026-10-09T19:00:00Z'))).toBe('261009.1900');+ expect(buildNumberFor(new Date('2026-01-02T00:07:00Z'))).toBe('260102.7');+ expect(isBundleVersion(buildNumberFor(new Date()))).toBe(true);+ });++ it('only ever rises, which App Store Connect requires of every upload', () => {+ const minutes = [+ '2026-10-09T23:59:00Z',+ '2026-10-10T00:00:00Z',+ '2026-12-31T23:59:00Z',+ '2027-01-01T00:00:00Z',+ ].map((t) => buildNumberFor(new Date(t)));+ const asTuple = (v) => v.split('.').map(Number);+ for (let i = 1; i < minutes.length; i++) {+ const [a, b] = [asTuple(minutes[i - 1]), asTuple(minutes[i])];+ expect(b[0] > a[0] || (b[0] === a[0] && b[1] > a[1])).toBe(true);+ }+ });+});++describe('parseArgs', () => {+ it('reads every flag', () => {+ expect(parseArgs(['--dry-run', '--carplay', '--export-only', '--skip-sync', '--build-number', '42', '--marketing-version', '1.2.0'])).toEqual({+ dryRun: true,+ carplay: true,+ exportOnly: true,+ skipSync: true,+ buildNumber: '42',+ marketingVersion: '1.2.0',+ });+ });++ it.each([+ [['--build-number'], /needs a value/],+ [['--build-number', '1.2.3.4'], /not one to three/],+ [['--marketing-version', 'v1'], /not one to three/],+ [['--upload'], /unknown option/],+ ])('refuses %j', (argv, message) => {+ expect(() => parseArgs(argv)).toThrow(message);+ });+});++describe('authArgs', () => {+ it('is empty without an App Store Connect key, so Xcode uses the signed-in account', () => {+ expect(authArgs({})).toEqual([]);+ });++ it('passes all three key settings to xcodebuild', () => {+ const args = authArgs({ ASC_KEY_ID: 'KEY123', ASC_ISSUER_ID: 'issuer-uuid', ASC_KEY_PATH: '/keys/AuthKey_KEY123.p8' });+ expect(args).toEqual([+ '-authenticationKeyPath',+ '/keys/AuthKey_KEY123.p8',+ '-authenticationKeyID',+ 'KEY123',+ '-authenticationKeyIssuerID',+ 'issuer-uuid',+ ]);+ });++ it('refuses a partial key', () => {+ expect(() => authArgs({ ASC_KEY_ID: 'KEY123' })).toThrow(/go together/);+ });+});++describe('exportOptionsPlist', () => {+ it('uploads to App Store Connect with automatic signing for the team', () => {+ const plist = exportOptionsPlist({ teamId: 'ABCDE12345', upload: true });+ expect(plist).toContain('<key>method</key>\n\t<string>app-store-connect</string>');+ expect(plist).toContain('<key>destination</key>\n\t<string>upload</string>');+ expect(plist).toContain('<key>teamID</key>\n\t<string>ABCDE12345</string>');+ expect(plist).toContain('<key>manageAppVersionAndBuildNumber</key>\n\t<false/>');+ });++ it('exports locally instead when asked', () => {+ expect(exportOptionsPlist({ teamId: 'ABCDE12345', upload: false })).toContain('<string>export</string>');+ });+});++describe('releasePlan', () => {+ const now = new Date('2026-10-09T19:00:00Z');++ it('checks, syncs, archives, then exports, in that order', () => {+ const plan = releasePlan({ ...parseArgs([]), now }, TEAM);+ expect(plan.steps.map(([cmd, args]) => `${cmd} ${args[0]}`)).toEqual([+ 'node scripts/check-ios-app.mjs',+ 'npm ci',+ 'npx cap',+ 'xcodebuild archive',+ 'xcodebuild -exportArchive',+ ]);+ const archive = plan.steps[3][1];+ expect(archive).toContain('DEVELOPMENT_TEAM=ABCDE12345');+ expect(archive).toContain('CURRENT_PROJECT_VERSION=261009.1900');+ expect(archive).toContain(`THREEWS_APP_ENTITLEMENTS=${BASE_ENTITLEMENTS}`);+ expect(archive.some((a) => a.startsWith('MARKETING_VERSION='))).toBe(false);+ expect(plan.archivePath.endsWith('App-261009.1900.xcarchive')).toBe(true);+ });++ it('signs with the CarPlay entitlements only when asked', () => {+ const plan = releasePlan({ ...parseArgs(['--carplay', '--skip-sync', '--marketing-version', '1.1']), now }, TEAM);+ const archive = plan.steps.find(([, args]) => args[0] === 'archive')[1];+ expect(archive).toContain(`THREEWS_APP_ENTITLEMENTS=${CARPLAY_ENTITLEMENTS}`);+ expect(archive).toContain('MARKETING_VERSION=1.1');+ expect(plan.steps.some(([cmd]) => cmd === 'npm')).toBe(false);+ });++ it('names entitlement files that exist in the Xcode project', () => {+ for (const file of [BASE_ENTITLEMENTS, CARPLAY_ENTITLEMENTS]) {+ expect(existsSync(join(IOS, 'native/App', file))).toBe(true);+ }+ const pbx = readFileSync(join(IOS, 'native/App/App.xcodeproj/project.pbxproj'), 'utf8');+ expect(pbx).toContain(`THREEWS_APP_ENTITLEMENTS = ${BASE_ENTITLEMENTS};`);+ });+});diff --git a/tests/ios-safari-handoff.test.js b/tests/ios-safari-handoff.test.jsnew file mode 100644index 000000000..b3e26f644--- /dev/null+++ b/tests/ios-safari-handoff.test.js@@ -0,0 +1,157 @@+// @vitest-environment jsdom+// @vitest-environment-options { "url": "https://three.ws/create" }+/**+ * The iOS app's Safari handoff (ios/src/native-bridge.js).+ *+ * In the app, paying, launching a coin, trading and buying credits open in+ * Safari instead of the WebView, because App Review does not allow them inside+ * an iOS app outside In-App Purchase. Two halves have to agree for that to hold:+ * the bridge decides which pages and which agreements-gate contexts leave the+ * app, and the money flows ask it before they start. A regression in either+ * shows up for the first time as a rejection email, so both are pinned here.+ */++import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++function fakeCapacitor() {+ const calls = [];+ return {+ calls,+ isNativePlatform: () => true,+ getPlatform: () => 'ios',+ Plugins: {+ Browser: { open: (opts) => (calls.push(['Browser.open', opts]), Promise.resolve()) },+ ThreeWsApp: {+ setBadge: () => Promise.resolve(),+ openInSafari: (opts) => (calls.push(['ThreeWsApp.openInSafari', opts]), Promise.resolve()),+ },+ App: { addListener: () => Promise.resolve({ remove() {} }) },+ PushNotifications: { addListener: () => Promise.resolve({ remove() {} }) },+ },+ };+}++const flush = () => new Promise((r) => setTimeout(r, 0));+const sheet = () => document.querySelector('.tw-handoff');++describe('Safari handoff inside the iOS app', () => {+ let cap;+ let mod;+ const realFetch = globalThis.fetch;++ beforeAll(async () => {+ cap = fakeCapacitor();+ globalThis.Capacitor = cap;+ globalThis.requestAnimationFrame = (cb) => setTimeout(cb, 0);+ mod = await import('../ios/src/native-bridge.js');+ mod.bootNativeIOS();+ });++ afterAll(() => {+ delete globalThis.Capacitor;+ delete globalThis.threeWsNative;+ globalThis.fetch = realFetch;+ });++ beforeEach(() => {+ cap.calls.length = 0;+ document.querySelectorAll('.tw-handoff').forEach((el) => el.remove());+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));+ document.body.innerHTML = '';+ });++ describe('handoffPathFor', () => {+ it.each([+ ['/launch', '/launch'],+ ['/launch/paired?ref=x', '/launch/paired?ref=x'],+ ['/launch/robinhood', '/launch/robinhood'],+ ['/credits.html', '/credits.html'],+ ['/pay/', '/pay/'],+ ['https://www.three.ws/three-launchpad', '/three-launchpad'],+ ['/markets/robinhood/desk', '/markets/robinhood/desk'],+ ])('sends %s to Safari', (href, expected) => {+ expect(mod.handoffPathFor(href)).toBe(expected);+ });++ it.each([+ ['/launches', 'the directory of launches, which only shows them'],+ ['/pay/simulator', 'a policy simulator that spends nothing'],+ ['/wallet', 'wallets stay in the app'],+ ['/create', 'everything else stays in the app'],+ ['https://example.com/launch', 'another site'],+ ])('keeps %s in the app (%s)', (href) => {+ expect(mod.handoffPathFor(href)).toBeNull();+ });+ });++ it('exposes the hook money flows call', () => {+ expect(typeof globalThis.threeWsNative?.requireSafari).toBe('function');+ });++ it('keeps wallet steps in the app and sends spending steps to Safari', () => {+ for (const context of ['withdraw', 'deposit', 'claim', 'fund-agent', 'master-send', 'agreements-page']) {+ expect(mod.requireSafari(undefined, { context })).toBe(false);+ }+ expect(sheet()).toBeNull();+ for (const context of ['trade', 'launch', 'swap', 'x402-pay', 'onramp', 'give', 'a-context-added-later']) {+ expect(mod.requireSafari(undefined, { context })).toBe(true);+ }+ expect(sheet()).not.toBeNull();+ });++ it('the agreements gate declines and shows the sheet for a trade, in the app', async () => {+ const { ensureRiskAck } = await import('../public/risk-ack.js');+ await expect(ensureRiskAck({ context: 'trade' })).resolves.toBe(false);+ expect(sheet()).not.toBeNull();+ });++ it('leaveAppForPayment takes over in the app', async () => {+ const { leaveAppForPayment } = await import('../src/shared/native-handoff.js');+ expect(leaveAppForPayment('/credits')).toBe(true);+ expect(sheet()).not.toBeNull();+ });++ it('a link to a payment page opens the sheet instead of navigating', () => {+ document.body.innerHTML = '<a href="/launch?mint=abc" id="go">Launch</a>';+ const ev = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 });+ document.getElementById('go').dispatchEvent(ev);+ expect(ev.defaultPrevented).toBe(true);+ const dialog = sheet();+ expect(dialog.getAttribute('role')).toBe('dialog');+ expect(dialog.getAttribute('aria-modal')).toBe('true');+ expect(document.activeElement?.hasAttribute('data-handoff-open')).toBe(true);+ });++ it('Open in Safari mints a code for this session and hands the URL to Safari', async () => {+ const minted = 'https://three.ws/api/auth/handoff?code=abc&next=%2Flaunch';+ globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => ({ url: minted }) }));+ mod.requireSafari('/launch');+ sheet().querySelector('[data-handoff-open]').click();+ await flush();+ await flush();+ const [url, init] = globalThis.fetch.mock.calls[0];+ expect(url).toBe('/api/auth/handoff');+ expect(init.method).toBe('POST');+ expect(init.credentials).toBe('include');+ expect(JSON.parse(init.body)).toEqual({ next: '/launch' });+ expect(cap.calls).toContainEqual(['ThreeWsApp.openInSafari', { url: minted }]);+ });++ it('signed out, Safari still goes through the handoff URL so universal links cannot reclaim it', async () => {+ globalThis.fetch = vi.fn(async () => ({ ok: false, status: 401, json: async () => ({}) }));+ await mod.openInSafari('/launch?mint=abc');+ expect(cap.calls).toContainEqual([+ 'ThreeWsApp.openInSafari',+ { url: 'https://three.ws/api/auth/handoff?next=%2Flaunch%3Fmint%3Dabc' },+ ]);+ });++ it('Not now closes the sheet and leaves the page alone', () => {+ mod.requireSafari('/launch');+ const dismiss = sheet().querySelector('[data-handoff-dismiss]');+ expect(dismiss.textContent).toBe('Not now');+ dismiss.click();+ expect(sheet().hasAttribute('data-open')).toBe(false);+ expect(location.pathname).toBe('/create');+ });+});diff --git a/vercel.json b/vercel.jsonindex e5cf9daa2..0866ad086 100644--- a/vercel.json+++ b/vercel.json@@ -5305,6 +5305,10 @@"src": "/api/auth/extension-token","dest": "/api/auth/extension-token.js"},+ {+ "src": "/api/auth/handoff",+ "dest": "/api/auth/handoff.js"+ },{"src": "/api/auth/([^/]+)","dest": "/api/auth/[action]?action=$1"