Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/DOCUMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ Each browser profile has its own Tailscale identity. Different profiles can use
### Identity & Configuration

- Create, switch, and delete multiple Tailscale profiles (identities).
- Point a profile at a self-hosted HTTP(S) control server such as Headscale. Changing servers signs the profile out and starts a new login on the new server.
- Point a profile at a self-hosted HTTP(S) control server such as Headscale. Changing servers starts a fresh login on the new server and keeps the previous account in Profiles. The previous server does not need to be reachable.
- Shields Up blocks all incoming connections.
- Run as Exit Node advertises this browser node as an exit node.
- Login and logout authenticate with Tailscale. Login URLs must match allowed origins.
Expand Down Expand Up @@ -237,7 +237,7 @@ interface StatusUpdate {

When `NeedsLogin` is active, the extension opens a validated `browseToURL` immediately when available. If the URL is missing and the helper advertises `supportsLogin`, the extension sends `login`, waits for a fresh `browseToURL` or `authURL`, validates the URL, and then opens it.

`set-prefs.prefs.controlURL` uses an empty string for Tailscale's default control plane and an HTTP(S) URL for a custom server. The helper validates the URL at the native-message boundary. A confirmed change clears server-scoped exit-node state, logs out the old identity, restarts with the new prefs, and requires a fresh login; failures attempt to restore the previous server.
`set-prefs.prefs.controlURL` uses an empty string for Tailscale's default control plane and an HTTP(S) URL for a custom server. The helper validates the URL and preferences before switching to an empty local profile. The new profile clears server-scoped exit-node state and requires a fresh login. The previous account remains in Profiles, and failures attempt to restore its identity and preferences. Switching does not require remote logout. Settings for the pending login survive a helper restart.

If a status payload would exceed the browser's 1 MiB native-message limit, the helper removes peers from the end until it fits and sets `peersTruncated` plus `totalPeers`. The popup displays a health warning instead of silently losing all status updates on very large tailnets.

Expand Down Expand Up @@ -381,6 +381,8 @@ The native host is a Go binary at `host/` using `tailscale.com/tsnet` pinned to
| `proxy.go` / `proxy_policy.go` | SOCKS5/HTTP multiplexing, authenticated destination policy, lazy quad-100 web client, and buffered CONNECT tunneling |
| `dns.go` / `exit_dns.go` | Restricted split-DNS forwarding and exit-node DNS behavior |
| `profiles.go` | Profile management through the current local-client snapshot |
| `saved_prefs.go` | Loads saved profile preferences before tsnet startup and persists settings for pending logins |
| `control_url.go` | Changes coordination servers using a fresh local profile, with rollback to the previous account |
| `taildrop.go` | Chunk reassembly, asynchronous cancellable `PushFile`, progress, and cleanup |
| `install.go` / `install_*.go` | Cross-platform native host installation and cleanup, including Chrome Flatpak sandbox state and registration |
| `peers.go` | Peer/status conversion from Tailscale types |
Expand All @@ -397,6 +399,8 @@ The native host is a Go binary at `host/` using `tailscale.com/tsnet` pinned to
5. **Host reads commands** in a loop from stdin, dispatches to handlers, and writes replies to stdout.
6. **On stdin EOF** (browser closed), the host cancels the watcher and active Taildrop transfers, closes the tsnet server, and exits cleanly.

Before starting tsnet, the host reads the selected account's saved preferences and supplies its coordination server, hostname, and advertised tags. It restores subnet-route acceptance, DNS, Shields Up, LAN access, SSH, and advertised routes before publishing the session to the proxy and status watcher. New browser profiles accept subnet routes by default. The extension supplies the startup connection intent and restores its selected exit node after the account is running. An unreadable preference record stops initialization instead of replacing the saved settings with defaults.

### Proxy Architecture

The proxy uses Tailscale's `proxymux.SplitSOCKSAndHTTP()` to multiplex a single listener:
Expand Down
88 changes: 88 additions & 0 deletions host/control_url.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package main

import (
"context"
"fmt"
"net/netip"
"time"

"tailscale.com/client/local"
"tailscale.com/ipn"
)

// switchControlURL starts a fresh local profile without requiring the previous
// control server to acknowledge logout. Keep the previous profile unchanged so
// a failed switch can restore its identity as well as its preferences.
func (h *Host) switchControlURL(lc *local.Client, partial partialPrefsUpdate) error {
finish := h.beginProxyProfileChange(lc)
defer finish()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

// Re-read after draining web mutations and stopping startup correction.
currentPrefs, err := lc.GetPrefs(ctx)
if err != nil {
return fmt.Errorf("failed to get current prefs: %w", err)
}
mp, changed, err := maskedPrefsForUpdate(partial, currentPrefs)
if err != nil {
return err
}
if !changed {
updated, err := lc.EditPrefs(ctx, mp)
if err != nil {
return fmt.Errorf("failed to set prefs: %w", err)
}
return h.savePendingProfilePrefs(lc, updated, false)
}
current, _, err := lc.ProfileStatus(ctx)
if err != nil {
return fmt.Errorf("failed to read current profile: %w", err)
}
updated := currentPrefs.Clone()
updated.ApplyEdits(mp)
updated.Persist = nil
updated.ProfileName = ""
updated.LoggedOut = false
updated.ExitNodeID = ""
updated.ExitNodeIP = netip.Addr{}
updated.AutoExitNode = ""
updated.InternalExitNodePrior = ""
if err := lc.CheckPrefs(ctx, updated); err != nil {
return fmt.Errorf("failed to set prefs: %w", err)
}

rollback := func(cause error) error {
rollbackCtx, rollbackCancel := context.WithTimeout(context.Background(), 30*time.Second)
defer rollbackCancel()
var restoreErr error
if current.ID != "" {
restoreErr = lc.SwitchProfile(rollbackCtx, current.ID)
} else {
restoreErr = lc.SwitchToEmptyProfile(rollbackCtx)
if restoreErr == nil {
restoreErr = h.savePendingProfilePrefs(lc, currentPrefs, true)
}
if restoreErr == nil {
restoreErr = lc.Start(rollbackCtx, ipn.Options{UpdatePrefs: currentPrefs})
}
}
if restoreErr != nil {
h.clearCachedStatus(nil)
return fmt.Errorf("failed to change control server: %w; also failed to restore previous profile: %v", cause, restoreErr)
}
h.clearCachedStatus(currentPrefs)
return fmt.Errorf("failed to change control server: %w; restored previous profile", cause)
}
if err := lc.SwitchToEmptyProfile(ctx); err != nil {
return rollback(err)
}
if err := h.savePendingProfilePrefs(lc, updated, true); err != nil {
return rollback(fmt.Errorf("failed to save pending profile: %w", err))
}
if err := lc.Start(ctx, ipn.Options{UpdatePrefs: updated}); err != nil {
return rollback(err)
}
h.clearCachedStatus(updated)
return nil
}
114 changes: 34 additions & 80 deletions host/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ type Host struct {

// proxyDial is a test seam; production leaves it nil and uses tsnet.
proxyDial func(context.Context, string, string) (net.Conn, error)

// stateDirForProfile is a test seam for exercising init with isolated state.
// Production leaves it nil and uses the normal per-browser state directory.
stateDirForProfile func(string) (string, error)
}

// newHost creates a new Host that reads from r and writes to w.
Expand Down Expand Up @@ -362,6 +366,7 @@ func (h *Host) handleRequestLocked(req Request) {
}
}

