mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 21:36:40 -10:00
devvm agent import and save checked each path they wrote in the store by path (storeGuard), then wrote by path (os.MkdirAll, state.WriteFileMode), so a link swapped into the store between the check and the write could lead the write elsewhere. They still check every path first, so a link fails the command, naming it, before the store changes; they now write only through the agent's folder in the store opened from devvm's config folder as a root (makeStoreDir, which makes it and the folders on its way through the config folder as a root, then openStoreDir), with state.WriteFileIn, a whole-file write through an os.Root. An import copied whatever an agent's folder held, one file at most 128 MiB, so a VM whose project folder is inside an agent's folder could fill the store that every VM with the agent mounts. Each agent's folder now gets agent save's bounds in all, 20,000 files and folders and 128 MiB: the walk stops at 20,000 (errFolderTooMany), the sizes as listed are counted (hostAgent.tooMuch), and a folder over either fails the import before anything is written, naming the folder and what to do (agent_import_too_much); the files' reads share the 128 MiB (h.read), so files that grew since the listing fail too. Before it reads anything, the import warns of each VM whose project folder is inside an agent's folder or holds it (agent_import_project_inside). A project folder that holds an agent's folder, such as ~/.pi for pi's ~/.pi/agent, let its VM put a link in the agent folder's place, which the import followed, copying whatever it led to, such as the home folder's files, into the store: the import now resolves the folder's path one link at a time (linkHops), leaves it out with agent_import_link_via_vm when a link in a VM's project folder leads it out of that folder (throughVM, shared with the link follower), its login with it (pi's auth.json), and reads the folder where the path led. Every agent's login file but Claude Code's ~/.claude.json, which was already a capped, regular-file read, was os.ReadFile by path, so a VM whose project folder held it could swap in a link to another file, a FIFO or an endless file between the check and the read: its path is now resolved once (linkHops), left out when a link in a VM's project folder leads it out of that folder (throughVM), and read where it led, through its folder opened with no link and never resolved again (openPhysical), opened without following one, a regular file of at most 128 MiB (claudeHostLogin), so a folder swapped for a link since fails the read. Tests: TestWriteFileIn, TestAgentImportTooMuch, TestAgentImportReadBudget, TestAgentImportProjectInside, TestAgentImportProjectHolds (a folder and a login led elsewhere), TestAgentImportLoginNoFollow, TestStoreOpsRefuseLinks (makeStoreDir). Co-Authored-By: Claude Opus 5.5 <[email protected]>
249 lines
9.8 KiB
Go
249 lines
9.8 KiB
Go
package vm
|
|
|
|
// Claude Code's own code in internal/vm: the hooks the code for every agent
|
|
// calls, which do something for Claude Code alone. Its ~/.claude.json is
|
|
// both its settings and its login file, which devvm merges into the VM's
|
|
// own and saves a part of. devvm keeps one Claude Code login, its OAuth
|
|
// login or a setup token's secret, and merges the OAuth login's copy into
|
|
// the VM's own .credentials.json, which keeps the VM's logins to MCP
|
|
// servers.
|
|
|
|
import (
|
|
"bytes"
|
|
"cmp"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"path"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/devvmhq/devvm/internal/agentlogin"
|
|
"github.com/devvmhq/devvm/internal/agents"
|
|
"github.com/devvmhq/devvm/internal/backend"
|
|
"github.com/devvmhq/devvm/internal/msg"
|
|
"github.com/devvmhq/devvm/internal/redact"
|
|
"github.com/devvmhq/devvm/internal/safefile"
|
|
"github.com/devvmhq/devvm/internal/secrets"
|
|
"github.com/devvmhq/devvm/internal/shell"
|
|
"github.com/devvmhq/devvm/internal/tools"
|
|
"github.com/devvmhq/devvm/internal/vmname"
|
|
)
|
|
|
|
// claude logs Claude Code in in the VM, its login's code pasted on this
|
|
// terminal, ok false for another agent: the VM's proxy saves its
|
|
// subscription's login in the store, or claude setup-token's token as the
|
|
// claude secret, and takes the other away. Then the VM is set up again, so
|
|
// it gets the login devvm keeps now, its token in the environment or its
|
|
// OAuth login's file, never both, and Run says which it saved.
|
|
func (e AgentLogin) claude(ctx context.Context, t *target, conf backend.Confinement, o AgentLoginOptions) (bool, error) {
|
|
if o.Agent != agents.Claude {
|
|
return false, nil
|
|
}
|
|
vm, store := t.f.Name, e.Proxy.Secrets
|
|
oauth, token, err := secrets.ClaudeOf(store).Sums(ctx)
|
|
if err != nil {
|
|
return true, err
|
|
}
|
|
if err := e.login(ctx, t, o); err != nil {
|
|
return true, err
|
|
}
|
|
oauth2, token2, err := secrets.ClaudeOf(store).Sums(ctx)
|
|
if err != nil {
|
|
return true, err
|
|
}
|
|
if o.SetupToken && (token2 == "" || token2 == token) || !o.SetupToken && (oauth2 == "" || oauth2 == oauth) {
|
|
return true, msg.AgentLoginNotSaved(o.Agent, vm)
|
|
}
|
|
if err := e.launcher.syncer.sync(ctx, t.b, t.st, t.f.Slug(), tools.Files(t.st), conf); err != nil {
|
|
return true, err
|
|
}
|
|
if o.SetupToken {
|
|
e.Info(msg.ClaudeSetupTokenSaved(vm))
|
|
} else {
|
|
e.Info(msg.AgentOwnLoginSaved(agents.Of(o.Agent).Display, vm))
|
|
}
|
|
if !secrets.ClaudeOf(store).Env().Empty() {
|
|
e.Warn(msg.ClaudeEnvTokenWins())
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// claudeSyncName is the name a launch's setup gives the VM's copy of the
|
|
// login of kind, merged true, for Claude Code's two files, which sync.sh
|
|
// merges into the VM's own rather than copying them: its .claude.json,
|
|
// claude.json, and its .credentials.json, claude-credentials.json, whose
|
|
// OAuth login replaces the VM's while the rest of the VM's file stays,
|
|
// such as its logins to MCP servers. Any other kind's is copied to its
|
|
// place below the home folder: "", false.
|
|
func claudeSyncName(kind string) (string, bool) {
|
|
switch kind {
|
|
case agents.Claude:
|
|
return "claude.json", true
|
|
case agents.ClaudeOAuth:
|
|
return "claude-credentials.json", true
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// claudeTokenUnsaved warns, as a launch's setup finds the VM's secret name
|
|
// with no value saved, that the claude secret has none, and reports
|
|
// whether it was the claude secret: no warning while devvm keeps Claude
|
|
// Code's OAuth login, which the VM gets instead (stageSecrets), never both.
|
|
func claudeTokenUnsaved(store *secrets.Store, name string, vm vmname.VM, warn func(msg.M)) bool {
|
|
if name != secrets.ClaudeToken {
|
|
return false
|
|
}
|
|
if !secrets.ClaudeOf(store).OAuthInstead(name) {
|
|
warn(msg.NoClaudeToken(vm))
|
|
}
|
|
return true
|
|
}
|
|
|
|
// claudeTokenInvalid reports whether v, the saved value of the VM's
|
|
// secret name, is a Claude Code token that isn't one from claude
|
|
// setup-token, so the VM doesn't get it.
|
|
func claudeTokenInvalid(name string, v redact.Secret) bool {
|
|
return name == secrets.ClaudeToken && !strings.HasPrefix(v.Reveal(), "sk-ant-oat01-") //nolint:forbidigo // the token's shape, before a VM gets its placeholder
|
|
}
|
|
|
|
// claudeSaves reports whether devvm agent save saves a part of the agent's
|
|
// login file too: Claude Code's ~/.claude.json (saver.claudeJSON).
|
|
func claudeSaves(agent string) bool { return agent == agents.Claude }
|
|
|
|
// claudeSaveLines are agentSaveScript's lines that send what devvm's store
|
|
// keeps of ~/.claude.json (agentlogin.ClaudeTopKeys), when names has Claude
|
|
// Code, so its per-project entries never leave the VM.
|
|
func claudeSaveLines(names []string) []string {
|
|
if !slices.Contains(names, agents.Claude) {
|
|
return nil
|
|
}
|
|
keys, _ := json.Marshal(agentlogin.ClaudeTopKeys())
|
|
own := `"$t/` + saveOwn
|
|
return []string{
|
|
`if [ -f ` + agents.ClaudeJSON + ` ] && [ ! -L ` + agents.ClaudeJSON + ` ]; then`,
|
|
` jq --argjson k ` + shell.Quote(string(keys)) + ` 'with_entries(select(.key as $x | any($k[]; . == $x)))' ` + agents.ClaudeJSON + ` > ` + own + `/claude.json" 2>/dev/null ||`,
|
|
` { rm -f ` + own + `/claude.json"; : > ` + own + `/claude-unreadable"; }`,
|
|
"fi",
|
|
}
|
|
}
|
|
|
|
// claudeHostLogin reads this machine's login file of the agent at path for
|
|
// devvm agent import: Claude Code's ~/.claude.json without its projects'
|
|
// history or API key (agentlogin.ClaudeCopy, a regular file, capped), in
|
|
// the home folder, which no VM's project folder is or holds; another
|
|
// agent's as it is, which is in the agent's folder, which a VM's may hold.
|
|
// So that one, at path, already resolved (linkHops), is read through its
|
|
// folder opened one folder at a time from / without following a link
|
|
// (openPhysical), never resolved again, itself opened without following
|
|
// one, a regular file of at most saveMaxBytes: a link on its way, a FIFO
|
|
// or an endless file that such a VM swapped in since fails.
|
|
func claudeHostLogin(agent, path string) ([]byte, error) {
|
|
if agent == agents.Claude {
|
|
return agentlogin.ClaudeCopy(path)
|
|
}
|
|
dir, err := openPhysical(filepath.Dir(path))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = dir.Close() }()
|
|
f, err := dir.Open(filepath.Base(path), safefile.Opts{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = f.Close() }()
|
|
return f.ReadAll(saveMaxBytes)
|
|
}
|
|
|
|
// claudePlugins is the agent's settings file p, data, as devvm agent import
|
|
// copies it from folder on this machine into store: Claude Code's plugin
|
|
// records name their folders by path, so the copy names them in the store,
|
|
// where VMs mount them. Any other file is as it is.
|
|
func claudePlugins(agent, p string, data []byte, folder, store string) []byte {
|
|
if agent != agents.Claude || path.Dir(p) != "plugins" || path.Ext(p) != ".json" {
|
|
return data
|
|
}
|
|
return renamePrefix(data, filepath.Join(folder, "plugins"), filepath.Join(store, "plugins"))
|
|
}
|
|
|
|
// claudeMarketplaces is Claude Code's records of its plugins'
|
|
// marketplaces, in its plugins folder.
|
|
const claudeMarketplaces = agents.ClaudePlugins + "/known_marketplaces.json"
|
|
|
|
// claudeRecords is the file n, data, of the VM's settings folder rel, as
|
|
// devvm agent save puts it into store: Claude Code's plugin records name
|
|
// their folders by path, in the VM's plugins folder below the VM's home
|
|
// (home, when the VM sent it), so the copy names them in the store, where
|
|
// VMs mount them. The VM's folder holds only what it added to its seed
|
|
// (agents.Seed), so its marketplaces' records join the store's, each
|
|
// replacing the store's of the same name, but those whose copy isn't in
|
|
// the store's marketplaces folder (claudeInStore), such as those Claude
|
|
// Code registered from the seed, which are the store's own: the store's
|
|
// file as it is when that changes none of them, and an error for one
|
|
// that isn't a JSON object. Any other file is as it is.
|
|
func claudeRecords(rel, n string, data []byte, home, store string) ([]byte, error) {
|
|
if rel != agents.ClaudePlugins || path.Dir(n) != rel || path.Ext(n) != ".json" {
|
|
return data, nil
|
|
}
|
|
to := filepath.Join(store, filepath.FromSlash(rel))
|
|
if n != claudeMarketplaces {
|
|
if home != "" {
|
|
data = renamePrefix(data, home+"/"+rel, to)
|
|
}
|
|
return data, nil
|
|
}
|
|
var vm map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &vm); err != nil || vm == nil {
|
|
return nil, cmp.Or(err, errNotObject)
|
|
}
|
|
old, _ := readStoreFile(filepath.Join(store, filepath.FromSlash(n)))
|
|
merged := map[string]json.RawMessage{}
|
|
_ = json.Unmarshal(old, &merged) // none, or a store's file that isn't JSON: the VM's alone
|
|
changed := old == nil
|
|
for name, m := range vm {
|
|
if home != "" {
|
|
m = renamePrefix(m, home+"/"+rel, to)
|
|
}
|
|
if !claudeInStore(m, to) {
|
|
continue
|
|
}
|
|
if !jsonEqual(merged[name], m) {
|
|
merged[name], changed = m, true
|
|
}
|
|
}
|
|
if !changed {
|
|
return old, nil
|
|
}
|
|
out, err := json.MarshalIndent(merged, "", " ")
|
|
return append(out, '\n'), err
|
|
}
|
|
|
|
// claudeInStore reports whether m, a marketplace's record, has its copy
|
|
// in the marketplaces folder of plugins, the store's plugins folder, by a
|
|
// clean path: the only records a seed can use. Those Claude Code
|
|
// registered from the seed name the seed's link instead, and a marketplace
|
|
// that Claude Code reads where it is, such as a folder of the VM's, has no
|
|
// copy there.
|
|
func claudeInStore(m json.RawMessage, plugins string) bool {
|
|
// By its exact key, as Claude Code reads it: Go's struct fields would
|
|
// take InstallLocation too.
|
|
var r map[string]json.RawMessage
|
|
var loc string
|
|
if json.Unmarshal(m, &r) != nil || json.Unmarshal(r["installLocation"], &loc) != nil {
|
|
return false
|
|
}
|
|
return loc == filepath.Clean(loc) && strings.HasPrefix(loc, plugins+"/marketplaces/")
|
|
}
|
|
|
|
// jsonEqual reports whether a and b are the same JSON, but for the space
|
|
// between its tokens.
|
|
func jsonEqual(a, b []byte) bool {
|
|
var ca, cb bytes.Buffer
|
|
return json.Compact(&ca, a) == nil && json.Compact(&cb, b) == nil && bytes.Equal(ca.Bytes(), cb.Bytes())
|
|
}
|
|
|
|
// errNotObject is claudeRecords' error for records that aren't a JSON
|
|
// object.
|
|
var errNotObject = errors.New("not a JSON object")
|