| 1 | |
| 2 | |
| 3 | package main |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "flag" |
| 11 | "fmt" |
| 12 | "html" |
| 13 | "io" |
| 14 | "log" |
| 15 | "net" |
| 16 | "net/http" |
| 17 | "os" |
| 18 | "os/exec" |
| 19 | "os/signal" |
| 20 | "path/filepath" |
| 21 | "strings" |
| 22 | "syscall" |
| 23 | "time" |
| 24 | |
| 25 | "github.com/sylvinus/agent-vm/internal/mobilelink" |
| 26 | ) |
| 27 | |
| 28 | const usage = `cage-mobile-link init --state NEW_DIRECTORY |
| 29 | cage-mobile-link fingerprint --state DIRECTORY |
| 30 | cage-mobile-link trust --state DIRECTORY --peer-pin VERIFIED_PUBLIC_FINGERPRINT |
| 31 | cage-mobile-link revoke --state DIRECTORY |
| 32 | cage-mobile-link host --state DIRECTORY [--relay HTTPS_ORIGIN] [--admin-token-file FILE] --invitation-out NEW_FILE --cage-bin ABSOLUTE_BINARY --config ABSOLUTE_CONFIG |
| 33 | cage-mobile-link host --state DIRECTORY [--relay HTTPS_ORIGIN] [--admin-token-file ABSOLUTE_FILE] --connection-out NEW_FILE --cage-bin ABSOLUTE_BINARY --config ABSOLUTE_CONFIG |
| 34 | cage-mobile-link host --state DIRECTORY --serve-saved |
| 35 | cage-mobile-link client --state DIRECTORY [--relay HTTPS_ORIGIN] --invitation-file FILE --web-dir BUILD_DIRECTORY --launch-file NEW_HTML_FILE [--listen 127.0.0.1:0] |
| 36 | cage-mobile-link client --state DIRECTORY [--relay HTTPS_ORIGIN] --connection-file FILE --web-dir BUILD_DIRECTORY --launch-file NEW_HTML_FILE [--listen 127.0.0.1:0] |
| 37 | ` |
| 38 | |
| 39 | func main() { |
| 40 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 41 | defer stop() |
| 42 | if err := run(ctx, os.Args[1:], os.Stdout, os.Stderr); err != nil && !errors.Is(err, flag.ErrHelp) && !errors.Is(err, context.Canceled) { |
| 43 | fmt.Fprintln(os.Stderr, "cage-mobile-link:", err) |
| 44 | os.Exit(1) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | |
| 49 | |
| 50 | func profileRelay(config string) (string, error) { |
| 51 | var prefs struct { |
| 52 | MobileRelay string `json:"mobile_relay"` |
| 53 | } |
| 54 | b, err := os.ReadFile(filepath.Join(filepath.Dir(config), "workbench.json")) |
| 55 | if errors.Is(err, os.ErrNotExist) { |
| 56 | return mobilelink.OfficialRelay, nil |
| 57 | } |
| 58 | if err != nil { |
| 59 | return "", err |
| 60 | } |
| 61 | if err := json.Unmarshal(b, &prefs); err != nil { |
| 62 | return "", err |
| 63 | } |
| 64 | if prefs.MobileRelay == "" { |
| 65 | return mobilelink.OfficialRelay, nil |
| 66 | } |
| 67 | if !strings.HasPrefix(prefs.MobileRelay, "https://") || !mobilelink.ValidRelayOrigin(prefs.MobileRelay) { |
| 68 | return "", errors.New("invalid mobile relay in Cage settings") |
| 69 | } |
| 70 | return prefs.MobileRelay, nil |
| 71 | } |
| 72 | |
| 73 | type clientInvitation struct { |
| 74 | ID string `json:"id"` |
| 75 | Token string `json:"client_token"` |
| 76 | ExpiresAt time.Time `json:"expires_at"` |
| 77 | } |
| 78 | |
| 79 | func run(ctx context.Context, args []string, out, errs io.Writer) error { |
| 80 | if len(args) == 0 || args[0] == "--help" || args[0] == "help" { |
| 81 | _, _ = io.WriteString(out, usage) |
| 82 | return nil |
| 83 | } |
| 84 | cmd := args[0] |
| 85 | f := flag.NewFlagSet("cage-mobile-link "+cmd, flag.ContinueOnError) |
| 86 | f.SetOutput(errs) |
| 87 | var state, pin, base, adminFile, invitation, connectionFile, cageBinary, config, webDir, launchFile, address string |
| 88 | var serveSaved bool |
| 89 | f.StringVar(&state, "state", "", "private device state directory") |
| 90 | switch cmd { |
| 91 | case "init", "fingerprint", "revoke": |
| 92 | case "trust": |
| 93 | f.StringVar(&pin, "peer-pin", "", "peer fingerprint verified through a trusted channel") |
| 94 | case "host": |
| 95 | f.StringVar(&base, "relay", "", "trusted relay HTTPS origin") |
| 96 | f.StringVar(&adminFile, "admin-token-file", "", "private relay admin token file") |
| 97 | f.StringVar(&invitation, "invitation-out", "", "new private file for client room credentials") |
| 98 | f.StringVar(&connectionFile, "connection-out", "", "new private file for the paired phone to save") |
| 99 | f.BoolVar(&serveSaved, "serve-saved", false, "keep serving the existing saved device pairing") |
| 100 | f.StringVar(&cageBinary, "cage-bin", "", "absolute path to trusted cage binary") |
| 101 | f.StringVar(&config, "config", "", "absolute path to the running Cage profile configuration") |
| 102 | case "client": |
| 103 | f.StringVar(&base, "relay", mobilelink.OfficialRelay, "trusted relay HTTPS origin") |
| 104 | f.StringVar(&invitation, "invitation-file", "", "private invitation supplied by the host") |
| 105 | f.StringVar(&connectionFile, "connection-file", "", "private saved connection file verified on this device") |
| 106 | f.StringVar(&webDir, "web-dir", "", "trusted build directory containing mobile.html") |
| 107 | f.StringVar(&launchFile, "launch-file", "", "new private local HTML entry file") |
| 108 | f.StringVar(&address, "listen", "127.0.0.1:0", "local numeric loopback UI listener") |
| 109 | default: |
| 110 | return errors.New("unknown command; use --help") |
| 111 | } |
| 112 | if err := f.Parse(args[1:]); err != nil { |
| 113 | return err |
| 114 | } |
| 115 | if state == "" || f.NArg() != 0 { |
| 116 | return errors.New("--state is required; positional arguments are not supported") |
| 117 | } |
| 118 | if cmd == "init" { |
| 119 | id, err := createIdentity(state) |
| 120 | if err == nil { |
| 121 | fmt.Fprintln(out, id.Pin) |
| 122 | } |
| 123 | return err |
| 124 | } |
| 125 | if cmd == "trust" { |
| 126 | return trust(state, pin) |
| 127 | } |
| 128 | if cmd == "revoke" { |
| 129 | return revoke(state) |
| 130 | } |
| 131 | id, err := loadIdentity(state) |
| 132 | if err != nil { |
| 133 | return err |
| 134 | } |
| 135 | if cmd == "fingerprint" { |
| 136 | fmt.Fprintln(out, id.Pin) |
| 137 | return nil |
| 138 | } |
| 139 | peer, err := trustedPeer(state) |
| 140 | if err != nil { |
| 141 | return err |
| 142 | } |
| 143 | if cmd == "host" { |
| 144 | if serveSaved { |
| 145 | if base != "" || adminFile != "" || invitation != "" || connectionFile != "" || cageBinary != "" || config != "" { |
| 146 | return errors.New("--serve-saved uses only the configuration saved for --state") |
| 147 | } |
| 148 | h, err := loadSavedHost(state, id.Pin, peer) |
| 149 | if err != nil { |
| 150 | return err |
| 151 | } |
| 152 | return savedService(ctx, state, h, errs) |
| 153 | } |
| 154 | if base == "" { |
| 155 | if adminFile != "" { |
| 156 | return errors.New("specify --relay together with --admin-token-file to confirm the destination of the private token") |
| 157 | } |
| 158 | if !filepath.IsAbs(config) { |
| 159 | return errors.New("host requires an absolute --config") |
| 160 | } |
| 161 | base, err = profileRelay(config) |
| 162 | if err != nil { |
| 163 | return err |
| 164 | } |
| 165 | } |
| 166 | if connectionFile != "" { |
| 167 | if invitation != "" { |
| 168 | return errors.New("choose --connection-out or --invitation-out") |
| 169 | } |
| 170 | h, err := configureSavedHost(state, connectionFile, id.Pin, peer, hostSettings{Relay: base, AdminFile: adminFile, CageBinary: cageBinary, Config: config}) |
| 171 | if err != nil { |
| 172 | return err |
| 173 | } |
| 174 | fmt.Fprintln(out, "Private saved connection file written. Verify the host fingerprint separately on the phone.") |
| 175 | return savedService(ctx, state, h, errs) |
| 176 | } |
| 177 | if !filepath.IsAbs(cageBinary) || !filepath.IsAbs(config) || invitation == "" { |
| 178 | return errors.New("host requires absolute --cage-bin, --config, and a new --invitation-out file") |
| 179 | } |
| 180 | b, err := localWorkbench(ctx, cageBinary, config) |
| 181 | if err != nil { |
| 182 | return err |
| 183 | } |
| 184 | defer b.Close() |
| 185 | admin, err := readAdminToken(adminFile) |
| 186 | if err != nil { |
| 187 | return err |
| 188 | } |
| 189 | room, err := mobilelink.CreateRoom(ctx, base, admin) |
| 190 | if err != nil { |
| 191 | return err |
| 192 | } |
| 193 | data, _ := json.Marshal(clientInvitation{room.ID, room.ClientToken, room.ExpiresAt}) |
| 194 | err = writeNewPrivate(invitation, data) |
| 195 | clear(data) |
| 196 | if err != nil { |
| 197 | return err |
| 198 | } |
| 199 | fmt.Fprintln(out, "Private client invitation saved. Waiting for the trusted device.") |
| 200 | active, stop := monitorTrust(ctx, func() bool { current, err := trustedPeer(state); return err == nil && current == peer }) |
| 201 | defer stop() |
| 202 | stopAwake := keepHostAwake(active, log.New(errs, "", 0)) |
| 203 | defer stopAwake() |
| 204 | err = mobilelink.ServeHost(active, base, room.ID, room.HostToken, id, peer, b) |
| 205 | if active.Err() != nil { |
| 206 | return context.Cause(active) |
| 207 | } |
| 208 | return err |
| 209 | } |
| 210 | if launchFile == "" || webDir == "" { |
| 211 | return errors.New("client requires --web-dir and a new --launch-file") |
| 212 | } |
| 213 | var room clientInvitation |
| 214 | if connectionFile != "" { |
| 215 | if invitation != "" { |
| 216 | return errors.New("choose --connection-file or --invitation-file") |
| 217 | } |
| 218 | room, err = resolveSaved(ctx, connectionFile, base, peer) |
| 219 | if err != nil { |
| 220 | return err |
| 221 | } |
| 222 | } else { |
| 223 | data, err := readPrivate(invitation, 4096) |
| 224 | if err != nil { |
| 225 | return err |
| 226 | } |
| 227 | err = json.Unmarshal(data, &room) |
| 228 | clear(data) |
| 229 | if err != nil || !room.ExpiresAt.After(time.Now()) { |
| 230 | return errors.New("invalid or expired client invitation") |
| 231 | } |
| 232 | } |
| 233 | host, _, err := net.SplitHostPort(address) |
| 234 | if err != nil || !net.ParseIP(host).IsLoopback() { |
| 235 | return errors.New("the local browser must use a numeric loopback address") |
| 236 | } |
| 237 | listener, err := net.Listen("tcp", address) |
| 238 | if err != nil { |
| 239 | return errors.New("cannot listen on the requested loopback address") |
| 240 | } |
| 241 | defer listener.Close() |
| 242 | client, err := mobilelink.ConnectClient(ctx, base, room.ID, room.Token, id, peer) |
| 243 | if err != nil { |
| 244 | return err |
| 245 | } |
| 246 | defer client.Close() |
| 247 | browser, entry, err := mobilelink.NewBrowser("http://"+listener.Addr().String(), webDir, client) |
| 248 | if err != nil { |
| 249 | return err |
| 250 | } |
| 251 | defer browser.Close() |
| 252 | page := []byte(`<!doctype html><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=` + html.EscapeString(entry) + `"><title>Cage</title>`) |
| 253 | err = writeNewPrivate(launchFile, page) |
| 254 | clear(page) |
| 255 | if err != nil { |
| 256 | return err |
| 257 | } |
| 258 | fmt.Fprintln(out, "Authenticated. Open the private HTML launch file on this device within two minutes.") |
| 259 | server := &http.Server{Handler: browser, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 45 * time.Second, IdleTimeout: time.Minute, MaxHeaderBytes: 16 << 10, ErrorLog: log.New(io.Discard, "", 0)} |
| 260 | stop := context.AfterFunc(ctx, func() { _ = server.Close() }) |
| 261 | defer stop() |
| 262 | err = server.Serve(listener) |
| 263 | if errors.Is(err, http.ErrServerClosed) { |
| 264 | return nil |
| 265 | } |
| 266 | return err |
| 267 | } |
| 268 | |
| 269 | type entryBuffer struct{ buf bytes.Buffer } |
| 270 | |
| 271 | func (b *entryBuffer) Write(p []byte) (int, error) { |
| 272 | if len(p) > (16<<10)-b.buf.Len() { |
| 273 | return 0, errors.New("Cage entry too large") |
| 274 | } |
| 275 | return b.buf.Write(p) |
| 276 | } |
| 277 | |
| 278 | func localWorkbench(ctx context.Context, cageBinary, config string) (*mobilelink.Workbench, error) { |
| 279 | ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 280 | defer cancel() |
| 281 | cmd := exec.CommandContext(ctx, cageBinary, "server-entry", "--json") |
| 282 | cmd.Env = append(os.Environ(), "CLAUDE_CAGE_CONFIG="+config) |
| 283 | buf := &entryBuffer{} |
| 284 | cmd.Stdout, cmd.Stderr = buf, io.Discard |
| 285 | if err := cmd.Run(); err != nil { |
| 286 | return nil, errors.New("Cage could not issue a local entry; start the selected profile first") |
| 287 | } |
| 288 | defer clear(buf.buf.Bytes()) |
| 289 | var entry struct{ Origin, Ticket string } |
| 290 | if json.Unmarshal(buf.buf.Bytes(), &entry) != nil { |
| 291 | return nil, errors.New("Cage returned an invalid local entry") |
| 292 | } |
| 293 | return mobilelink.OpenWorkbench(ctx, entry.Origin, entry.Ticket) |
| 294 | } |