Skip to content
Closed
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
3 changes: 2 additions & 1 deletion docs/DOCUMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,7 @@ 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` | Reads a profile's saved prefs before tsnet start and builds the restore edit |
| `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 @@ -392,7 +393,7 @@ The native host is a Go binary at `host/` using `tailscale.com/tsnet` pinned to

1. **Browser launches the host** via native messaging (stdin/stdout). Not a terminal -- goes directly to messaging mode.
2. **Proxy starts** on `127.0.0.1:0`. The port is sent back to the extension via `procRunning`.
3. **Extension sends `init`** with a profile identifier restricted to 1-64 ASCII letters, numbers, underscores, or hyphens. Host creates a `tsnet.Server` at `~/.config/tailscale-browser-ext/<ID>/` and atomically installs it as the current session.
3. **Extension sends `init`** with a profile identifier restricted to 1-64 ASCII letters, numbers, underscores, or hyphens. Host creates a `tsnet.Server` at `~/.config/tailscale-browser-ext/<ID>/` and atomically installs it as the current session. `tsnet.Server.Start` resets the profile's prefs to its defaults, so the host reads the saved prefs first: the coordination server and hostname are passed into tsnet, and subnet-route acceptance, DNS, Shields Up, LAN access, SSH, and advertised routes are reapplied after start. The extension restores its selected exit node, and new profiles accept subnet routes by default.
4. **IPN bus watcher** monitors state, prefs, netmap, browse-to-URL, and health changes. Errors trigger bounded exponential retries; each change schedules a debounced full `StatusUpdate` from the same session snapshot.
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.
Expand Down
52 changes: 43 additions & 9 deletions host/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/netip"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
Expand All @@ -20,6 +21,7 @@ import (
"tailscale.com/client/local"
"tailscale.com/ipn"
"tailscale.com/ipn/ipnstate"
"tailscale.com/ipn/store"
"tailscale.com/tailcfg"
"tailscale.com/tsnet"
"tailscale.com/types/netmap"
Expand Down Expand Up @@ -362,6 +364,9 @@ func (h *Host) handleRequestLocked(req Request) {
}
}

