Skip to content

Serve the iPhone's Funnel and Cloudflare Tunnel modes from the Mac - #371

Closed
oliverames wants to merge 61 commits into
mattt:mainfrom
oliverames:feat/ios-funnel-cloudflare-modes
Closed

oliverames wants to merge 61 commits into
mattt:mainfrom
oliverames:feat/ios-funnel-cloudflare-modes

Conversation

@oliverames

@oliverames oliverames commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Stack. Stacked on #370, and it also needs #308 and the Funnel, OAuth and Cloudflare Tunnel work in #352, so the diff shows those commits as well. Review only the three commits at the end. It cannot merge before #308 and #352; it is tracked in #364. I am keeping it open for review so you can see where #369's Funnel and Cloudflare modes get their Mac side.

What it does and why

#369 lets the iPhone choose Funnel or Cloudflare Tunnel, but the Mac has nothing listening for them, so those modes report "isn't available". This connects the two.

What changed

  • When a public host starts, changes or stops, the Mac publishes the wss://…/mobile URLs for Funnel and Cloudflare to MobileService.updateRemoteEndpoints, so pairing codes and the welcome carry them.
  • A GET /mobile on an active public host with upgrade headers and no Origin header gets a 101 and goes to acceptWebSocket, with the mode taken from the Host header.
  • The path is kept apart from everything else. The check runs before the token and OAuth checks, so a bearer token or OAuth token does nothing at /mobile, every other request for it returns 404, and no MCP session is created for it. acceptWebSocket does the device-key handshake, so an unpaired phone is refused and a silent one is dropped after the hello timeout. The existing public connection cap (16) and 15-second request deadline still apply.

Testing

  • imcp-serverTests, full suite: 375 tests, 1 skipped, 0 failures. MobilePublicRoutingTests has 9 new tests: publishing and clearing the addresses, host-to-mode routing, and refusals for a wrong host, a loopback host, an Origin header, no upgrade, a bearer token and a POST, with /mcp and OAuth still answering. Over a real loopback listener with a real MobileService, an unpaired device is refused and disconnected, a wrong key is refused, a paired device gets an accepted welcome, and a silent phone is dropped.
  • macOS and iOS targets build.
  • CI: the macOS 27 build (Xcode 27.1) passes on this branch.
  • On a device: the Cloudflare route worked from my iPhone in my integration build, which has this wiring (TestFlight builds 30, 31 and 32, uploaded and VALID). That build is not this branch, which sits on Serve MCP over HTTP to your other devices on Tailscale #308 and feat: Remote Access via Tailscale Funnel & Cloudflare Tunnel with OAuth 2.1 #352 as they are in this stack.

Not verified

This is out of draft with these gaps stated:

  • A real Funnel tunnel and a real Tailscale connection through this branch.
  • A full encrypted session through a public host in this branch; only the welcome was checked in the tests.
  • One earlier full test run had 3 failures in MobileLinkTests (an "Address already in use" and two JSON decode errors) that did not repeat in 3 isolated runs and 2 full runs. I haven't found the cause.

Decisions to check

  • The Mac doesn't advertise its tailnet MagicDNS name, because Serve MCP over HTTP to your other devices on Tailscale #308's embedded node runs in userspace and nothing on it listens for the mobile port. The Tailscale route keeps using the Mac's own Tailscale address.
  • updateRemoteEndpoints gained an optional cloudflareURL; a URL typed in Settings still wins.
  • A link already upgraded through a public host stays open until it drops, even if remote access stops.

mattt added 30 commits October 26, 2026 11:21
Clients on another device in the owner's tailnet can now use iMCP
while the Mac keeps the data, permissions, and tool settings.
iMCP listens on the Mac's tailnet address, accepts only untagged devices
that belong to the Mac's Tailscale user, and requires a named access token
on every request. Settings creates, edits, re-rolls, and deletes tokens,
and a token can never use a service or tool that is off in iMCP.
Remote sessions pass a pre-approved ConnectionApprovalGate, because a valid access token takes the place of the approval dialog. The remote access test file moves to Tests/imcp-serverTests with the other tests.
Link TailscaleKit 0.2.0-imcp.1 from mattt/libtailscale into the app target, which embeds it like Sparkle. The framework is arm64-only and requires macOS 15.6, so the app target now builds only for arm64 with a deployment target of 15.6, and the app no longer runs on Intel Macs. The CLI, the helper, and the tests don't link the framework and keep their settings.
A sandboxed iMCP can't run the Tailscale command-line tool, and a listener on the Mac's shared tailnet address can be taken over by another local process. iMCP now runs an embedded Tailscale node with its own identity and address, and listens only on that address.

