diff --git a/changelog.d/fixed-18740-session-login-adopt-back-codex-opencode.md b/changelog.d/fixed-18740-session-login-adopt-back-codex-opencode.md new file mode 100644 index 0000000000..c4abe6001b --- /dev/null +++ b/changelog.d/fixed-18740-session-login-adopt-back-codex-opencode.md @@ -0,0 +1 @@ +- **Sessions: a Codex or OpenCode login refreshed inside a session is adopted back into the shared login, so the agents are no longer left on a dead one** ([#18740](https://github.com/hivecommons/hive/issues/18740)). A session gets a full copy of `.codex/auth.json` and `.local/share/opencode/auth.json`. Codex's ChatGPT login and an OpenCode OAuth provider entry rotate their refresh token on refresh, so a session that refreshed its copy held the only valid login: the agents, which link to the shared file, failed their next refresh and fell to a login prompt, and deleting the session deleted the login. The hive now adopts a strictly newer login from a session HOME into the shared file, the same safety net #18728 added for Claude: at boot, on every credential-bridge poll, at a session's start or resume, and before a session is deleted (a newer login that cannot be adopted keeps the session). Newer means the session's file was written after the shared one and, for Codex, records a later `last_refresh` with a different refresh token; for OpenCode, per provider entry, a later `expires` with a different refresh token. Only the refreshed OpenCode entries are replaced; other entries, API-key logins and providers the shared file does not hold are left alone. The replaced file is kept as `auth.json.stale-`, and `user_session_login_adopted` records the session, trigger, vendor and file, never token material. A session still holds a copy that can refresh (whether each CLI accepts a login without its refresh token is unverified), so a session and an agent refreshing in the same few seconds converge on the newer login at the next poll rather than being prevented. diff --git a/src/crux/agent/usersession_home.go b/src/crux/agent/usersession_home.go index 9f0803793b..7346493ef7 100644 --- a/src/crux/agent/usersession_home.go +++ b/src/crux/agent/usersession_home.go @@ -168,7 +168,10 @@ func (r *UserSessionRuntime) prepareSandbox(id string, uid int) error { // refresh token, and a newer login already in the session HOME is adopted // into the shared file first (usersession_login.go). // -// For every other vendor the copy is skipped when the session's file was +// A Codex or OpenCode login the session's CLI refreshed is adopted into the +// shared file first when it is strictly newer (usersession_login_rotating.go). +// +// For every vendor but Claude the copy is skipped when the session's file was // written after the shared one. That is the state of an unchanged copy from // an earlier start, and also of a login the CLI in the session rewrote itself // (a token refresh): re-copying an older shared file over it on a resume @@ -183,6 +186,12 @@ func (r *UserSessionRuntime) copyLoginFiles(id string, uid int) { _ = r.syncClaudeLogin(id, sessionLoginTriggerStart, sessionLoginModeStart) continue } + if l, ok := rotatingSessionLoginFor(rel); ok { + // A login the session's CLI refreshed (Codex, OpenCode) goes into + // the shared file first (usersession_login_rotating.go). Reported + // inside; a failure must not block the session. + _ = r.syncRotatingLogin(id, sessionLoginTriggerStart, l) + } src := filepath.Join(sharedAgentHome, rel) dest := filepath.Join(home, rel) if sessionLoginCopyIsCurrent(src, dest) { diff --git a/src/crux/agent/usersession_login.go b/src/crux/agent/usersession_login.go index 48a2e01446..ad04e8bc00 100644 --- a/src/crux/agent/usersession_login.go +++ b/src/crux/agent/usersession_login.go @@ -386,15 +386,20 @@ func (r *UserSessionRuntime) loginOps() sessionLoginOps { // syncClaudeLogin checks one session's Claude login and reports the outcome. func (r *UserSessionRuntime) syncClaudeLogin(id, trigger string, mode sessionLoginMode) error { res, err := r.loginOps().checkSessionClaudeLogin(id, mode) + reportSessionLogin(r.logger, r.loginAudit(), id, trigger, res, err) + return err +} + +// loginAudit is the audit function of a session login check made by the +// runtime, nil when no sink is installed. +func (r *UserSessionRuntime) loginAudit() func(string, map[string]any) { r.auditMu.Lock() sink := r.auditSink r.auditMu.Unlock() - var audit func(string, map[string]any) - if sink != nil { - audit = func(action string, fields map[string]any) { sink.Record(auditActorSystem, action, "", fields) } + if sink == nil { + return nil } - reportSessionLogin(r.logger, audit, id, trigger, res, err) - return err + return func(action string, fields map[string]any) { sink.Record(auditActorSystem, action, "", fields) } } // ---- manager side @@ -461,7 +466,9 @@ func (w *sessionLoginCache) forget(keep map[string]bool) { // syncUserSessionClaudeLogins checks the Claude login of every session // sandbox on this hive: it adopts a strictly newer login a session holds into // the shared file (with an audit entry) and brings every session's copy up to -// date with the shared one. It returns the ids it adopted a login from. +// date with the shared one. It returns the ids it adopted a Claude login +// from. The same sweep adopts a newer Codex or OpenCode login +// (syncUserSessionRotatingLogins). // // It runs at boot, on the credential-bridge poll and after a dashboard // sign-in, whether or not any agent uses Claude: sessions use the shared @@ -484,6 +491,8 @@ func (m *Manager) syncUserSessionClaudeLogins(trigger string) []string { if !e.IsDir() || !userSessionIDPattern.MatchString(id) { continue } + // Codex and OpenCode logins (usersession_login_rotating.go). + m.syncUserSessionRotatingLogins(id, trigger, ops, force, present) path := filepath.Join(userSessionHome(id), userSessionClaudeLoginRel) stamp, ok := sessionLoginStampOf(path, target) if !ok { diff --git a/src/crux/agent/usersession_login_rotating.go b/src/crux/agent/usersession_login_rotating.go new file mode 100644 index 0000000000..bc941641a7 --- /dev/null +++ b/src/crux/agent/usersession_login_rotating.go @@ -0,0 +1,375 @@ +package agent + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "log/slog" + "os" + "path/filepath" + "sync" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/crux/sharedfile" +) + +// Codex and OpenCode logins in a session HOME, adopted back into the shared +// login when a session refreshed them (#18740, a follow-up to #18724). +// +// A session gets a plain copy of these two files (userSessionLoginFiles). +// Both can hold a ROTATING refresh token: Codex's ChatGPT login, and an +// OpenCode provider entry of type "oauth". When the CLI in a session refreshes +// its copy, the refresh rotates the token, the session's copy becomes the +// only valid login, and the shared file every agent uses is left stale. The +// agents link to that shared file (Codex: each agent's CODEX_HOME/auth.json +// is a symlink to it, setupCodexHome; OpenCode: each agent's +// $XDG_DATA_HOME/opencode is a symlink to the shared directory, +// xdgDataSharedBridges), so the shared file is the single owner of each +// login, and the CLIs of the agents write their own refreshes into it. +// +// The fix here is ADOPT-BACK, the same safety net usersession_login.go has for +// Claude: when a session's file holds a strictly newer login than the shared +// file, that login is written into the shared file atomically, the replaced +// shared file is kept beside it as ".stale-", and +// user_session_login_adopted is audited. It runs at the same points as the +// Claude check: at boot, on every credential-bridge poll, at a session's +// start or resume, and before a session's sandbox is removed (a login that +// cannot be adopted keeps the sandbox). +// +// What a session is NOT given here, unlike Claude, is a copy that cannot +// refresh. Whether each CLI accepts a login file without its refresh token +// (Codex may reject one) has not been verified against the CLIs, so the +// session keeps a full copy and stays a refresh holder. Adopt-back makes the +// fleet converge on the newest login within one poll; it does not stop a +// session and an agent refreshing the same token in the same few seconds. +// +// "Strictly newer" is decided from the files' own freshness fields and +// modification times only: +// +// - Codex: the session's file was written after the shared one, holds a +// complete ChatGPT login (access and refresh token), records a +// last_refresh later than the shared file's, and its refresh token +// differs from the shared one. The shared file must itself hold a ChatGPT +// login: an API-key login does not rotate and is never replaced. +// - OpenCode, per provider entry: the session's file was written after the +// shared one, both entries are "oauth" with a refresh token, the +// session's records a later "expires", and its refresh token differs. +// Only those entries are replaced; every other entry of the shared file +// is kept as it is, and an entry the shared file does not have is not +// added. +// +// Token values are compared only for equality, in memory, and never logged, +// audited or put in an error. + +// The rotating entries of userSessionLoginFiles. +const ( + userSessionCodexLoginRel = ".codex/auth.json" + userSessionOpenCodeLoginRel = ".local/share/opencode/auth.json" +) + +// rotatingSessionLogin is one vendor login a session holds as a full copy +// whose refresh token rotates. +type rotatingSessionLogin struct { + rel string // relative to HOME, in the session and in the shared home + vendor string // for logs and the audit detail + // adopt returns the new content of the shared file when sess holds a + // strictly newer login than shared, nil when there is nothing to adopt. + // It never logs and never returns token material in an error. + adopt func(sess, shared []byte, sessMod, sharedMod time.Time) []byte +} + +var rotatingSessionLogins = []rotatingSessionLogin{ + {rel: userSessionCodexLoginRel, vendor: "codex", adopt: adoptCodexLogin}, + {rel: userSessionOpenCodeLoginRel, vendor: "opencode", adopt: adoptOpenCodeLogin}, +} + +// rotatingSessionLoginFor returns the rotating login stored at rel. +func rotatingSessionLoginFor(rel string) (rotatingSessionLogin, bool) { + for _, l := range rotatingSessionLogins { + if l.rel == rel { + return l, true + } + } + return rotatingSessionLogin{}, false +} + +// sessionRotatingLoginMu serialises every read-compare-write of a rotating +// shared login made by the hive (the manager's poll, a session's start and +// its removal), so two sessions holding newer logins settle on the later one. +// The agents' CLIs write the shared file without it; replaceSharedLogin +// refuses to replace a shared file that changed after it was judged. +var sessionRotatingLoginMu sync.Mutex + +// errSharedLoginChanged: the shared file changed between the judgement and +// the write. Nothing was written; the next check judges again. +var errSharedLoginChanged = errors.New("the shared login changed while it was being compared; nothing was replaced") + +// ---- Codex + +// codexLoginFile is the part of Codex's auth.json the judgement reads. +type codexLoginFile struct { + Tokens *struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + } `json:"tokens"` + LastRefresh string `json:"last_refresh"` +} + +// parseCodexLogin returns the refresh token and the last refresh time of a +// Codex login file. ok is false when data is not a login file with a ChatGPT +// refresh token; last is zero when the file records no (valid) refresh time. +func parseCodexLogin(data []byte) (access, refresh string, last time.Time, ok bool) { + var f codexLoginFile + if err := json.Unmarshal(data, &f); err != nil || f.Tokens == nil || f.Tokens.RefreshToken == "" { + return "", "", time.Time{}, false + } + if t, err := time.Parse(time.RFC3339Nano, f.LastRefresh); err == nil { + last = t + } + return f.Tokens.AccessToken, f.Tokens.RefreshToken, last, true +} + +// codexLoginKeys are the top-level keys of a Codex login file that make up +// the ChatGPT login; an adoption takes exactly these from the session's file. +var codexLoginKeys = []string{"tokens", "last_refresh", "auth_mode"} + +// adoptCodexLogin implements rotatingSessionLogin.adopt for Codex: the +// shared file with the session's ChatGPT login in place of its own, or nil. +func adoptCodexLogin(sess, shared []byte, sessMod, sharedMod time.Time) []byte { + if !sessMod.After(sharedMod) { + return nil + } + sAccess, sRefresh, sLast, ok := parseCodexLogin(sess) + if !ok || sAccess == "" || sLast.IsZero() { + return nil + } + _, hRefresh, hLast, ok := parseCodexLogin(shared) + if !ok || sRefresh == hRefresh || !sLast.After(hLast) { + return nil + } + var sessTop, sharedTop map[string]json.RawMessage + if json.Unmarshal(sess, &sessTop) != nil || json.Unmarshal(shared, &sharedTop) != nil || sharedTop == nil { + return nil + } + for _, k := range codexLoginKeys { + if v, ok := sessTop[k]; ok { + sharedTop[k] = v + } + } + out, err := json.MarshalIndent(sharedTop, "", " ") + if err != nil { + return nil + } + return append(out, '\n') +} + +// ---- OpenCode + +// openCodeAuthEntry is the part of one OpenCode auth.json provider entry the +// judgement reads. +type openCodeAuthEntry struct { + Type string `json:"type"` + Access string `json:"access"` + Refresh string `json:"refresh"` + Expires int64 `json:"expires"` +} + +// openCodeOAuthEntry parses one provider entry; ok is false unless it is an +// "oauth" entry with a refresh token. +func openCodeOAuthEntry(raw json.RawMessage) (openCodeAuthEntry, bool) { + var e openCodeAuthEntry + if err := json.Unmarshal(raw, &e); err != nil || e.Type != "oauth" || e.Refresh == "" { + return openCodeAuthEntry{}, false + } + return e, true +} + +// adoptOpenCodeLogin implements rotatingSessionLogin.adopt for OpenCode: the +// shared file with every provider entry the session holds strictly newer +// replaced by the session's, or nil when there is none. +func adoptOpenCodeLogin(sess, shared []byte, sessMod, sharedMod time.Time) []byte { + if !sessMod.After(sharedMod) { + return nil + } + var sessTop, sharedTop map[string]json.RawMessage + if json.Unmarshal(sess, &sessTop) != nil || json.Unmarshal(shared, &sharedTop) != nil || sharedTop == nil { + return nil + } + changed := false + for provider, sharedRaw := range sharedTop { + h, ok := openCodeOAuthEntry(sharedRaw) + if !ok { + continue + } + s, ok := openCodeOAuthEntry(sessTop[provider]) + if !ok || s.Access == "" || s.Refresh == h.Refresh || s.Expires <= h.Expires { + continue + } + sharedTop[provider] = sessTop[provider] + changed = true + } + if !changed { + return nil + } + out, err := json.MarshalIndent(sharedTop, "", " ") + if err != nil { + return nil + } + return out +} + +// ---- the check + +// rotatingLoginKey is the sessionLoginCache key of one session's rotating +// login; the Claude check keys the same cache by the bare session id. +func rotatingLoginKey(id, rel string) string { return id + "\x00" + rel } + +// reconcileRotatingLogin adopts a strictly newer login of one vendor from a +// session HOME into the shared file. The session's copy is never written: +// after an adoption it holds the same login as the shared file. The caller +// holds sessionRotatingLoginMu. +func (o sessionLoginOps) reconcileRotatingLogin(id string, l rotatingSessionLogin) (sessionLoginResult, error) { + var none sessionLoginResult + home := userSessionHome(id) + path := filepath.Join(home, l.rel) + target := filepath.Join(sharedAgentHome, l.rel) + + info, err := os.Lstat(path) + if errors.Is(err, fs.ErrNotExist) { + return none, nil + } + if err != nil { + return none, fmt.Errorf("inspecting the session's %s login: %w", l.vendor, err) + } + if !info.Mode().IsRegular() { + return none, nil + } + sharedInfo, err := os.Lstat(target) + if errors.Is(err, fs.ErrNotExist) { + // No shared login to split from. + return none, nil + } + if err != nil { + return none, fmt.Errorf("inspecting the shared %s login: %w", l.vendor, err) + } + if !info.ModTime().After(sharedInfo.ModTime()) { + // Not written after the shared file: an unchanged copy, or one an + // adoption already settled. Nothing is read. + return none, nil + } + if !sharedInfo.Mode().IsRegular() { + // The session's file may hold the newest login, and the shared one + // is nothing hive could compare or replace: report it, so a removal + // keeps the session. + return none, fmt.Errorf("%w: the shared %s login %s is not a regular file", sharedfile.ErrUnsafeLocation, l.vendor, target) + } + data, err := o.readSessionLogin(home, path) + if errors.Is(err, fs.ErrNotExist) { + return none, nil + } + if err != nil { + return none, err + } + shared, err := sharedfile.ReadNoFollow(target, claudeBridgeMaxCredentialBytes) + if errors.Is(err, fs.ErrNotExist) { + return none, nil + } + if err != nil { + return none, fmt.Errorf("reading the shared %s login: %w", l.vendor, err) + } + merged := l.adopt(data, shared, info.ModTime(), sharedInfo.ModTime()) + if merged == nil { + return none, nil + } + stale, err := replaceSharedLogin(target, merged, sharedInfo, o.now()) + if err != nil { + return none, fmt.Errorf("%w (%s); adopting it failed: %w", crux.ErrUserSessionHoldsLogin, l.vendor, err) + } + return sessionLoginResult{action: sessionLoginAdopted, staleShared: stale}, nil +} + +// replaceSharedLogin writes data over the shared login target, keeping the +// previous file beside it, provided target is still the file that was judged +// (same modification time and size). The new file keeps the old one's mode +// and, where the hive may, its owner, so every agent reaches it as before. +func replaceSharedLogin(target string, data []byte, judged os.FileInfo, now time.Time) (string, error) { + info, err := sharedfile.CheckLocation(target) + if err != nil { + return "", err + } + if info == nil || !info.ModTime().Equal(judged.ModTime()) || info.Size() != judged.Size() { + return "", errSharedLoginChanged + } + stale, err := preserveClaudeCredential(target, now) + if err != nil { + return "", fmt.Errorf("preserve shared login: %w", err) + } + if err := sharedfile.Replace(target, data, info.Mode().Perm(), sharedfile.Options{PreserveOwner: true}); err != nil { + return stale, err + } + return stale, nil +} + +// checkRotatingLogin runs one check under sessionRotatingLoginMu. +func (o sessionLoginOps) checkRotatingLogin(id string, l rotatingSessionLogin) (sessionLoginResult, error) { + sessionRotatingLoginMu.Lock() + defer sessionRotatingLoginMu.Unlock() + return o.reconcileRotatingLogin(id, l) +} + +// reportRotatingLogin logs and audits one check. Only an adoption is +// audited. The fields are the session id, the trigger, the vendor and file +// paths; never token material. +func reportRotatingLogin(logger *slog.Logger, audit func(action string, fields map[string]any), id, trigger string, l rotatingSessionLogin, res sessionLoginResult, err error) { + if res.action == sessionLoginAdopted { + logger.Warn("user session login: the session held a newer login than the shared file; adopted it into the shared login", + "session", id, "trigger", trigger, "vendor", l.vendor, "login", l.rel, "stale_shared_file", res.staleShared) + if audit != nil { + audit(AuditUserSessionLoginAdopted, auditFields( + "outcome", "success", + "session", id, + "trigger", trigger, + "vendor", l.vendor, + "login", l.rel, + "stale_shared_file", res.staleShared, + )) + } + } + if err != nil { + logger.Warn("user session login: check failed", "session", id, "trigger", trigger, "vendor", l.vendor, "error", err) + } +} + +// syncRotatingLogin checks one session's login of one vendor and reports it. +func (r *UserSessionRuntime) syncRotatingLogin(id, trigger string, l rotatingSessionLogin) error { + res, err := r.loginOps().checkRotatingLogin(id, l) + reportRotatingLogin(r.logger, r.loginAudit(), id, trigger, l, res, err) + return err +} + +// syncUserSessionRotatingLogins checks every rotating login of one session +// sandbox from the manager's sweep (syncUserSessionClaudeLogins), marking the +// cache keys it saw in present. +func (m *Manager) syncUserSessionRotatingLogins(id, trigger string, ops sessionLoginOps, force bool, present map[string]bool) { + for _, l := range rotatingSessionLogins { + path := filepath.Join(userSessionHome(id), l.rel) + target := filepath.Join(sharedAgentHome, l.rel) + stamp, ok := sessionLoginStampOf(path, target) + if !ok { + continue + } + key := rotatingLoginKey(id, l.rel) + present[key] = true + now := ops.now() + if !m.sessionLogins.due(key, stamp, now, force) { + continue + } + res, err := ops.checkRotatingLogin(id, l) + reportRotatingLogin(m.logger, func(action string, fields map[string]any) { m.audit(action, "", fields) }, id, trigger, l, res, err) + if after, aok := sessionLoginStampOf(path, target); aok { + m.sessionLogins.record(key, after, now) + } + } +} diff --git a/src/crux/agent/usersession_login_rotating_test.go b/src/crux/agent/usersession_login_rotating_test.go new file mode 100644 index 0000000000..751859c1d9 --- /dev/null +++ b/src/crux/agent/usersession_login_rotating_test.go @@ -0,0 +1,472 @@ +package agent + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/crux/config" +) + +// Every credential in this file is synthetic: each token string carries +// bridgeTestTokenSentinel, so a test can prove that no log line, audit field +// or error ever holds token material. + +// codexTestLogin is a synthetic Codex ChatGPT login file. +func codexTestLogin(tag string, lastRefresh time.Time) []byte { + return []byte(fmt.Sprintf(`{ + "OPENAI_API_KEY": null, + "auth_mode": "chatgpt", + "tokens": { + "id_token": "id-%[1]s-%[2]s", + "access_token": "acc-%[1]s-%[2]s", + "refresh_token": "ref-%[1]s-%[2]s", + "account_id": "account-test" + }, + "last_refresh": %[3]q +} +`, tag, bridgeTestTokenSentinel, lastRefresh.UTC().Format(time.RFC3339Nano))) +} + +// openCodeTestEntry is a synthetic OpenCode "oauth" provider entry. +func openCodeTestEntry(tag string, expires time.Time) string { + return fmt.Sprintf(`{"type":"oauth","refresh":"ref-%[1]s-%[2]s","access":"acc-%[1]s-%[2]s","expires":%[3]d}`, + tag, bridgeTestTokenSentinel, expires.UnixMilli()) +} + +// openCodeTestLogin is a synthetic OpenCode auth.json: one rotating OAuth +// provider and one API-key provider. +func openCodeTestLogin(tag string, expires time.Time) []byte { + return []byte(fmt.Sprintf(`{"anthropic":%s,"openrouter":{"type":"api","key":"key-%s"}}`, + openCodeTestEntry(tag, expires), bridgeTestTokenSentinel)) +} + +// codexRefresh / openCodeRefresh return the refresh token a test file holds. +func codexRefresh(t *testing.T, path string) string { + t.Helper() + _, refresh, _, ok := parseCodexLogin(mustRead(t, path)) + if !ok { + t.Fatalf("%s is not a Codex ChatGPT login", path) + } + return refresh +} + +func openCodeEntries(t *testing.T, path string) map[string]json.RawMessage { + t.Helper() + var top map[string]json.RawMessage + if err := json.Unmarshal(mustRead(t, path), &top); err != nil { + t.Fatalf("%s is not an OpenCode auth file: %v", path, err) + } + return top +} + +func openCodeRefresh(t *testing.T, path, provider string) string { + t.Helper() + e, ok := openCodeOAuthEntry(openCodeEntries(t, path)[provider]) + if !ok { + t.Fatalf("%s has no OAuth entry for %s", path, provider) + } + return e.Refresh +} + +// rotatingTestVendor drives one vendor through the shared scenarios. +type rotatingTestVendor struct { + rel string + // login builds a synthetic login whose freshness field is fresh. + login func(tag string, fresh time.Time) []byte + // refresh reads the refresh token of the vendor's login at path. + refresh func(t *testing.T, path string) string +} + +func rotatingTestVendors() map[string]rotatingTestVendor { + return map[string]rotatingTestVendor{ + "codex": {rel: userSessionCodexLoginRel, login: codexTestLogin, refresh: codexRefresh}, + "opencode": {rel: userSessionOpenCodeLoginRel, login: openCodeTestLogin, refresh: func(t *testing.T, path string) string { + return openCodeRefresh(t, path, "anthropic") + }}, + } +} + +func (f *sessionLoginFixture) adoptionsOf(vendor string) []recordedAudit { + f.sink.mu.Lock() + defer f.sink.mu.Unlock() + var out []recordedAudit + for _, e := range f.sink.entries { + if e.Action == AuditUserSessionLoginAdopted && e.Fields["vendor"] == vendor { + out = append(out, e) + } + } + return out +} + +func TestAdoptCodexLogin(t *testing.T) { + now := time.Now() + old, recent := now.Add(-time.Hour), now + shared := codexTestLogin("shared", now.Add(-2*time.Hour)) + rotated := codexTestLogin("rotated", now) + apiKey := []byte(`{"OPENAI_API_KEY":"sk-` + bridgeTestTokenSentinel + `"}`) + cases := []struct { + name string + sess, shared []byte + sessMod, sharedMod time.Time + want bool + }{ + {"refreshed in the session", rotated, shared, recent, old, true}, + {"written before the shared file", rotated, shared, old, recent, false}, + {"same refresh token (an unchanged copy)", shared, shared, recent, old, false}, + {"earlier last refresh", codexTestLogin("older", now.Add(-3*time.Hour)), shared, recent, old, false}, + {"no last refresh in the session", []byte(`{"tokens":{"access_token":"a","refresh_token":"r2"}}`), shared, recent, old, false}, + {"no access token", []byte(`{"tokens":{"access_token":"","refresh_token":"r2"},"last_refresh":"` + now.UTC().Format(time.RFC3339) + `"}`), shared, recent, old, false}, + {"session holds an API key only", apiKey, shared, recent, old, false}, + {"shared is an API-key login", rotated, apiKey, recent, old, false}, + {"session is not JSON", []byte("not a login"), shared, recent, old, false}, + {"shared login without last refresh", rotated, []byte(`{"tokens":{"access_token":"a","refresh_token":"r"}}`), recent, old, true}, + } + for _, c := range cases { + got := adoptCodexLogin(c.sess, c.shared, c.sessMod, c.sharedMod) + if (got != nil) != c.want { + t.Errorf("%s: adopted = %v, want %v", c.name, got != nil, c.want) + } + } + + // An adoption takes the session's ChatGPT login and keeps everything + // else the shared file holds. + sharedWithKey := []byte(strings.Replace(string(shared), `"OPENAI_API_KEY": null`, `"OPENAI_API_KEY": "sk-fleet", "future_field": 7`, 1)) + out := adoptCodexLogin(rotated, sharedWithKey, recent, old) + _, refresh, last, ok := parseCodexLogin(out) + if !ok || refresh != "ref-rotated-"+bridgeTestTokenSentinel || !last.Equal(now.UTC()) { + t.Errorf("the adopted file does not hold the session's login") + } + var top map[string]any + if err := json.Unmarshal(out, &top); err != nil { + t.Fatal(err) + } + if top["OPENAI_API_KEY"] != "sk-fleet" || top["future_field"] != float64(7) { + t.Errorf("the adoption dropped the shared file's other fields: %v", top["OPENAI_API_KEY"]) + } +} + +func TestAdoptOpenCodeLogin(t *testing.T) { + now := time.Now() + old, recent := now.Add(-time.Hour), now + shared := []byte(fmt.Sprintf(`{"anthropic":%s,"github-copilot":%s,"openai":%s,"openrouter":{"type":"api","key":"key-fleet"}}`, + openCodeTestEntry("a-shared", now.Add(time.Minute)), + openCodeTestEntry("g-shared", now.Add(time.Hour)), + openCodeTestEntry("o-shared", now.Add(time.Hour)))) + sess := []byte(fmt.Sprintf(`{"anthropic":%s,"github-copilot":%s,"openai":%s,"openrouter":{"type":"api","key":"key-session"},"google":%s}`, + openCodeTestEntry("a-rotated", now.Add(8*time.Hour)), // newer: adopted + openCodeTestEntry("g-older", now.Add(time.Minute)), // older: kept + openCodeTestEntry("o-shared", now.Add(2*time.Hour)), // same refresh token: kept + openCodeTestEntry("google-own", now.Add(8*time.Hour)))) // not in the shared file: not added + + out := adoptOpenCodeLogin(sess, shared, recent, old) + if out == nil { + t.Fatal("a newer provider entry was not adopted") + } + var top map[string]json.RawMessage + if err := json.Unmarshal(out, &top); err != nil { + t.Fatal(err) + } + refresh := func(p string) string { + e, _ := openCodeOAuthEntry(top[p]) + return e.Refresh + } + if refresh("anthropic") != "ref-a-rotated-"+bridgeTestTokenSentinel { + t.Error("the refreshed entry was not adopted") + } + if refresh("github-copilot") != "ref-g-shared-"+bridgeTestTokenSentinel || refresh("openai") != "ref-o-shared-"+bridgeTestTokenSentinel { + t.Error("an entry that is not newer was replaced") + } + if !bytes.Contains(top["openrouter"], []byte("key-fleet")) { + t.Error("the shared API-key entry was replaced") + } + if _, ok := top["google"]; ok { + t.Error("an entry the shared file did not hold was added") + } + + if adoptOpenCodeLogin(sess, shared, old, recent) != nil { + t.Error("a session file written before the shared one was adopted") + } + if adoptOpenCodeLogin(shared, shared, recent, old) != nil { + t.Error("an unchanged copy was adopted") + } + if adoptOpenCodeLogin([]byte("not json"), shared, recent, old) != nil { + t.Error("a file that is not JSON was adopted") + } +} + +// The failure the issue describes, for each rotating vendor: the CLI in a +// session refreshed its copy, which rotated the refresh token. The newer +// login must reach the shared file, once, with an audit entry and the old +// shared file kept beside it. +func TestSessionRefresh_CodexAndOpenCodeNeverLeaveTheSharedLoginStale(t *testing.T) { + for vendor, v := range rotatingTestVendors() { + t.Run(vendor, func(t *testing.T) { + f := newSessionLoginFixture(t) + now := time.Now() + target := filepath.Join(sharedAgentHome, v.rel) + writeLoginAt(t, target, v.login("shared", now.Add(-2*time.Hour)), now.Add(-time.Hour)) + f.start(t) + path := filepath.Join(userSessionHome(testSessionID), v.rel) + if got := v.refresh(t, path); got != "ref-shared-"+bridgeTestTokenSentinel { + t.Fatal("the session did not get the shared login") + } + if len(f.adoptionsOf(vendor)) != 0 { + t.Fatal("a plain start adopted a login") + } + + writeLoginAt(t, path, v.login("rotated", now.Add(8*time.Hour)), now) + f.m.syncUserSessionClaudeLogins(sessionLoginTriggerWatchdog) + + if got := v.refresh(t, target); got != "ref-rotated-"+bridgeTestTokenSentinel { + t.Error("the shared login does not hold the session's refreshed login") + } + if n := len(staleFilesBeside(t, target)); n != 1 { + t.Errorf("replaced shared login preserved %d times, want 1", n) + } + recs := f.adoptionsOf(vendor) + if len(recs) != 1 { + t.Fatalf("%d adoptions audited, want 1", len(recs)) + } + rec := recs[0] + if rec.Fields["session"] != testSessionID || rec.Fields["trigger"] != sessionLoginTriggerWatchdog || + rec.Fields["login"] != v.rel || rec.Fields["outcome"] != "success" { + t.Errorf("audit = %+v", rec) + } + + // Converged: further checks, forced or not, change nothing. + before := mustRead(t, target) + for i := 0; i < 3; i++ { + f.m.syncUserSessionClaudeLogins(sessionLoginTriggerSignIn) + f.r.copyLoginFiles(testSessionID, testSessionUID) + } + if !bytes.Equal(mustRead(t, target), before) || len(f.adoptionsOf(vendor)) != 1 { + t.Error("the login did not settle after one adoption") + } + if got := v.refresh(t, path); got != "ref-rotated-"+bridgeTestTokenSentinel { + t.Error("the session lost the login it refreshed") + } + f.assertNoTokenMaterial(t) + }) + } +} + +// A session start or resume adopts first, so the shared file the copy is +// then compared with is already the newer login. +func TestUserSessionStart_AdoptsANewerCodexLogin(t *testing.T) { + f := newSessionLoginFixture(t) + now := time.Now() + target := filepath.Join(sharedAgentHome, userSessionCodexLoginRel) + writeLoginAt(t, target, codexTestLogin("shared", now.Add(-2*time.Hour)), now.Add(-time.Hour)) + f.start(t) + path := filepath.Join(userSessionHome(testSessionID), userSessionCodexLoginRel) + writeLoginAt(t, path, codexTestLogin("rotated", now), now) + + f.r.copyLoginFiles(testSessionID, testSessionUID) + if codexRefresh(t, target) != "ref-rotated-"+bridgeTestTokenSentinel { + t.Error("a resume did not adopt the session's newer login") + } + recs := f.adoptionsOf("codex") + if len(recs) != 1 || recs[0].Fields["trigger"] != sessionLoginTriggerStart { + t.Errorf("audit = %+v", recs) + } + f.assertNoTokenMaterial(t) +} + +// An agent refreshed the shared login after the session's copy was made: the +// shared file is newer and is never replaced by the session's older copy. +func TestSessionLogin_OlderSessionCodexLoginIsNeverAdopted(t *testing.T) { + f := newSessionLoginFixture(t) + now := time.Now() + target := filepath.Join(sharedAgentHome, userSessionCodexLoginRel) + writeLoginAt(t, target, codexTestLogin("first", now.Add(-3*time.Hour)), now.Add(-2*time.Hour)) + f.start(t) + agentRefresh := codexTestLogin("agent", now.Add(-time.Minute)) + writeLoginAt(t, target, agentRefresh, now) + f.m.syncUserSessionClaudeLogins(sessionLoginTriggerSignIn) + if !bytes.Equal(mustRead(t, target), agentRefresh) || len(f.adoptionsOf("codex")) != 0 { + t.Error("an older session login replaced the agents' newer one") + } + + // The session's CLI rewrites its file later with an OLDER refresh time + // (it saved something else): written after, but not newer. + path := filepath.Join(userSessionHome(testSessionID), userSessionCodexLoginRel) + writeLoginAt(t, path, codexTestLogin("stale", now.Add(-2*time.Hour)), now.Add(time.Minute)) + f.m.syncUserSessionClaudeLogins(sessionLoginTriggerSignIn) + if !bytes.Equal(mustRead(t, target), agentRefresh) || len(f.adoptionsOf("codex")) != 0 { + t.Error("a session login with an older last refresh was adopted") + } +} + +// Deleting a session must never delete the only valid login, for these +// vendors too. +func TestSessionRemove_NeverDestroysTheOnlyValidCodexOrOpenCodeLogin(t *testing.T) { + for vendor, v := range rotatingTestVendors() { + t.Run(vendor+"/adopted before removal", func(t *testing.T) { + f := newSessionLoginFixture(t) + now := time.Now() + target := filepath.Join(sharedAgentHome, v.rel) + writeLoginAt(t, target, v.login("shared", now.Add(-2*time.Hour)), now.Add(-time.Hour)) + f.start(t) + writeLoginAt(t, filepath.Join(userSessionHome(testSessionID), v.rel), v.login("rotated", now.Add(8*time.Hour)), now) + + if err := f.r.Remove(testSessionID); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(userSessionSandboxDir(testSessionID)); err == nil { + t.Error("the sandbox survived Remove") + } + if v.refresh(t, target) != "ref-rotated-"+bridgeTestTokenSentinel { + t.Error("the session's login was deleted with the session instead of being adopted") + } + recs := f.adoptionsOf(vendor) + if len(recs) != 1 || recs[0].Fields["trigger"] != sessionLoginTriggerRemove { + t.Errorf("audit = %+v", recs) + } + f.assertNoTokenMaterial(t) + }) + t.Run(vendor+"/kept when it cannot be adopted", func(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root passes the shared-directory ownership check this test relies on") + } + f := newSessionLoginFixture(t) + now := time.Now() + target := filepath.Join(sharedAgentHome, v.rel) + writeLoginAt(t, target, v.login("shared", now.Add(-2*time.Hour)), now.Add(-time.Hour)) + f.start(t) + path := filepath.Join(userSessionHome(testSessionID), v.rel) + rotated := v.login("rotated", now.Add(8*time.Hour)) + writeLoginAt(t, path, rotated, now) + // A world-writable shared directory: sharedfile refuses to write + // there, so the adoption fails. + dir := filepath.Dir(target) + if err := os.Chmod(dir, 0o777); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + + err := f.r.Remove(testSessionID) + if err == nil || !errors.Is(err, crux.ErrUserSessionHoldsLogin) { + t.Fatalf("Remove = %v, want a refusal that keeps the session", err) + } + if !bytes.Equal(mustRead(t, path), rotated) { + t.Error("the session's login is gone although it was never adopted") + } + if strings.Contains(err.Error(), bridgeTestTokenSentinel) { + t.Error("token material in the error") + } + f.assertNoTokenMaterial(t) + }) + t.Run(vendor+"/an unchanged copy is just removed", func(t *testing.T) { + f := newSessionLoginFixture(t) + now := time.Now() + target := filepath.Join(sharedAgentHome, v.rel) + shared := v.login("shared", now.Add(-2*time.Hour)) + writeLoginAt(t, target, shared, now.Add(-time.Hour)) + f.start(t) + if err := f.r.Remove(testSessionID); err != nil { + t.Fatal(err) + } + if !bytes.Equal(mustRead(t, target), shared) || f.adoptions() != 0 { + t.Error("removing an ordinary session touched the shared login") + } + }) + } +} + +// A shared file that changed after it was judged (an agent's CLI wrote its +// own refresh) is never overwritten by the adoption. +func TestReplaceSharedLogin_RefusesASharedFileThatChanged(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "auth.json") + now := time.Now() + writeLoginAt(t, target, codexTestLogin("judged", now), now.Add(-time.Hour)) + judged, err := os.Lstat(target) + if err != nil { + t.Fatal(err) + } + agent := codexTestLogin("agent", now.Add(time.Minute)) + writeLoginAt(t, target, agent, now) + + _, err = replaceSharedLogin(target, codexTestLogin("session", now), judged, now) + if !errors.Is(err, errSharedLoginChanged) { + t.Fatalf("err = %v, want errSharedLoginChanged", err) + } + if !bytes.Equal(mustRead(t, target), agent) || len(staleFilesBeside(t, target)) != 0 { + t.Error("a shared login that changed after the judgement was touched") + } + + // Unchanged since the judgement: replaced, with the mode kept. + if err := os.Chmod(target, 0o640); err != nil { + t.Fatal(err) + } + judged, _ = os.Lstat(target) + stale, err := replaceSharedLogin(target, codexTestLogin("session", now), judged, now) + if err != nil || stale == "" { + t.Fatalf("replace = %q, %v", stale, err) + } + if st, _ := os.Lstat(target); st.Mode().Perm() != 0o640 { + t.Errorf("mode = %v, want the shared file's 0640 kept", st.Mode().Perm()) + } + if !bytes.Equal(mustRead(t, stale), agent) { + t.Error("the replaced shared login was not preserved") + } +} + +// Several sessions holding newer logins, judged concurrently by the sweep +// and by per-session checks: the shared file ends on the latest one, whole. +func TestSessionLogin_ConcurrentCodexChecksConvergeOnOneLogin(t *testing.T) { + const sessions = 6 + withSharedAgentHome(t) + t.Setenv(userSessionSandboxDirEnv, filepath.Join(t.TempDir(), "sandbox")) + t.Setenv(userSessionUIDBaseEnv, "") + t.Setenv(userSessionUIDSlotsEnv, "") + t.Setenv(userSessionGIDEnv, "") + priv := func(context.Context, string, io.Reader, ...string) ([]byte, error) { + return nil, errors.New("unexpected helper") + } + useSessionLoginPriv(t, priv) + m := NewManager(map[string]config.AgentConfig{}, slog.New(slog.NewTextHandler(io.Discard, nil)), ProjectContext{}) + m.SetAuditSink(&fakeAuditSink{}) + + now := time.Now() + target := filepath.Join(sharedAgentHome, userSessionCodexLoginRel) + writeLoginAt(t, target, codexTestLogin("shared", now.Add(-time.Hour)), now.Add(-time.Hour)) + ids := make([]string, sessions) + for i := range ids { + ids[i] = fmt.Sprintf("%012x", i+1) + at := now.Add(time.Duration(i+1) * time.Hour) + writeLoginAt(t, filepath.Join(userSessionHome(ids[i]), userSessionCodexLoginRel), codexTestLogin(fmt.Sprintf("s%d", i), at), at) + } + codex, _ := rotatingSessionLoginFor(userSessionCodexLoginRel) + ops := sessionLoginOps{priv: priv, statUID: func(string) (int, error) { return testSessionUID, nil }, now: time.Now} + var wg sync.WaitGroup + for _, id := range ids { + wg.Add(2) + go func(id string) { + defer wg.Done() + _, _ = ops.checkRotatingLogin(id, codex) + }(id) + go func() { + defer wg.Done() + m.syncUserSessionClaudeLogins(sessionLoginTriggerSignIn) + }() + } + wg.Wait() + m.syncUserSessionClaudeLogins(sessionLoginTriggerSignIn) + + if got := codexRefresh(t, target); got != fmt.Sprintf("ref-s%d-%s", sessions-1, bridgeTestTokenSentinel) { + t.Error("the shared login is not the latest session login") + } +} diff --git a/src/crux/agent/usersession_remove.go b/src/crux/agent/usersession_remove.go index 9655b8611f..5e7f6f2e87 100644 --- a/src/crux/agent/usersession_remove.go +++ b/src/crux/agent/usersession_remove.go @@ -76,15 +76,14 @@ func (r *UserSessionRuntime) Remove(id string) error { // (The CLI creates files and directories with private modes; the hive // must be able to look at the login path to judge it.) r.makeHomeReadable(id) - if err := r.syncClaudeLogin(id, sessionLoginTriggerRemove, sessionLoginModeRemove); err != nil { - switch { - case errors.Is(err, sharedfile.ErrTooLarge): - // Over the size of any credentials file: not a login, so there - // is nothing to keep. syncClaudeLogin logged it. - case errors.Is(err, crux.ErrUserSessionHoldsLogin): + if err := keepSessionForLogin(r.syncClaudeLogin(id, sessionLoginTriggerRemove, sessionLoginModeRemove)); err != nil { + return err + } + // The same for a Codex or OpenCode login the session's CLI refreshed + // (usersession_login_rotating.go). + for _, l := range rotatingSessionLogins { + if err := keepSessionForLogin(r.syncRotatingLogin(id, sessionLoginTriggerRemove, l)); err != nil { return err - default: - return fmt.Errorf("this session's sign-in could not be checked, so its files are kept: %w", err) } } r.workspaceMu.Lock() @@ -112,6 +111,23 @@ func (r *UserSessionRuntime) Remove(id string) error { return nil } +// keepSessionForLogin turns the outcome of a login check made before a +// removal into the error that stops it, nil when the removal may go on. +func keepSessionForLogin(err error) error { + switch { + case err == nil: + return nil + case errors.Is(err, sharedfile.ErrTooLarge): + // Over the size of any credentials file: not a login, so there is + // nothing to keep. The check logged it. + return nil + case errors.Is(err, crux.ErrUserSessionHoldsLogin): + return err + default: + return fmt.Errorf("this session's sign-in could not be checked, so its files are kept: %w", err) + } +} + // Removed reports whether nothing of session id is left on disk: no sandbox, // no worktrees and none of the directories earlier releases made. It answers // false when that cannot be told (the sandbox root itself is missing or diff --git a/src/crux/audit.go b/src/crux/audit.go index a75667a009..fe1f1514dd 100644 --- a/src/crux/audit.go +++ b/src/crux/audit.go @@ -61,12 +61,13 @@ const ( AuditClaudeCredentialRefreshed = "claude_credential_refreshed" // AuditUserSessionLoginAdopted is recorded when a user session's HOME held - // a Claude login strictly newer than the shared one (the CLI in the - // session refreshed, or signed in, on its own copy) and hive adopted it - // into the shared login so the fleet and the session keep ONE login. The - // detail names the session, the trigger (boot, watchdog, sign-in, - // session-start, session-remove) and where the replaced shared file was - // preserved; it never carries token material. + // a Claude, Codex or OpenCode login strictly newer than the shared one + // (the CLI in the session refreshed, or signed in, on its own copy) and + // hive adopted it into the shared login so the fleet and the session keep + // ONE login. The detail names the session, the trigger (boot, watchdog, + // sign-in, session-start, session-remove), where the replaced shared file + // was preserved and, for Codex and OpenCode, the vendor and login file; it + // never carries token material. AuditUserSessionLoginAdopted = "user_session_login_adopted" ) diff --git a/src/crux/usersession_types.go b/src/crux/usersession_types.go index 6aa472c691..c229ffa0ec 100644 --- a/src/crux/usersession_types.go +++ b/src/crux/usersession_types.go @@ -140,7 +140,7 @@ var ( // written. ErrUserSessionInboxSymlink = errors.New("refusing to write through a symlinked .hive/inbox directory") // ErrUserSessionHoldsLogin is wrapped by Remove when the session's HOME - // holds a Claude login that is usable and strictly newer than the shared + // holds a Claude, Codex or OpenCode login strictly newer than the shared // one and adopting it into the shared login failed. Nothing of the session // is removed: deleting it would delete the hive's only valid sign-in. ErrUserSessionHoldsLogin = errors.New("this session holds the hive's current sign-in") diff --git a/src/docs/api-reference/sessions.md b/src/docs/api-reference/sessions.md index 8981b7f825..3d3881c0ff 100644 --- a/src/docs/api-reference/sessions.md +++ b/src/docs/api-reference/sessions.md @@ -132,6 +132,8 @@ The Claude login is copied **without its refresh token**. A session uses the fle If a session's HOME holds a complete Claude login that is usable and strictly newer than the shared one (a copy from an older release that the CLI refreshed, or a sign-in done inside the session), the hive adopts it into the shared login, keeps the replaced file as `.credentials.json.stale-`, and records `user_session_login_adopted` with `session`, `trigger` (`boot`, `watchdog`, `sign-in`, `session-start` or `session-remove`) and `stale_shared_file`, never token material. The check also runs before a session is deleted. Having nothing to adopt (no login file, an expired copy, a copy without a refresh token, a file that is not a credential) is not a failure and does not slow the delete. Only a strictly newer, usable login that cannot be adopted stops it: nothing is removed, the session is kept, and its `delete_error` reads `this session holds the hive's current sign-in; adopting it failed: ` (logged at WARN and audited). A login file that cannot be read at all also keeps the session, with the reason. A hive whose agents were locked out this way recovers at its next boot or poll without a new sign-in, provided the session that holds the login has not been deleted. +Codex's ChatGPT login and an OpenCode OAuth provider entry are copied whole, refresh token included, and rotate when the CLI in the session refreshes them. When the session's file holds a strictly newer login than the shared one (Codex: a later `last_refresh` and a different refresh token; OpenCode, per provider entry: a later `expires` and a different refresh token; in both cases the file was written after the shared one), the hive adopts it into the shared file at the same points and with the same delete rule as the Claude login. The replaced file is kept as `auth.json.stale-`, and `user_session_login_adopted` also carries `vendor` (`codex` or `opencode`) and `login` (the file). An API-key login is never replaced, and an OpenCode provider the shared file does not hold is not added ([#18740](https://github.com/hivecommons/hive/issues/18740)). + ## Seeding from the Inbox The Inbox's **🔗 Share ▾ → Hive → spek…** sends one item, or the multi-select, into a session: a new one (`POST /api/sessions` with `seed_items`) or a running one the caller may type into (`POST /api/sessions/{id}/seed`). Roles are the Inbox share rule (`requireInboxShareRole`: a verified owner or read-write) plus the Send rule for the session: the `read` role gets 403, a private session of someone else 404. At most 20 items per call. The hive reads each item's current content (title, summary, transcript or the hive's own machine transcript, highlights) and writes **one markdown file per item** at `/.hive/inbox/-.md`, where `` is the session's workspace (its own work dir when it has none): diff --git a/src/docs/security-model.md b/src/docs/security-model.md index 8994c6f314..ae61713948 100644 --- a/src/docs/security-model.md +++ b/src/docs/security-model.md @@ -622,11 +622,33 @@ importance: when it is newer. The audit entry is the record of it, and a dashboard sign-in puts the hive back on the operator's account. The other vendors' files are still plain copies, refresh token included - where the vendor stores one. Codex's ChatGPT login and an OpenCode OAuth - entry rotate on refresh and can split from the shared file the same way; - Gemini's Google refresh token and the Copilot CLI token do not rotate. For - all of them a resume no longer overwrites a file the session's CLI rewrote - after the shared one was written. + where the vendor stores one. Gemini's Google refresh token and the Copilot + CLI token do not rotate. Codex's ChatGPT login (`.codex/auth.json`) and an + OpenCode OAuth entry (`opencode/auth.json`) do, so a session that refreshes + its copy holds the only valid login; for these two the hive **adopts** that + login back into the shared file the agents link to + ([#18740](https://github.com/hivecommons/hive/issues/18740)). Codex: the + session's file was written after the shared one, holds a ChatGPT login + with a different refresh token and records a later `last_refresh`, and the + shared file itself holds a ChatGPT login (an API-key login does not rotate + and is never replaced). OpenCode, per provider entry: both entries are + `oauth`, the session's has a different refresh token and a later + `expires`, and the session's file was written after the shared one; only + those entries are replaced, every other entry of the shared file is kept, + and a provider the shared file does not hold is not added. Only those + fields and modification times decide; token values are never logged. The + replaced file is kept as `auth.json.stale-`, the new one keeps the + old one's mode (and owner, where the hive may set it), and + `user_session_login_adopted` names the session, trigger, vendor and file. + It runs when the Claude check runs, deletion included: a newer login that + cannot be adopted keeps the session. Unlike Claude, a session still holds a + copy that can refresh, because whether each CLI accepts a login without its + refresh token has not been verified. So a session and an agent can still + refresh the same token within one poll; the shared file then converges on + the newer login at the next poll, and the hive never overwrites a shared + file that changed after it was compared. For all of these vendors a resume + no longer overwrites a file the session's CLI rewrote after the shared one + was written. - **Terminal access is bound.** ttyd listens on loopback without a secret a session uid could not read (its `-c` credential is visible in `/proc`), so session attaches are gated by a per-session token, HMAC-SHA256 of the tmux @@ -693,9 +715,10 @@ importance: ([inbox-recording.md](inbox-recording.md)); `/terminal/` and `/api/` keep `display-capture=()`. -Audit: `user_session_login_adopted` (a newer Claude login found in a session -home was adopted into the shared login; session id, trigger and the preserved -file's path, never token material), `session_created`, `session_started` (the +Audit: `user_session_login_adopted` (a newer Claude, Codex or OpenCode login +found in a session home was adopted into the shared login; session id, +trigger, the preserved file's path and, for Codex and OpenCode, the vendor and +file, never token material), `session_created`, `session_started` (the outcome of the background start), `session_autostart` (how the startup auto-answer ended and which screens it answered), `session_closed`, `session_renamed`, `session_input` and `session_upload` record the user and session id (never input text).