// startupPrefs are applied to a profile with no saved prefs. tsnet does not
// accept subnet routes by default, but Tailchrome's proxy rules are built from
// accepted PrimaryRoutes, so new profiles enable route acceptance.
func startupPrefs() *ipn.MaskedPrefs {
return &ipn.MaskedPrefs{
Prefs: ipn.Prefs{
Expand All @@ -371,6 +376,30 @@ func startupPrefs() *ipn.MaskedPrefs {
}
}

// newProfileServer prepares the tsnet.Server for a browser profile's state
// directory. It opens the state store the way tsnet would and reads the saved
// prefs first, because Start overwrites them (#153). An unreadable prefs entry
// is logged and treated as a new profile rather than blocking startup.
func newProfileServer(stateDir string) (*tsnet.Server, *ipn.Prefs, error) {
st, err := store.New(log.Printf, filepath.Join(stateDir, "tailscaled.state"))
if err != nil {
return nil, nil, fmt.Errorf("failed to open state: %v", err)
}
saved, err := loadSavedProfilePrefs(st)
if err != nil {
log.Printf("ignoring saved prefs: %v", err)
saved = nil
}
return &tsnet.Server{
Dir: stateDir,
Store: st,
Hostname: savedHostname(saved),
ControlURL: savedControlURL(saved),
RunWebClient: true,
Logf: log.Printf,
}, saved, nil
}

// handleInit initializes (or reuses) a tsnet.Server for the given browser profile.
func (h *Host) handleInit(req Request) {
if !validInitID.MatchString(req.InitID) {
Expand Down Expand Up @@ -444,11 +473,13 @@ 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,11 +500,14 @@ 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.Server.Start reset the profile's prefs to its defaults. Reapply
// what was saved before publishing the first status update (#153).
prefsCtx, prefsCancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err = lc.EditPrefs(prefsCtx, startupPrefs())
_, err = lc.EditPrefs(prefsCtx, restoredStartupPrefs(saved))
if err != nil && saved != nil {
log.Printf("restoring saved prefs failed, using startup defaults: %v", err)
_, err = lc.EditPrefs(prefsCtx, startupPrefs())
}
prefsCancel()
if err != nil {
h.send(Reply{
Expand Down
122 changes: 122 additions & 0 deletions host/saved_prefs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package main

import (
"encoding/json"
"errors"
"fmt"

"tailscale.com/ipn"
)

// loadSavedProfilePrefs returns the prefs saved for the profile the node will
// start on, or nil when that profile has none yet. tsnet.Server.Start replaces
// the stored prefs with its defaults on every launch, keeping only the node
// identity, so they must be read before Start and reapplied after it (#153).
//
// The starting profile is the one named by the current-profile key, provided
// it is still a known profile; LocalBackend falls back to a new, empty profile
// otherwise, and so does this function.
func loadSavedProfilePrefs(st ipn.StateStore) (*ipn.Prefs, error) {
current, err := st.ReadState(ipn.CurrentProfileStateKey)
if errors.Is(err, ipn.ErrStateNotExist) || len(current) == 0 {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("reading current profile: %w", err)
}
profileKey := ipn.StateKey(current)

knownRaw, err := st.ReadState(ipn.KnownProfilesStateKey)
if errors.Is(err, ipn.ErrStateNotExist) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("reading known profiles: %w", err)
}
var known map[ipn.ProfileID]struct {
Key ipn.StateKey
}
if err := json.Unmarshal(knownRaw, &known); err != nil {
return nil, fmt.Errorf("parsing known profiles: %w", err)
}
found := false
for _, profile := range known {
if profile.Key == profileKey {
found = true
break
}
}
if !found {
return nil, nil
}

raw, err := st.ReadState(profileKey)
if errors.Is(err, ipn.ErrStateNotExist) || len(raw) == 0 {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("reading saved prefs: %w", err)
}
// Drop the node identity ("Config"). tsnet keeps it on its own, and its
// hardware attestation key cannot be decoded without the platform TPM.
var fields map[string]json.RawMessage
if err := json.Unmarshal(raw, &fields); err != nil {
return nil, fmt.Errorf("parsing saved prefs: %w", err)
}
delete(fields, "Config")
stripped, err := json.Marshal(fields)
if err != nil {
return nil, err
}
prefs := ipn.NewPrefs()
if err := json.Unmarshal(stripped, prefs); err != nil {
return nil, fmt.Errorf("parsing saved prefs: %w", err)
}
return prefs, nil
}

// savedHostname returns the hostname tsnet should start with.
func savedHostname(saved *ipn.Prefs) string {
if saved != nil && saved.Hostname != "" {
return saved.Hostname
}
return "browser-ext"
}

// savedControlURL returns a custom coordination server saved for the profile,
// or "" to let tsnet choose (TS_CONTROL_URL or the Tailscale default). It must
// reach tsnet before Start: once started on the wrong server, the node would
// present its identity there.
func savedControlURL(saved *ipn.Prefs) string {
if saved == nil {
return ""
}
return controlURLForPrefs(saved.ControlURL)
}

// restoredStartupPrefs reapplies the settings the extension can change that
// tsnet.Server.Start reset. Hostname and ControlURL go to tsnet directly,
// WantRunning follows the init request, and the extension restores its
// selected exit node itself. A profile with no saved prefs gets the defaults
// from startupPrefs.
func restoredStartupPrefs(saved *ipn.Prefs) *ipn.MaskedPrefs {
if saved == nil {
return startupPrefs()
}
return &ipn.MaskedPrefs{
Prefs: ipn.Prefs{
RouteAll: saved.RouteAll,
ExitNodeAllowLANAccess: saved.ExitNodeAllowLANAccess,
CorpDNS: saved.CorpDNS,
ShieldsUp: saved.ShieldsUp,
RunSSH: saved.RunSSH,
AdvertiseRoutes: saved.AdvertiseRoutes,
},
RouteAllSet: true,
ExitNodeAllowLANAccessSet: true,
CorpDNSSet: true,
ShieldsUpSet: true,
RunSSHSet: true,
AdvertiseRoutesSet: true,
}
}
Loading
Loading