The node keeps its state in the app's container and runs only while remote access is on. Settings shows the login link, the node's state, MagicDNS name, and tailnet address, and lets the owner log in with an auth key, rename the device, and log out.

For each connection, the server asks the node who the peer is, and accepts only untagged devices of the node's own user. Access tokens, their permissions, and their binding to one device stay the same. The HTTP server reads and writes TailscaleKit connections, and runs their blocking calls on their own threads.

The node is behind a small protocol, so the tests use a fake node to check authorization, Host and Origin validation, and the login states.
The README no longer asks for the Tailscale app on the Mac. It describes the login, auth keys, and logout, and says that WireGuard encrypts the plain HTTP traffic and that the node's address belongs only to iMCP. The download requirements now say macOS 15.6 on Apple silicon.
Link TailscaleKit 0.2.0-imcp.2 from mattt/libtailscale, which is universal (arm64 and x86_64) and requires macOS 15.1. The app target builds for the default architectures again, with a deployment target of macOS 15.1, as on main, and the README's download requirement is macOS 15.3 again. A later TailscaleKit release will drop the x86_64 slice.
TailscaleKit contains only a Swift interface that Swift 6.4 generated, so the app needs Xcode 27.1 or later. Of the GitHub-hosted images, only xcode-27 has Xcode 27.1; macos-26 stops at Xcode 26.6. CI now builds with Xcode 27.1 on xcode-27 and drops the Xcode 26.0 and 27.0 entries, which can't build the framework. The release workflow also moves from Xcode 26.0 on macos-26 to Xcode 27.1 on xcode-27.
…ailscalekit

# Conflicts:
#	App/Controllers/ServerController.swift
#	iMCP.xcodeproj/project.pbxproj
Define the Health, Finance, and Alarms tools once in Shared/Companion,
store what the iPhone sends in an encrypted SQLite cache,
and answer read-only calls from that cache with synced_at and stale.
Generalize HomeInput into ToolInput so both services validate arguments.
The iPhone app dials the Mac over TLS with pre-shared keys,
pairs with a one-time code from a QR code in Settings > Companion,
and serves the companion tools as an MCP server on that connection.
The Mac calls tools live when the phone is connected,
retries a lost read or an alarm change that carries its ID,
and pulls queued changes from the phone's outbox into its cache.
Scripts/install-companion.sh builds and installs the app with your team.
Answer the Health tools live from HealthKit,
let the user allow each group of types from the app,
and queue anchored changes for the Mac: daily statistics for quantity types
and full records for sleep, workouts, and health records.
When HealthKit is locked, the Mac answers reads from its cache.
Create one-time, weekly, and countdown alarms with the ID the Mac sends,
so a retried call returns the existing alarm instead of a second one.
A widget extension shows a running timer as a Live Activity with a stop button,
the app lists the alarms that AI apps created and cancels them,
and the phone sends its alarm list to the Mac whenever AlarmKit reports a change.
Answer the Finance tools live and queue account, balance, and transaction
changes for the Mac with FinanceKit history tokens.
A background delivery extension queues changes while the app isn't running.
The code stays inactive until a build carries the FinanceKit entitlement,
which Scripts/install-companion.sh --finance requests;
without it, the Finance tools say why they're unavailable.
Add Alarms, Finance, and Health to the README and its hero image,
describe how to install, pair, and use the companion,
add Scripts/check-companion.py for read-only checks through imcp-server,
and build the companion unsigned in CI.
When the iPhone drops a connection, disconnect the Mac's MCP client,
so pending calls fail over to the cache and syncing resumes on the next connection.
Keep lines that arrive before MCP reads them, end a closed channel's stream
with an error, and enforce read and open time limits.
Reject outbox writes from a sync that a cache reset overtook, run each
service's sync one at a time, and give the FinanceKit reason in cached answers.
The Mac used to send the device key inside the pairing session,
so anyone with the QR secret who recorded that session could recover it.
Now each side sends a one-time X25519 public key, both derive the device key
from the shared secret salted with the pairing key, and each side's proof
covers the public keys so neither can be swapped.
The iOS app is now iMCP on the device and builds for iPhone and iPad.
Targets, folders, and shared code use iOS and Mobile names,
the Mac's Settings pane is iPhone & iPad,
and the Bonjour type, pairing link, and status tool drop the companion name.
The name no longer collides with the separate Companion debugging app
that the README describes.
The macOS 26 runner's Xcode 26.0 has no iOS platform,
so the iOS app's build couldn't find a destination.
Download the platform when it's missing and allow time for the download.
AlarmKit shows its own stop control on the alarm alert,
so the app doesn't need an App Intent for it.
The timer Live Activity now shows the countdown without a stop button.
Oliver Ames added 21 commits November 16, 2026 18:13
…h address

