Phase 11, part 1: agents and their keys
Agents are users of kind agent, each given modules to read, or to read and act on, and the CRM scope. Admins make them under Settings → Agents, on every edition; keys (sm_…) are shown once and kept as hashes, can expire, be rotated (the old one works a day) or revoked, and record their last use. /mcp takes agent keys and offers each agent only the tools its scopes allow. On the local edition, mcp-token is the key of a built-in Hermes agent with the CRM and the Market. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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:<id>=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
|
||||
}
|
||||
@@ -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(`<pre id="key">(sm_[A-Za-z0-9]+)</pre>`)
|
||||
|
||||
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</a> <span class=\"pill\">built in</span>") || !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 ""
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
|
||||
<p><a href="/settings/agents/{{.Agent.ID}}">← {{.Agent.Name}}</a></p>
|
||||
<h2>{{if eq .Why "rotated"}}{{.Agent.Name}}'s new key{{else}}{{.Agent.Name}}'s key{{end}}</h2>
|
||||
<section class="card">
|
||||
<p><strong>Copy it now: it isn't shown again.</strong> Only a hash of it is kept.</p>
|
||||
<pre id="key">{{.Key}}</pre>
|
||||
<button type="button" class="secondary" data-copy="key">Copy</button>
|
||||
{{if eq .Why "rotated"}}<p class="help">The old key keeps working for another day; switch whatever uses it to this one.</p>{{end}}
|
||||
{{if .Hermes}}<p class="help">It's also in <code>mcp-token</code> in the data folder now. Hermes itself uses the socket and needs nothing; Claude Code's setup needs the new key: <code>claude mcp remove supermarket</code>, then add it again as below.</p>{{end}}
|
||||
</section>
|
||||
<section class="card">
|
||||
<h2>Using it</h2>
|
||||
<p>An MCP client reaches <code>{{.MCPURL}}</code> (streamable HTTP) with the header <code>Authorization: Bearer <key></code>. For Claude Code:</p>
|
||||
<pre id="claude">claude mcp add --transport http supermarket {{.MCPURL}} --header "Authorization: Bearer {{.Key}}"</pre>
|
||||
<button type="button" class="secondary small" data-copy="claude">Copy</button>
|
||||
</section>
|
||||
{{end}}{{template "settings-end"}}{{end}}
|
||||
@@ -0,0 +1,49 @@
|
||||
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}{{$a := .Row}}
|
||||
<p><a href="/settings/agents">← Agents</a></p>
|
||||
<h2>{{$a.Name}}{{if $a.BuiltIn}} <span class="pill">built in</span>{{end}}{{if eq $a.Status "disabled"}} <span class="pill">turned off</span>{{end}}</h2>
|
||||
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
|
||||
|
||||
<form class="card" method="post" action="/settings/agents/{{$a.ID}}/save">
|
||||
<label>Name <input name="name" value="{{$a.Name}}" required></label>
|
||||
<label>What it's for <textarea name="description" rows="2">{{$a.Description}}</textarea></label>
|
||||
{{template "agent-scopes" (dict "Scopes" $a.Modules "Grants" .Grants)}}
|
||||
<button type="submit">Save</button>
|
||||
</form>
|
||||
|
||||
<section class="card" id="keys">
|
||||
<h2>Keys</h2>
|
||||
<table class="list">
|
||||
<thead><tr><th>Key</th><th>Made</th><th>Expires</th><th>Last used</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{{range $a.Keys}}<tr>
|
||||
<td><code>{{.Prefix}}…</code>
|
||||
{{if not .Revoked.IsZero}} <span class="pill">revoked {{ago .Revoked}}</span>
|
||||
{{else if not (.Working $d.Now)}} <span class="pill">stopped</span>
|
||||
{{else if not .Retires.IsZero}} <span class="pill warn">replaced: works until {{.Retires.Local.Format "2 Jan 15:04"}}</span>
|
||||
{{else}} <span class="pill ok">working</span>{{end}}</td>
|
||||
<td>{{.Created.Local.Format "2 Jan 2006"}}</td>
|
||||
<td>{{if .Expires.IsZero}}<span class="muted">never</span>{{else}}{{.Expires.Local.Format "2 Jan 2006"}}{{end}}</td>
|
||||
<td>{{if .Used.IsZero}}<span class="muted">never</span>{{else}}{{ago .Used}}{{with .UsedFrom}} <span class="muted small">from {{.}}</span>{{end}}{{end}}</td>
|
||||
<td>{{if .Working $d.Now}}<form class="inline" method="post" action="/settings/agents/{{$a.ID}}/revoke" data-confirm="Revoke this key? Whatever uses it stops at once."><input type="hidden" name="key" value="{{.ID}}"><button type="submit" class="secondary small danger">Revoke</button></form>{{end}}</td>
|
||||
</tr>{{else}}<tr><td colspan="5" class="muted">No keys.</td></tr>{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="actions">
|
||||
<form class="inline" method="post" action="/settings/agents/{{$a.ID}}/rotate"><button type="submit" class="secondary">Rotate the key</button></form>
|
||||
<form class="inline row" method="post" action="/settings/agents/{{$a.ID}}/new-key"><label class="small">Expires <input type="date" name="expires"></label><button type="submit" class="secondary">Add a key</button></form>
|
||||
</div>
|
||||
<p class="help"><strong>Rotate</strong> makes a new key; the old one keeps working for a day, so whatever uses it can be switched over. After a leak, <strong>revoke</strong> it instead: it stops at once.</p>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="actions">
|
||||
{{if eq $a.Status "disabled"}}
|
||||
<form class="inline" method="post" action="/settings/agents/{{$a.ID}}/enable"><button type="submit" class="secondary">Turn it back on</button></form>
|
||||
{{else}}
|
||||
<form class="inline" method="post" action="/settings/agents/{{$a.ID}}/disable"><button type="submit" class="secondary danger">Turn it off</button></form>
|
||||
{{end}}
|
||||
{{if not $a.BuiltIn}}<form class="inline" method="post" action="/settings/agents/{{$a.ID}}/remove" data-confirm="Remove {{$a.Name}} and its keys for good?"><button type="submit" class="danger">Remove</button></form>{{end}}
|
||||
</div>
|
||||
<p class="help">Turned off, none of its keys work, until it's turned back on.</p>
|
||||
</section>
|
||||
{{end}}{{template "settings-end"}}{{end}}
|
||||
@@ -0,0 +1,33 @@
|
||||
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}
|
||||
<h2>Agents</h2>
|
||||
<p class="lede">Programs that use Supermarket over MCP, each with its own key, given modules to read, or to read and act on. Agents reach <code>{{.MCPURL}}</code> with <code>Authorization: Bearer <key></code>.</p>
|
||||
|
||||
{{if .Rows}}
|
||||
<section class="card">
|
||||
<table class="list">
|
||||
<thead><tr><th>Agent</th><th>May</th><th>Keys</th><th>Last used</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Rows}}<tr>
|
||||
<td><a href="/settings/agents/{{.ID}}">{{.Name}}</a>{{if .BuiltIn}} <span class="pill">built in</span>{{end}}{{if eq .Status "disabled"}} <span class="pill">turned off</span>{{end}}{{with .Description}}<br><span class="muted small">{{truncate 120 .}}</span>{{end}}</td>
|
||||
<td>{{.Access}}</td>
|
||||
<td>{{if .Working}}{{.Working}} working{{else}}<span class="warn-text">none working</span>{{end}}</td>
|
||||
<td>{{with .Last}}{{ago .Used}}{{with .UsedFrom}} <span class="muted small">from {{.}}</span>{{end}}{{else}}<span class="muted">never</span>{{end}}</td>
|
||||
</tr>{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
<form class="card" method="post" action="/settings/agents" id="new">
|
||||
<h2>New agent</h2>
|
||||
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
|
||||
<div class="cols">
|
||||
<label>Name <input name="name" value="{{.Form.Name}}" required placeholder="e.g. Morning writer"></label>
|
||||
<label>Key expires <span class="muted">(optional)</span> <input type="date" name="expires" value="{{.Form.Expires}}"></label>
|
||||
</div>
|
||||
<label>What it's for <textarea name="description" rows="2" placeholder="e.g. Drafts posts from What to write next, every morning">{{.Form.Description}}</textarea></label>
|
||||
{{template "agent-scopes" (dict "Scopes" .Form.Scopes "Grants" .Grants)}}
|
||||
<p class="help">Its key is shown once, after this. Only a hash of it is kept.</p>
|
||||
<button type="submit">Create the agent</button>
|
||||
</form>
|
||||
{{end}}{{template "settings-end"}}{{end}}
|
||||
@@ -146,6 +146,7 @@
|
||||
<a href="/settings/profile" {{if eq .Nav "settings/profile"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Profile</a>
|
||||
<div class="nav-label">Connections</div>
|
||||
<a href="/settings/connections" {{if eq .Nav "settings/connections"}}aria-current="page"{{end}}>{{template "icon" "core"}}All connections</a>
|
||||
<a href="/settings/agents" {{if eq .Nav "settings/agents"}}aria-current="page"{{end}}>{{template "icon" "ai"}}Agents</a>
|
||||
<a href="/settings/posting" {{if eq .Nav "settings/posting"}}aria-current="page"{{end}}>{{template "icon" "accounts"}}Posting accounts</a>
|
||||
<a href="/settings/accounts" {{if eq .Nav "settings/accounts"}}aria-current="page"{{end}}>{{template "icon" "accounts"}}Social accounts</a>
|
||||
<a href="/settings/core" {{if eq .Nav "settings/core"}}aria-current="page"{{end}}>{{template "icon" "core"}}Core & Hermes</a>
|
||||
@@ -278,6 +279,22 @@
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
{{/* An agent's scopes: {{template "agent-scopes" (dict "Scopes" … "Grants" …)}} */}}
|
||||
{{define "agent-scopes"}}{{$sc := .Scopes}}
|
||||
<fieldset class="access">
|
||||
<legend>May</legend>
|
||||
<table class="list access-grid"><tbody>
|
||||
{{range .Grants}}{{$a := print (index $sc .ID)}}<tr>
|
||||
<td>{{.Name}}</td>
|
||||
<td><label class="check"><input type="radio" name="scope:{{.ID}}" value="" {{if eq $a ""}}checked{{end}}> Nothing</label></td>
|
||||
<td><label class="check"><input type="radio" name="scope:{{.ID}}" value="read" {{if eq $a "view"}}checked{{end}}> Read</label></td>
|
||||
<td><label class="check"><input type="radio" name="scope:{{.ID}}" value="act" {{if eq $a "edit"}}checked{{end}}> Read and act</label></td>
|
||||
</tr>{{end}}
|
||||
</tbody></table>
|
||||
<p class="help"><em>Read and act</em> 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).</p>
|
||||
</fieldset>
|
||||
{{end}}
|
||||
|
||||
{{/* Users (Settings → Users, and one user's page). */}}
|
||||
{{define "user-status"}}{{if eq .Status "invited"}}{{if .InviteEnd.IsZero}}<span class="pill warn">Invitation expired</span>{{else}}<span class="pill">Invited</span> <span class="muted small">until {{.InviteEnd.Local.Format "2 Jan"}}</span>{{end}}{{else if eq .Status "disabled"}}<span class="pill">Turned off</span>{{else if .Locked}}<span class="pill warn">Locked</span>{{else}}<span class="pill ok">Active</span>{{if .TwoFactor}} <span class="muted small">two-factor</span>{{end}}{{end}}{{end}}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user