diff --git a/PLAN.md b/PLAN.md index ca7bba1..4ba260d 100644 --- a/PLAN.md +++ b/PLAN.md @@ -53,8 +53,9 @@ branch `phase10` (2026-11-25), not yet merged: schema 36, a new the visible changes are posting accounts, Connections, Activity, and a CSRF token in every form. -**Next: Phase 11, agents.** Phase 12 still needs who adds Supermarket's -client to Authelia. +**Next: Phase 11, agents.** Part 1 (agent users and keys) is built on +branch `phase11`. Phase 12 still needs who adds Supermarket's client to +Authelia. **Coming back to it (for the agent working on it):** - Run the tests inside the sandbox with @@ -2523,6 +2524,34 @@ module, Settings and their fragments answer 403. The log shows each step. Every edition gets this, including local, where an agent key replaces the single `mcp-token`. A commit after each part. +**Part 1 built 2026-11-26** on branch `phase11`. +- Schema 37: `agent_keys` (the key's SHA-256, its first characters, when + made, expiry, when a rotation retires it, revoked, last use and from + where) and `users.description`. An agent is a user of kind *agent* + (an address at `agents.invalid` nobody mails), with a membership whose + modules are *read* (view) or *read and act* (edit), and the `crm` scope + for the CRM bridge's tools. Agents never sign in on the web, aren't on + Settings → Users, and get no email or posting grid row. +- Keys are `sm_` and 40 random characters, shown once (`no-store`). A + key works until it expires, is revoked, or, after *Rotate*, a day after + its replacement was made; turning the agent off stops all of them. Wrong + keys count per IP like failed sign-ins (20 in 15 minutes, then a wait). +- Settings → Agents, for admins, on every edition (the local edition has + no Users page, so agents have their own): the list (what each may do, + working keys, last use), *New agent* (name, what it's for, scopes, an + optional expiry), and each agent's page: scopes, keys (revoke one), rotate, + add a key, turn off, remove. All of it in the audit log. +- `/mcp` takes agent keys only, and builds each agent's server from its + scopes: the CRM tools and `bridge_checkin` need `crm` (act), the Market + list needs the Market (read); the profile is for every agent. The module + tools come in part 2. +- On local, `mcp-token` becomes the key of a built-in *Hermes* agent with + the CRM (act) and the Market (read): the Market too because install.sh + gives Claude Code the same key for the profile and Market tools. It can be + turned off but not removed; rotating writes the new key to `mcp-token`. + The socket stays as it is (everything, no key). The server edition has no + built-in Hermes: an admin makes an agent with the CRM scope. + 1. **Agent users and their keys.** - An admin creates an agent on Settings → Users → *New agent*. It has a name, a description, and the modules it's given, each *read* or diff --git a/README.md b/README.md index 8ab8594..2228057 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,7 @@ The old terminal app used `http://localhost:8080/callback`; you can remove that - The port is published on `127.0.0.1` only, so other machines can't reach it, whatever the firewall says. - The local edition has no login, so it protects itself from web pages open in the same browser: it only answers requests addressed to `localhost` (against DNS rebinding), and refuses form posts that don't come from its own pages: each form carries a random token that another site can't know, and the browser's `Origin` must be the app's own. - The container runs as you, with a read-only filesystem, no Linux capabilities and `no-new-privileges`. It can write only its data folder. -- `/mcp` requires the bearer token in `mcp-token`. +- `/mcp` requires an agent's key (Settings → Agents). The key in `mcp-token` belongs to the built-in Hermes agent, which may work the CRM queue and read the Market; each agent gets only the tools for what it was given. ## The server edition diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index 5513836..2b9087f 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -323,12 +323,19 @@ func run(log *slog.Logger) error { Version: version, MCPToken: token, MCPSocket: filepath.Join(hostData, filepath.Base(mcpSocket)), - MCP: mcpserver.Handler(database, token, version), Mail: appMail(cfg), Log: log, ImportStatus: status, ImportErr: importErr, } + // Agents reach /mcp with their keys. On the local edition, mcp-token is + // the key of the built-in Hermes agent. + srv.MCP = mcpserver.Handler(database, version, srv.AgentAuth) + if local { + if err := srv.EnsureHermes(token); err != nil { + return err + } + } handler, err := srv.Handler() if err != nil { return err diff --git a/internal/db/migrations.go b/internal/db/migrations.go index 804ee99..0765232 100644 --- a/internal/db/migrations.go +++ b/internal/db/migrations.go @@ -165,6 +165,26 @@ CREATE TABLE audit_log ( CREATE INDEX audit_log_at ON audit_log(at); CREATE INDEX audit_log_user ON audit_log(user_id, at); ALTER TABLE outreach ADD COLUMN created_by INTEGER NOT NULL DEFAULT 0; +`, + }, + // 37 + { + Note: "agents' keys, and a description for each agent", + SQLite: ` +CREATE TABLE agent_keys ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + hash TEXT NOT NULL UNIQUE, -- the SHA-256 of the key; the key itself is shown once + prefix TEXT NOT NULL, -- its first characters, to tell keys apart + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL DEFAULT '', -- '' for never + retires_at TEXT NOT NULL DEFAULT '', -- replaced by a newer key: works until then + revoked_at TEXT NOT NULL DEFAULT '', + used_at TEXT NOT NULL DEFAULT '', + used_from TEXT NOT NULL DEFAULT '' -- the address of its last use +); +CREATE INDEX agent_keys_user ON agent_keys(user_id); +ALTER TABLE users ADD COLUMN description TEXT NOT NULL DEFAULT ''; `, }, } diff --git a/internal/mcpserver/mcpserver.go b/internal/mcpserver/mcpserver.go index 71c9003..5fe7750 100644 --- a/internal/mcpserver/mcpserver.go +++ b/internal/mcpserver/mcpserver.go @@ -5,7 +5,6 @@ package mcpserver import ( "context" - "crypto/subtle" "encoding/json" "errors" "fmt" @@ -14,6 +13,7 @@ import ( "net/http" "os" "strings" + "sync" "time" "github.com/modelcontextprotocol/go-sdk/mcp" @@ -25,27 +25,86 @@ import ( "supermarket/internal/profile" ) -// Handler returns the /mcp handler. Requests without "Authorization: Bearer -// " are refused. -func Handler(d *db.DB, token, version string) http.Handler { - server := newServer(d, version) - h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, - &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true}) +// Caller is the agent a request comes from, and what it may do. +type Caller struct { + ID int64 + Name string + // Can says whether the agent may read (act false) or change things in + // a module or scope (market, crm, …). + Can func(scope string, act bool) bool +} + +// Authenticator finds the caller of a request from its bearer key; an +// error refuses it. +type Authenticator func(r *http.Request, key string) (*Caller, error) + +// Handler returns the /mcp handler. Each request needs an agent's key +// ("Authorization: Bearer sm_…"), and is offered only the tools the +// agent's scopes allow. +func Handler(d *db.DB, version string, auth Authenticator) http.Handler { + var mu sync.Mutex + servers := map[string]*mcp.Server{} // by the scopes' signature: a few at most + h := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server { + c, _ := r.Context().Value(callerKey{}).(*Caller) + sig := signature(c) + mu.Lock() + defer mu.Unlock() + if srv, ok := servers[sig]; ok { + return srv + } + srv := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil) + addTools(srv, d, c) + servers[sig] = srv + return srv + }, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true}) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") - if !ok || token == "" || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 { + key, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + var c *Caller + var err error + if ok && key != "" { + c, err = auth(r, strings.TrimSpace(key)) + } + if !ok || key == "" || err != nil || c == nil { w.Header().Set("WWW-Authenticate", `Bearer realm="supermarket"`) http.Error(w, "unauthorized", http.StatusUnauthorized) return } - h.ServeHTTP(w, r) + h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), callerKey{}, c))) }) } +type callerKey struct{} + +// scopes are what tools are offered by: each, read or act. +var scopes = []string{"market", "crm"} + +// signature names the tools a caller gets. +func signature(c *Caller) string { + if c == nil { + return "*" + } + var b strings.Builder + for _, sc := range scopes { + switch { + case c.Can(sc, true): + b.WriteString(sc + ":act,") + case c.Can(sc, false): + b.WriteString(sc + ":read,") + } + } + return b.String() +} + +// can says whether the caller (nil: the local socket, everything) may use +// a scope. +func can(c *Caller, scope string, act bool) bool { + return c == nil || c.Can(scope, act) +} + func newServer(d *db.DB, version string) *mcp.Server { server := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil) - addTools(server, d) + addTools(server, d, nil) return server } @@ -159,7 +218,8 @@ type checkinArgs struct { Note string `json:"note,omitempty" jsonschema:"a short note on anything that failed"` } -func addTools(s *mcp.Server, d *db.DB) { +// addTools adds the tools the caller may use (nil: all). +func addTools(s *mcp.Server, d *db.DB, c *Caller) { mcp.AddTool(s, &mcp.Tool{ Name: "profile_get", Description: "The company profile: what the company sells, its products, target customers, voice, websites, social accounts and keywords.", @@ -172,123 +232,128 @@ func addTools(s *mcp.Server, d *db.DB) { return res, nil, err }) - mcp.AddTool(s, &mcp.Tool{ - Name: "inventory_list", - Description: "The Market: partners (whose news we amplify), competitors (whom we position against) and projects we watch, with their accounts, keywords and talking points.", - }, func(ctx context.Context, _ *mcp.CallToolRequest, args inventoryArgs) (*mcp.CallToolResult, any, error) { - entries, err := inventory.List(d, strings.ToLower(strings.TrimSpace(args.Relationship))) - if err != nil { - return nil, nil, err - } - if entries == nil { - entries = []inventory.Entry{} - } - res, err := jsonResult(entries) - return res, nil, err - }) - - mcp.AddTool(s, &mcp.Tool{ - Name: "crm_pending_actions", - Description: "The CRM work Supermarket has queued for you: records to create in EspoCRM, and whether to copy recently " + - "changed CRM records back to Supermarket. Call it at the start of each CRM run and follow its instructions exactly.", - }, func(ctx context.Context, _ *mcp.CallToolRequest, _ noArgs) (*mcp.CallToolResult, any, error) { - now := time.Now() - actions, err := crm.Claim(d, now, 25) - if err != nil { - return nil, nil, err - } - out := pendingResult{Instructions: crmInstructions, Actions: []pendingAction{}} - for _, a := range actions { - out.Actions = append(out.Actions, pendingAction{ID: a.ID, Do: a.Kind, Entity: a.Entity, Fields: a.Fields, FindExisting: a.Match}) - } - due, since, err := crm.SyncDue(d, now) - if err != nil { - return nil, nil, err - } - if due { - if err := crm.StartSync(d, now); err != nil { - return nil, nil, err - } - req := &syncRequest{Entities: crm.SyncEntities, Fields: crmSyncFields} - if !since.IsZero() { - // A little overlap, so nothing changed during the last sync is missed. - req.ModifiedSince = since.Add(-10 * time.Minute).UTC().Format("2006-01-02 15:04:05") - } - out.Sync = req - } - res, err := jsonResult(out) - return res, nil, err - }) - - mcp.AddTool(s, &mcp.Tool{ - Name: "crm_report_result", - Description: "Report the result of one action from crm_pending_actions: created (with the new record's id), existing (with the matching record's id), or failed (with the error).", - }, func(ctx context.Context, _ *mcp.CallToolRequest, args reportArgs) (*mcp.CallToolResult, any, error) { - err := crm.Report(d, args.ID, crm.Result{Outcome: strings.ToLower(strings.TrimSpace(args.Outcome)), EspoID: args.EspoID, Error: args.Error}, time.Now()) - if err != nil { - return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: err.Error()}}}, nil, nil - } - return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "Recorded."}}}, nil, nil - }) - - mcp.AddTool(s, &mcp.Tool{ - Name: "crm_ingest", - Description: "Send Supermarket the CRM records crm_pending_actions asked you to sync, in batches; set done=true on the last call.", - }, func(ctx context.Context, _ *mcp.CallToolRequest, args ingestArgs) (*mcp.CallToolResult, any, error) { - entity := strings.TrimSpace(args.Entity) - known := false - for _, e := range crm.SyncEntities { - known = known || strings.EqualFold(e, entity) - if strings.EqualFold(e, entity) { - entity = e - } - } - if !known { - return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{ - Text: "entity must be one of " + strings.Join(crm.SyncEntities, ", ")}}}, nil, nil - } - now := time.Now() - var recs []crm.Record - skipped := 0 - for _, f := range args.Records { - r, err := crm.RecordFrom(entity, f, now) + if can(c, "market", false) { + mcp.AddTool(s, &mcp.Tool{ + Name: "inventory_list", + Description: "The Market: partners (whose news we amplify), competitors (whom we position against) and projects we watch, with their accounts, keywords and talking points.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, args inventoryArgs) (*mcp.CallToolResult, any, error) { + entries, err := inventory.List(d, strings.ToLower(strings.TrimSpace(args.Relationship))) if err != nil { - skipped++ - continue - } - recs = append(recs, r) - } - if err := crm.Ingest(d, recs); err != nil { - return nil, nil, err - } - if args.Done { - if err := crm.FinishSync(d, now); err != nil { return nil, nil, err } - } - msg := fmt.Sprintf("Stored %d %s record(s).", len(recs), entity) - if skipped > 0 { - msg += fmt.Sprintf(" Skipped %d without an id.", skipped) - } - if args.Done { - msg += " Sync finished." - } - return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: msg}}}, nil, nil - }) + if entries == nil { + entries = []inventory.Entry{} + } + res, err := jsonResult(entries) + return res, nil, err + }) - mcp.AddTool(s, &mcp.Tool{ - Name: "bridge_checkin", - Description: "Tell Supermarket that the agent can reach it and the Core's mcphub MCP server. Call it with the names of the mcphub tools you have.", - }, func(ctx context.Context, _ *mcp.CallToolRequest, args checkinArgs) (*mcp.CallToolResult, any, error) { - agent := strings.TrimSpace(args.Agent) - if agent == "" { - agent = "unknown" - } - if err := bridge.Record(d, bridge.Checkin{Agent: agent, MCPHubTools: args.MCPHubTools, Note: strings.TrimSpace(args.Note)}); err != nil { - return nil, nil, err - } - return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{ - Text: "Checked in. Supermarket has recorded the mcphub tools you can use.", - }}}, nil, nil - }) + } + // The CRM queue, worked through the Core (Hermes' bridge). + if can(c, "crm", true) { + mcp.AddTool(s, &mcp.Tool{ + Name: "crm_pending_actions", + Description: "The CRM work Supermarket has queued for you: records to create in EspoCRM, and whether to copy recently " + + "changed CRM records back to Supermarket. Call it at the start of each CRM run and follow its instructions exactly.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, _ noArgs) (*mcp.CallToolResult, any, error) { + now := time.Now() + actions, err := crm.Claim(d, now, 25) + if err != nil { + return nil, nil, err + } + out := pendingResult{Instructions: crmInstructions, Actions: []pendingAction{}} + for _, a := range actions { + out.Actions = append(out.Actions, pendingAction{ID: a.ID, Do: a.Kind, Entity: a.Entity, Fields: a.Fields, FindExisting: a.Match}) + } + due, since, err := crm.SyncDue(d, now) + if err != nil { + return nil, nil, err + } + if due { + if err := crm.StartSync(d, now); err != nil { + return nil, nil, err + } + req := &syncRequest{Entities: crm.SyncEntities, Fields: crmSyncFields} + if !since.IsZero() { + // A little overlap, so nothing changed during the last sync is missed. + req.ModifiedSince = since.Add(-10 * time.Minute).UTC().Format("2006-01-02 15:04:05") + } + out.Sync = req + } + res, err := jsonResult(out) + return res, nil, err + }) + + mcp.AddTool(s, &mcp.Tool{ + Name: "crm_report_result", + Description: "Report the result of one action from crm_pending_actions: created (with the new record's id), existing (with the matching record's id), or failed (with the error).", + }, func(ctx context.Context, _ *mcp.CallToolRequest, args reportArgs) (*mcp.CallToolResult, any, error) { + err := crm.Report(d, args.ID, crm.Result{Outcome: strings.ToLower(strings.TrimSpace(args.Outcome)), EspoID: args.EspoID, Error: args.Error}, time.Now()) + if err != nil { + return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: err.Error()}}}, nil, nil + } + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "Recorded."}}}, nil, nil + }) + + mcp.AddTool(s, &mcp.Tool{ + Name: "crm_ingest", + Description: "Send Supermarket the CRM records crm_pending_actions asked you to sync, in batches; set done=true on the last call.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, args ingestArgs) (*mcp.CallToolResult, any, error) { + entity := strings.TrimSpace(args.Entity) + known := false + for _, e := range crm.SyncEntities { + known = known || strings.EqualFold(e, entity) + if strings.EqualFold(e, entity) { + entity = e + } + } + if !known { + return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{ + Text: "entity must be one of " + strings.Join(crm.SyncEntities, ", ")}}}, nil, nil + } + now := time.Now() + var recs []crm.Record + skipped := 0 + for _, f := range args.Records { + r, err := crm.RecordFrom(entity, f, now) + if err != nil { + skipped++ + continue + } + recs = append(recs, r) + } + if err := crm.Ingest(d, recs); err != nil { + return nil, nil, err + } + if args.Done { + if err := crm.FinishSync(d, now); err != nil { + return nil, nil, err + } + } + msg := fmt.Sprintf("Stored %d %s record(s).", len(recs), entity) + if skipped > 0 { + msg += fmt.Sprintf(" Skipped %d without an id.", skipped) + } + if args.Done { + msg += " Sync finished." + } + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: msg}}}, nil, nil + }) + + mcp.AddTool(s, &mcp.Tool{ + Name: "bridge_checkin", + Description: "Tell Supermarket that the agent can reach it and the Core's mcphub MCP server. Call it with the names of the mcphub tools you have.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, args checkinArgs) (*mcp.CallToolResult, any, error) { + agent := strings.TrimSpace(args.Agent) + if agent == "" { + agent = "unknown" + } + if err := bridge.Record(d, bridge.Checkin{Agent: agent, MCPHubTools: args.MCPHubTools, Note: strings.TrimSpace(args.Note)}); err != nil { + return nil, nil, err + } + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{ + Text: "Checked in. Supermarket has recorded the mcphub tools you can use.", + }}}, nil, nil + }) + } } diff --git a/internal/users/agents.go b/internal/users/agents.go new file mode 100644 index 0000000..37fef17 --- /dev/null +++ b/internal/users/agents.go @@ -0,0 +1,228 @@ +package users + +import ( + "crypto/rand" + "database/sql" + "errors" + "math/big" + "strings" + "time" + + "supermarket/internal/db" + "supermarket/internal/slug" +) + +// Agents are users of kind Agent: no password, no sign-in page, but keys +// that reach /mcp. Each has modules like a member ("read" is View, "read +// and act" is Edit), and maybe the CRM scope. + +// CRMScope is the scope of the tools that work the CRM queue through the +// Core (Hermes' bridge). It's kept with the modules. +const CRMScope = "crm" + +// KeyPrefix starts every agent key. +const KeyPrefix = "sm_" + +// RotationGrace is how long a key replaced by a new one keeps working. +const RotationGrace = 24 * time.Hour + +// Key is one of an agent's keys (never the key itself). +type Key struct { + ID int64 + User int64 + Prefix string // sm_ and its first characters + Created time.Time + Expires time.Time // zero: never + Retires time.Time // zero, or when a rotation ends it + Revoked time.Time + Used time.Time + UsedFrom string +} + +// Working says whether the key opens /mcp now. +func (k *Key) Working(now time.Time) bool { + return k.Revoked.IsZero() && (k.Expires.IsZero() || now.Before(k.Expires)) && (k.Retires.IsZero() || now.Before(k.Retires)) +} + +// ErrBadKey is a key that's unknown, revoked, expired, retired, or whose +// agent is turned off. +var ErrBadKey = errors.New("this key doesn't work") + +// CreateAgent adds an agent: a user of kind Agent, active, with a made-up +// address no mail goes to. +func CreateAgent(d *db.DB, name, description string, now time.Time) (*User, error) { + name = strings.TrimSpace(name) + if name == "" { + return nil, errors.New("give the agent a name") + } + tag := make([]byte, 4) + _, _ = rand.Read(tag) + base := slug.Make(name) + if base == "" { + base = "agent" + } + u := &User{Email: base + "-" + strings.ToLower(b32.EncodeToString(tag)[:6]) + "@agents.invalid", Name: name, Description: description, Kind: Agent, Status: Active} + return u, Create(d, u, now) +} + +// SaveAgent changes an agent's name and description. +func SaveAgent(d *db.DB, id int64, name, description string) error { + name = strings.TrimSpace(name) + if name == "" { + return errors.New("give the agent a name") + } + _, err := d.Exec(`UPDATE users SET name = ?, description = ? WHERE id = ? AND kind = 'agent'`, name, strings.TrimSpace(description), id) + return err +} + +const keyAlphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789" + +// newKey is sm_ and 40 random characters (about 230 bits). +func newKey() (string, error) { + var b strings.Builder + b.WriteString(KeyPrefix) + max := big.NewInt(int64(len(keyAlphabet))) + for i := 0; i < 40; i++ { + n, err := rand.Int(rand.Reader, max) + if err != nil { + return "", err + } + b.WriteByte(keyAlphabet[n.Int64()]) + } + return b.String(), nil +} + +// NewKey makes a key for an agent, valid until expires (zero: never), and +// returns it: the only time it's seen. +func NewKey(d *db.DB, user int64, expires, now time.Time) (string, *Key, error) { + key, err := newKey() + if err != nil { + return "", nil, err + } + k, err := AddKey(d, user, key, expires, now) + return key, k, err +} + +// AddKey keeps a key made elsewhere (the local edition's mcp-token). +func AddKey(d *db.DB, user int64, key string, expires, now time.Time) (*Key, error) { + prefix := key + if len(prefix) > 10 { + prefix = prefix[:10] + } + k := &Key{User: user, Prefix: prefix, Created: now, Expires: expires} + var err error + k.ID, err = d.Insert(`INSERT INTO agent_keys (user_id, hash, prefix, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`, + user, hashToken(key), prefix, ts(now), tsOrEmpty(expires)) + return k, err +} + +func tsOrEmpty(t time.Time) string { + if t.IsZero() { + return "" + } + return ts(t) +} + +// Rotate makes a new key for an agent; the working ones it had keep +// working for RotationGrace, then stop. The new key keeps the old one's +// expiry date (none, if any had none). +func Rotate(d *db.DB, user int64, now time.Time) (string, *Key, error) { + keys, err := Keys(d, user) + if err != nil { + return "", nil, err + } + var expires time.Time + for _, k := range keys { + if k.Working(now) && !k.Expires.IsZero() && k.Expires.After(expires) { + expires = k.Expires + } + } + for _, k := range keys { + if k.Working(now) && k.Expires.IsZero() { + expires = time.Time{} + break + } + } + if _, err := d.Exec(`UPDATE agent_keys SET retires_at = ? WHERE user_id = ? AND revoked_at = '' AND (retires_at = '' OR retires_at > ?)`, + ts(now.Add(RotationGrace)), user, ts(now.Add(RotationGrace))); err != nil { + return "", nil, err + } + return NewKey(d, user, expires, now) +} + +// Revoke stops one of an agent's keys at once. +func Revoke(d *db.DB, user, key int64, now time.Time) error { + _, err := d.Exec(`UPDATE agent_keys SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at = ''`, ts(now), key, user) + return err +} + +// RevokeAll stops all of an agent's keys at once. +func RevokeAll(d *db.DB, user int64, now time.Time) error { + _, err := d.Exec(`UPDATE agent_keys SET revoked_at = ? WHERE user_id = ? AND revoked_at = ''`, ts(now), user) + return err +} + +const keyCols = `id, user_id, prefix, created_at, expires_at, retires_at, revoked_at, used_at, used_from` + +func scanKey(row interface{ Scan(...any) error }) (*Key, error) { + var k Key + var created, expires, retires, revoked, used string + if err := row.Scan(&k.ID, &k.User, &k.Prefix, &created, &expires, &retires, &revoked, &used, &k.UsedFrom); err != nil { + return nil, err + } + k.Created, k.Expires, k.Retires, k.Revoked, k.Used = parseTS(created), parseTS(expires), parseTS(retires), parseTS(revoked), parseTS(used) + return &k, nil +} + +// Keys are an agent's keys, newest first. +func Keys(d *db.DB, user int64) ([]*Key, error) { + rows, err := d.Query(`SELECT `+keyCols+` FROM agent_keys WHERE user_id = ? ORDER BY id DESC`, user) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*Key + for rows.Next() { + k, err := scanKey(rows) + if err != nil { + return nil, err + } + out = append(out, k) + } + return out, rows.Err() +} + +// usedEvery is how often a key's use is written down. +const usedEvery = time.Minute + +// Authenticate finds the agent a key belongs to, if the key works, and +// notes its use. +func Authenticate(d *db.DB, key, from string, now time.Time) (*User, *Key, error) { + if !strings.HasPrefix(key, KeyPrefix) && len(key) < 32 { + return nil, nil, ErrBadKey + } + k, err := scanKey(d.QueryRow(`SELECT `+keyCols+` FROM agent_keys WHERE hash = ?`, hashToken(key))) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil, ErrBadKey + } + if err != nil { + return nil, nil, err + } + if !k.Working(now) { + return nil, nil, ErrBadKey + } + u, err := ByID(d, k.User) + if errors.Is(err, ErrNotFound) || (err == nil && (u.Kind != Agent || u.Status != Active)) { + return nil, nil, ErrBadKey + } + if err != nil { + return nil, nil, err + } + if now.Sub(k.Used) >= usedEvery || k.UsedFrom != from { + k.Used, k.UsedFrom = now, from + if _, err := d.Exec(`UPDATE agent_keys SET used_at = ?, used_from = ? WHERE id = ?`, ts(now), from, k.ID); err != nil { + return nil, nil, err + } + } + return u, k, nil +} diff --git a/internal/users/agents_test.go b/internal/users/agents_test.go new file mode 100644 index 0000000..1cb8dd3 --- /dev/null +++ b/internal/users/agents_test.go @@ -0,0 +1,107 @@ +package users + +import ( + "errors" + "strings" + "testing" + "time" +) + +func TestAgentKeys(t *testing.T) { + d := openDB(t) + now := time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC) + a, err := CreateAgent(d, "Morning writer", "Drafts posts from What to write next.", now) + if err != nil { + t.Fatal(err) + } + if a.Kind != Agent || a.Status != Active || !strings.HasSuffix(a.Email, "@agents.invalid") || !strings.HasPrefix(a.Email, "morning-writer-") { + t.Errorf("agent %+v", a) + } + if _, err := CreateAgent(d, " ", "", now); err == nil { + t.Error("no name accepted") + } + // Agents never sign in with a password. + if CheckPassword(a, "") { + t.Error("password") + } + + key, k, err := NewKey(d, a.ID, now.Add(30*24*time.Hour), now) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(key, "sm_") || len(key) != 43 || k.Prefix != key[:10] { + t.Errorf("key %q, prefix %q", key, k.Prefix) + } + u, got, err := Authenticate(d, key, "203.0.113.7", now) + if err != nil || u.ID != a.ID || got.ID != k.ID { + t.Fatalf("auth: %v", err) + } + keys, _ := Keys(d, a.ID) + if keys[0].UsedFrom != "203.0.113.7" || !keys[0].Used.Equal(now) { + t.Errorf("use not noted: %+v", keys[0]) + } + for _, bad := range []string{"", "sm_nope", key + "x", strings.ToUpper(key)} { + if _, _, err := Authenticate(d, bad, "", now); !errors.Is(err, ErrBadKey) { + t.Errorf("%q: %v", bad, err) + } + } + // Expiry. + if _, _, err := Authenticate(d, key, "", now.Add(31*24*time.Hour)); !errors.Is(err, ErrBadKey) { + t.Error("expired key works") + } + + // Rotation: the old key works for a day; the new one keeps the expiry. + key2, k2, err := Rotate(d, a.ID, now) + if err != nil { + t.Fatal(err) + } + if !k2.Expires.Equal(now.Add(30 * 24 * time.Hour)) { + t.Errorf("new key's expiry %v", k2.Expires) + } + if _, _, err := Authenticate(d, key, "", now.Add(23*time.Hour)); err != nil { + t.Error("old key stopped within the day") + } + if _, _, err := Authenticate(d, key, "", now.Add(RotationGrace)); !errors.Is(err, ErrBadKey) { + t.Error("old key works after a day") + } + if _, _, err := Authenticate(d, key2, "", now.Add(RotationGrace)); err != nil { + t.Error("new key doesn't work") + } + + // Revoking stops it at once; turning the agent off stops every key. + Revoke(d, a.ID, k2.ID, now) + if _, _, err := Authenticate(d, key2, "", now); !errors.Is(err, ErrBadKey) { + t.Error("revoked key works") + } + key3, _, _ := NewKey(d, a.ID, time.Time{}, now) + SetStatus(d, a.ID, Disabled) + if _, _, err := Authenticate(d, key3, "", now); !errors.Is(err, ErrBadKey) { + t.Error("a turned-off agent's key works") + } + SetStatus(d, a.ID, Active) + RevokeAll(d, a.ID, now) + if _, _, err := Authenticate(d, key3, "", now); !errors.Is(err, ErrBadKey) { + t.Error("revoke all") + } + + // A person's "key" never authenticates, even if one were stored. + p := &User{Email: "pat@example.com", Status: Active} + Create(d, p, now) + AddKey(d, p.ID, "sm_person_key_0123456789012345678901234", time.Time{}, now) + if _, _, err := Authenticate(d, "sm_person_key_0123456789012345678901234", "", now); !errors.Is(err, ErrBadKey) { + t.Error("a person's key works") + } + + // A legacy token (64 hex digits) is a key too. + legacy := strings.Repeat("ab", 32) + AddKey(d, a.ID, legacy, time.Time{}, now) + if _, _, err := Authenticate(d, legacy, "", now); err != nil { + t.Errorf("legacy token: %v", err) + } + if err := Delete(d, a.ID); err != nil { + t.Fatal(err) + } + if ks, _ := Keys(d, a.ID); len(ks) != 0 { + t.Error("keys outlived the agent") + } +} diff --git a/internal/users/users.go b/internal/users/users.go index 938770e..be2f11a 100644 --- a/internal/users/users.go +++ b/internal/users/users.go @@ -76,6 +76,7 @@ type User struct { Kind Kind Status Status Title string + Description string // an agent's: what it's for TimeZone string Photo string Emails []string // the emails they want (the daily SEO email, …) @@ -137,13 +138,13 @@ func NormalEmail(s string) (string, error) { return strings.ToLower(s), nil } -const userCols = `id, email, name, kind, status, password_hash, title, time_zone, photo, emails, created_at, signed_in_at, failed_signins, locked_at, two_factor, totp_step, recovery_codes` +const userCols = `id, email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at, signed_in_at, failed_signins, locked_at, two_factor, totp_step, recovery_codes` func scanUser(row interface{ Scan(...any) error }) (*User, error) { var u User var kind, status, emails, created, signedIn, locked, codes string var twoFactor int - err := row.Scan(&u.ID, &u.Email, &u.Name, &kind, &status, &u.passwordHash, &u.Title, &u.TimeZone, &u.Photo, &emails, &created, &signedIn, + err := row.Scan(&u.ID, &u.Email, &u.Name, &kind, &status, &u.passwordHash, &u.Title, &u.Description, &u.TimeZone, &u.Photo, &emails, &created, &signedIn, &u.FailedSignIns, &locked, &twoFactor, &u.totpStep, &codes) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound @@ -184,9 +185,9 @@ func Create(d *db.DB, u *User, now time.Time) error { } emails, _ := json.Marshal(u.Emails) u.Created = now - u.ID, err = d.Insert(`INSERT INTO users (email, name, kind, status, password_hash, title, time_zone, photo, emails, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - u.Email, strings.TrimSpace(u.Name), string(u.Kind), string(u.Status), u.passwordHash, u.Title, u.TimeZone, u.Photo, string(emails), ts(now)) + u.ID, err = d.Insert(`INSERT INTO users (email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + u.Email, strings.TrimSpace(u.Name), string(u.Kind), string(u.Status), u.passwordHash, u.Title, strings.TrimSpace(u.Description), u.TimeZone, u.Photo, string(emails), ts(now)) return err } @@ -264,7 +265,7 @@ func Delete(d *db.DB, id int64) error { defer tx.Rollback() // Not left to ON DELETE CASCADE: SQLite enforces it only with // foreign_keys on, and an imported database may not have had them. - for _, q := range []string{`DELETE FROM sessions WHERE user_id = ?`, `DELETE FROM links WHERE user_id = ?`, `DELETE FROM memberships WHERE user_id = ?`, `DELETE FROM users WHERE id = ?`} { + for _, q := range []string{`DELETE FROM sessions WHERE user_id = ?`, `DELETE FROM links WHERE user_id = ?`, `DELETE FROM agent_keys WHERE user_id = ?`, `DELETE FROM memberships WHERE user_id = ?`, `DELETE FROM users WHERE id = ?`} { if _, err := tx.Exec(q, id); err != nil { return err } diff --git a/internal/web/activity.go b/internal/web/activity.go index 6364f2e..fbbbb1a 100644 --- a/internal/web/activity.go +++ b/internal/web/activity.go @@ -176,6 +176,8 @@ var actionLabels = map[string]string{ "opened-pull-request": "opened a pull request", "closed-pull-request": "closed a pull request", "created-site": "started a site", "sent-to-indexnow": "sent pages to IndexNow", "restored-backup": "restored a backup", "changed-suppression": "changed the suppression list", "synced-mailing-lists": "synced the mailing lists", "changed-profile": "changed the company profile", + "agent-created": "made the agent", "agent-changed": "changed what this agent may do:", "key-rotated": "rotated the key of", + "key-made": "made a new key for", "key-revoked": "revoked a key of", } func actionLabel(a string) string { diff --git a/internal/web/agents.go b/internal/web/agents.go new file mode 100644 index 0000000..5eb9c09 --- /dev/null +++ b/internal/web/agents.go @@ -0,0 +1,420 @@ +package web + +import ( + "errors" + "net/http" + "strconv" + "strings" + "time" + + "supermarket/internal/audit" + "supermarket/internal/fileutil" + "supermarket/internal/mcpserver" + "supermarket/internal/users" +) + +// Agents: programs that reach Supermarket over MCP with a key. Each is a +// user of kind agent, given modules to read, or to read and act on, and +// maybe the CRM scope (Hermes' bridge). Admins manage them under Settings +// → Agents, on every edition. + +// AgentAuth checks a bearer key for /mcp. Wrong keys count against the +// caller's address, like failed sign-ins. +func (s *Server) AgentAuth(r *http.Request, key string) (*mcpserver.Caller, error) { + now := time.Now() + ip := clientIP(r) + ipKey := "mcp:ip:" + ip + if s.throttled(ipKey, users.MaxFailsPerIP, now) { + return nil, users.ErrBadKey + } + u, _, err := users.Authenticate(s.DB, key, ip, now) + if err != nil { + if errors.Is(err, users.ErrBadKey) { + _ = users.Fail(s.DB, ipKey, users.ThrottleWindow, now) + s.Log.Info("mcp: a key was refused", "ip", ip) + } else { + s.Log.Error("mcp: checking a key", "err", err) + } + return nil, err + } + m, err := users.MembershipOf(s.DB, users.Team, u.ID) + if err != nil { + return nil, users.ErrBadKey + } + return &mcpserver.Caller{ID: u.ID, Name: u.Name, Can: m.Can}, nil +} + +// hermesKey is the setting naming the local edition's built-in Hermes agent. +const hermesKey = "agents:hermes" + +// EnsureHermes makes the local edition's built-in Hermes agent, with the +// CRM scope, and makes mcp-token one of its keys: what used to be the one +// token for /mcp is now Hermes' key. Its socket stays as it is. +func (s *Server) EnsureHermes(token string) error { + if token == "" { + return nil + } + now := time.Now() + var id int64 + if ok, err := s.DB.GetJSON(hermesKey, &id); err != nil { + return err + } else if ok { + if _, err := users.ByID(s.DB, id); errors.Is(err, users.ErrNotFound) { + ok = false + } else if err != nil { + return err + } + if ok { + // The token file may be new (a restore, a new install). + if _, _, err := users.Authenticate(s.DB, token, "", now); errors.Is(err, users.ErrBadKey) { + _, err = users.AddKey(s.DB, id, token, time.Time{}, now) + return err + } + return nil + } + } + u, err := users.CreateAgent(s.DB, "Hermes", "The Hermes agent on this computer: works the CRM queue through your Core, and reads the Market (Claude Code, set up by install.sh, uses its key too). Its key is mcp-token in the data folder; it also reaches Supermarket through the socket there.", now) + if err != nil { + return err + } + if err := users.Join(s.DB, users.Team, u.ID, users.Member, map[string]users.Access{users.CRMScope: users.Edit, "market": users.View}, now); err != nil { + return err + } + if _, err := users.AddKey(s.DB, u.ID, token, time.Time{}, now); err != nil { + return err + } + s.record(audit.Entry{Kind: audit.System, Action: "agent-created", Target: "Hermes", Detail: "built in, with the key in mcp-token"}) + return s.DB.PutJSON(hermesKey, u.ID) +} + +// isHermes says whether an agent is the built-in one. +func (s *Server) isHermes(id int64) bool { + var h int64 + ok, _ := s.DB.GetJSON(hermesKey, &h) + return ok && h == id && !s.signsIn() +} + +// agentGrants are what an agent can be given: the modules, and the CRM. +func agentGrants() []grant { + return append(grants(), grant{users.CRMScope, "CRM through the Core"}) +} + +// agentRow is an agent in the list. +type agentRow struct { + users.TeamUser + Access string + Keys []*users.Key + Working int // keys that work now + Last *users.Key // the last used + BuiltIn bool +} + +func (s *Server) agentRows(now time.Time) ([]agentRow, error) { + list, err := users.Members(s.DB, users.Team) + if err != nil { + return nil, err + } + var out []agentRow + for _, m := range list { + if m.Kind != users.Agent { + continue + } + row := agentRow{TeamUser: m, Access: agentAccessText(m.Membership), BuiltIn: s.isHermes(m.ID)} + if row.Keys, err = users.Keys(s.DB, m.ID); err != nil { + return nil, err + } + for _, k := range row.Keys { + if k.Working(now) { + row.Working++ + } + if !k.Used.IsZero() && (row.Last == nil || k.Used.After(row.Last.Used)) { + row.Last = k + } + } + out = append(out, row) + } + return out, nil +} + +// agentAccessText is an agent's scopes: "SEO (read), Content (read and act)". +func agentAccessText(m users.Membership) string { + var parts []string + for _, g := range agentGrants() { + switch m.Modules[g.ID] { + case users.Edit: + parts = append(parts, g.Name+" (read and act)") + case users.View: + parts = append(parts, g.Name+" (read)") + } + } + if len(parts) == 0 { + return "Nothing yet" + } + return strings.Join(parts, ", ") +} + +// agentScopesFromForm reads scope:=read|act|"". +func agentScopesFromForm(r *http.Request) map[string]users.Access { + out := map[string]users.Access{} + for _, g := range agentGrants() { + switch r.PostFormValue("scope:" + g.ID) { + case "read": + out[g.ID] = users.View + case "act": + out[g.ID] = users.Edit + } + } + return out +} + +// expiryFromForm reads an optional date (the key stops at its start, in +// the server's time zone). +func expiryFromForm(r *http.Request, now time.Time) (time.Time, error) { + v := strings.TrimSpace(r.PostFormValue("expires")) + if v == "" { + return time.Time{}, nil + } + t, err := time.ParseInLocation("2006-01-02", v, time.Local) + if err != nil { + return time.Time{}, errors.New("the expiry isn't a date") + } + if !t.After(now) { + return time.Time{}, errors.New("the expiry has passed: choose a later date, or none") + } + return t, nil +} + +type agentsData struct { + Rows []agentRow + Grants []grant + Form agentForm + MCPURL string + Problem string +} + +type agentForm struct { + Name, Description, Expires string + Scopes map[string]users.Access +} + +func (s *Server) agentsPage(w http.ResponseWriter, r *http.Request) { + if !viewerOf(r).Member.Admin() { + s.forbidden(w, r) + return + } + s.renderAgents(w, r, agentsData{}, http.StatusOK) +} + +func (s *Server) renderAgents(w http.ResponseWriter, r *http.Request, d agentsData, code int) { + rows, err := s.agentRows(time.Now()) + if err != nil { + s.serverError(w, err) + return + } + d.Rows, d.Grants, d.MCPURL = rows, agentGrants(), s.mcpURL() + if code != http.StatusOK { + w.WriteHeader(code) + } + s.render(w, r, "agents", page{Title: "Agents", Nav: "settings/agents", Data: d}) +} + +// mcpURL is where agents reach /mcp. +func (s *Server) mcpURL() string { + if s.signsIn() { + return s.PublicURL + "/mcp" + } + return "http://127.0.0.1:" + publicPort(s.PublicURL) + "/mcp" +} + +func (s *Server) agentCreate(w http.ResponseWriter, r *http.Request) { + if !viewerOf(r).Member.Admin() { + s.forbidden(w, r) + return + } + now := time.Now() + f := agentForm{Name: strings.TrimSpace(r.PostFormValue("name")), Description: strings.TrimSpace(r.PostFormValue("description")), + Expires: r.PostFormValue("expires"), Scopes: agentScopesFromForm(r)} + expires, err := expiryFromForm(r, now) + switch { + case f.Name == "": + err = errors.New("give the agent a name") + case err == nil && len(f.Scopes) == 0: + err = errors.New("give the agent at least one module to read") + } + if err != nil { + s.renderAgents(w, r, agentsData{Form: f, Problem: sentence(err.Error()) + "."}, http.StatusUnprocessableEntity) + return + } + u, err := users.CreateAgent(s.DB, f.Name, f.Description, now) + if err == nil { + err = users.Join(s.DB, users.Team, u.ID, users.Member, f.Scopes, now) + } + var key string + if err == nil { + key, _, err = users.NewKey(s.DB, u.ID, expires, now) + } + if err != nil { + s.serverError(w, err) + return + } + s.audit(r, "agent-created", u.Name, agentAccessText(users.Membership{Role: users.Member, Modules: f.Scopes})) + s.showKey(w, r, u, key, "new") +} + +// showKey shows a key once. +func (s *Server) showKey(w http.ResponseWriter, r *http.Request, u *users.User, key, why string) { + w.Header().Set("Cache-Control", "no-store") + s.render(w, r, "agent-key", page{Title: u.Name, Nav: "settings/agents", Data: map[string]any{ + "Agent": u, "Key": key, "Why": why, "MCPURL": s.mcpURL(), "Grace": users.RotationGrace, + "Hermes": s.isHermes(u.ID), + }}) +} + +type agentData struct { + Row agentRow + Grants []grant + Problem string + Now time.Time +} + +// agentTarget is the agent named by {id}. +func (s *Server) agentTarget(w http.ResponseWriter, r *http.Request) *users.User { + if !viewerOf(r).Member.Admin() { + s.forbidden(w, r) + return nil + } + id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64) + u, err := users.ByID(s.DB, id) + if errors.Is(err, users.ErrNotFound) || (err == nil && u.Kind != users.Agent) { + http.NotFound(w, r) + return nil + } + if err != nil { + s.serverError(w, err) + return nil + } + return u +} + +func (s *Server) agentPage(w http.ResponseWriter, r *http.Request) { + if u := s.agentTarget(w, r); u != nil { + s.renderAgent(w, r, u, "", http.StatusOK) + } +} + +func (s *Server) renderAgent(w http.ResponseWriter, r *http.Request, u *users.User, problem string, code int) { + now := time.Now() + rows, err := s.agentRows(now) + if err != nil { + s.serverError(w, err) + return + } + for _, row := range rows { + if row.ID == u.ID { + if code != http.StatusOK { + w.WriteHeader(code) + } + s.render(w, r, "agent", page{Title: u.Name, Nav: "settings/agents", Data: agentData{Row: row, Grants: agentGrants(), Problem: problem, Now: now}}) + return + } + } + http.NotFound(w, r) +} + +// agentAction: save, rotate, revoke, disable, enable, remove. +func (s *Server) agentAction(w http.ResponseWriter, r *http.Request) { + u := s.agentTarget(w, r) + if u == nil { + return + } + now := time.Now() + back := "/settings/agents/" + strconv.FormatInt(u.ID, 10) + var err error + switch r.PathValue("action") { + case "save": + scopes := agentScopesFromForm(r) + if len(scopes) == 0 { + s.renderAgent(w, r, u, "Give the agent at least one module to read, or turn it off.", http.StatusUnprocessableEntity) + return + } + if err = users.SaveAgent(s.DB, u.ID, r.PostFormValue("name"), r.PostFormValue("description")); err != nil { + s.renderAgent(w, r, u, sentence(err.Error())+".", http.StatusUnprocessableEntity) + return + } + if err = users.Join(s.DB, users.Team, u.ID, users.Member, scopes, now); err == nil { + s.audit(r, "agent-changed", u.Name, agentAccessText(users.Membership{Role: users.Member, Modules: scopes})) + redirect(w, r, back, "saved") + return + } + case "rotate": + var key string + if key, _, err = users.Rotate(s.DB, u.ID, now); err == nil { + if s.isHermes(u.ID) { + err = s.newHermesToken(key) + } + if err == nil { + s.audit(r, "key-rotated", u.Name, "the old key works for another day") + s.showKey(w, r, u, key, "rotated") + return + } + } + case "new-key": + var expires time.Time + if expires, err = expiryFromForm(r, now); err != nil { + s.renderAgent(w, r, u, sentence(err.Error())+".", http.StatusUnprocessableEntity) + return + } + var key string + if key, _, err = users.NewKey(s.DB, u.ID, expires, now); err == nil { + s.audit(r, "key-made", u.Name, "") + s.showKey(w, r, u, key, "new") + return + } + case "revoke": + kid, _ := strconv.ParseInt(r.PostFormValue("key"), 10, 64) + if err = users.Revoke(s.DB, u.ID, kid, now); err == nil { + s.audit(r, "key-revoked", u.Name, "") + redirect(w, r, back, "key-revoked") + return + } + case "disable": + if err = users.SetStatus(s.DB, u.ID, users.Disabled); err == nil { + s.audit(r, "disabled", u.Name, "an agent: its keys stop working") + redirect(w, r, back, "agent-off") + return + } + case "enable": + if err = users.SetStatus(s.DB, u.ID, users.Active); err == nil { + s.audit(r, "enabled", u.Name, "an agent") + redirect(w, r, back, "enabled") + return + } + case "remove": + if s.isHermes(u.ID) { + s.renderAgent(w, r, u, "Hermes is built in: turn it off instead.", http.StatusUnprocessableEntity) + return + } + if err = users.Delete(s.DB, u.ID); err == nil { + s.audit(r, "removed-user", u.Name, "an agent") + redirect(w, r, "/settings/agents", "removed") + return + } + default: + http.NotFound(w, r) + return + } + s.serverError(w, err) +} + +// newHermesToken writes Hermes' new key to mcp-token, where the local +// edition's tools (Claude Code's setup, supermarket token) read it. +func (s *Server) newHermesToken(key string) error { + if s.DataDir == "" { + return nil + } + if err := fileutil.WriteFileAtomic(s.DataDir+"/mcp-token", []byte(key+"\n"), 0o600); err != nil { + return err + } + s.MCPToken = key + return nil +} diff --git a/internal/web/agents_test.go b/internal/web/agents_test.go new file mode 100644 index 0000000..1bb2aa6 --- /dev/null +++ b/internal/web/agents_test.go @@ -0,0 +1,171 @@ +package web + +import ( + "bytes" + "encoding/json" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "testing" + "time" + + "supermarket/internal/users" +) + +// mcpTools lists the tools a key is offered, or returns the status. +func mcpTools(h http.Handler, key string) (int, []string) { + raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}) + rec := do(h, http.MethodPost, "/mcp", bytes.NewReader(raw), map[string]string{ + "Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Authorization": "Bearer " + key}) + if rec.Code != http.StatusOK { + return rec.Code, nil + } + var out struct { + Result struct { + Tools []struct{ Name string } `json:"tools"` + } `json:"result"` + } + json.Unmarshal(rec.Body.Bytes(), &out) + var names []string + for _, t := range out.Result.Tools { + names = append(names, t.Name) + } + return rec.Code, names +} + +var keyRe = regexp.MustCompile(`
(sm_[A-Za-z0-9]+)
`) + +func TestLocalHermesAgent(t *testing.T) { + s, h := newTestServer(t, nil) + // mcp-token is the built-in Hermes' key: CRM, and reading the Market. + code, tools := mcpTools(h, testToken) + got := strings.Join(tools, " ") + if code != http.StatusOK || !strings.Contains(got, "crm_pending_actions") || !strings.Contains(got, "inventory_list") { + t.Fatalf("hermes: %d %v", code, tools) + } + body := do(h, http.MethodGet, "/settings/agents", nil, nil).Body.String() + if !strings.Contains(body, ">Hermes built in") || !strings.Contains(body, "CRM through the Core (read and act)") { + t.Errorf("agents page: %s", body) + } + // Starting again doesn't make a second Hermes. + if err := s.EnsureHermes(testToken); err != nil { + t.Fatal(err) + } + if n, _ := users.Count(s.DB); n != 1 { + t.Errorf("%d users", n) + } + // Rotating Hermes' key writes it to mcp-token. + var id int64 + s.DB.GetJSON(hermesKey, &id) + rec := postForm(h, "/settings/agents/"+strconv.FormatInt(id, 10)+"/rotate", url.Values{}) + m := keyRe.FindStringSubmatch(rec.Body.String()) + if m == nil || s.MCPToken != m[1] || rec.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("rotate: %s", rec.Body.String()) + } + // Both work for a day. + for _, k := range []string{testToken, m[1]} { + if code, _ := mcpTools(h, k); code != http.StatusOK { + t.Errorf("after rotating, %s…: %d", k[:6], code) + } + } + // Hermes can't be removed, only turned off. + if rec := postForm(h, "/settings/agents/"+strconv.FormatInt(id, 10)+"/remove", url.Values{}); rec.Code != http.StatusUnprocessableEntity { + t.Errorf("remove hermes: %d", rec.Code) + } +} + +func TestAgents(t *testing.T) { + s, h := newServerEdition(t) + owner := addUser(t, s, "owner@example.com", users.Owner, nil) + oc := sessionFor(t, s, owner) + member := addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.Edit}) + if rec := as(h, sessionFor(t, s, member), http.MethodGet, "/settings/agents", nil); rec.Code != http.StatusForbidden { + t.Errorf("member: %d", rec.Code) + } + // No built-in Hermes on a server, and no key works yet. + if code, _ := mcpTools(h, testToken); code != http.StatusUnauthorized { + t.Errorf("mcp-token on a server: %d", code) + } + + if rec := as(h, oc, http.MethodPost, "/settings/agents", url.Values{"name": {"Writer"}}); rec.Code != http.StatusUnprocessableEntity { + t.Errorf("no scopes: %d", rec.Code) + } + if rec := as(h, oc, http.MethodPost, "/settings/agents", url.Values{"name": {"Writer"}, "scope:seo": {"read"}, "expires": {"2020-01-01"}}); rec.Code != http.StatusUnprocessableEntity { + t.Errorf("expiry passed: %d", rec.Code) + } + rec := as(h, oc, http.MethodPost, "/settings/agents", url.Values{"name": {"Writer"}, "description": {"Drafts"}, + "scope:content": {"act"}, "scope:seo": {"read"}, "scope:market": {"read"}, "expires": {time.Now().AddDate(0, 1, 0).Format("2006-01-02")}}) + m := keyRe.FindStringSubmatch(rec.Body.String()) + if rec.Code != http.StatusOK || m == nil { + t.Fatalf("create: %d %s", rec.Code, rec.Body.String()) + } + key := m[1] + if !strings.Contains(rec.Body.String(), "https://") && !strings.Contains(rec.Body.String(), "/mcp") { + t.Error("no address to use it at") + } + code, tools := mcpTools(h, key) + got := strings.Join(tools, " ") + if code != http.StatusOK || !strings.Contains(got, "inventory_list") || strings.Contains(got, "crm_") { + t.Errorf("writer's tools: %d %v", code, tools) + } + agent, _ := users.ByEmail(s.DB, mustAgentEmail(t, s, "Writer")) + page := as(h, oc, http.MethodGet, "/settings/agents/"+strconv.FormatInt(agent.ID, 10), nil).Body.String() + if !strings.Contains(page, key[:10]+"…") || strings.Contains(page, key) || !strings.Contains(page, "from 192.0.2.1") { + t.Errorf("agent page: %s", page) + } + // Agents aren't people: not on Users, no sign-in. + if body := as(h, oc, http.MethodGet, "/settings/users", nil).Body.String(); strings.Contains(body, "Writer") { + t.Error("an agent on the Users page") + } + + // Revoking stops the key at once. + keys, _ := users.Keys(s.DB, agent.ID) + as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/revoke", url.Values{"key": {strconv.FormatInt(keys[0].ID, 10)}}) + if code, _ := mcpTools(h, key); code != http.StatusUnauthorized { + t.Errorf("revoked: %d", code) + } + // A new key, then the agent turned off: no key works. + rec = as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/new-key", url.Values{}) + key2 := keyRe.FindStringSubmatch(rec.Body.String())[1] + if code, _ := mcpTools(h, key2); code != http.StatusOK { + t.Errorf("new key: %d", code) + } + as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/disable", url.Values{}) + if code, _ := mcpTools(h, key2); code != http.StatusUnauthorized { + t.Errorf("turned off: %d", code) + } + // Changing its scopes changes its tools. + as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/enable", url.Values{}) + as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/save", url.Values{"name": {"Writer"}, "scope:seo": {"read"}}) + if _, tools := mcpTools(h, key2); strings.Contains(strings.Join(tools, " "), "inventory_list") { + t.Errorf("market taken away, still offered: %v", tools) + } + // The log. + body := as(h, oc, http.MethodGet, "/settings/activity", nil).Body.String() + for _, want := range []string{"made the agent", "revoked a key of", "changed what this agent may do:"} { + if !strings.Contains(body, want) { + t.Errorf("activity lacks %q", want) + } + } + // Many wrong keys from one address: refused for a while. + for i := 0; i < users.MaxFailsPerIP; i++ { + mcpTools(h, "sm_wrong") + } + if code, _ := mcpTools(h, key2); code != http.StatusUnauthorized { + t.Errorf("after many wrong keys: %d", code) + } +} + +func mustAgentEmail(t *testing.T, s *Server, name string) string { + t.Helper() + list, _ := users.Members(s.DB, users.Team) + for _, m := range list { + if m.Kind == users.Agent && m.Name == name { + return m.Email + } + } + t.Fatalf("no agent %s", name) + return "" +} diff --git a/internal/web/auth_test.go b/internal/web/auth_test.go index e0de0a0..9cd8f7b 100644 --- a/internal/web/auth_test.go +++ b/internal/web/auth_test.go @@ -19,6 +19,13 @@ func newServerEdition(t *testing.T) (*Server, http.Handler) { t.Helper() s, h := newTestServer(t, nil) s.Config = &config.Config{Edition: config.Server} + // The server edition has no built-in Hermes. + var hermes int64 + if ok, _ := s.DB.GetJSON(hermesKey, &hermes); ok { + users.Delete(s.DB, hermes) + s.DB.Exec(`DELETE FROM settings WHERE key = ?`, hermesKey) + s.DB.Exec(`DELETE FROM audit_log`) + } s.Mail = &appmail.Outbox{} files, err := storage.Open(config.Storage{Dir: t.TempDir()}) if err != nil { diff --git a/internal/web/server.go b/internal/web/server.go index 0878fe9..ee307d0 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -344,6 +344,10 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("GET /settings/about", s.aboutPage) mux.HandleFunc("GET /settings/connections", s.connectionsPage) mux.HandleFunc("GET /settings/activity", s.activityPage) + mux.HandleFunc("GET /settings/agents", s.agentsPage) + mux.HandleFunc("POST /settings/agents", s.agentCreate) + mux.HandleFunc("GET /settings/agents/{id}", s.agentPage) + mux.HandleFunc("POST /settings/agents/{id}/{action}", s.agentAction) mux.HandleFunc("GET /settings/posting", s.postingPage) mux.HandleFunc("POST /settings/posting", s.postingSave) mux.HandleFunc("POST /settings/posting/{id}/remove", s.postingRemove) @@ -698,6 +702,8 @@ var flashes = map[string]string{ "signed-out-user": "Signed out everywhere.", "removed": "Removed.", "joined": "Welcome to Supermarket.", + "key-revoked": "Revoked: that key no longer works.", + "agent-off": "Turned off: none of its keys work.", "account-removed": "Signed out: posts scheduled to it are back in Posts.", "own-account-connected": "Connected: you can post as it, and an admin can let others.", "deleted": "Deleted.", diff --git a/internal/web/server_test.go b/internal/web/server_test.go index fbc055c..b6e02e2 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -54,9 +54,12 @@ func newTestServer(t *testing.T, c *core.Core) (*Server, http.Handler) { s := &Server{ DB: d, Secrets: sec, Core: c, DataDir: dir, PublicURL: "http://localhost:8470", Version: "test", MCPToken: testToken, - MCP: mcpserver.Handler(d, testToken, "test"), Log: slog.New(slog.NewTextHandler(io.Discard, nil)), } + s.MCP = mcpserver.Handler(d, "test", s.AgentAuth) + if err := s.EnsureHermes(testToken); err != nil { + t.Fatal(err) + } h, err := s.Handler() if err != nil { t.Fatal(err) diff --git a/internal/web/templates/agent-key.html b/internal/web/templates/agent-key.html new file mode 100644 index 0000000..ca7dcbe --- /dev/null +++ b/internal/web/templates/agent-key.html @@ -0,0 +1,17 @@ +{{define "content"}}{{template "settings-start" .}}{{with .Data}} +

← {{.Agent.Name}}

+

{{if eq .Why "rotated"}}{{.Agent.Name}}'s new key{{else}}{{.Agent.Name}}'s key{{end}}

+
+

Copy it now: it isn't shown again. Only a hash of it is kept.

+
{{.Key}}
+ + {{if eq .Why "rotated"}}

The old key keeps working for another day; switch whatever uses it to this one.

{{end}} + {{if .Hermes}}

It's also in mcp-token in the data folder now. Hermes itself uses the socket and needs nothing; Claude Code's setup needs the new key: claude mcp remove supermarket, then add it again as below.

{{end}} +
+
+

Using it

+

An MCP client reaches {{.MCPURL}} (streamable HTTP) with the header Authorization: Bearer <key>. For Claude Code:

+
claude mcp add --transport http supermarket {{.MCPURL}} --header "Authorization: Bearer {{.Key}}"
+ +
+{{end}}{{template "settings-end"}}{{end}} diff --git a/internal/web/templates/agent.html b/internal/web/templates/agent.html new file mode 100644 index 0000000..03581cf --- /dev/null +++ b/internal/web/templates/agent.html @@ -0,0 +1,49 @@ +{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}{{$a := .Row}} +

← Agents

+

{{$a.Name}}{{if $a.BuiltIn}} built in{{end}}{{if eq $a.Status "disabled"}} turned off{{end}}

+{{with .Problem}}{{end}} + +
+ + + {{template "agent-scopes" (dict "Scopes" $a.Modules "Grants" .Grants)}} + +
+ +
+

Keys

+ + + + {{range $a.Keys}} + + + + + + {{else}}{{end}} + +
KeyMadeExpiresLast used
{{.Prefix}}… + {{if not .Revoked.IsZero}} revoked {{ago .Revoked}} + {{else if not (.Working $d.Now)}} stopped + {{else if not .Retires.IsZero}} replaced: works until {{.Retires.Local.Format "2 Jan 15:04"}} + {{else}} working{{end}}{{.Created.Local.Format "2 Jan 2006"}}{{if .Expires.IsZero}}never{{else}}{{.Expires.Local.Format "2 Jan 2006"}}{{end}}{{if .Used.IsZero}}never{{else}}{{ago .Used}}{{with .UsedFrom}} from {{.}}{{end}}{{end}}{{if .Working $d.Now}}
{{end}}
No keys.
+
+
+
+
+

Rotate makes a new key; the old one keeps working for a day, so whatever uses it can be switched over. After a leak, revoke it instead: it stops at once.

+
+ +
+
+ {{if eq $a.Status "disabled"}} +
+ {{else}} +
+ {{end}} + {{if not $a.BuiltIn}}
{{end}} +
+

Turned off, none of its keys work, until it's turned back on.

+
+{{end}}{{template "settings-end"}}{{end}} diff --git a/internal/web/templates/agents.html b/internal/web/templates/agents.html new file mode 100644 index 0000000..8725c60 --- /dev/null +++ b/internal/web/templates/agents.html @@ -0,0 +1,33 @@ +{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}} +

Agents

+

Programs that use Supermarket over MCP, each with its own key, given modules to read, or to read and act on. Agents reach {{.MCPURL}} with Authorization: Bearer <key>.

+ +{{if .Rows}} +
+ + + + {{range .Rows}} + + + + + {{end}} + +
AgentMayKeysLast used
{{.Name}}{{if .BuiltIn}} built in{{end}}{{if eq .Status "disabled"}} turned off{{end}}{{with .Description}}
{{truncate 120 .}}{{end}}
{{.Access}}{{if .Working}}{{.Working}} working{{else}}none working{{end}}{{with .Last}}{{ago .Used}}{{with .UsedFrom}} from {{.}}{{end}}{{else}}never{{end}}
+
+{{end}} + +
+

New agent

+ {{with .Problem}}{{end}} +
+ + +
+ + {{template "agent-scopes" (dict "Scopes" .Form.Scopes "Grants" .Grants)}} +

Its key is shown once, after this. Only a hash of it is kept.

+ +
+{{end}}{{template "settings-end"}}{{end}} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 6f9ecef..53b82d0 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -146,6 +146,7 @@ {{template "icon" "profile"}}Profile {{template "icon" "core"}}All connections + {{template "icon" "ai"}}Agents {{template "icon" "accounts"}}Posting accounts {{template "icon" "accounts"}}Social accounts {{template "icon" "core"}}Core & Hermes @@ -278,6 +279,22 @@ {{end}} +{{/* An agent's scopes: {{template "agent-scopes" (dict "Scopes" … "Grants" …)}} */}} +{{define "agent-scopes"}}{{$sc := .Scopes}} +
+ May + + {{range .Grants}}{{$a := print (index $sc .ID)}} + + + + + {{end}} +
{{.Name}}
+

Read and act lets it change things, such as writing drafts. Anything that leaves Supermarket (a post, an email, a site push) waits for a person's approval (Phase 11, part 3).

+
+{{end}} + {{/* Users (Settings → Users, and one user's page). */}} {{define "user-status"}}{{if eq .Status "invited"}}{{if .InviteEnd.IsZero}}Invitation expired{{else}}Invited until {{.InviteEnd.Local.Format "2 Jan"}}{{end}}{{else if eq .Status "disabled"}}Turned off{{else if .Locked}}Locked{{else}}Active{{if .TwoFactor}} two-factor{{end}}{{end}}{{end}} diff --git a/internal/web/users.go b/internal/web/users.go index 81917e5..fb39d29 100644 --- a/internal/web/users.go +++ b/internal/web/users.go @@ -116,6 +116,9 @@ func (s *Server) memberRows() ([]memberRow, error) { now := time.Now() out := make([]memberRow, 0, len(list)) for _, m := range list { + if m.Kind == users.Agent { + continue // under Settings → Agents + } row := memberRow{TeamUser: m, Access: accessText(m.Membership)} if m.Status == users.Invited { if row.InviteEnd, err = users.LinkExpiry(s.DB, users.InviteLink, m.ID, now); err != nil {