Authorization requests get a 6-character confirmation code shown on the waiting page and in the approval request, plus a 256-bit poll secret in an HttpOnly, Secure, SameSite=Lax cookie. Only a poll with the cookie can get the code redirect. The approval shows the full client ID and redirect URI.

The Client ID metadata fetch resolves once, checks every address, and connects to the checked address with Network.framework, using the hostname for SNI and certificate verification. It also blocks 64:ff9b::/96, 64:ff9b:1::/48, 2002::/16, fec0::/10 and ::/96.
URL.path and URL.query decode %0D%0A into a line break, so a client ID
URL could inject headers into the pinned HTTP/1.0 request. Use the
encoded forms and refuse any target byte outside printable ASCII.
The phone can dial the Mac from two places at once (the foreground loop and a
background flush). Replacing the live link cancelled the sync in progress and
started the same race again. attach() now keeps the current link for the same
device while it answers a status call within a short time, and replaces it
when it doesn't. A cancelled sync is logged at debug instead of as an error.
The foreground loop, a background flush, and pull to refresh each dialed the
Mac on their own, and the Mac treats two connections from one device as a
conflict. They now join a single dial, and the channel is served by one task
that the loop waits on. Pull to refresh reuses the open connection, retries the
dial now instead of waiting out the backoff, and returns within eight seconds
whatever the Mac or HealthKit is doing. The retry delay tops out at ten seconds,
and the status shows when the phone last connected.
…e phone

Every tool call a client makes (succeeded, failed, or denied) is recorded with
the client, service, tool, whether it writes, and how long it took. The Mac
keeps the last 500 in Application Support, tracks what each paired device has
acknowledged, and pushes the rest over the existing link with a new
activity_sync call. The store opens from disk, so events recorded before a
relaunch reach the phone, and activity syncs before the pull so a short
connection still delivers it.
The phone accepts activity_sync, keeps the events in its own Application Support
folder, and lists them under Activity with a filter for reads, writes, and
denied or failed calls, search by client, service, or tool, and Clear. Unpairing
removes the history, because the next Mac numbers its events again.
iOS kills an app with 0xdead10cc when it is suspended while holding a
SQLite lock on a file in a shared container, and background syncs can be
suspended mid-write. Only the app reads the outbox (the widget extension
reads nothing from the group), so the database now lives in the app's own
Application Support directory. An outbox left in the group container by an
earlier build is checkpointed and moved with its queued batches and
HealthKit anchors. Preferences stay in the group's UserDefaults.
HealthKit wakes and alarm updates synced without an assertion, so iOS
could suspend the app while a sync held the outbox. Every sync, pull, and
acknowledgement now runs inside BackgroundWork, which begins a UIKit
background task and cancels the work if iOS expires it. The outbox
checks for cancellation at the start of its write transaction and rolls
back, so no transaction is open across a suspension.
The pairing code and the Mac's welcome now carry optional Tailscale,
Funnel, and Cloudflare Tunnel endpoints, and MobileTransportMode names
the routes a phone may use. Over a WebSocket, the phone and the Mac agree
a key with X25519, derive directional keys with HKDF<SHA256>, and frame
every message with ChaChaPoly under strictly increasing counters, so a
tunnel only ever sees ciphertext. The Mac advertises its own Tailscale
address and the port its TLS listener last used, takes a typed host
override, and can run a loopback WebSocket listener for a tunnel to
forward to. The advertising hooks for Funnel and for a host that remote
access knows are in place but nothing calls them yet.
The phone saves the routes from the pairing code and the Mac's welcome,
tries them in order, and gives every route but the last a six second
budget so a dead route can't use up the time the next one needs. A mode
that the Mac offered no route for fails with a message that says so
instead of a vague timeout.
The status screen shows which route carries the connection, and a new
Connection Mode screen lists every route. A route that the Mac hasn't
offered an address for is marked unavailable, with the reason, instead
of being left to time out. The addresses the Mac gave the phone can be
edited there.
Settings shows which route a connected device uses, lets the person limit
the Mac to the local network, turn off Tailscale VPN, type a Tailscale
host, and set up a Cloudflare Tunnel address and the local port the Mac
listens on for it.
Remote access publishes its public WebSocket addresses to the iPhone link
and clears them when the hosts go away. A WebSocket upgrade at /mobile on an
active public host goes to MobileService.acceptWebSocket with the mode of its
host, before and apart from the token and OAuth checks. Every other request
for /mobile answers 404.
@oliverames

Copy link
Copy Markdown
Contributor Author

Replaced by #386, the same change cut as one PR so it can merge on its own.

@oliverames oliverames closed this Nov 18, 2026
@oliverames
oliverames deleted the feat/ios-funnel-cloudflare-modes branch November 18, 2026 21:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants