diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 1e7a6f6..31f7f61 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -1,5 +1,6 @@ { "name": "october", "owner": { "name": "October" }, + "metadata": { "description": "Agent Intercom plugins for connecting Claude Code sessions to other agents." }, "plugins": [{ "name": "agent-intercom", "source": "./plugin", "description": "Messages, shared work and native inbox notifications for connected agents." }] } diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 0000000..d6c6a2c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,43 @@ +name: Bug report +description: Report incorrect behavior in the agentintercom CLI, daemon, SDKs or workspace UI. +labels: [bug] +body: + - type: markdown + attributes: + value: | + Report security vulnerabilities privately through the security policy, not here. + Never post tokens, connection files, private messages or account links. + - type: textarea + id: what-happened + attributes: + label: What happened + description: What you did, what you expected, and what happened instead. + validations: + required: true + - type: textarea + id: reproduce + attributes: + label: Steps to reproduce + description: Commands or steps, with credentials replaced by placeholders. + validations: + required: true + - type: input + id: version + attributes: + label: Version + description: Output of `agentintercom version`, or the commit you built from. + validations: + required: true + - type: input + id: platform + attributes: + label: Platform + description: Operating system and architecture, plus the agent app and its version if one is involved. + validations: + required: true + - type: textarea + id: logs + attributes: + label: Relevant output + description: Error messages or `agentintercom doctor --json` output, with secrets removed. + render: text diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..ad3ff94 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Report a security vulnerability + url: https://github.com/october-dev/agentintercom/security/advisories/new + about: Report vulnerabilities privately instead of opening a public issue. diff --git a/CHANGELOG.md b/CHANGELOG.md index 384f9fb..cc253fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,50 @@ ## Unreleased +Changes on `main` after the `0.2.0` release candidate. They are not in the +published `agentintercom-cli@0.2.0` package; build from source to use them +before the next release. + +- Add `task claim`, `task release`, `task complete` and `task progress` CLI + commands for shared tasks (#196). +- Add `question list` and `question answer` to answer pending agent questions + from a terminal (#195). +- Let `agent run` read the scope token from `--scope-token-file` or + `--scope-token-fd` (#155). +- Add `downloadAttachment` to the TypeScript client, with integrity checks (#197). +- Run the Cursor adapter under `agent run` and let `doctor` find `cursor-agent` + (#209). +- Exit with status 0 for subcommand `--help` (#191). +- Preserve the HTTP status when a Go client error body is not valid JSON (#190). +- Report failed `attachment upload` requests instead of printing `null`. +- Exit `agent run` and `session start` with the managed command's exit status, + and with a failure status after an interrupt. +- TypeScript client: report requests that fail without a runtime response as + `BusNetworkError`, `BusTimeoutError` or `BusAbortError` (subclasses of the new + `BusTransportError`, which keeps the `INTERNAL` code for compatibility) with + the underlying `cause`. +- Go and TypeScript clients: release an inbox reservation when its commit fails + or is cancelled, so messages return to the inbox without waiting 30 seconds. +- npm launcher: let Windows Ctrl+C reach the native process instead of + terminating it, and report signal exits (including SIGPIPE) as `128 + signal`. +- Return `NOT_FOUND` when completing or releasing an unknown task, accept + escalation answers when the message backlog is full, and expire messages + before releasing an expired inbox reservation. +- Refuse a runtime directory or discovery file owned by another local user. +- Hosted: recover OAuth client registration capacity from abandoned clients, + send the RFC 9207 `iss` authorization response parameter, and limit admins + to revoking member invitations. +- Hosted: optional per-client rate limits for OAuth registration and + authorization and device pairing, keyed on a proxy forwarding header + (`hosted serve --client-ip-header`, `--trusted-proxy`). +- Hosted: a member can no longer restore a connection that a workspace owner or + admin revoked by replacing it (migration `015_connection_revoker.sql`), and + one workspace's file deletion no longer stalls file access in others. +- Hosted: replaying a redeemed OAuth authorization code with its PKCE verifier + revokes the tokens issued from that code. + +## 0.2.0 (release candidate) + - Use the Agent Intercom product name, `agentintercom` command and `agentintercom-cli` npm package. Move the repository and Go module to `october-dev/agentintercom`. The @@ -14,6 +58,6 @@ - Preserve existing protocol 0.1 health/archive identifiers, local data paths, `OCTOBER_BUS_*` configuration, applied migrations and hosted deployment paths. -These changes are not a claim that an npm release or hosted launch has occurred. +`0.2.0` is published to npm under the `candidate` tag; it is not a hosted launch. See [releases](https://github.com/october-dev/agentintercom/releases) for published versions and [compatibility](compatibility/registry.json) for qualified adapters. diff --git a/README.md b/README.md index d72e2e4..00cc62e 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ npx agentintercom-cli@0.2.0 demo **Release note:** Version `0.2.0` is currently a release candidate. Use the version shown above when installing, since npm's `latest` tag still points to a placeholder. -On Windows or using a different agent? Check out the [connection options](https://github.com/october-dev/agentintercom#ways-to-connect). +On Windows or using a different agent? Check out the [connection options](https://github.com/october-dev/agentintercom/blob/main/docs/connect-sessions.md). Need help? See the [installation guide](https://github.com/october-dev/agentintercom/blob/main/docs/installation.md). diff --git a/SECURITY.md b/SECURITY.md index 5d0c790..a4e0b43 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -24,6 +24,6 @@ Security reports may cover: - malicious protocol inputs or denial of service; - adapter behavior that bypasses a harness permission boundary. -The current reference runtime is local-first and binds to loopback. Remote deployments need a separate authenticated transport and threat review. +The local runtime binds to loopback. Self-hosted workspaces use the authenticated HTTPS service described in [hosted workspaces](docs/hosted-workspaces.md) and [production hardening](docs/production-hardening.md); reports about that service, its OAuth and account flows, and the browser workspace are in scope. See [the local threat model](docs/threat-model.md) for current assumptions and limits. diff --git a/adapters/cursor/README.md b/adapters/cursor/README.md index 3937b96..b6e5fd3 100644 --- a/adapters/cursor/README.md +++ b/adapters/cursor/README.md @@ -97,7 +97,7 @@ Doctor probes a separate temporary bridge. Its `hostExecutable` identifies which | Discover and notify | Ask Cursor to call `list_peers` and send `codex-builder` a short `message_peer` with mode `notify`. Ask Codex to call `check_inbox`, then `acknowledge_messages` with the processed IDs. | | Request and reply | Ask Codex to send Cursor a `request` with a fresh `idempotencyKey` and one short `text` context item. Ask Cursor to pull, acknowledge, and send a `response` with `responseTo` set to the request ID. Codex can pull and acknowledge the reply, then check the original ID with `message_receipt`. Its `responseMessageId` should match the reply. | | Share a task | Ask Cursor to call `add_task`, then ask Codex to find the task with `list_tasks`, claim it, and complete it. Cursor can check the final state. | -| Ask a human | Ask Cursor to call `ask_user` with a short question. In the operator terminal, run `agentintercom question list --workspace cursor-demo`, then `agentintercom question answer --workspace cursor-demo --id QUESTION_ID --answer yes` with the returned ID. Have Cursor pull and acknowledge the answer. | +| Ask a human | Ask Cursor to call `ask_user` with a short question. In the operator terminal, run `agentintercom question list --workspace cursor-demo` (newer than `0.2.0`; use a source build), then `agentintercom question answer --workspace cursor-demo --id QUESTION_ID --answer yes` with the returned ID. Have Cursor pull and acknowledge the answer. | Use `check_inbox` between work steps. For a short check use `waitMs=1000`. Queued work waits until the host pulls. Send only the context the peer needs. An incoming request still goes through the recipient's normal permission controls. diff --git a/bus/archive.go b/bus/archive.go index 14a17a3..fa0b5f0 100644 --- a/bus/archive.go +++ b/bus/archive.go @@ -681,7 +681,7 @@ func validateArchive(archive *ScopeArchive) error { } } } - if activeMessages > messageBacklogCap { + if activeMessages > maxActiveMessages { return Errorf(CodeInvalidArgument, "Archive message backlog exceeds the scope limit") } for _, message := range archive.Messages { diff --git a/bus/attachments.go b/bus/attachments.go index 2587b04..73c7207 100644 --- a/bus/attachments.go +++ b/bus/attachments.go @@ -16,6 +16,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "unicode" @@ -71,6 +72,7 @@ type attachmentFiles struct { mu sync.Mutex directory string root *os.Root + readRoot atomic.Pointer[os.Root] lock *os.File temporary bool } @@ -142,11 +144,30 @@ func (f *attachmentFiles) open(source string) error { return err } f.root, f.lock = root, lock + f.readRoot.Store(root) return nil } + +// readable opens the directory if needed and returns its root for reading. +// Reads do not hold f.mu, so one workspace's large reads or exports never +// serialize another's; callers hold maintenance.RLock, which close waits for. +func (f *attachmentFiles) readable(source string) (*os.Root, error) { + if root := f.readRoot.Load(); root != nil { + return root, nil + } + f.mu.Lock() + defer f.mu.Unlock() + if err := f.open(source); err != nil { + return nil, err + } + return f.root, nil +} func (f *attachmentFiles) close() { + f.maintenance.Lock() + defer f.maintenance.Unlock() f.mu.Lock() defer f.mu.Unlock() + f.readRoot.Store(nil) if f.root != nil { _ = f.root.Close() } @@ -476,12 +497,11 @@ func (s *Store) ReadAttachment(ctx context.Context, scopeID, id string, offset i if err := consumeAttachmentTransfer(ctx, tx, scopeID, size, false); err != nil { return result, err } - s.files.mu.Lock() - defer s.files.mu.Unlock() - if err := s.files.open(s.source); err != nil { + root, err := s.files.readable(s.source) + if err != nil { return result, err } - data, err := s.readAttachmentFile(a, offset, size) + data, err := readAttachmentFile(root, a, offset, size) if err != nil { return result, err } @@ -491,12 +511,12 @@ func (s *Store) ReadAttachment(ctx context.Context, scopeID, id string, offset i } return result, tx.Commit() } -func (s *Store) readAttachmentFile(a Attachment, offset, size int64) ([]byte, error) { - info, err := s.files.root.Lstat(a.ID) +func readAttachmentFile(root *os.Root, a Attachment, offset, size int64) ([]byte, error) { + info, err := root.Lstat(a.ID) if err != nil || !info.Mode().IsRegular() || info.Size() != a.Size || (runtime.GOOS != "windows" && info.Mode().Perm()&0077 != 0) { return nil, Errorf(CodeInternal, "Attachment file is unavailable; restore it from backup") } - file, err := s.files.root.Open(a.ID) + file, err := root.Open(a.ID) if err != nil { return nil, Errorf(CodeInternal, "Attachment file is unavailable") } @@ -518,8 +538,6 @@ func (s *Store) readAttachmentFile(a Attachment, offset, size int64) ([]byte, er return data, nil } func (s *Store) DeleteAttachment(ctx context.Context, scopeID, id string) error { - s.files.maintenance.Lock() - defer s.files.maintenance.Unlock() kind, actor, err := channelAuthor(ctx, scopeID) if err != nil { return err @@ -557,8 +575,15 @@ func (s *Store) DeleteAttachment(ctx context.Context, scopeID, id string) error if err := tx.Commit(); err != nil { return err } - // The exclusive maintenance lock lets an in-progress backup finish first. - // If unlinking fails, metadata still blocks reads and maintenance retries it. + // The committed tombstone already hides the file. Unlink it now only if no + // read, export or backup that may have seen the old metadata is running; + // waiting for them would let one workspace's long export stall every + // workspace's file access behind this deletion. Otherwise, or if unlinking + // fails, garbage collection removes the file later. + if !s.files.maintenance.TryLock() { + return nil + } + defer s.files.maintenance.Unlock() s.files.mu.Lock() defer s.files.mu.Unlock() if err := s.files.open(s.source); err == nil { diff --git a/bus/attachments_archive.go b/bus/attachments_archive.go index 3e402ae..ebd6ccc 100644 --- a/bus/attachments_archive.go +++ b/bus/attachments_archive.go @@ -36,14 +36,13 @@ func (s *Store) exportAttachments(ctx context.Context, tx sqlExecutor, scopeID s if len(archive.Attachments) == 0 { return nil } - s.files.mu.Lock() - defer s.files.mu.Unlock() - if err := s.files.open(s.source); err != nil { + root, err := s.files.readable(s.source) + if err != nil { return err } for i := range archive.Attachments { a := &archive.Attachments[i] - data, err := s.readAttachmentFile(a.Attachment, 0, a.Size) + data, err := readAttachmentFile(root, a.Attachment, 0, a.Size) if err != nil { return err } @@ -132,7 +131,7 @@ func (s *Store) importAttachments(ctx context.Context, tx sqlExecutor, archive S } // A retry after a rolled-back import may find the already durable bytes. if _, err := s.files.root.Lstat(a.ID); err == nil { - if _, err := s.readAttachmentFile(a.Attachment, 0, a.Size); err != nil { + if _, err := readAttachmentFile(s.files.root, a.Attachment, 0, a.Size); err != nil { return err } } else if !os.IsNotExist(err) { diff --git a/bus/attachments_test.go b/bus/attachments_test.go index 50ccdbc..ef6b822 100644 --- a/bus/attachments_test.go +++ b/bus/attachments_test.go @@ -367,3 +367,88 @@ func TestAttachmentBackupLockPreservesBytesAndAllowsCoordination(t *testing.T) { _, err = a.runtime.UploadAttachment(ctx, a.plannerToken, UploadAttachmentInput{Name: "resumed"}, []byte("new bytes")) requireNoError(t, err) } + +// One workspace's long export or file read must not stall another workspace's +// file access, even while the first deletes a file. +func TestAttachmentDeletionDoesNotStallOtherWorkspaces(t *testing.T) { + a := setupAgents(t, ":memory:") + defer a.runtime.Close() + ctx := context.Background() + store := a.runtime.store.(*Store) + mine, err := a.runtime.UploadAttachment(ctx, a.plannerToken, UploadAttachmentInput{Name: "mine"}, []byte("tenant a")) + requireNoError(t, err) + other, err := a.runtime.CreateScope(ctx, CreateScopeInput{}) + requireNoError(t, err) + agent, err := a.runtime.RegisterAgent(ctx, other.ScopeToken, RegisterAgentInput{ID: "neighbour", DisplayName: "Neighbour"}) + requireNoError(t, err) + theirs, err := a.runtime.UploadAttachment(ctx, agent.AgentToken, UploadAttachmentInput{Name: "theirs"}, []byte("tenant b")) + requireNoError(t, err) + + within := func(name string, work func() error) { + t.Helper() + done := make(chan error, 1) + go func() { done <- work() }() + select { + case err := <-done: + requireNoError(t, err) + case <-time.After(5 * time.Second): + t.Fatalf("%s was blocked by another workspace", name) + } + } + // Workspace A's export is in progress (exports hold this shared lock). + store.files.maintenance.RLock() + var release sync.Once + defer release.Do(store.files.maintenance.RUnlock) + within("deletion during an export", func() error { return a.runtime.DeleteAttachment(ctx, a.plannerToken, mine.ID) }) + within("another workspace's read", func() error { + content, err := a.runtime.ReadAttachment(ctx, agent.AgentToken, theirs.ID, 0, 100) + if err == nil && string(content.Data) != "tenant b" { + t.Errorf("read returned %q", content.Data) + } + return err + }) + within("another workspace's upload", func() error { + _, err := a.runtime.UploadAttachment(ctx, agent.AgentToken, UploadAttachmentInput{Name: "more"}, []byte("more")) + return err + }) + // Export requires no active executions; pause the neighbour's briefly. + var lifecycle string + requireNoError(t, store.db.QueryRowContext(ctx, "SELECT lifecycle FROM agents WHERE scope_id=?", other.ScopeID).Scan(&lifecycle)) + _, err = store.db.ExecContext(ctx, "UPDATE agents SET lifecycle='offline' WHERE scope_id=?", other.ScopeID) + requireNoError(t, err) + within("another workspace's export", func() error { + archive, err := a.runtime.ExportScope(ctx, other.ScopeID) + if err == nil && len(archive.Attachments) != 2 { + t.Errorf("export contained %d attachments", len(archive.Attachments)) + } + return err + }) + _, err = store.db.ExecContext(ctx, "UPDATE agents SET lifecycle=? WHERE scope_id=?", lifecycle, other.ScopeID) + requireNoError(t, err) + // The export may still read the deleted file's bytes, so they stay until + // garbage collection runs with no reader present. + _, err = os.Stat(filepath.Join(store.files.directory, mine.ID)) + requireNoError(t, err) + _, err = a.runtime.ReadAttachment(ctx, a.plannerToken, mine.ID, 0, 100) + requireCode(t, err, CodeNotFound) + release.Do(store.files.maintenance.RUnlock) + _, err = store.CollectAttachmentGarbage(ctx) + requireNoError(t, err) + _, err = os.Stat(filepath.Join(store.files.directory, mine.ID)) + require(t, os.IsNotExist(err), "deferred deletion was not collected") + + // A slow write elsewhere (holding the file mutex) does not block reads. + store.files.mu.Lock() + var unlock sync.Once + defer unlock.Do(store.files.mu.Unlock) + within("a read during another write", func() error { + _, err := a.runtime.ReadAttachment(ctx, agent.AgentToken, theirs.ID, 0, 100) + return err + }) + unlock.Do(store.files.mu.Unlock) + + // With no reader present, deletion unlinks the file immediately. + requireNoError(t, a.runtime.DeleteAttachment(ctx, agent.AgentToken, theirs.ID)) + _, err = os.Stat(filepath.Join(store.files.directory, theirs.ID)) + require(t, os.IsNotExist(err), "idle deletion did not unlink the file") +} diff --git a/bus/backup.go b/bus/backup.go index 71e3a11..743f4be 100644 --- a/bus/backup.go +++ b/bus/backup.go @@ -164,7 +164,7 @@ func (s *Store) BackupBundle(ctx context.Context, output io.Writer) error { if err := s.files.open(s.source); err != nil { return err } - data, err := s.readAttachmentFile(a, 0, a.Size) + data, err := readAttachmentFile(s.files.root, a, 0, a.Size) if err != nil { return err } diff --git a/bus/client.go b/bus/client.go index 3ce255a..9e65a50 100644 --- a/bus/client.go +++ b/bus/client.go @@ -197,7 +197,16 @@ func (c Client) PullInbox(ctx context.Context, limit int, wait time.Duration) ([ if err != nil || reservation == nil { return nil, err } - return c.CommitInbox(ctx, reservation.ID) + messages, err := c.CommitInbox(ctx, reservation.ID) + if err != nil { + // Return the messages to the inbox now rather than after the + // reservation expires. This is best effort and ignores the caller's + // cancellation; a reservation that did commit is unaffected. + release, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + _ = c.ReleaseInbox(release, reservation.ID) + cancel() + } + return messages, err } func (c Client) AcknowledgeMessages(ctx context.Context, messageIDs []string) (int64, error) { diff --git a/bus/client_test.go b/bus/client_test.go index 305de2d..8c99ef6 100644 --- a/bus/client_test.go +++ b/bus/client_test.go @@ -1,10 +1,12 @@ package bus import ( + "context" "encoding/json" "errors" "net/http" "net/http/httptest" + "sync/atomic" "testing" ) @@ -97,3 +99,29 @@ func TestClientUploadAttachmentResponses(t *testing.T) { }) } } + +func TestPullInboxReleasesReservationWhenCommitFails(t *testing.T) { + var released atomic.Bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/v1/inbox/reserve": + w.Write([]byte(`{"ok":true,"result":{"id":"res_1","messages":[]}}`)) + case "/v1/inbox/res_1/commit": + w.WriteHeader(http.StatusServiceUnavailable) + w.Write([]byte(`{"ok":false,"error":{"code":"UNAVAILABLE","message":"try again"}}`)) + case "/v1/inbox/res_1/release": + released.Store(true) + w.Write([]byte(`{"ok":true,"result":{}}`)) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + _, err := (Client{Address: server.URL, Token: "agent"}).PullInbox(context.Background(), 10, 0) + if err == nil { + t.Fatal("failed commit was reported as success") + } + if !released.Load() { + t.Fatal("reservation was not released after a failed commit") + } +} diff --git a/bus/daemon.go b/bus/daemon.go index afee3fe..c065aa9 100644 --- a/bus/daemon.go +++ b/bus/daemon.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "net/url" "os" "os/user" @@ -71,7 +72,7 @@ func DefaultDaemonPaths() (DaemonPaths, error) { } func ReadRunFile(path string) (RunFile, error) { - data, err := os.ReadFile(path) + data, err := readPrivateRunFile(path) if err != nil { return RunFile{}, err } @@ -86,6 +87,41 @@ func ReadRunFile(path string) (RunFile, error) { return run, nil } +// readPrivateRunFile reads the discovery file only when it and its directory +// belong to the current user. Without this check another local account could +// plant a run file in a shared temporary directory and receive the scope +// tokens that clients send to the advertised address. +func readPrivateRunFile(path string) ([]byte, error) { + invalid := errors.New("Agent Intercom run file is not private to the current user") + directory, err := os.Lstat(filepath.Dir(path)) + if err != nil { + return nil, err + } + if directory.Mode()&os.ModeSymlink != 0 || !directory.IsDir() || !ownedByCurrentUser(directory) || (runtime.GOOS != "windows" && directory.Mode().Perm()&0o022 != 0) { + return nil, invalid + } + before, err := os.Lstat(path) + if err != nil { + return nil, err + } + if !before.Mode().IsRegular() || !ownedByCurrentUser(before) || (runtime.GOOS != "windows" && before.Mode().Perm()&0o077 != 0) { + return nil, invalid + } + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + after, err := file.Stat() + if err != nil { + return nil, err + } + if !os.SameFile(before, after) { + return nil, invalid + } + return io.ReadAll(io.LimitReader(file, 1<<16)) +} + func writeRunFile(path string, run RunFile) error { data, err := json.MarshalIndent(run, "", " ") if err != nil { @@ -137,6 +173,9 @@ func secureDirectory(path string) error { if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { return fmt.Errorf("%s must be a real directory", path) } + if !ownedByCurrentUser(info) { + return fmt.Errorf("%s is owned by another user; set OCTOBER_BUS_RUNTIME_DIR or XDG_RUNTIME_DIR to a private directory", path) + } if runtime.GOOS != "windows" { if err := os.Chmod(path, 0o700); err != nil { return err diff --git a/bus/file_lock_unix.go b/bus/file_lock_unix.go index 0622243..778f0d5 100644 --- a/bus/file_lock_unix.go +++ b/bus/file_lock_unix.go @@ -20,3 +20,11 @@ func validateDatabaseLinks(_ string, info os.FileInfo) error { } return nil } + +// ownedByCurrentUser reports whether info describes a file owned by the +// effective user. Discovery files may live under a shared temporary +// directory, so another local account must not be able to plant them. +func ownedByCurrentUser(info os.FileInfo) bool { + stat, ok := info.Sys().(*syscall.Stat_t) + return ok && int(stat.Uid) == os.Geteuid() +} diff --git a/bus/file_lock_windows.go b/bus/file_lock_windows.go index 55a52fb..f45efd1 100644 --- a/bus/file_lock_windows.go +++ b/bus/file_lock_windows.go @@ -36,3 +36,7 @@ func validateDatabaseLinks(path string, _ os.FileInfo) error { } return nil } + +// ownedByCurrentUser is not enforced on Windows, where the runtime directory +// is created under the per-user temporary directory. +func ownedByCurrentUser(os.FileInfo) bool { return true } diff --git a/bus/hosted_accounts_test.go b/bus/hosted_accounts_test.go index f3fd077..4af2189 100644 --- a/bus/hosted_accounts_test.go +++ b/bus/hosted_accounts_test.go @@ -227,3 +227,25 @@ func TestHostedAllowanceCountsDeliveriesNotRetriesOrReplies(t *testing.T) { _, err = a.runtime.Heartbeat(ctx, x.AgentToken, HeartbeatInput{Lifecycle: LifecycleIdle}) requireCode(t, err, CodeUnauthenticated) } + +func TestHostedAdminsRevokeOnlyInvitationsTheyCanIssue(t *testing.T) { + ctx, a := hostedTestAccounts(t) + owner, admin := hostedTestUser(t, "invite-owner"), hostedTestUser(t, "invite-admin") + w, err := a.CreateWorkspace(ctx, owner, "Invitation roles") + requireNoError(t, err) + defer a.runtime.DeleteScope(context.Background(), w.ID) + promotion, err := a.Invite(ctx, owner, w.ID, admin.Email, "admin") + requireNoError(t, err) + _, err = a.AcceptInvite(ctx, admin, promotion.Token) + requireNoError(t, err) + adminInvite, err := a.Invite(ctx, owner, w.ID, "second-admin@example.test", "admin") + requireNoError(t, err) + memberInvite, err := a.Invite(ctx, admin, w.ID, "member@example.test", "member") + requireNoError(t, err) + requireCode(t, a.RevokeInvite(ctx, admin, w.ID, adminInvite.ID), CodePermissionDenied) + requireNoError(t, a.RevokeInvite(ctx, admin, w.ID, memberInvite.ID)) + requireNoError(t, a.RevokeInvite(ctx, owner, w.ID, adminInvite.ID)) + pending, err := a.Invites(ctx, owner, w.ID) + requireNoError(t, err) + require(t, len(pending) == 0, "revoked invitations remain pending: %#v", pending) +} diff --git a/bus/hosted_client_limits.go b/bus/hosted_client_limits.go new file mode 100644 index 0000000..c5abf9c --- /dev/null +++ b/bus/hosted_client_limits.go @@ -0,0 +1,171 @@ +package bus + +import ( + "errors" + "net" + "net/http" + "net/netip" + "strings" + "sync" + "time" + + "golang.org/x/time/rate" +) + +// HostedClientAddress enables per-client rate limits on the unauthenticated +// OAuth and device-pairing endpoints. The hosted listener runs behind a TLS +// proxy, so every TCP peer is the proxy; the client address therefore comes +// from a forwarding header that only trusted proxies may set. +type HostedClientAddress struct { + // Header names the forwarding header the proxy sets, for example + // X-Forwarded-For. Its value is a comma-separated list of addresses with + // the address the nearest proxy saw last. + Header string + // TrustedProxies lists the networks whose entries in Header are skipped. + // The TCP peer must belong to one of them, or the header is ignored and + // the peer itself is the client. Empty means loopback only. + TrustedProxies []netip.Prefix +} + +func (c *HostedClientAddress) validate() error { + if c == nil { + return nil + } + if c.Header == "" || strings.ContainsAny(c.Header, " \t\r\n,:") { + return errors.New("client address header must be a single header name") + } + for _, prefix := range c.TrustedProxies { + if !prefix.IsValid() { + return errors.New("trusted proxy networks must be valid CIDR prefixes") + } + } + return nil +} + +func (c *HostedClientAddress) trusted(addr netip.Addr) bool { + addr = addr.Unmap() + if len(c.TrustedProxies) == 0 { + return addr.IsLoopback() + } + for _, prefix := range c.TrustedProxies { + if prefix.Contains(addr) { + return true + } + } + return false +} + +// clientKey returns the rate-limit key for a request: the first address, +// reading the forwarding header from the right, that is not a trusted proxy. +// IPv6 clients are grouped by /64 so a single host cannot rotate addresses +// within its own allocation to escape its limit. +func (c *HostedClientAddress) clientKey(r *http.Request) (netip.Prefix, bool) { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + host = r.RemoteAddr + } + peer, err := netip.ParseAddr(host) + if err != nil { + return netip.Prefix{}, false + } + client := peer.Unmap() + if c.trusted(client) { + values := r.Header.Values(c.Header) + hops := []string{} + for _, value := range values { + hops = append(hops, strings.Split(value, ",")...) + } + for i := len(hops) - 1; i >= 0; i-- { + addr, err := netip.ParseAddr(strings.TrimSpace(hops[i])) + if err != nil { + // A malformed hop cannot be attributed; keep the last trusted + // address so the request still counts against a bucket. + break + } + client = addr.Unmap() + if !c.trusted(client) { + break + } + } + } + bits := 32 + if client.Is6() { + bits = 64 + } + prefix, err := client.Prefix(bits) + return prefix, err == nil +} + +const ( + clientLimiterCapacity = 10_000 + clientLimiterIdle = 10 * time.Minute +) + +type clientLimiterEntry struct { + limiter *rate.Limiter + seen time.Time +} + +// clientLimiter keeps a bounded token bucket per client. When the table is +// full of recently active clients, new clients are admitted without a +// per-client bucket; the endpoint's global limit still applies to them. +type clientLimiter struct { + mu sync.Mutex + limit rate.Limit + burst int + clients map[netip.Prefix]*clientLimiterEntry + now func() time.Time +} + +func newClientLimiter(limit rate.Limit, burst int) *clientLimiter { + return &clientLimiter{limit: limit, burst: burst, clients: map[netip.Prefix]*clientLimiterEntry{}, now: time.Now} +} + +func (l *clientLimiter) allow(key netip.Prefix) bool { + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + entry := l.clients[key] + if entry == nil { + if len(l.clients) >= clientLimiterCapacity { + for k, e := range l.clients { + if now.Sub(e.seen) > clientLimiterIdle { + delete(l.clients, k) + } + } + if len(l.clients) >= clientLimiterCapacity { + return true + } + } + entry = &clientLimiterEntry{limiter: rate.NewLimiter(l.limit, l.burst)} + l.clients[key] = entry + } + entry.seen = now + return entry.limiter.AllowN(now, 1) +} + +// endpointLimit applies an optional per-client limit before the endpoint's +// global limit, so a client over its own allowance does not consume capacity +// shared with everyone else. +type endpointLimit struct { + global *rate.Limiter + client *clientLimiter + address *HostedClientAddress +} + +func newEndpointLimit(address *HostedClientAddress, global, perClient rate.Limit, globalBurst, clientBurst int) *endpointLimit { + l := &endpointLimit{global: rate.NewLimiter(global, globalBurst), address: address} + if address != nil { + l.client = newClientLimiter(perClient, clientBurst) + } + return l +} + +func (l *endpointLimit) allow(r *http.Request) bool { + if l.client != nil { + if key, ok := l.address.clientKey(r); ok && !l.client.allow(key) { + return false + } + } + return l.global.Allow() +} diff --git a/bus/hosted_client_limits_test.go b/bus/hosted_client_limits_test.go new file mode 100644 index 0000000..69a47e0 --- /dev/null +++ b/bus/hosted_client_limits_test.go @@ -0,0 +1,125 @@ +package bus + +import ( + "net/http" + "net/http/httptest" + "net/netip" + "strings" + "testing" + "time" + + "golang.org/x/time/rate" +) + +func clientRequest(remote string, forwarded ...string) *http.Request { + r := httptest.NewRequest("POST", "https://bus.example.test/oauth/register", nil) + r.RemoteAddr = remote + for _, value := range forwarded { + r.Header.Add("X-Forwarded-For", value) + } + return r +} + +func TestHostedClientAddressUsesRightmostUntrustedHop(t *testing.T) { + loopback := &HostedClientAddress{Header: "X-Forwarded-For"} + proxies := &HostedClientAddress{Header: "X-Forwarded-For", TrustedProxies: []netip.Prefix{netip.MustParsePrefix("127.0.0.1/32"), netip.MustParsePrefix("10.0.0.0/8")}} + for _, tc := range []struct { + name string + policy *HostedClientAddress + request *http.Request + want string + }{ + {"proxy-supplied client", loopback, clientRequest("127.0.0.1:5000", "203.0.113.7"), "203.0.113.7/32"}, + // A client cannot choose its key by prepending its own entries. + {"spoofed leftmost entries", loopback, clientRequest("127.0.0.1:5000", "198.51.100.1, 203.0.113.7"), "203.0.113.7/32"}, + {"repeated header lines", loopback, clientRequest("127.0.0.1:5000", "198.51.100.1", "203.0.113.7"), "203.0.113.7/32"}, + {"chained trusted proxies", proxies, clientRequest("127.0.0.1:5000", "198.51.100.1, 203.0.113.7, 10.1.2.3"), "203.0.113.7/32"}, + {"untrusted peer ignores header", loopback, clientRequest("192.0.2.10:5000", "203.0.113.7"), "192.0.2.10/32"}, + {"missing header counts against the proxy", loopback, clientRequest("127.0.0.1:5000"), "127.0.0.1/32"}, + {"malformed hop is not attributed", loopback, clientRequest("127.0.0.1:5000", "203.0.113.7, not-an-ip"), "127.0.0.1/32"}, + {"IPv6 clients group by /64", loopback, clientRequest("[::1]:5000", "2001:db8:1:2:aaaa::1"), "2001:db8:1:2::/64"}, + {"IPv4-mapped IPv6", loopback, clientRequest("127.0.0.1:5000", "::ffff:203.0.113.7"), "203.0.113.7/32"}, + } { + got, ok := tc.policy.clientKey(tc.request) + require(t, ok && got.String() == tc.want, "%s: got %v (%v), want %s", tc.name, got, ok, tc.want) + } +} + +func TestHostedClientAddressValidation(t *testing.T) { + var none *HostedClientAddress + requireNoError(t, none.validate()) + requireNoError(t, (&HostedClientAddress{Header: "X-Forwarded-For"}).validate()) + for _, bad := range []*HostedClientAddress{{}, {Header: "X-Forwarded-For, X-Real-IP"}, {Header: "X-Real-IP:"}, {Header: "X-Forwarded-For", TrustedProxies: []netip.Prefix{{}}}} { + require(t, bad.validate() != nil, "accepted invalid client address policy %+v", bad) + } +} + +func TestEndpointLimitIsolatesClients(t *testing.T) { + policy := &HostedClientAddress{Header: "X-Forwarded-For"} + limit := newEndpointLimit(policy, rate.Every(time.Hour), rate.Every(time.Hour), 10, 2) + noisy := clientRequest("127.0.0.1:1", "203.0.113.1") + for range 2 { + require(t, limit.allow(noisy), "client refused within its burst") + } + // Requests over the client's own limit must not drain the shared budget. + for range 50 { + require(t, !limit.allow(noisy), "client exceeded its own limit") + } + for i := range 8 { + other := clientRequest("127.0.0.1:1", "198.51.100."+string(rune('1'+i))) + require(t, limit.allow(other), "a noisy client starved client %d", i) + } + require(t, !limit.allow(clientRequest("127.0.0.1:1", "192.0.2.99")), "global limit no longer applies") + + // Without a client address policy only the global limit applies. + global := newEndpointLimit(nil, rate.Every(time.Hour), rate.Every(time.Hour), 3, 1) + for range 3 { + require(t, global.allow(noisy), "global-only limit refused within its burst") + } + require(t, !global.allow(clientRequest("127.0.0.1:1", "198.51.100.1")), "global-only limit exceeded") +} + +func TestClientLimiterBoundsItsTable(t *testing.T) { + now := time.Unix(1_000_000, 0) + l := newClientLimiter(rate.Every(time.Hour), 1) + l.now = func() time.Time { return now } + key := func(i int) netip.Prefix { + return netip.PrefixFrom(netip.AddrFrom4([4]byte{10, byte(i >> 16), byte(i >> 8), byte(i)}), 32) + } + for i := range clientLimiterCapacity { + require(t, l.allow(key(i)), "new client %d refused", i) + } + require(t, !l.allow(key(0)), "known client bypassed its limit") + // A full table of active clients admits newcomers to the global limit only. + overflow := key(clientLimiterCapacity) + require(t, l.allow(overflow) && l.allow(overflow), "overflow client was refused") + require(t, len(l.clients) == clientLimiterCapacity, "table grew past its capacity: %d", len(l.clients)) + // Idle entries are evicted to make room again. + now = now.Add(clientLimiterIdle + time.Second) + require(t, l.allow(overflow), "overflow client refused after idle eviction") + require(t, !l.allow(overflow), "overflow client not tracked after eviction") + require(t, len(l.clients) == 1, "idle clients were not evicted: %d", len(l.clients)) +} + +func TestHostedRegistrationLimitIsPerClient(t *testing.T) { + f := newHostedOAuthFixture(t) + h, err := NewHostedServer(f.h.accounts, HostedServerOptions{PublicURL: "https://bus.example.test", Identity: f.h.identity, ClientAddress: &HostedClientAddress{Header: "X-Forwarded-For"}}) + requireNoError(t, err) + register := func(client string) int { + r := httptest.NewRequest("POST", "https://bus.example.test/oauth/register", strings.NewReader(`{"client_name":"Limit test","redirect_uris":["http://127.0.0.1:5555/callback"],"token_endpoint_auth_method":"none"}`)) + r.Header.Set("Content-Type", "application/json") + r.RemoteAddr = "127.0.0.1:40000" + r.Header.Set("X-Forwarded-For", client) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code + } + codes := map[int]int{} + for range 10 { + codes[register("203.0.113.1")]++ + } + require(t, codes[201] == 5 && codes[429] == 5, "per-client registration limit not applied: %v", codes) + require(t, register("198.51.100.1") == 201, "another client was starved by the first") + _, err = NewHostedServer(f.h.accounts, HostedServerOptions{PublicURL: "https://bus.example.test", Identity: f.h.identity, ClientAddress: &HostedClientAddress{}}) + require(t, err != nil, "accepted a client address policy without a header") +} diff --git a/bus/hosted_connection_revocation_test.go b/bus/hosted_connection_revocation_test.go new file mode 100644 index 0000000..4be0c93 --- /dev/null +++ b/bus/hosted_connection_revocation_test.go @@ -0,0 +1,48 @@ +package bus + +import "testing" + +func TestHostedAdminRevocationCannotBeUndoneByReplacement(t *testing.T) { + f := newHostedOAuthFixture(t) + a, ctx := f.h.accounts, f.ctx + member := hostedTestUser(t, "revoked-member") + invite, err := a.Invite(ctx, f.user, f.workspace.ID, member.Email, "member") + requireNoError(t, err) + _, err = a.AcceptInvite(ctx, member, invite.Token) + requireNoError(t, err) + + // An owner or admin revokes the member's key; the member cannot restore it. + revoked, err := a.CreateMCPKey(ctx, member, f.workspace.ID, "Member app", "") + requireNoError(t, err) + requireNoError(t, a.RevokeDevice(ctx, f.user, f.workspace.ID, revoked.ID)) + _, err = a.CreateMCPKey(ctx, member, f.workspace.ID, "Member app", revoked.ID) + requireCode(t, err, CodePermissionDenied) + machine, err := a.EnrollDevice(ctx, member, f.workspace.ID, "Member machine") + requireNoError(t, err) + requireNoError(t, a.RevokeDevice(ctx, f.user, f.workspace.ID, machine.ID)) + pairing, err := a.BeginDevicePairing(ctx, "Member machine") + requireNoError(t, err) + err = a.completeDevicePairing(ctx, member, pairing.UserCode, f.workspace.ID, machine.ID, true) + requireCode(t, err, CodePermissionDenied) + devices, err := a.Devices(ctx, f.user, f.workspace.ID) + requireNoError(t, err) + for _, d := range devices { + if d.ID == revoked.ID || d.ID == machine.ID { + require(t, d.RevokedAt != "", "revoked connection %s was restored", d.ID) + } + } + + // A connection its owner revoked can still be replaced, keeping its inbox. + own, err := a.CreateMCPKey(ctx, member, f.workspace.ID, "Own app", "") + requireNoError(t, err) + requireNoError(t, a.RevokeDevice(ctx, member, f.workspace.ID, own.ID)) + replaced, err := a.CreateMCPKey(ctx, member, f.workspace.ID, "Own app", own.ID) + requireNoError(t, err) + require(t, replaced.ID == own.ID && replaced.Token != own.Token, "self-revoked connection was not replaced in place") + + // An admin revoking an already self-revoked connection still blocks restoring it. + requireNoError(t, a.RevokeDevice(ctx, member, f.workspace.ID, own.ID)) + requireNoError(t, a.RevokeDevice(ctx, f.user, f.workspace.ID, own.ID)) + _, err = a.CreateMCPKey(ctx, member, f.workspace.ID, "Own app", own.ID) + requireCode(t, err, CodePermissionDenied) +} diff --git a/bus/hosted_devices.go b/bus/hosted_devices.go index a3e9172..5b9816f 100644 --- a/bus/hosted_devices.go +++ b/bus/hosted_devices.go @@ -224,15 +224,20 @@ func (a *HostedAccounts) replaceConnectionTx(ctx context.Context, tx sqlExecutor if err := workspaceOpen(ctx, tx, scopeID); err != nil { return WorkspaceDevice{}, err } - var ownerID, kind string + var ownerID, kind, revokedBy string var created int64 - err := tx.QueryRowContext(ctx, "SELECT user_id,kind,created_at FROM hosted_devices WHERE scope_id=? AND device_id=?", scopeID, deviceID).Scan(&ownerID, &kind, &created) + err := tx.QueryRowContext(ctx, "SELECT user_id,kind,created_at,revoked_by FROM hosted_devices WHERE scope_id=? AND device_id=?", scopeID, deviceID).Scan(&ownerID, &kind, &created, &revokedBy) if errors.Is(err, sql.ErrNoRows) || (err == nil && (ownerID != user.ID || kind != expectedKind)) { return WorkspaceDevice{}, Errorf(CodePermissionDenied, "Only your own connections of the same kind can be replaced here") } if err != nil { return WorkspaceDevice{}, err } + // Replacement would otherwise undo a workspace owner's or admin's revocation + // and restore the connection's inbox. + if revokedBy != "" { + return WorkspaceDevice{}, Errorf(CodePermissionDenied, "A workspace admin revoked this connection; create a new connection instead") + } if err := checkHostedConnectionLimit(ctx, tx, scopeID, user.ID, deviceID); err != nil { return WorkspaceDevice{}, err } @@ -318,7 +323,13 @@ func (a *HostedAccounts) RevokeDevice(ctx context.Context, user HostedUser, scop if err := retireHostedSessions(ctx, tx, scopeID, "", deviceID); err != nil { return err } - if _, err := tx.ExecContext(ctx, "UPDATE hosted_devices SET revoked_at=? WHERE device_id=? AND revoked_at=0", nowMillis(), deviceID); err != nil { + revokedBy := "" + if ownerID != user.ID { + revokedBy = user.ID + } + // Record another member's revocation even on an already revoked connection, + // so its owner cannot restore it by replacement. + if _, err := tx.ExecContext(ctx, "UPDATE hosted_devices SET revoked_at=CASE WHEN revoked_at=0 THEN ? ELSE revoked_at END,revoked_by=CASE WHEN ?<>'' THEN ? ELSE revoked_by END WHERE device_id=?", nowMillis(), revokedBy, revokedBy, deviceID); err != nil { return err } if err := tx.Commit(); err != nil { diff --git a/bus/hosted_http.go b/bus/hosted_http.go index 8ee5d55..b593d95 100644 --- a/bus/hosted_http.go +++ b/bus/hosted_http.go @@ -6,6 +6,7 @@ import ( "net/http" "net/url" "strings" + "time" "github.com/go-oauth2/oauth2/v4/server" "golang.org/x/time/rate" @@ -16,6 +17,9 @@ type HostedServerOptions struct { AllowedOrigins []string Identity HostedIdentityVerifier Billing *HostedBilling + // ClientAddress enables per-client limits on unauthenticated OAuth and + // device-pairing endpoints. Nil keeps only the global limits. + ClientAddress *HostedClientAddress } type HostedServer struct { @@ -28,8 +32,10 @@ type HostedServer struct { origins map[string]bool requests chan struct{} oauth *server.Server - oauthRegistration *rate.Limiter - oauthAuthorization *rate.Limiter + oauthRegistration *endpointLimit + oauthAuthorization *endpointLimit + pairingCreation *endpointLimit + pairingPolling *endpointLimit oauthRequests chan struct{} billing *HostedBilling } @@ -39,6 +45,9 @@ func NewHostedServer(accounts *HostedAccounts, options HostedServerOptions) (*Ho if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" || options.Identity == nil || accounts == nil { return nil, errors.New("hosted service requires an HTTPS public origin, accounts and identity verifier") } + if err := options.ClientAddress.validate(); err != nil { + return nil, err + } h := &HostedServer{accounts: accounts, identity: options.Identity, routes: http.NewServeMux(), publicURL: strings.TrimRight(options.PublicURL, "/"), host: u.Host, origins: map[string]bool{}, requests: make(chan struct{}, 64)} if options.Billing != nil && (options.Billing.accounts != accounts || options.Billing.options.PublicURL != h.publicURL) { return nil, errors.New("billing must belong to this hosted service and origin") @@ -142,8 +151,11 @@ func NewHostedServer(accounts *HostedAccounts, options HostedServerOptions) (*Ho } writeResult(w, http.StatusOK, result) }) - h.oauthRegistration = rate.NewLimiter(1, 30) - h.oauthAuthorization = rate.NewLimiter(5, 50) + client := options.ClientAddress + h.oauthRegistration = newEndpointLimit(client, 1, rate.Every(10*time.Second), 30, 5) + h.oauthAuthorization = newEndpointLimit(client, 5, 1, 50, 10) + h.pairingCreation = newEndpointLimit(client, 1, rate.Every(5*time.Second), 20, 5) + h.pairingPolling = newEndpointLimit(client, 50, 2, 100, 10) h.oauthRequests = make(chan struct{}, 32) h.registerOAuthRoutes() h.registerDevicePairingRoutes() diff --git a/bus/hosted_identity.go b/bus/hosted_identity.go index 4bdcd52..023d724 100644 --- a/bus/hosted_identity.go +++ b/bus/hosted_identity.go @@ -124,7 +124,9 @@ func (v *SupabaseIdentity) Authenticate(ctx context.Context, token string) (Host return cached.user, nil } result, err, _ := v.pending.Do(digest, func() (any, error) { - request, err := http.NewRequestWithContext(ctx, http.MethodGet, v.origin+"/auth/v1/user", nil) + // Concurrent callers share this lookup, so one caller's cancellation + // must not fail the others. The client timeout still bounds it. + request, err := http.NewRequestWithContext(context.WithoutCancel(ctx), http.MethodGet, v.origin+"/auth/v1/user", nil) if err != nil { return HostedUser{}, err } diff --git a/bus/hosted_identity_test.go b/bus/hosted_identity_test.go index ae6beff..940477e 100644 --- a/bus/hosted_identity_test.go +++ b/bus/hosted_identity_test.go @@ -78,3 +78,32 @@ func TestHostedIdentityRejectsPrivilegedPublicKeys(t *testing.T) { _, err := NewSupabaseIdentity("https://auth.example.test", anon, nil) requireNoError(t, err) } + +func TestHostedIdentitySharedLookupSurvivesOneCallerCancelling(t *testing.T) { + const id = "0b8f6b52-5f7a-4f4e-9d0c-1f2a3b4c5d6e" + arrived, release := make(chan struct{}), make(chan struct{}) + var once atomic.Bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if once.CompareAndSwap(false, true) { + close(arrived) + } + <-release + writeJSON(w, 200, map[string]any{"id": id, "email": "shared@example.test", "email_confirmed_at": "2026-01-01T00:00:00Z", "is_anonymous": false}) + })) + defer server.Close() + verifier, err := NewSupabaseIdentity(server.URL, "sb_publishable_fixture_key_for_tests", nil) + requireNoError(t, err) + claims, _ := json.Marshal(map[string]any{"sub": id, "iss": server.URL + "/auth/v1", "aud": "authenticated", "exp": time.Now().Add(time.Hour).Unix(), "role": "authenticated"}) + token := "e30." + base64.RawURLEncoding.EncodeToString(claims) + ".test-signature" + first, cancel := context.WithCancel(context.Background()) + firstDone := make(chan error, 1) + go func() { _, err := verifier.Authenticate(first, token); firstDone <- err }() + <-arrived + secondDone := make(chan error, 1) + go func() { _, err := verifier.Authenticate(context.Background(), token); secondDone <- err }() + time.Sleep(20 * time.Millisecond) + cancel() + close(release) + <-firstDone + requireNoError(t, <-secondDone) +} diff --git a/bus/hosted_maintenance.go b/bus/hosted_maintenance.go index 367de29..ec7b56a 100644 --- a/bus/hosted_maintenance.go +++ b/bus/hosted_maintenance.go @@ -2,6 +2,8 @@ package bus import ( "context" + "database/sql" + "errors" "log" "time" ) @@ -78,7 +80,10 @@ AND NOT EXISTS(SELECT 1 FROM hosted_checkout_attempts c WHERE c.scope_id=w.scope return err } if _, err := a.store.PruneScope(ctx, id, now-int64(90*24*time.Hour/time.Millisecond), true); err != nil { - lastError = err + // A workspace deleted after it was selected has nothing left to prune. + if !errors.Is(err, sql.ErrNoRows) { + lastError = err + } continue } if _, err := a.store.db.ExecContext(ctx, "UPDATE hosted_workspaces SET maintenance_completed_at=? WHERE scope_id=?", nowMillis(), id); err != nil { diff --git a/bus/hosted_oauth.go b/bus/hosted_oauth.go index ef316ab..0291614 100644 --- a/bus/hosted_oauth.go +++ b/bus/hosted_oauth.go @@ -48,7 +48,7 @@ func (h *HostedServer) registerOAuthRoutes() { h.routes.HandleFunc("GET /.well-known/oauth-protected-resource", metadata) h.routes.HandleFunc("GET /.well-known/oauth-protected-resource/mcp", metadata) h.routes.HandleFunc("GET /.well-known/oauth-authorization-server", func(w http.ResponseWriter, r *http.Request) { - writeJSON(w, 200, map[string]any{"issuer": h.publicURL, "authorization_endpoint": h.publicURL + "/oauth/authorize", "token_endpoint": h.publicURL + "/oauth/token", "registration_endpoint": h.publicURL + "/oauth/register", "revocation_endpoint": h.publicURL + "/oauth/revoke", "response_types_supported": []string{"code"}, "grant_types_supported": []string{"authorization_code", "refresh_token"}, "token_endpoint_auth_methods_supported": []string{"none", "client_secret_basic", "client_secret_post"}, "code_challenge_methods_supported": []string{"S256"}, "scopes_supported": []string{hostedOAuthScope}}) + writeJSON(w, 200, map[string]any{"issuer": h.publicURL, "authorization_endpoint": h.publicURL + "/oauth/authorize", "token_endpoint": h.publicURL + "/oauth/token", "registration_endpoint": h.publicURL + "/oauth/register", "revocation_endpoint": h.publicURL + "/oauth/revoke", "response_types_supported": []string{"code"}, "grant_types_supported": []string{"authorization_code", "refresh_token"}, "token_endpoint_auth_methods_supported": []string{"none", "client_secret_basic", "client_secret_post"}, "code_challenge_methods_supported": []string{"S256"}, "scopes_supported": []string{hostedOAuthScope}, "authorization_response_iss_parameter_supported": true}) }) h.routes.HandleFunc("POST /oauth/register", h.oauthRegister) h.routes.HandleFunc("GET /oauth/authorize", h.oauthAuthorize) @@ -59,7 +59,7 @@ func (h *HostedServer) registerOAuthRoutes() { } func (h *HostedServer) oauthRegister(w http.ResponseWriter, r *http.Request) { - if !h.oauthRegistration.Allow() { + if !h.oauthRegistration.allow(r) { oauthFailure(w, 429, "temporarily_unavailable", "Client registration is busy; retry shortly") return } @@ -118,8 +118,7 @@ func (h *HostedServer) oauthRegister(w http.ResponseWriter, r *http.Request) { return } defer tx.Rollback() - var count int - if err := tx.QueryRowContext(r.Context(), "SELECT COUNT(*) FROM oauth_clients").Scan(&count); err != nil || count >= 50000 { + if !reserveOAuthClientCapacity(r.Context(), tx) { oauthFailure(w, 503, "temporarily_unavailable", "Registration capacity is unavailable") return } @@ -149,7 +148,7 @@ func (h *HostedServer) oauthRegister(w http.ResponseWriter, r *http.Request) { } func (h *HostedServer) oauthAuthorize(w http.ResponseWriter, r *http.Request) { - if !h.oauthAuthorization.Allow() { + if !h.oauthAuthorization.allow(r) { oauthFailure(w, 429, "temporarily_unavailable", "Authorization is busy; retry shortly") return } @@ -296,6 +295,8 @@ func (h *HostedServer) oauthConsent(ctx context.Context, user HostedUser, w http if pending.state != "" { query.Set("state", pending.state) } + // RFC 9207 lets clients that use several authorization servers detect mix-up. + query.Set("iss", h.publicURL) if input.Approve { if _, err := hostedMember(ctx, tx, input.WorkspaceID, user.ID); err != nil { return nil, err @@ -332,3 +333,32 @@ func (h *HostedServer) oauthConsent(ctx context.Context, user HostedUser, w http redirect.RawQuery = query.Encode() return map[string]string{"redirectUrl": redirect.String()}, nil } + +// hostedOAuthClientLimit bounds anonymous dynamic client registration. +var hostedOAuthClientLimit = 50000 + +// reserveOAuthClientCapacity reports whether another client may register. +// Registration is unauthenticated, so at capacity it first evicts the oldest +// clients that are more than a day old and hold no pending request or token. +// Such a client can no longer authorize anything without a new flow, and +// MCP clients register again when their client ID is unknown. +func reserveOAuthClientCapacity(ctx context.Context, tx sqlExecutor) bool { + var count int + if err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM oauth_clients").Scan(&count); err != nil { + return false + } + if count < hostedOAuthClientLimit { + return true + } + cutoff := nowMillis() - int64(24*time.Hour/time.Millisecond) + if _, err := tx.ExecContext(ctx, `DELETE FROM oauth_clients WHERE client_id IN (SELECT c.client_id FROM oauth_clients c WHERE c.created_at= messageBacklogCap { + // An answer to a pending escalation completes accepted work, so a full + // backlog must not leave the human unable to answer. Answers get bounded + // headroom of their own. + limit := messageBacklogCap + if ctx.Value(completionDeliveryKey{}) == true { + limit = maxActiveMessages + } + if backlog >= limit { return Message{}, Errorf(CodeBackpressure, "Scope message backlog is full") } if err := consumeHostedDelivery(ctx, tx, scopeID, mode, now); err != nil { @@ -1132,6 +1141,11 @@ func (s *Store) CommitInbox(ctx context.Context, principal Principal, reservatio if err != nil { return nil, err } + // Materialize message expiry first, so an expired reservation never + // releases a message that has itself expired. + if err := expireMessages(ctx, tx, principal.ScopeID, nowMillis()); err != nil { + return nil, err + } if expiresAt <= nowMillis() { if err := releaseReservation(ctx, tx, principal.ScopeID, principal.AgentID, reservationID); err != nil { return nil, err @@ -1141,9 +1155,6 @@ func (s *Store) CommitInbox(ctx context.Context, principal Principal, reservatio } return nil, Errorf(CodeConflict, "Inbox reservation expired") } - if err := expireMessages(ctx, tx, principal.ScopeID, nowMillis()); err != nil { - return nil, err - } rows, err := tx.QueryContext(ctx, `SELECT `+messageColumns+` FROM messages WHERE reservation_id=? AND scope_id=? AND to_kind='agent' AND to_id=? AND state='reserved' ORDER BY created_at`, reservationID, principal.ScopeID, principal.AgentID) if err != nil { return nil, err @@ -1471,6 +1482,16 @@ func (s *Store) ClaimTask(ctx context.Context, principal Principal, taskID strin return task, nil } +// requireTaskExists distinguishes an unknown task from one in the wrong state. +func requireTaskExists(ctx context.Context, q sqlExecutor, scopeID, taskID string) error { + var exists int + err := q.QueryRowContext(ctx, `SELECT 1 FROM tasks WHERE scope_id=? AND task_id=?`, scopeID, taskID).Scan(&exists) + if errors.Is(err, sql.ErrNoRows) { + return Errorf(CodeNotFound, "Task "+taskID+" was not found") + } + return err +} + func (s *Store) CompleteTask(ctx context.Context, principal Principal, taskID, note string) (Task, error) { tx, err := s.beginTx(ctx, principal.ScopeID) if err != nil { @@ -1488,6 +1509,9 @@ func (s *Store) CompleteTask(ctx context.Context, principal Principal, taskID, n } changed, _ := result.RowsAffected() if changed != 1 { + if err := requireTaskExists(ctx, tx, principal.ScopeID, taskID); err != nil { + return Task{}, err + } return Task{}, Errorf(CodeConflict, "Task "+taskID+" is not claimed by this agent") } if err := appendEvent(ctx, tx, principal.ScopeID, "task.completed", taskID, eventAttributes( @@ -1522,6 +1546,9 @@ func (s *Store) ReleaseTask(ctx context.Context, principal Principal, taskID str } changed, _ := result.RowsAffected() if changed != 1 { + if err := requireTaskExists(ctx, tx, principal.ScopeID, taskID); err != nil { + return Task{}, err + } return Task{}, Errorf(CodeConflict, "Task "+taskID+" is not claimed by this execution") } if err := appendEvent(ctx, tx, principal.ScopeID, "task.released", taskID, eventAttributes( diff --git a/cmd/agentintercom/attachment.go b/cmd/agentintercom/attachment.go index a169d39..f2cc955 100644 --- a/cmd/agentintercom/attachment.go +++ b/cmd/agentintercom/attachment.go @@ -80,6 +80,9 @@ func attachmentCommand(args []string, in io.Reader, out io.Writer) error { return errors.New("attachment exceeds 16 MiB") } result, err = client.UploadAttachment(ctx, bus.UploadAttachmentInput{Name: *name, MediaType: *media, IdempotencyKey: *key}, data) + if err != nil { + return err + } case "download": if *file == "" || *file == "-" { return errors.New("download requires --file ; bytes are never printed to the terminal") diff --git a/cmd/agentintercom/attachment_test.go b/cmd/agentintercom/attachment_test.go index edc5142..4977bd5 100644 --- a/cmd/agentintercom/attachment_test.go +++ b/cmd/agentintercom/attachment_test.go @@ -56,4 +56,11 @@ func TestAttachmentCLIUploadDownloadAndNoOverwrite(t *testing.T) { if bytes.Contains(out.Bytes(), data) { t.Fatal("binary bytes were printed to the terminal") } + + t.Setenv("OCTOBER_BUS_AGENT_TOKEN", "invalid-agent-token") + out.Reset() + err = attachmentCommand([]string{"upload", "--address", server.URL, "--file", "-", "--name", "rejected.bin"}, bytes.NewReader(data), &out) + if err == nil { + t.Fatalf("rejected upload reported success: %q", out.String()) + } } diff --git a/cmd/agentintercom/exit_code_unix_test.go b/cmd/agentintercom/exit_code_unix_test.go new file mode 100644 index 0000000..d0d1fe0 --- /dev/null +++ b/cmd/agentintercom/exit_code_unix_test.go @@ -0,0 +1,20 @@ +//go:build darwin || linux + +package main + +import ( + "errors" + "fmt" + "os/exec" + "testing" +) + +func TestExitCodePassesManagedChildStatusThrough(t *testing.T) { + err := exec.Command("sh", "-c", "exit 7").Run() + if code := exitCode(fmt.Errorf("wrapped: %w", err)); code != 7 { + t.Fatalf("child exit status became %d", code) + } + if code := exitCode(errors.New("refused")); code != 1 { + t.Fatalf("ordinary failure became %d", code) + } +} diff --git a/cmd/agentintercom/hosted.go b/cmd/agentintercom/hosted.go index 05dcbb6..bdc9462 100644 --- a/cmd/agentintercom/hosted.go +++ b/cmd/agentintercom/hosted.go @@ -8,6 +8,7 @@ import ( "fmt" "net" "net/http" + "net/netip" "os" "os/signal" "strings" @@ -37,6 +38,9 @@ func hostedCommand(args []string) error { } flags.Var(&origins, "allow-origin", "additional exact HTTPS browser origin; repeatable") flags.Var(&issuers, "auth-issuer", "additional exact trusted Auth issuer; repeatable") + clientHeader := flags.String("client-ip-header", "", "forwarding header (for example X-Forwarded-For) that the TLS proxy sets to the client address; enables per-client limits on OAuth and device pairing") + var proxies stringList + flags.Var(&proxies, "trusted-proxy", "proxy IP or CIDR whose forwarding-header entries are skipped; repeatable; default loopback") if err := flags.Parse(args[1:]); err != nil { return err } @@ -46,6 +50,10 @@ func hostedCommand(args []string) error { if *attachments == "" { return errors.New("--attachments-dir or OCTOBER_BUS_ATTACHMENTS_DIR is required for hosted file storage") } + clientAddress, err := hostedClientAddress(*clientHeader, proxies) + if err != nil { + return err + } host, _, err := net.SplitHostPort(*listen) if err != nil || net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback() { return errors.New("hosted listener must use a loopback IP; publish it through the TLS proxy") @@ -84,7 +92,7 @@ func hostedCommand(args []string) error { stopBilling := billing.StartMaintenance() defer stopBilling() } - handler, err := bus.NewHostedServer(accounts, bus.HostedServerOptions{PublicURL: *public, AllowedOrigins: origins, Identity: identity, Billing: billing}) + handler, err := bus.NewHostedServer(accounts, bus.HostedServerOptions{PublicURL: *public, AllowedOrigins: origins, Identity: identity, Billing: billing, ClientAddress: clientAddress}) if err != nil { return err } @@ -116,3 +124,25 @@ func hostedCommand(args []string) error { } return closeErr } + +func hostedClientAddress(header string, proxies []string) (*bus.HostedClientAddress, error) { + if header == "" { + if len(proxies) != 0 { + return nil, errors.New("--trusted-proxy requires --client-ip-header") + } + return nil, nil + } + address := &bus.HostedClientAddress{Header: header} + for _, value := range proxies { + prefix, err := netip.ParsePrefix(value) + if err != nil { + addr, addrErr := netip.ParseAddr(value) + if addrErr != nil { + return nil, fmt.Errorf("--trusted-proxy %q is not an IP address or CIDR prefix", value) + } + prefix = netip.PrefixFrom(addr.Unmap(), addr.Unmap().BitLen()) + } + address.TrustedProxies = append(address.TrustedProxies, prefix.Masked()) + } + return address, nil +} diff --git a/cmd/agentintercom/hosted_client_address_test.go b/cmd/agentintercom/hosted_client_address_test.go new file mode 100644 index 0000000..8a20217 --- /dev/null +++ b/cmd/agentintercom/hosted_client_address_test.go @@ -0,0 +1,28 @@ +package main + +import "testing" + +func TestHostedClientAddressFlags(t *testing.T) { + if address, err := hostedClientAddress("", nil); err != nil || address != nil { + t.Fatalf("per-client limits enabled without a header: %v %v", address, err) + } + if _, err := hostedClientAddress("", []string{"10.0.0.1"}); err == nil { + t.Fatal("accepted --trusted-proxy without --client-ip-header") + } + address, err := hostedClientAddress("X-Forwarded-For", []string{"10.0.0.1", "192.168.0.0/16", "::1"}) + if err != nil { + t.Fatal(err) + } + want := []string{"10.0.0.1/32", "192.168.0.0/16", "::1/128"} + if address.Header != "X-Forwarded-For" || len(address.TrustedProxies) != len(want) { + t.Fatalf("unexpected policy %+v", address) + } + for i, prefix := range address.TrustedProxies { + if prefix.String() != want[i] { + t.Fatalf("proxy %d = %s, want %s", i, prefix, want[i]) + } + } + if _, err := hostedClientAddress("X-Forwarded-For", []string{"proxy.example"}); err == nil { + t.Fatal("accepted a host name as a trusted proxy") + } +} diff --git a/cmd/agentintercom/main.go b/cmd/agentintercom/main.go index 80d21d1..985b708 100644 --- a/cmd/agentintercom/main.go +++ b/cmd/agentintercom/main.go @@ -1066,8 +1066,11 @@ func runAgent(args []string) error { return closeSession() case <-signalCtx.Done(): stopChild() - <-childDone - return closeSession() + childErr := <-childDone + if closeErr := closeSession(); closeErr != nil { + return closeErr + } + return childErr } } @@ -1225,6 +1228,16 @@ func stdinIsTerminal() bool { func main() { if err := run(); err != nil && !errors.Is(err, flag.ErrHelp) { fmt.Fprintln(os.Stderr, err) - os.Exit(1) + os.Exit(exitCode(err)) } } + +// exitCode passes a managed child's exit status through, so scripts that wrap +// a command with agent run or session start can see whether it failed. +func exitCode(err error) int { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) && exitErr.ExitCode() > 0 { + return exitErr.ExitCode() + } + return 1 +} diff --git a/cmd/agentintercom/message.go b/cmd/agentintercom/message.go index 171155c..ebbc80a 100644 --- a/cmd/agentintercom/message.go +++ b/cmd/agentintercom/message.go @@ -36,7 +36,7 @@ func executionClient(address string) (bus.Client, error) { } ip := net.ParseIP(u.Hostname()) if u.Scheme != "https" && !(u.Scheme == "http" && ip != nil && ip.IsLoopback()) { - return bus.Client{}, errors.New("remote Bus connections require HTTPS") + return bus.Client{}, errors.New("remote Bus connections require HTTPS; for a local daemon use a literal loopback address such as http://127.0.0.1:PORT") } return bus.Client{Address: strings.TrimRight(address, "/"), Token: token, HTTP: &http.Client{Timeout: 30 * time.Second, CheckRedirect: refuseMCPRedirect}}, nil diff --git a/deploy/hosted/STANDALONE.md b/deploy/hosted/STANDALONE.md index 496350c..282ee20 100644 --- a/deploy/hosted/STANDALONE.md +++ b/deploy/hosted/STANDALONE.md @@ -52,7 +52,9 @@ backoff. Do not increase database timeouts to conceal a saturated deployment. Create a dedicated system user with no login shell and no home directory. Put each reviewed release into `/opt/october-bus-hosted/releases//`, owned by -root and not writable by the service account. Include the executable, `backup.py`, +root and not writable by the service account. Include the executable (the +release archives name it `agentintercom`; the units and commands here call it +`october-bus`, so install it under that name or adjust them), `backup.py`, this directory's SQL files and the source commit identifier. Point `current` at the selected release using an atomic symlink replacement. Do not overwrite the executable used by an older service. diff --git a/deploy/hosted/migrations/015_connection_revoker.sql b/deploy/hosted/migrations/015_connection_revoker.sql new file mode 100644 index 0000000..0ce3d4a --- /dev/null +++ b/deploy/hosted/migrations/015_connection_revoker.sql @@ -0,0 +1,5 @@ +-- Records which member revoked someone else's connection. Empty means the +-- connection's owner revoked it or the service did (for example after a +-- replayed grant). An owner may restore their own connection by replacing it, +-- but not one that a workspace owner or admin revoked. +ALTER TABLE hosted_devices ADD COLUMN revoked_by TEXT NOT NULL DEFAULT ''; diff --git a/deploy/hosted/migrations/README.md b/deploy/hosted/migrations/README.md index bf13128..8b350a4 100644 --- a/deploy/hosted/migrations/README.md +++ b/deploy/hosted/migrations/README.md @@ -12,8 +12,8 @@ manager. Remote connections require `sslmode=verify-full` and a trusted CA. Never pass the URL on the command line or commit it. ```sh -october-bus database migrate -october-bus database check +agentintercom database migrate +agentintercom database check ``` `migrate` takes a transaction advisory lock, verifies the recorded SHA-256 of each @@ -166,3 +166,11 @@ Drops the encrypted owner scope credential reserved by the original hosted schema. Hosted owner operations authorize verified membership directly; no code reads that credential. The opaque scope digest stays for the shared runtime's schema, while connection/session credentials keep their separate encryption. + +## Connection revoker: 015_connection_revoker.sql + +Adds `hosted_devices.revoked_by`, set to the revoking member when a workspace +owner or admin revokes another member's connection. Replacing a connection +otherwise restores it with its inbox; a connection revoked by someone else can +no longer be restored that way, so its owner must create a new connection. +Existing rows default to an empty value and keep their previous behavior. diff --git a/docs/cli-messages.md b/docs/cli-messages.md index 926ea2e..4897754 100644 --- a/docs/cli-messages.md +++ b/docs/cli-messages.md @@ -4,7 +4,15 @@ A connected process can use CLI commands with the same execution credential as MCP. `agent run` supplies that credential and keeps its lease alive. It removes workspace and administrator tokens from the child environment. -For example, start two shell sessions in a local workspace: +For example, start two shell sessions in a local workspace. If the daemon is not +already running as a login service, start it with `agentintercom start` in +another terminal, then create the workspace once: + +```sh +agentintercom workspace create project +``` + +Then start the two sessions: ```sh agentintercom agent run --scope project --id first --name 'First session' -- bash @@ -47,6 +55,10 @@ refuse redirects. A CLI connection does not itself wake an idle agent. ## Shared tasks +The `claim`, `release`, `complete` and `progress` commands below are newer than +`agentintercom-cli@0.2.0`; use a [source build](installation.md#build-from-source) +until the next release. + The same two shells can split work through shared tasks. In the first shell: ```sh diff --git a/docs/clients.md b/docs/clients.md index 0c9c988..1813b56 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -193,3 +193,25 @@ try { ``` The public error codes and HTTP mappings are defined in the [protocol specification](../spec/0.1/README.md). + +A TypeScript request that fails before the runtime responds throws a +`BusTransportError`: `BusNetworkError` when the connection fails, +`BusTimeoutError` when `timeoutMs` elapses, or `BusAbortError` when the caller's +`signal` aborts it. Each subclass sets `transport` (`'network'`, `'timeout'` or +`'aborted'`) and `cause`. A mutation's outcome is then unknown: retry it with the +same idempotency key or read its receipt. For compatibility these errors still +extend `BusError` with code `INTERNAL`, so check the class before the code: + +```ts +import { BusError, BusTransportError } from 'agentintercom-cli' + +try { + await session.client.listPeers({ timeoutMs: 5_000 }) +} catch (error) { + if (error instanceof BusTransportError) { + // No response from the runtime; error.transport says why. + } else if (error instanceof BusError) { + // The runtime reported error.code. + } +} +``` diff --git a/docs/connect-sessions.md b/docs/connect-sessions.md index 632054f..200a834 100644 --- a/docs/connect-sessions.md +++ b/docs/connect-sessions.md @@ -120,7 +120,9 @@ hosted OAuth support is claimed by generating configuration. ## Answer an agent's question When an agent calls `ask_user`, the question waits for the workspace owner. On a -headless machine you can answer it from a terminal: +headless machine you can answer it from a terminal. The `question` commands are +newer than `agentintercom-cli@0.2.0`; use a +[source build](installation.md#build-from-source) until the next release. ```sh agentintercom question list --workspace my-project diff --git a/docs/desktop-remote-integration.md b/docs/desktop-remote-integration.md index 36ed207..92d0fa4 100644 --- a/docs/desktop-remote-integration.md +++ b/docs/desktop-remote-integration.md @@ -1,6 +1,6 @@ # October Desktop remote integration contract -The native helper implements the Agents Anywhere connection contract. Publication, +The native helper implements the managed remote connection contract. Publication, consumer pin updates and real remote-host qualification remain separate steps; see the follow-ups below. The integration preserves the gateway authentication and readiness fixes from PR #125. @@ -13,9 +13,9 @@ ownership, commands, artifacts, evidence and what remains on the Desktop side. | Component | Owns | | --- | --- | -| October Bus native helper (`october-bus`) | MCP bridge over a controller-managed connection, per-request credential reread, next-call reconnect without replaying a failed mutation, Claude/Codex lifecycle hook, bounded setup check, hosted-gateway self-registration. | +| Agent Intercom native helper (`agentintercom`) | MCP bridge over a controller-managed connection, per-request credential reread, next-call reconnect without replaying a failed mutation, Claude/Codex lifecycle hook, bounded setup check, hosted-gateway self-registration. | | October Desktop / Core | Canvas identity, execution credentials and their renewal/retirement, the connection file writer, SSH supervision and the loopback route, tmux ownership and foreground proof, safe input delivery, helper installation, Settings cards, readiness decisions. | -| October Cloud controller | Hosted authority, HTTPS worker MCP/hook routes, worker admission and lifecycle while the laptop is off. Deployment and live qualification remain controller work. | +| October hosted service | Hosted authority, HTTPS worker MCP/hook routes, worker admission and lifecycle while the laptop is off. Deployment and live qualification remain controller work. | There is one authority per collaboration scope. The helper never starts a second daemon or database for a Desktop workspace; it forwards Desktop Core's actual @@ -28,10 +28,10 @@ All three read the same connection file, from `--connection-file` or | Command | Role | Exit | | --- | --- | --- | -| `october-bus mcp stdio --connection-file ` | Long-lived MCP bridge for the harness. Refuses if launcher credentials, local registration flags or `--remote` are also present. | Non-zero only on startup failure; runtime failures surface as tool errors plus one stderr line per failure class. | -| `october-bus hook [--connection-file ] [claude\|codex]` | Per-event lifecycle reporter, invoked by the harness. Same argv shape as Desktop's `bus-hook.mjs` (` []`). | Always 0. Silent and offline when no file is named. | -| `october-bus mcp check [--connection-file ] [--json]` | Setup diagnostic: file validation plus one JSON-RPC `ping`. Never `initialize`, never touches the inbox. | 0 on `ok`, 1 otherwise. | -| `october-bus version [--json]` (or `--version`) | Version pin verification: `{"runtimeVersion","protocolVersion"}`. | 0 | +| `agentintercom mcp stdio --connection-file ` | Long-lived MCP bridge for the harness. Refuses if launcher credentials, local registration flags or `--remote` are also present. | Non-zero only on startup failure; runtime failures surface as tool errors plus one stderr line per failure class. | +| `agentintercom hook [--connection-file ] [claude\|codex]` | Per-event lifecycle reporter, invoked by the harness. Same argv shape as Desktop's Node hook script (` []`). | Always 0. Silent and offline when no file is named. | +| `agentintercom mcp check [--connection-file ] [--json]` | Setup diagnostic: file validation plus one JSON-RPC `ping`. Never `initialize`, never touches the inbox. | 0 on `ok`, 1 otherwise. | +| `agentintercom version [--json]` (or `--version`) | Version pin verification: `{"runtimeVersion","protocolVersion"}`. | 0 | Failure classes for all of them: `invalid-configuration`, `expired-credential`, `retired-execution`, `unreachable`, `refused-credential`, `authority-unavailable`, @@ -48,9 +48,8 @@ Failure classes for all of them: `invalid-configuration`, `expired-credential`, `canvas`/`node`/`launch` on hook routes. They are never authority; Core resolves identity from the Bearer and refuses conflicting labels. - **Credentials.** `agentToken` is the execution's MCP capability (the token - Desktop registers with `capability.bindMcp`, `terminal:`). `hookToken` - is the execution's hook capability (the token `bindHookCapability` mints for - the same `terminal:` binding). Both are 32 random bytes, unpadded + Desktop binds to the `terminal:` execution). `hookToken` is the + execution's hook capability, minted for the same `terminal:` binding. Both are 32 random bytes, unpadded base64url. Nothing else ever enters the file: not the Core desktop/CLI credential, not the process-lifetime `busHookToken()`, not a scope token. - **Renewal.** Write a new file and `rename(2)` it over the old one. The bridge @@ -64,7 +63,7 @@ Failure classes for all of them: `invalid-configuration`, `expired-credential`, - **Route.** `endpoint` is HTTPS or literal-loopback HTTP; `httpHost` carries Core's real port when the SSH reverse-forward port differs. Redirects refuse. The standalone hosted Bus gateway uses HTTPS with `/bus/mcp` and no `httpHost`; - it does not serve hooks. Saturday cloud uses its existing HTTPS + it does not serve hooks. The October hosted service uses its HTTPS `/api/compute/workers//mcp` and sibling `/hook/*` routes, with `gateway` binding the record to that origin. Unknown file fields still refuse. Neither mode sends `Origin` or `X-October-Caller-Pid`. @@ -99,8 +98,8 @@ Verified by the tests listed under evidence: See [examples/desktop-remote](../examples/desktop-remote/) for complete files. - **Claude Code.** Per-launch `settings.json` hooks call - `"" hook ` with the same events and args as - `claudeLaunchSettings` today (`session-start`, `pre-prompt`, `stop`, + `"" hook ` with the same events and args as Desktop's + existing launch settings (`session-start`, `pre-prompt`, `stop`, `stop-failure`, `session-end`, `notify`, `permission-request`, `post-tool-use`, `post-tool-use-failure`, `ask-user-question`, `ask-user-question-resolved`). The per-launch `.mcp.json` runs @@ -126,12 +125,12 @@ Release artifacts (`.github/workflows/release.yml`, tag `v`): | Artifact | Contents | | --- | --- | -| `october-bus__linux_amd64.tar.gz`, `october-bus__linux_arm64.tar.gz` | Directory `october-bus__linux_/` containing `october-bus`, `october-bus-conformance`, `LICENSE`, `README.md`, `docs/`, `spec/`, `adapters/`, `compatibility/`, `assets/`. | +| `agentintercom__linux_amd64.tar.gz`, `agentintercom__linux_arm64.tar.gz` | Directory `agentintercom__linux_/` containing `agentintercom`, `agentintercom-conformance`, `LICENSE`, `README.md`, `docs/`, `spec/`, `adapters/`, `compatibility/`, `assets/`. | | `checksums.txt` | `sha256sum` lines for every release file; verify with `sha256sum -c`. | | `remote-bus-runtime.json` | Desktop's version-1 pin manifest: runtime/protocol versions, exact source commit, clean-build qualification, and archive/binary SHA-256 for both Linux architectures. | | `LICENSE` | Standalone license for redistributors, also included inside each archive. | -| `october-bus_v_linux_.spdx.json` | SPDX SBOM. | -| GitHub build-provenance attestation | Verify with `gh attestation verify --repo october-dev/october-bus`. | +| `agentintercom_v_linux_.spdx.json` | SPDX SBOM. | +| GitHub build-provenance attestation | Verify with `gh attestation verify --repo october-dev/agentintercom`. | The release workflow smoke-tests (`version`, `version --json`, `demo`) the Linux amd64 archive on `ubuntu-latest` and the Linux arm64 archive on @@ -143,20 +142,19 @@ Install on a worker (the controller performs this over SSH; users do nothing): ```sh VERSION=; ARCH= -ARCHIVE="october-bus_${VERSION}_linux_${ARCH}.tar.gz" +ARCHIVE="agentintercom_${VERSION}_linux_${ARCH}.tar.gz" # Download the archive and checksums.txt on the laptop from the GitHub release, # verify, then stream the archive over SSH stdin as the existing installer does. sha256sum --ignore-missing -c checksums.txt # must print: ${ARCHIVE}: OK -gh attestation verify "${ARCHIVE}" --repo october-dev/october-bus -tar -xzf "${ARCHIVE}" "october-bus_${VERSION}_linux_${ARCH}/october-bus" -install -m 0755 "october-bus_${VERSION}_linux_${ARCH}/october-bus" \ - ~/.october/servers//versions//bin/october-bus -~/.october/servers//versions//bin/october-bus version --json +gh attestation verify "${ARCHIVE}" --repo october-dev/agentintercom +tar -xzf "${ARCHIVE}" "agentintercom_${VERSION}_linux_${ARCH}/agentintercom" +install -m 0755 "agentintercom_${VERSION}_linux_${ARCH}/agentintercom" \ + ~/.october/servers//versions//bin/agentintercom +~/.october/servers//versions//bin/agentintercom version --json # {"protocolVersion":"0.1","runtimeVersion":""} ``` -Copy the published `remote-bus-runtime.json` into Desktop's -`src/shared/remote-bus-runtime.json`. Verify its archive and binary hashes and +Pin the published `remote-bus-runtime.json` in the controller. Verify its archive and binary hashes and compare both versions after installation. `qualification: "release"` records the reviewed CI artifact path, not a claim of live model qualification. No daemon is started; no credential is copied by the installer. @@ -167,18 +165,18 @@ integration; not a release): ```sh VERSION=$(node -p "require('./sdk/typescript/package.json').version") for ARCH in amd64 arm64; do - DIR="october-bus_${VERSION}_linux_${ARCH}"; mkdir -p "dist/${DIR}" + DIR="agentintercom_${VERSION}_linux_${ARCH}"; mkdir -p "dist/${DIR}" CGO_ENABLED=0 GOOS=linux GOARCH=${ARCH} go build -trimpath \ - -ldflags "-s -w -X github.com/october-dev/october-bus/bus.Version=${VERSION}" \ - -o "dist/${DIR}/october-bus" ./cmd/october-bus + -ldflags "-s -w -X github.com/october-dev/agentintercom/bus.Version=${VERSION}" \ + -o "dist/${DIR}/agentintercom" ./cmd/agentintercom tar -C dist -czf "dist/${DIR}.tar.gz" "${DIR}" done (cd dist && sha256sum *.tar.gz > checksums.txt) ``` -The optional npm route (`@october-dev/october-bus@0.1.0-next.15` with -`@october-dev/october-bus-linux-{x64,arm64}` optional dependencies, launcher -`cli/october-bus.cjs`) carries the same binary but requires Node 20+ on the +The optional npm route (`agentintercom-cli` with +`@october-dev/agentintercom-linux-{x64,arm64}` optional dependencies, launcher +`cli/agentintercom.cjs`) carries the same binary but requires Node 20+ on the worker; it is documented in [releases.md](releases.md) and is not the managed install path. Nothing was published by this work. @@ -192,7 +190,7 @@ Claude/Codex model, no cloud provisioning, no publication. | `go test ./cmd/october-bus ./internal/... -count=1 -race` | ok (20.4 s, 2.5 s) | | `go test ./... -count=1` | ok, all five packages | | `go vet ./cmd/october-bus ./internal/...`, `go build ./...`, `gofmt -l` | clean | -| Desktop opt-in `OCTOBER_BUS_TEST_BINARY=… vitest run src/core/agent-api.integration.test.ts -t 'native Bus bridge'` | 1 passed, 36 skipped. Real helper ↔ temporary Core through a TCP forward: send, reply, inbox pull, receipt ack, renewed credential, refusal recovery, execution-change refusal. | +| October Desktop opt-in native bridge integration test (`OCTOBER_BUS_TEST_BINARY=…`) | 1 passed, 36 skipped. Real helper ↔ temporary Core through a TCP forward: send, reply, inbox pull, receipt ack, renewed credential, refusal recovery, execution-change refusal. | | Linux cross-builds | `ELF 64-bit LSB executable, x86-64 … statically linked` and `… ARM aarch64 … statically linked`; archives 6.2 MB and 5.7 MB. | | Fixture exercise (`examples/desktop-remote`) | `mcp check` → `unreachable`, exit 1; bound hook → one stderr line, exit 0; unbound hook → silent, exit 0; `mcp stdio` without identity → refuses. | @@ -215,14 +213,13 @@ hosted gateway with a live TLS endpoint, laptop-off operation. ### Integration follow-up (2026-09-24) - `go test -race -count=1 ./...` passed all ten packages; `go vet ./...` passed. -- Desktop at `d5f7a0e2dbeb72cdd69b503e0f50367b79bfde88`: the opt-in native - bridge test passed against the built helper (1 passed, 40 skipped). It uses +- October Desktop: the opt-in native bridge test passed against the built helper (1 passed, 40 skipped). It uses the real Core API and a local TCP forward for messaging, replies, inbox acknowledgement, credential renewal, refusal recovery and execution fencing. -- Saturday PR #63 at `6c867ee3eae760f7616b7b6b8d507b5e509ef46b`: the actual - `ComputeController.heartbeat` writer, with synthetic store/authority dependencies, - produced a connection accepted unchanged by both `validateLease` and the built - helper. Against a deliberately closed HTTPS loopback endpoint, `mcp check` +- October hosted service: its connection-file writer, with synthetic + store/authority dependencies, + produced a connection accepted unchanged by both the service's own lease + validation and the built helper. Against a deliberately closed HTTPS loopback endpoint, `mcp check` reports `unreachable`, resolving the previous `invalid-configuration` failure on `gateway`. This proves the writer/reader contract, not a live cloud service. - `TestManagedMCPCloudHTTPSConnection` exercises the full cloud-shaped record @@ -232,8 +229,8 @@ hosted gateway with a live TLS endpoint, laptop-off operation. - Hook fixtures now reject `Origin` and `X-October-Caller-Pid`, matching Desktop's remote listener. Startup/discovery refusal tests verify that authority response bodies and tokens cannot appear in managed bridge diagnostics. -- The setup probe requires a valid ping result. In particular, Saturday's HTTP - 400 credential refusal cannot be mistaken for successful admission. +- The setup probe requires a valid ping result. In particular, the hosted service's + HTTP 400 credential refusal cannot be mistaken for successful admission. - The Linux manifest test builds real clean fixture binaries for both architectures, verifies their archive/binary hashes and rejects wrong commits, dirty source, wrong architecture and absent VCS metadata. Release-policy tests @@ -248,7 +245,7 @@ consumer's cloud integration. - Connection-file mode is Unix-only; Windows ACL checks are not implemented. - Hooks support `claude` and `codex` only; other flavors are refused on stderr. - Hooks use Desktop-compatible routes on the endpoint's origin and path prefix. - Desktop Core and Saturday compute serve them; the standalone Bus gateway does + Desktop Core and the hosted compute gateway serve them; the standalone Bus gateway does not. - `mcp check` proves route and credential admission, not agent readiness. Only the controller's process/foreground evidence can say the model is ready or @@ -266,10 +263,10 @@ consumer's cloud integration. - `c6f66cc` merge of `feat/hosted-mcp-gateway` (`dba3ece`, PR #120). - The documentation, fixture and release-workflow commit that follows. -## Required Desktop follow-ups +## Controller integration requirements -1. **Connection file writer.** Add `hookToken` (the `terminal:` hook - capability from `bindHookCapability`) next to `agentToken`; renew both by +1. **Connection file writer.** Write `hookToken` (the `terminal:` hook + capability) next to `agentToken`; renew both by atomic rename; delete the file on retirement; never reuse labels for a replacement execution. Keep `scopeId`/`agentId`/`executionId` = canvas/node/epoch. @@ -277,11 +274,10 @@ consumer's cloud integration. session environment for every managed launch (Codex needs it; Claude may use the explicit flag in its per-launch `.mcp.json`). 3. **Hook installation.** Generate hook commands as `"" hook ` with - the existing `arg` strings instead of `"" "