package http import ( "context" "encoding/json" "fmt" "log" "mime" "net" "net/http" "net/url" "os" "path" "path/filepath" "strings" "sync" "sync/atomic" "github.com/sainteye/clawdline/internal/adapters/devices" "github.com/sainteye/clawdline/internal/adapters/nextconfig" "github.com/sainteye/clawdline/internal/config" "github.com/sainteye/clawdline/internal/contract" "github.com/sainteye/clawdline/internal/domain/auth" "github.com/sainteye/clawdline/internal/domain/capacity" "github.com/sainteye/clawdline/internal/productcopy" ) // The gate is in front of every route, and it is the Swift app's // RemoteServer.dispatch preamble: the two refusals about who is allowed to be // asking at all, then a token for everything that is not on the open list, // then, for anything that changes something, the Origin check, the capability // it needs, and the body's type. // // The change checks are stricter than the Swift app's, which compares only // the Origin's host. A browser keeps one cookie per host whatever the port, so // a page on any other 127.0.0.1 port was "our page" there, and its plain-text // form post carried this daemon's cookie into a board write. Here: // // - An Origin must be this request's own origin: scheme, host and port. // - A change carried by the cookie must say where it came from — an Origin, // and a Sec-Fetch-Site of same-origin when there is one. The cookie is sent // whether or not the page asking wanted it sent; a header token is not. // - A change's body is JSON or nothing. A page elsewhere can post a form or // plain text without asking; it cannot send application/json without the // browser first asking this daemon, which does not answer yes. // // There is no exception for loopback. Through Tailscale Serve every request // comes from 127.0.0.1, and a web page the person is visiting can reach a local port // too — with a DNS rebinding, as same-origin. const ( // sessionCookie is this daemon's cookie. Not `clawdline`, which is the // Swift app's: a browser keeps one cookie per name per host whatever the // port, so sharing the name would have each app overwrite the other's and // sign the person out of whichever they used last. sessionCookie = "clawdline-next" // machineHeader carries the orchestrator credential, as in the Swift app. machineHeader = "X-Clawdline-Orchestrator" // actorHeader is a request saying it must not be judged as this machine's // orchestrator, whatever credential it happens to carry, and actorDevice // is its one value. // // **It can only take authority away.** A request that names it is judged // by its device credential alone; it cannot name a device, a capability or // a sender, so a caller that sets it can reach nothing it could not reach // without it and loses every route the machine door opens. That is why the // gate honours it from anybody, which a credential-shaped header could // never be. // // It exists because this daemon answers a Cloud viewer through its own // routes in process, stamped with this machine's own credentials // (internal/transport/cloud's `LocalAuthorizer`), and some of those routes // ask *which door* the caller came in by and give a narrower answer to the // machine than to a person. The Swift app has no such header because it // has no such problem: a verified Cloud request is a source of its own // there, with `read` and `send` and no orchestrator credential // (`RemoteServer.permission(for:)`). This is the same sentence, said where // this port can say it. See internal/app/cloudops. // // **This machine has two credentials that mean "me", and the header closes // both.** The orchestrator token opens `/v1/orchestrator/*`; the local // token is the one the shell and this daemon's own scripts hold, and a // verdict for it says `Local`. A route that exempts `Local` is exempting // this machine's own hand — `/v1/push/unsubscribe` lets it remove any // device's subscription, which is how a script cleans up after itself, and // `/v1/settings` lets it change a global keyboard grab. An in-process // Cloud request carries the local token by construction, so closing only // the orchestrator door would have left a person on their phone wearing // the script's exemption. Neither door is one a person needs, and taking // both away is the whole of what this header may do. actorHeader = "X-Clawdline-Actor" actorDevice = "device" ) // judgedAsDevice is whether this request asked not to be the machine. func judgedAsDevice(r *http.Request) bool { return strings.EqualFold(strings.TrimSpace(r.Header.Get(actorHeader)), actorDevice) } // notThisMachine is the verdict as a request that named an actor is judged by: // the same device, the same capabilities, and not this machine. It only ever // removes: a verdict that was not `Local` comes back unchanged. // // The capabilities stay as they are, deliberately. An in-process Cloud request // carries this machine's own token, so a Cloud viewer keeps read, send and // Admin; Admin is what lets it manage the board (boardViewer), which a device // paired on this machine's own network may not. func notThisMachine(v auth.Verdict) auth.Verdict { v.Local = false return v } // gate holds what the checks read. One per state directory per process, // because the authority behind it is the only writer of that directory's // device file. type gate struct { files *devices.Files auth *auth.Authority // err is why the gate could not open. Every route behind it is then // refused; an unreadable device file is never an empty one. err error // tailscale is `tailscale_hostname` while `remote` is on, and "" while it // is off or the name is unset: the address Tailscale Serve proxies to // this daemon's loopback port. Serve keeps running whatever this daemon // says, so the switch is enforced here, on every request, and not by // stopping anything. It is read when the gate opens and again on every // settings write that touches either key. tailscale atomic.Pointer[string] port int // dir is the state directory used by the gate and local adapters. dir string machineWarned sync.Once } var ( gates sync.Map // dir -> *gate gateMu sync.Mutex ) func (s *Server) gate() *gate { if g, ok := gates.Load(s.cfg.Dir); ok { return g.(*gate) } gateMu.Lock() defer gateMu.Unlock() if g, ok := gates.Load(s.cfg.Dir); ok { return g.(*gate) } g := openGate(s.cfg) gates.Store(s.cfg.Dir, g) return g } // AuthReady opens the gate and says whether it opened. The daemon asks before // it listens, so a device file that cannot be read stops it at startup rather // than answering every request with a refusal. func (s *Server) AuthReady() error { return s.gate().err } // swiftDirs is the retired Swift app's directory, spelled as the fixed path // that app always used. Nothing under it is opened, read or accepted here. func swiftDirs() []string { home, err := os.UserHomeDir() if err != nil { return nil } return []string{filepath.Join(home, ".config", "clawdline")} } func openGate(cfg config.Config) *gate { g := &gate{port: cfg.Port, dir: cfg.Dir} files, err := devices.Open(cfg.Dir, swiftDirs()...) if err != nil { g.err = fmt.Errorf("the device store at %s could not be opened: %w", cfg.Dir, err) log.Printf("auth: %v", g.err) return g } g.files = files // The audit rotates at the capacity register's `audit.security` size, and // the device list refuses an addition at its `devices.list` limit. files.SetAuditLimit(CapacityLimit(capacity.AuditSecurity)) files.SetDeviceLimit(CapacityLimit(capacity.DevicesList)) a, err := auth.New(files, auth.Options{}) if err != nil { g.err = fmt.Errorf("the device store at %s could not be read: %w", cfg.Dir, err) log.Printf("auth: %v", g.err) return g } // This machine's own token exists from the moment the daemon starts, so a // script or the shell finds a key already there rather than a 401. if _, err := a.LocalToken(); err != nil { g.err = fmt.Errorf("the local token could not be written: %w", err) log.Printf("auth: %v", g.err) return g } g.auth = a if _, err := files.MachineToken(); err != nil { g.machineWarned.Do(func() { log.Printf("auth: orchestrator token unusable, machine authentication is refused: %v", err) }) } if v, err := nextconfig.Open(cfg.Dir).Read(); err == nil { g.setTailscale(v) } // Paths only. Neither token is ever written to the log. log.Printf("auth: local token at %s, orchestrator token at %s, audit at %s", files.LocalTokenPath(), files.MachineTokenPath(), files.AuditPath()) return g } // setTailscale takes `tailscale_hostname` and `remote` from one reading of // the settings. The name admits requests only while remote access is on, and // a value that is not a Tailscale name admits nothing. func (g *gate) setTailscale(v nextconfig.Values) { h, _ := v.String("tailscale_hostname") remote, _ := v.Bool("remote") if !remote || !nextconfig.ValidTailscaleHostname(h) { h = "" } g.tailscale.Store(&h) } // tailscaleHostname is the Tailscale name the Host check accepts now, or "". func (g *gate) tailscaleHostname() string { if h := g.tailscale.Load(); h != nil { return *h } return "" } // viaTailscale is whether this request named the Tailscale address. Serve // connects from loopback with the Host the phone asked for, so the Host is // the only thing that tells it from a request made on this machine. It can // only narrow: a local caller who spells that Host is judged as a device. func (g *gate) viaTailscale(r *http.Request) bool { name := g.tailscaleHostname() return name != "" && hostOnly(r.Host) == name } // access is what the gate learned about a request, for the handlers behind it. type access struct { machine bool verdict auth.Verdict // gate is the gate that judged the request, so a handler that answers a // question about the door (health's `password`) asks the authority that // made this verdict and no other. gate *gate } type accessKey struct{} func accessOf(r *http.Request) access { a, _ := r.Context().Value(accessKey{}).(access) return a } // maySend is the Swift writeGate's capability half: a device that may type // into a session. The machine token is not a way round it, as it is not in the // Swift app — it opens the orchestrator's routes, not a session's. func maySend(r *http.Request) bool { v := accessOf(r).verdict return v.Allowed && v.Caps.Has(auth.Send) } // machineAuthed is whether the request carried this daemon's orchestrator // credential on a route that accepts it. func machineAuthed(r *http.Request) bool { return accessOf(r).machine } func (g *gate) wrap(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/v1/api-performance" { w.Header().Set("Cache-Control", "no-store") } // Before anything else, and before authentication: these are about // who is allowed to be asking at all, not about who they are. if msg := g.crossOriginRefusal(r); msg != "" { writeAuthRefusal(w, http.StatusForbidden, "forbidden", msg) return } // And before that again: a path that two readers can read as two // different routes is refused here, whoever is asking. See readable // path below — this is the clause the `%2F` bypass walked through. if !readablePath(r.URL.EscapedPath()) { writeAuthRefusal(w, http.StatusBadRequest, "bad_request", "Could not read that request") return } p := routePath(r) // This capability has its own constant-time bearer/HMAC verification. // Never convert it to a device grant or let a device cookie bypass it. if routineHookDeliveryRoute(r) { next.ServeHTTP(w, r) return } // A request through Tailscale Serve arrives from loopback like the // shell's own, and is a paired device's all the same: neither this // machine's local-token exemptions nor the orchestrator door apply. device := judgedAsDevice(r) || g.viaTailscale(r) machine := machineScoped(p) && !device && g.verifyMachine(r.Header.Get(machineHeader)) verdict := g.permission(r) if device { verdict = notThisMachine(verdict) } if !openPath(p) && !machine && !taskSecretRoute(r.Method, p) && !verdict.Allowed { if g.err != nil { writeAuthRefusal(w, http.StatusServiceUnavailable, "store_unavailable", "The device store could not be read, so nothing behind the gate is answered.") return } // A token this daemon does hold, on a route it does not open, is // not "missing or not this daemon's": saying so sent a session on // 2026-10-15 looking for a stale token file when the token was // fine and /v1/diagnostics simply takes a device's credential. if !device && g.verifyMachine(r.Header.Get(machineHeader)) { writeAuthRefusal(w, http.StatusForbidden, "forbidden", machineScopeMessage) return } writeAuthRefusal(w, http.StatusUnauthorized, "unauthorized", unauthorizedMessage) return } // Dispatch rules may include a person's private instructions. A paired // device's read token must not see them through a GET. if p == "/v1/settings/dispatch-policy" && !(verdict.Allowed && verdict.Local) { writeAuthRefusal(w, http.StatusForbidden, "forbidden", "Only this machine may read its dispatch policy.") return } // Reads are exempt from what follows: they are already gated by the // token, and a page elsewhere cannot read the answer. if isChange(r.Method) { if !fromThisPage(r) { writeAuthRefusal(w, http.StatusForbidden, "forbidden", "That request did not come from this page.") return } policyPath := p // The metadata exception applies only to the exact spelling that // will reach the Bot handler, never a mux normalization alias. if projectAssistantMetadataWrite(r.Method, p) && p != r.URL.EscapedPath() { policyPath = "" } if status, code, msg := writePolicy(r.Method, policyPath, machine, verdict); status != 0 { writeAuthRefusal(w, status, code, msg) return } if !gateEvidenceBody(r) && !jsonOrNothing(r) { writeAuthRefusal(w, http.StatusUnsupportedMediaType, "unsupported_media_type", "A change is sent as application/json.") return } } // The credential stops here. Nothing behind the gate needs it, and the // proxy behind it would otherwise hand this daemon's token to the Swift // app. stripCredentials(r) ctx := context.WithValue(r.Context(), accessKey{}, access{machine: machine, verdict: verdict, gate: g}) next.ServeHTTP(w, r.WithContext(ctx)) }) } // openPath is the list that needs no token, and each entry is on it for a // reason rather than for convenience: a person cannot sign in through a page // that will not load, cannot pair with a machine they cannot ask, and a // browser fetches its icon before it knows who anybody is. None of these // answers names a session, a repository, a path or a credential. // // `/assets/` and `/strings/` are this console's bundle, which Vite writes where // the Swift page keeps `/app/`: the same files for everybody, and the door has // to be drawn before anybody is let through it. func openPath(p string) bool { switch p { case "/", "/index.html", "/manifest.webmanifest", "/hero-orchestration.webp", "/v1/health", "/v1/strings", "/sw.js", "/favicon.ico": return true } for _, prefix := range []string{"/v1/auth/", "/app/", "/assets/", "/strings/"} { if strings.HasPrefix(p, prefix) { return true } } for _, prefix := range []string{"/splash-", "/icon-", "/project-"} { if strings.HasPrefix(p, prefix) && strings.HasSuffix(p, ".png") { return true } } return false } // machineScoped is where the orchestrator credential is accepted in place of a // device: the orchestrator's own routes, the board, the token ledger, the // project-place list a schedule write names, reusable text, and worktree reads. // `/v1/next/coordinator` is the one `/v1/next/` name left that the // orchestrator's credential opens; the shadows of the board and the schedules // are gone (D07). func machineScoped(p string) bool { if p == "/v1/tool-library" || p == "/v1/tool-library/prepare" { return true } if squadAgentPath(p) { return true } if parts := strings.Split(strings.TrimPrefix(p, "/v1/sessions/"), "/"); strings.HasPrefix(p, "/v1/sessions/") && len(parts) == 2 && parts[0] != "" && parts[1] == "outputs" { return true } if strings.HasPrefix(p, "/v1/orchestrator/") { return true } // The new board (work.go): a session reads it, and relays a person's // words to it under their run; the handler refuses a session's own. if strings.HasPrefix(p, "/v1/work/") { return true } // The token ledger (usage.go): a session reads its own bill, and every // route there only reads. if strings.HasPrefix(p, "/v1/usage/") { return true } // Things waiting to be verified (verify.go): a session reads them and // writes its notes on them through the CLI. if p == "/v1/verifications" || strings.HasPrefix(p, "/v1/verifications/") { return true } // The Playbook CLI lists and edits saved launch messages through the // same receipt-backed snippet handlers as the console. if p == "/v1/snippets" || strings.HasPrefix(p, "/v1/snippets/") { return true } // The browser bridge (browser.go): an agent's commands and the native // messaging host's poll. Each handler says which of machine and person it takes. if strings.HasPrefix(p, "/v1/browser/") { return true } // A Session's Ops documents: `clawdline ops` reads and resolves them. if p == "/v1/ops" || strings.HasPrefix(p, "/v1/ops/") { return true } switch p { case "/v1/doctor", "/v1/board", "/v1/next/coordinator", "/v1/places": return true case "/v1/devstacks": // `clawdline project devstack` verifies a Project's .devstack.json // (devstacks.go). The route only reads, answers GET alone and runs // none of a project's commands; the guide told agents to check it // while only a paired device could (2026-11-07). return true case "/v1/artifacts/images": // Storing a session's pictures is the orchestrator's (images.go); the // handler refuses a device, as the Swift app does. return true case "/v1/update", "/v1/update/fresh", "/v1/update/apply": // `clawdline update` on this machine reads its own daemon's answer, // and `--apply` asks it to install a release and follows the update // (update.go); a device needs send to apply. return true } if strings.HasPrefix(p, "/v1/projects/") { parts := strings.Split(strings.TrimPrefix(p, "/v1/projects/"), "/") // A Project's shared memory: a session of either assistant reads // and writes it through `clawdline memory` (project_memory.go). // A Project's Ops documents: `clawdline ops` adds links (ops_documents.go). return len(parts) >= 2 && (parts[1] == "worktrees" || parts[1] == "memory" || parts[1] == "memory-dream" || parts[1] == "memory-search" || parts[1] == "memory-groups" || parts[1] == "ops") } return false } // taskSecretRoute is where a child reports with its own task secret, which // the broker's handler checks (orchestrator.go). func taskSecretRoute(method, p string) bool { // A child's proposal (proposals.go): the handler authenticates the // secret, and records it for the child's root. if method == http.MethodPost && p == "/v1/orchestrator/proposals" { return true } if !strings.HasPrefix(p, "/v1/orchestrator/tasks/") { return false } switch method { case http.MethodPost: return strings.HasSuffix(p, "/complete") || strings.HasSuffix(p, "/notify") || strings.HasSuffix(p, "/landing") || strings.HasSuffix(p, "/progress") || strings.HasSuffix(p, "/accepted") || strings.HasSuffix(p, "/verification-note") || strings.HasSuffix(p, "/gate-evidence") || strings.HasSuffix(p, "/gate-result") case http.MethodGet: return strings.HasSuffix(p, "/inflight") } return false } // gateEvidenceBody is the one changing body that is intentionally not JSON: // its exact bytes are the evidence artifact and its Content-Type is persisted // in the receipt. The custom task-secret and metadata headers force a browser // preflight; the handler authenticates that secret before storing any bytes. func gateEvidenceBody(r *http.Request) bool { return r.Method == http.MethodPost && strings.HasPrefix(routePath(r), "/v1/orchestrator/tasks/") && strings.HasSuffix(routePath(r), "/gate-evidence") } // writePolicy is the capability each changing route needs, for the routes // whose handlers this gate does not own. Session actions check it themselves // (actions.go), as does dispatch (orchestrator.go), each with the Swift app's // sentence. func writePolicy(method, p string, machine bool, v auth.Verdict) (int, string, string) { if !isChange(method) { return 0, "", "" } send := v.Allowed && v.Caps.Has(auth.Send) if v.Allowed && !v.Local && !send && !machine && !strings.HasPrefix(p, "/v1/auth/") && p != "/v1/terminals" && !strings.HasPrefix(p, "/v1/terminals/") && p != "/v1/squad-packages/preview" && p != "/v1/squad-packages/export" && p != "/v1/push/subscribe" && p != "/v1/push/unsubscribe" && p != "/v1/push/test" && !projectAssistantMetadataWrite(method, p) { return http.StatusForbidden, "forbidden", "This device may read, and not send." } switch { case strings.HasPrefix(p, "/v1/cloud/peer/"): if !send { return http.StatusForbidden, "forbidden", "This device may read, and not send peer work." } case p == sessionBoardRoute: if !machine && !send { return http.StatusForbidden, "forbidden", "This device may read, and not change Session message boards." } case p == "/v1/orchestrator/schedules" || strings.HasPrefix(p, "/v1/orchestrator/schedules/"): // Two doors, as in the Swift app: a device that may send, or this // machine's orchestrator. if !machine && !send { return http.StatusForbidden, "forbidden", "This device may read, and not send." } case p == "/v1/orchestrator/schedule-webhooks/bind": // The Cloud bind command's local half, the same two doors: the hosted // console binds a hook as a device that may send. if !machine && !send { return http.StatusForbidden, "forbidden", "This device may read, and not send." } case p == "/v1/board": if !machine && !send { return http.StatusForbidden, "forbidden", "This device may only read the board." } case strings.HasPrefix(p, "/v1/work/"): if !machine && !send { return http.StatusForbidden, "forbidden", "This device may only read the board." } case p == "/v1/verifications" || strings.HasPrefix(p, "/v1/verifications/"): if !machine && !send { return http.StatusForbidden, "forbidden", "This device may read the verifications, and not change them." } case p == "/v1/next/coordinator": if !machine { return http.StatusForbidden, "forbidden", "Moving the machine coordinator needs the orchestrator token." } case p == "/v1/update/apply": // Installing a release restarts this daemon: this machine's token, // or a device that may send (update.go checks it again). if !machine && !send { return http.StatusForbidden, "forbidden", "This device may read, and not send." } case p == "/v1/settings" || p == "/v1/settings/project-assistants": // The Swift app has no such route: its settings are a native window. // Here they are the hotkey, a global keyboard grab, so only this // machine's own token changes them. if !(v.Allowed && v.Local) { return http.StatusForbidden, "forbidden", "Only this machine's own token may change its settings." } case p == "/v1/voice/setup": // This writes a large local model file. A paired reader or sender may // inspect readiness, but only the console on this machine may install it. if !(v.Allowed && v.Local) { return http.StatusForbidden, "forbidden", "Only this machine's own token may install its voice model." } case p == "/v1/settings/dispatch-policy": if !(v.Allowed && v.Local) { return http.StatusForbidden, "forbidden", "Only this machine may read or change its dispatch policy." } case p == "/v1/settings/browser": // The handler limits this route to controls shown by the local browser. // Cloud's carry table deliberately has no entry for it. if !(v.Allowed && (v.Local || send)) { return http.StatusForbidden, "forbidden", "This device may read, and not change machine settings." } case p == "/v1/notification-rules": if !(v.Allowed && (v.Local || send)) { return http.StatusForbidden, "forbidden", "This device may read, and not change notification rules." } case p == "/v1/settings/voice": // The voice cards' narrow route, carried to a paired phone so it can // turn dictation cleanup on and edit the vocabulary. A remote device // needs Send, as it does for the default models. if !(v.Allowed && (v.Local || v.Caps.Has(auth.Send))) { return http.StatusForbidden, "forbidden", "This device may read, and not change voice settings." } case p == "/v1/settings/copilot": // The voice copilot's settings, carried to a paired phone. Writing them // stores the OpenAI key; a remote device needs Send, as for voice. if !(v.Allowed && (v.Local || v.Caps.Has(auth.Send))) { return http.StatusForbidden, "forbidden", "This device may read, and not change the voice copilot settings." } case p == "/v1/voice/copilot-session" || p == "/v1/voice/copilot-live" || p == "/v1/voice/copilot-briefing" || p == "/v1/voice/copilot-decide" || p == "/v1/voice/copilot-recap" || p == "/v1/voice/copilot-question" || p == "/v1/voice/copilot-journal" || p == "/v1/voice/copilot-work": // Each starts work billed to the person: a client secret opens a // Realtime call on the machine's key, a GPT-Live start opens a Live session on it, a briefing runs an assistant turn, // a decision or a recap asks a text model on that key. if !(v.Allowed && (v.Local || v.Caps.Has(auth.Send))) { return http.StatusForbidden, "forbidden", "This device may not start a voice copilot call." } case p == "/v1/settings/default-models": // This narrow route is the Settings surface carried to a paired phone. // A local console may write it, and a remote device needs Send just as // every other Cloud command does. No other setting is accepted there. if !(v.Allowed && (v.Local || v.Caps.Has(auth.Send))) { return http.StatusForbidden, "forbidden", "This device may read, and not change default models." } case p == "/v1/settings/work-gates" || p == "/v1/settings/workflow" || p == "/v1/settings/integrations": // This narrow route exposes only the two future-assignment gate // defaults. A paired device needs Send to change them, as it does for // the other machine-wide controls carried to Settings. if !(v.Allowed && (v.Local || v.Caps.Has(auth.Send))) { return http.StatusForbidden, "forbidden", "This device may read, and not change work gates." } case p == "/v1/integrations/github" || p == "/v1/integrations/github/device" || p == "/v1/integrations/jira" || strings.HasPrefix(p, "/v1/issue-sync/"): // Connecting or forgetting this machine's GitHub authorization is the // person's act: this machine, or a paired device that may send. if !(v.Allowed && (v.Local || v.Caps.Has(auth.Send))) { return http.StatusForbidden, "forbidden", "This device may read, and not change the issue tracker connections." } case p == "/v1/settings/notifications": if !(v.Allowed && (v.Local || v.Caps.Has(auth.Send))) { return http.StatusForbidden, "forbidden", "This device may read, and not change notification preferences." } case p == "/v1/squad-packages/preview" || p == "/v1/squad-packages/export": // Preview grants and public exports leave catalog and settings unchanged. // The export handler separately requires Send for selected private scopes. if !v.Allowed { return http.StatusForbidden, "forbidden", "This device may not read squad packages." } case p == "/v1/tool-library" || p == "/v1/tool-library/prepare": if !machine && !(v.Allowed && (v.Local || v.Caps.Has(auth.Send))) { return http.StatusForbidden, "forbidden", "Saving or preparing a tool needs send permission." } case strings.HasPrefix(p, "/v1/squad-packages/") || strings.HasPrefix(p, "/v1/squad/"): if machine && squadAgentPath(p) { return 0, "", "" } if !(v.Allowed && (v.Local || v.Caps.Has(auth.Send))) { return http.StatusForbidden, "forbidden", "This device may read the squad, and not change it." } case p == "/v1/orchestrator/tasks" || strings.HasPrefix(p, "/v1/orchestrator/tasks/"): // dispatch.go, and the task-secret routes. case p == "/v1/orchestrator/proposals": // proposals.go: the orchestrator token, or a child's task secret, // which the handler checks. case strings.HasPrefix(p, "/v1/orchestrator/"): if !machine { return http.StatusForbidden, "forbidden", "That needs the orchestrator token." } } return 0, "", "" } // Only these two POSTs acknowledge this reader's own metadata. No suffix, // alternate method, encoded action, empty/dot ID or nested route inherits it. func projectAssistantMetadataWrite(method, p string) bool { if method != http.MethodPost || !strings.HasPrefix(p, "/v1/project-assistants/") { return false } parts := strings.Split(strings.TrimPrefix(p, "/v1/project-assistants/"), "/") return len(parts) == 2 && paHTTPSafeBotID(decodeSegment(parts[0])) && (parts[1] == "read" || parts[1] == "observed") } // crossOriginRefusal is the Host check and the Sec-Fetch-Site check, which // come before authentication because they are about a browser being made to // ask on somebody else's behalf. "" means neither applies. func (g *gate) crossOriginRefusal(r *http.Request) string { if isCrossSiteSubresource(r.Header) { return "Cross-site requests are not answered." } if !isAllowedHost(r.Host, g.tailscaleHostname()) { return "Wrong host." } return "" } // isCrossSiteSubresource is a cross-site request that is not somebody // following a link. Typing the address into a bar showing another page is // cross-site too, and says navigate/document, which a script's fetch cannot. // Absent headers mean it is not a browser, and the token is what it needs. func isCrossSiteSubresource(h http.Header) bool { if h.Get("Sec-Fetch-Site") != "cross-site" { return false } return !(h.Get("Sec-Fetch-Mode") == "navigate" && h.Get("Sec-Fetch-Dest") == "document") } // isAllowedHost is the DNS-rebinding defence: rebinding changes what a name // resolves to, never the Host header, so a Host this daemon does not answer // to is refused before anything else is looked at. Besides loopback the one // name is the Tailscale name, matched exactly, which is "" while remote access // is off. The Cloudflare tunnel's names went with it: `*.trycloudflare.com` on // 2026-10-19 and the named tunnel's `remote_hostname` on 2026-10-20. func isAllowedHost(header, tailscale string) bool { host := hostOnly(header) if host == "" { return false } switch host { case "127.0.0.1", "localhost", "::1": return true } return tailscale != "" && host == tailscale } // hostOnly is a Host header's name, lowercase, without its port or IPv6 // brackets; "" when the brackets do not close. func hostOnly(header string) string { host := strings.ToLower(strings.TrimSpace(header)) if strings.HasPrefix(host, "[") { end := strings.Index(host, "]") if end < 0 { return "" } return host[1:end] } if i := strings.LastIndex(host, ":"); i >= 0 { host = host[:i] } return host } // isChange is every method but the two that only read. func isChange(method string) bool { return method != http.MethodGet && method != http.MethodHead } // fromThisPage is the Origin half of a change. A request with an Origin must // have been sent by a page with this request's own origin. A request that // carries this daemon's cookie, and no header token, must have an Origin — // every browser sends one on a change — and a Sec-Fetch-Site, when it has one, // of same-origin. A script with a header token needs neither: a page elsewhere // cannot add that header without asking first. func fromThisPage(r *http.Request) bool { origin := r.Header.Get("Origin") if origin != "" && !sameOrigin(origin, r) { return false } if !cookieCarried(r) { return true } if origin == "" { return false } site := r.Header.Get("Sec-Fetch-Site") return site == "" || site == "same-origin" } // cookieCarried is whether the credential a request would be judged by is // this daemon's cookie: there is one, and there is no header token in front // of it. func cookieCarried(r *http.Request) bool { if headerBearer(r) != "" { return false } _, err := r.Cookie(sessionCookie) return err == nil } // sameOrigin is whether origin is the origin this request was addressed to. // Everything is compared — scheme, host and port — because a browser keeps // cookies per host and not per port, and so a page on another port of this // host is exactly the page the cookie cannot tell apart. func sameOrigin(origin string, r *http.Request) bool { got, ok := originOf(origin) if !ok { return false } want, ok := requestOrigin(r) return ok && got == want } // requestOrigin is how a browser spells the origin this request went to: the // scheme — https when the proxy in front (Tailscale Serve) says so, since this daemon itself // speaks only http — then the Host it asked for, with the port written out. // X-Forwarded-Proto cannot be set by a page elsewhere without asking first, // and a local caller who sets it is only describing its own request. func requestOrigin(r *http.Request) (string, bool) { scheme := "http" if strings.EqualFold(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")), "https") { scheme = "https" } return canonicalOrigin(scheme, r.Host) } // originOf reads an Origin header: a scheme, a host and perhaps a port, and // nothing else. "null" and anything with a path are not origins. func originOf(header string) (string, bool) { u, err := url.Parse(header) if err != nil || u.Opaque != "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" { return "", false } scheme := strings.ToLower(u.Scheme) if scheme != "http" && scheme != "https" { return "", false } return canonicalOrigin(scheme, u.Host) } // canonicalOrigin is scheme://host:port, lowercase, with the scheme's default // port written out, so that two spellings of one origin compare equal. func canonicalOrigin(scheme, hostport string) (string, bool) { u := url.URL{Host: hostport} host := strings.ToLower(u.Hostname()) if host == "" { return "", false } port := u.Port() if port == "" { port = map[string]string{"http": "80", "https": "443"}[scheme] } return scheme + "://" + net.JoinHostPort(host, port), true } // jsonOrNothing is the body half of a change: application/json, or no body // and no type. A form, plain text and a typeless body are the three a page // elsewhere can send without asking. func jsonOrNothing(r *http.Request) bool { ct := r.Header.Get("Content-Type") if ct == "" { return r.ContentLength == 0 } mt, _, err := mime.ParseMediaType(ct) return err == nil && mt == "application/json" } // bearer is the token a request carries: the header, which a script uses, or // the cookie, which exists because EventSource cannot set a header at all. func bearer(r *http.Request) string { if t := headerBearer(r); t != "" { return t } if c, err := r.Cookie(sessionCookie); err == nil { return strings.TrimSpace(c.Value) } return "" } // headerBearer is the Authorization header's bearer token, or "". func headerBearer(r *http.Request) string { if h := r.Header.Get("Authorization"); len(h) > 7 && strings.EqualFold(h[:7], "bearer ") { return strings.TrimSpace(h[7:]) } return "" } func (g *gate) permission(r *http.Request) auth.Verdict { if g.auth == nil { return auth.Verdict{} } return g.auth.Verify(bearer(r)) } func (g *gate) verifyMachine(presented string) bool { if g.files == nil || presented == "" { return false } expected, err := g.files.MachineToken() if err != nil { g.machineWarned.Do(func() { log.Printf("auth: orchestrator token unusable, machine authentication is refused: %v", err) }) return false } return auth.VerifySecret(expected, presented) } // stripCredentials removes this daemon's credentials from a request that has // been let through: the Authorization header when it is a bearer, the // orchestrator header, and this daemon's cookie. Other cookies are left, so // the proxy still carries the Swift app's own. func stripCredentials(r *http.Request) { if h := r.Header.Get("Authorization"); len(h) > 7 && strings.EqualFold(h[:7], "bearer ") { r.Header.Del("Authorization") } r.Header.Del(machineHeader) cookies := r.Cookies() if len(cookies) == 0 { return } var kept []string for _, c := range cookies { if c.Name != sessionCookie { kept = append(kept, c.Name+"="+c.Value) } } r.Header.Del("Cookie") if len(kept) > 0 { r.Header.Set("Cookie", strings.Join(kept, "; ")) } } // routePath is the one string every decision about a request's route is made // on, at the gate and behind it: **the string `http.ServeMux` dispatches by**. // // That is `EscapedPath` — the path as the caller wrote it, percent-encoding // and all — cleaned of dot segments, which is what net/http's `findHandler` // matches patterns against (`server.go`: `path = cleanPath(escapedPath)`, and // `routing_tree.go` compares the segments of that string). // // The gate used to decide on `r.URL.Path`, and those are not the same string. // net/http has already decoded that one, so `%2F` is a separator in it and a // character in the mux's — and // `/v1/sessions/..%2F..%2Fv1%2Fauth%2Fx/git` read as `/v1/auth/x/git` here, // which is on the open list, while the mux still read one session id and ran // the session's handler. No token, and `/git` and `/info` take a full reading // of the machine (ps, tmux, osascript) before they look anything up. The Swift // app never had that gap because its `request.path` is the raw target and its // router switches on the same string; this is that property, stated. // // Anything that needs a *name* out of the path — a session id, a place id — // splits this string first and decodes one segment, which is what // `decodeSegment` is for. The whole path is never decoded and then split: that // order is the bug. func routePath(r *http.Request) string { return cleanPath(r.URL.EscapedPath()) } // readablePath reports whether every segment of a path names one thing. // // The rule, rather than the spelling that was caught: **a path segment is a // name, and a name holds no separator.** So a segment is refused when it does // not decode at all, when what it decodes to is `.` or `..`, and when what it // decodes to holds a separator — `/`, `\` on the platforms where that is one, // or NUL, which ends a name inside every system call underneath this. That // covers `%2F` and `%2f`, `%2e%2e`, a literal `..`, and any later spelling of // the same idea, because it asks what the segment *means* rather than how it // was typed. // // It is deliberately in front of authentication: a request nobody can read one // way should not first be judged as though everybody agreed what it said. The // answer is the Swift app's own refusal for a request it could not read // (`RemoteServer.response(for:)`, `.badRequest`). // // Empty segments are not refused: a trailing slash makes one, and `cleanPath` // resolves repeated slashes the way the mux does. func readablePath(escaped string) bool { for _, segment := range strings.Split(escaped, "/") { name, err := url.PathUnescape(segment) if err != nil { return false } if name == "." || name == ".." || strings.ContainsAny(name, `/\`+"\x00") { return false } } return true } // cleanPath is the path the decision is made on: dot segments and repeated // slashes resolved, a trailing slash kept. The mux redirects an unclean path // anyway; deciding on the clean one means the open list cannot be walked out // of with `/app/../`. func cleanPath(p string) string { if p == "" { return "/" } c := path.Clean("/" + p) if strings.HasSuffix(p, "/") && c != "/" { c += "/" } return c } // unauthorizedMessage is the 401 every gate answers: no credential, or one // this daemon does not hold. A script on this machine reads the token file // the CLI reads (cmd/clawdline/broker.go machineToken); another device pairs. const unauthorizedMessage = "No valid credential came with this request: the X-Clawdline-Orchestrator token is " + "missing or is not this daemon's, or the device is not paired. A script on this machine sends the contents of " + "the orchestrator-token file in Clawdline's directory, as every clawdline command does; a token from another " + "directory or an older install is refused. See which directory and port the CLI uses: `clawdline doctor`." // machineScopeMessage is the 403 for the orchestrator token on a route that is // not machineScoped: the credential is good and the route is a device's. const machineScopeMessage = "This daemon's X-Clawdline-Orchestrator token was recognised, but this route does " + "not accept it: only a paired device's token may call it. Every clawdline command calls only routes that " + "token opens." // writeAuthRefusal sends the Swift app's error envelope, which is what its // page reads: `{"error":{"code","message","request_id"}}`. func writeAuthRefusal(w http.ResponseWriter, status int, code, message string) { writeAuthError(w, status, contract.AuthError{Code: code, Message: message}) } func writeRawAuthRefusal(w http.ResponseWriter, status int, code, message string) { writeAuthErrorWithSource(w, status, contract.AuthError{Code: code, Message: message}, false) } func writeAuthError(w http.ResponseWriter, status int, e contract.AuthError) { writeAuthErrorWithSource(w, status, e, true) } func writeAuthErrorWithSource(w http.ResponseWriter, status int, e contract.AuthError, fixed bool) { e.DetailKey = "" if fixed { e.DetailKey = productcopy.HTTPRefusalKey(e.Message) } markFixedRefusalKey(w, e.DetailKey) e.RequestID = requestID() w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(status) enc := json.NewEncoder(w) enc.SetEscapeHTML(false) _ = enc.Encode(contract.AuthRefusal{Error: e}) }