package opencode import ( "context" "encoding/json" "fmt" "net/url" "os" "path/filepath" "strings" "syscall" ) // The V2 OpenCode service authenticates every /api request with HTTP Basic // auth: the fixed user "opencode" (unless PIPELINES_OPENCODE_ENDPOINT_USERNAME // overrides it) and a password. A client that does not already hold the // service password obtains its own by pairing: POST /api/pair returns a // single-use code and GET /auth/connect/{code} returns the paired token, which // is then sent as the Basic password exactly like the service password. There // is no bearer or api-key header, verified against the installed 2.0.20 binary // (`opencode api POST /api/pair`, then an unauthenticated `curl` of the // `/auth/connect/{code}` link `opencode pair` prints). // // The broker pairs once, stores the token in an owner-only file beside the // other Pipelines configuration, and reuses it. The bootstrap for the pair call // is the operator's own local service credential (the file `opencode service // start` writes); it is read, never stored and never logged. // OpenCodeServiceStateEnvKey overrides the directory holding the OpenCode // service state file. It is the XDG state location, so the usual override // applies for tests and for a service that keeps its state elsewhere. const OpenCodeServiceStateEnvKey = "XDG_STATE_HOME" // serviceCredentialLimit bounds the service state file read. const serviceCredentialLimit = 64 << 10 // EndpointAttach is the outcome of attaching the chat broker to the operator's // OpenCode endpoint: the ready, non-owning connection plus exactly how the // credential was obtained, so the caller can report the attach (and any // non-fatal caveat) without ever touching the credential itself. type EndpointAttach struct { Connection *Connection // Mode is "password-file" when the operator supplied the Basic password // directly, "paired" when a token from this run's pairing was stored, and // "paired-stored" when a token stored by an earlier run was reused. Mode string // Note carries a non-fatal caveat such as a paired credential that could not // be persisted; empty when there is none. It never contains a credential. Note string } // OpenCodeStateDirectory is the directory `opencode` keeps its service state // (including service.json, the owner-only file `opencode service start` // writes) in: $XDG_STATE_HOME/opencode or the XDG default // ~/.local/state/opencode. func OpenCodeStateDirectory() (string, error) { if dir := strings.TrimSpace(os.Getenv(OpenCodeServiceStateEnvKey)); dir != "" { return filepath.Join(dir, "opencode"), nil } home, err := os.UserHomeDir() if err != nil { return "", err } if home == "" { return "", fmt.Errorf("operator home directory is empty") } return filepath.Join(home, ".local", "state", "opencode"), nil } // ServiceCredentialPath is the local OpenCode service state file the pair // bootstrap reads. It is the operator's own machine configuration. func ServiceCredentialPath() (string, error) { dir, err := OpenCodeStateDirectory() if err != nil { return "", err } return filepath.Join(dir, "service.json"), nil } // ReadServiceCredential reads the service password from the operator's local // OpenCode service state file. The file is held to the same private-file rule // as the other credential files (a regular, single-owner, 0600 file with a // bounded read), so a world-readable or foreign-owned file is refused rather // than trusted. An empty path yields no credential. func ReadServiceCredential(path string) (string, error) { if strings.TrimSpace(path) == "" { return "", nil } if err := checkPrivateFile(path, serviceCredentialLimit); err != nil { return "", fmt.Errorf("cannot read the local OpenCode service credential") } data, err := os.ReadFile(path) if err != nil { return "", fmt.Errorf("cannot read the local OpenCode service credential") } var state struct { URL string `json:"url"` Password string `json:"password"` } if err := json.Unmarshal(data, &state); err != nil || strings.TrimSpace(state.Password) == "" { return "", fmt.Errorf("the local OpenCode service credential is not usable") } return strings.TrimSpace(state.Password), nil } // PairEndpoint exchanges one fresh credential with the running service: it // calls POST /api/pair on the already-authenticated connection and completes // the returned single-use code at GET /auth/connect/{code}. It reuses // nativeRequest, so the pair request carries the same Basic auth, bounds and // JSON checks as every other call and no second HTTP client is introduced. A // blank bootstrap is a clear refusal rather than a guessed credential. func PairEndpoint(ctx context.Context, rawURL, bootstrapPassword string) (string, error) { base, err := NormalizeEndpointURL(rawURL) if err != nil { return "", err } if strings.TrimSpace(bootstrapPassword) == "" { return "", fmt.Errorf("OpenCode endpoint %s needs a password or a local OpenCode service credential to pair", base) } conn := &Connection{ Backend: "v2", URL: base, password: bootstrapPassword, username: strings.TrimSpace(os.Getenv(EndpointUsernameEnvKey)), models: map[string]map[string]string{}, responses: map[string][]byte{}, } codeCtx, cancel := context.WithTimeout(ctx, endpointProbeTimeout) defer cancel() data, err := conn.nativeRequest(codeCtx, "post", "/api/pair", nil, "") if err != nil { return "", fmt.Errorf("OpenCode endpoint %s could not start a pairing: %w", base, err) } var issued struct { Code string `json:"code"` ExpiresIn int `json:"expires_in"` } if json.Unmarshal(data, &issued) != nil || strings.TrimSpace(issued.Code) == "" { return "", fmt.Errorf("OpenCode endpoint %s returned no pairing code", base) } tokenCtx, cancelToken := context.WithTimeout(ctx, endpointProbeTimeout) defer cancelToken() tokenData, err := conn.nativeRequest(tokenCtx, "get", "/auth/connect/"+url.PathEscape(issued.Code), nil, "") if err != nil { return "", fmt.Errorf("OpenCode endpoint %s refused the pairing code: %w", base, err) } var paired struct { Token string `json:"token"` } if json.Unmarshal(tokenData, &paired) != nil || strings.TrimSpace(paired.Token) == "" { return "", fmt.Errorf("OpenCode endpoint %s returned no paired credential", base) } return strings.TrimSpace(paired.Token), nil } // OpenEndpointAttached attaches chat to the operator's endpoint with the first // credential that works, in precedence order: an explicit password (the // password-file reference), a paired token stored by an earlier run, and a // freshly paired token. The returned connection never owns a process. When a // stored token is refused with 401 it is cleared and the broker pairs once // more, so a credential the service has rotated heals without operator action; // any other refusal is returned as-is. // // credentialPath is where the paired token is kept (owner-only). No credential // is ever written to the log or the returned error; only the endpoint and the // mode are. func OpenEndpointAttached(ctx context.Context, rawURL, explicitPassword, bootstrapPassword, credentialPath string) (EndpointAttach, error) { base, err := NormalizeEndpointURL(rawURL) if err != nil { return EndpointAttach{}, err } // 1. An explicit password (the operator's password-file reference) is used // as given: it needs no pairing and is never replaced. if strings.TrimSpace(explicitPassword) != "" { conn, err := probeEndpoint(ctx, base, explicitPassword) if err != nil { return EndpointAttach{}, err } return EndpointAttach{Connection: conn, Mode: "password-file"}, nil } // 2. A token a previous run paired and stored. stored, found, err := ReadPairedCredential(credentialPath, base) if err != nil { return EndpointAttach{}, err } if found { conn, err := probeEndpoint(ctx, base, stored) if err == nil { return EndpointAttach{Connection: conn, Mode: "paired-stored"}, nil } if conn == nil || !conn.unauthorized { return EndpointAttach{}, err } // The stored token was refused: drop it and pair a fresh one below. if clearErr := ClearPairedCredential(credentialPath); clearErr != nil { return EndpointAttach{}, clearErr } } // 3. Pair a fresh token with the local service credential as bootstrap. token, err := PairEndpoint(ctx, base, bootstrapPassword) if err != nil { return EndpointAttach{}, err } conn, err := probeEndpoint(ctx, base, token) if err != nil { return EndpointAttach{}, err } attach := EndpointAttach{Connection: conn, Mode: "paired"} if credentialPath != "" { if writeErr := WritePairedCredential(credentialPath, base, token); writeErr != nil { // The attached connection works for this run; only persistence // failed, so the next start re-pairs instead of failing closed. attach.Note = "the paired credential could not be stored; chat will re-pair on the next start" } } return attach, nil } // pairedCredential is the owner-only record of a token a previous run paired // with one endpoint. The endpoint is stored so a token paired for one service // is never offered to another. type pairedCredential struct { Endpoint string `json:"endpoint"` Token string `json:"token"` } // ReadPairedCredential returns the stored token for endpoint, found false when // no credential file exists or it belongs to a different endpoint. A file that // exists but is not a private, owner-held regular file is an error, never a // silently ignored credential. func ReadPairedCredential(path, endpoint string) (string, bool, error) { if strings.TrimSpace(path) == "" { return "", false, nil } info, err := os.Lstat(path) if err != nil { if os.IsNotExist(err) { return "", false, nil } return "", false, fmt.Errorf("cannot read the stored OpenCode pairing") } if !info.Mode().IsRegular() || info.Mode().Perm() != 0600 { return "", false, fmt.Errorf("the stored OpenCode pairing is not a private file") } if stat, ok := info.Sys().(*syscall.Stat_t); !ok || stat.Uid != uint32(os.Getuid()) { return "", false, fmt.Errorf("the stored OpenCode pairing belongs to another user") } data, err := os.ReadFile(path) if err != nil { return "", false, fmt.Errorf("cannot read the stored OpenCode pairing") } var credential pairedCredential if err := json.Unmarshal(data, &credential); err != nil { return "", false, fmt.Errorf("the stored OpenCode pairing is not usable") } if credential.Endpoint != endpoint || strings.TrimSpace(credential.Token) == "" { return "", false, nil } return credential.Token, true, nil } // WritePairedCredential stores the paired token in an owner-only file: the // directory is created 0700 and the file is written 0600 through a temporary // file in the same directory and renamed over the target, so a reader never // sees a partial record. func WritePairedCredential(path, endpoint, token string) error { if strings.TrimSpace(path) == "" { return fmt.Errorf("no location to store the OpenCode pairing") } if strings.TrimSpace(token) == "" { return fmt.Errorf("no OpenCode pairing token to store") } dir := filepath.Dir(path) if err := os.MkdirAll(dir, 0700); err != nil { return fmt.Errorf("cannot create the OpenCode pairing directory") } data, err := json.Marshal(pairedCredential{Endpoint: endpoint, Token: token}) if err != nil { return err } temp, err := os.CreateTemp(dir, "opencode-pairing-*.json") if err != nil { return fmt.Errorf("cannot create the OpenCode pairing file") } name := temp.Name() if err := temp.Chmod(0600); err != nil { temp.Close() os.Remove(name) return fmt.Errorf("cannot secure the OpenCode pairing file") } if _, err := temp.Write(data); err != nil { temp.Close() os.Remove(name) return fmt.Errorf("cannot write the OpenCode pairing file") } if err := temp.Close(); err != nil { os.Remove(name) return fmt.Errorf("cannot write the OpenCode pairing file") } if err := os.Rename(name, path); err != nil { os.Remove(name) return fmt.Errorf("cannot store the OpenCode pairing file") } return nil } // ClearPairedCredential removes a stored pairing that the service refused. func ClearPairedCredential(path string) error { if strings.TrimSpace(path) == "" { return nil } if err := os.Remove(path); err != nil && !os.IsNotExist(err) { return fmt.Errorf("cannot clear the refused OpenCode pairing") } return nil } // checkPrivateFile applies the shared private-file rule: a regular file with // exact 0600 permissions, owned by the current user and no larger than limit. func checkPrivateFile(path string, limit int64) error { info, err := os.Lstat(path) if err != nil { return err } if !info.Mode().IsRegular() || info.Mode().Perm() != 0600 || info.Size() > limit { return fmt.Errorf("not a private file") } if stat, ok := info.Sys().(*syscall.Stat_t); !ok || stat.Uid != uint32(os.Getuid()) { return fmt.Errorf("belongs to another user") } return nil }