// startupPrefs supplies defaults only when the profile has no saved settings.
func startupPrefs() *ipn.MaskedPrefs {
return &ipn.MaskedPrefs{
Prefs: ipn.Prefs{
Expand Down Expand Up @@ -419,16 +424,17 @@ func (h *Host) handleInit(req Request) {
h.cancelTransfers()
h.clearCachedStatus(nil)

homeDir, err := os.UserHomeDir()
if err != nil {
h.send(Reply{
Cmd: "init",
Init: &InitReply{Error: fmt.Sprintf("failed to get home dir: %v", err)},
})
return
stateDirForProfile := h.stateDirForProfile
if stateDirForProfile == nil {
stateDirForProfile = func(initID string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to get home dir: %w", err)
}
return hostStateDir(homeDir, initID)
}
}

stateDir, err := hostStateDir(homeDir, req.InitID)
stateDir, err := stateDirForProfile(req.InitID)
if err != nil {
h.send(Reply{
Cmd: "init",
Expand All @@ -444,11 +450,10 @@ func (h *Host) handleInit(req Request) {
return
}

server := &tsnet.Server{
Dir: stateDir,
Hostname: "browser-ext",
RunWebClient: true,
Logf: log.Printf,
server, saved, err := newProfileServer(stateDir)
if err != nil {
h.send(Reply{Cmd: "init", Init: &InitReply{Error: err.Error()}})
return
}

if err := server.Start(); err != nil {
Expand All @@ -469,16 +474,15 @@ func (h *Host) handleInit(req Request) {
return
}

// tsnet does not accept subnet routes by default. Tailchrome's proxy rules
// are built from accepted PrimaryRoutes, so enable route acceptance before
// publishing the first status update.
// tsnet.Start resets preferences. Restore the saved settings before making
// the session available to the proxy or publishing its first status.
prefsCtx, prefsCancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err = lc.EditPrefs(prefsCtx, startupPrefs())
_, err = lc.EditPrefs(prefsCtx, restoredStartupPrefs(saved))
prefsCancel()
if err != nil {
h.send(Reply{
Cmd: "init",
Init: &InitReply{Error: fmt.Sprintf("failed to accept subnet routes: %v", err)},
Init: &InitReply{Error: fmt.Sprintf("failed to apply startup prefs: %v", err)},
})
server.Close()
return
Expand Down Expand Up @@ -945,72 +949,22 @@ func (h *Host) handleSetPrefs(req Request) {
h.cancelStartupCorrection()
}
if controlURLChanged {
finishProfileChange := h.beginProxyProfileChange(lc)
defer finishProfileChange()
}

updatedPrefs, err := lc.EditPrefs(ctx, mp)
if err != nil {
h.sendError("set-prefs", fmt.Sprintf("failed to set prefs: %v", err))
return
}

if controlURLChanged {
// Exit-node selection and node identity are scoped to the previous
// tailnet; clear them so a now-invalid ExitNodeID (a StableNodeID from
// the old control server) isn't carried onto the new one.
updatedPrefs.ExitNodeID = ""
updatedPrefs.ExitNodeIP = netip.Addr{}

h.clearCachedStatus(updatedPrefs)

// Explicitly log out so the previous control plane's node key and
// profile identity are discarded. Without this, restarting with the
// new ControlURL would carry the old identity to the new server and
// the IPN engine could skip the interactive login prompt.
logoutCtx, logoutCancel := context.WithTimeout(context.Background(), 10*time.Second)
if err := lc.Logout(logoutCtx); err != nil {
logoutCancel()
log.Printf("logout during controlURL change failed, restoring previous URL: %v", err)

rollbackCtx, rollbackCancel := context.WithTimeout(context.Background(), 30*time.Second)
rollbackErr := lc.Start(rollbackCtx, ipn.Options{UpdatePrefs: currentPrefs})
rollbackCancel()
if rollbackErr != nil {
h.clearCachedStatus(currentPrefs)
h.sendError("set-prefs", fmt.Sprintf("failed to logout before changing control URL: %v; also failed to restore previous control URL: %v", err, rollbackErr))
return
}

h.clearCachedStatus(currentPrefs)
if err := h.switchControlURL(lc, partial); err != nil {
h.handleGetStatus()
h.sendError("set-prefs", fmt.Sprintf("failed to logout before changing control URL: %v; restored previous control URL", err))
h.sendError("set-prefs", err.Error())
return
}
logoutCancel()

restartCtx, restartCancel := context.WithTimeout(context.Background(), 30*time.Second)
if err := lc.Start(restartCtx, ipn.Options{UpdatePrefs: updatedPrefs}); err != nil {
restartCancel()
log.Printf("restart with updated control URL failed, restoring previous URL: %v", err)

rollbackCtx, rollbackCancel := context.WithTimeout(context.Background(), 30*time.Second)
rollbackErr := lc.Start(rollbackCtx, ipn.Options{UpdatePrefs: currentPrefs})
rollbackCancel()
if rollbackErr != nil {
h.clearCachedStatus(currentPrefs)
h.sendError("set-prefs", fmt.Sprintf("failed to restart with updated control URL: %v; also failed to restore previous control URL: %v", err, rollbackErr))
return
}

h.clearCachedStatus(currentPrefs)
h.handleGetStatus()
// The logout above already discarded the previous session, so the
// prefs are restored but the node is signed out and must log in again.
h.sendError("set-prefs", fmt.Sprintf("failed to switch control server: %v; reverted to your previous server, but you have been signed out and must log in again", err))
h.handleListProfiles()
} else {
updatedPrefs, err := lc.EditPrefs(ctx, mp)
if err != nil {
h.sendError("set-prefs", fmt.Sprintf("failed to set prefs: %v", err))
return
}
if err := h.savePendingProfilePrefs(lc, updatedPrefs, false); err != nil {
h.sendError("set-prefs", fmt.Sprintf("failed to save pending profile: %v", err))
return
}
restartCancel()
}

h.handleGetStatus()
Expand Down
Loading
Loading