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:
2026-11-25 10:26:31 -07:00
co-authored by Claude Opus 5.5
parent da16736fb4
commit da2d56f8d2
19 changed files with 1323 additions and 138 deletions
+31 -2
View File
@@ -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 the visible changes are posting accounts, Connections, Activity, and a
CSRF token in every form. CSRF token in every form.
**Next: Phase 11, agents.** Phase 12 still needs who adds Supermarket's **Next: Phase 11, agents.** Part 1 (agent users and keys) is built on
client to Authelia. branch `phase11`. Phase 12 still needs who adds Supermarket's client to
Authelia.
**Coming back to it (for the agent working on it):** **Coming back to it (for the agent working on it):**
- Run the tests inside the sandbox with - 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 Every edition gets this, including local, where an agent key replaces the
single `mcp-token`. A commit after each part. 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.** 1. **Agent users and their keys.**
- An admin creates an agent on Settings → Users → *New agent*. It has a - 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 name, a description, and the modules it's given, each *read* or
+1 -1
View File
@@ -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 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 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. - 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 ## The server edition
+8 -1
View File
@@ -323,12 +323,19 @@ func run(log *slog.Logger) error {
Version: version, Version: version,
MCPToken: token, MCPToken: token,
MCPSocket: filepath.Join(hostData, filepath.Base(mcpSocket)), MCPSocket: filepath.Join(hostData, filepath.Base(mcpSocket)),
MCP: mcpserver.Handler(database, token, version),
Mail: appMail(cfg), Mail: appMail(cfg),
Log: log, Log: log,
ImportStatus: status, ImportStatus: status,
ImportErr: importErr, 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() handler, err := srv.Handler()
if err != nil { if err != nil {
return err return err
+20
View File
@@ -165,6 +165,26 @@ CREATE TABLE audit_log (
CREATE INDEX audit_log_at ON audit_log(at); CREATE INDEX audit_log_at ON audit_log(at);
CREATE INDEX audit_log_user ON audit_log(user_id, at); CREATE INDEX audit_log_user ON audit_log(user_id, at);
ALTER TABLE outreach ADD COLUMN created_by INTEGER NOT NULL DEFAULT 0; 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 '';
`, `,
}, },
} }
+77 -12
View File
@@ -5,7 +5,6 @@ package mcpserver
import ( import (
"context" "context"
"crypto/subtle"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@@ -14,6 +13,7 @@ import (
"net/http" "net/http"
"os" "os"
"strings" "strings"
"sync"
"time" "time"
"github.com/modelcontextprotocol/go-sdk/mcp" "github.com/modelcontextprotocol/go-sdk/mcp"
@@ -25,27 +25,86 @@ import (
"supermarket/internal/profile" "supermarket/internal/profile"
) )
// Handler returns the /mcp handler. Requests without "Authorization: Bearer // Caller is the agent a request comes from, and what it may do.
// <token>" are refused. type Caller struct {
func Handler(d *db.DB, token, version string) http.Handler { ID int64
server := newServer(d, version) Name string
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, // Can says whether the agent may read (act false) or change things in
&mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true}) // 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) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") key, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || token == "" || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 { 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"`) w.Header().Set("WWW-Authenticate", `Bearer realm="supermarket"`)
http.Error(w, "unauthorized", http.StatusUnauthorized) http.Error(w, "unauthorized", http.StatusUnauthorized)
return 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 { func newServer(d *db.DB, version string) *mcp.Server {
server := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil) server := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil)
addTools(server, d) addTools(server, d, nil)
return server return server
} }
@@ -159,7 +218,8 @@ type checkinArgs struct {
Note string `json:"note,omitempty" jsonschema:"a short note on anything that failed"` 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{ mcp.AddTool(s, &mcp.Tool{
Name: "profile_get", Name: "profile_get",
Description: "The company profile: what the company sells, its products, target customers, voice, websites, social accounts and keywords.", Description: "The company profile: what the company sells, its products, target customers, voice, websites, social accounts and keywords.",
@@ -172,6 +232,7 @@ func addTools(s *mcp.Server, d *db.DB) {
return res, nil, err return res, nil, err
}) })
if can(c, "market", false) {
mcp.AddTool(s, &mcp.Tool{ mcp.AddTool(s, &mcp.Tool{
Name: "inventory_list", 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.", Description: "The Market: partners (whose news we amplify), competitors (whom we position against) and projects we watch, with their accounts, keywords and talking points.",
@@ -187,6 +248,9 @@ func addTools(s *mcp.Server, d *db.DB) {
return res, nil, err return res, nil, err
}) })
}
// The CRM queue, worked through the Core (Hermes' bridge).
if can(c, "crm", true) {
mcp.AddTool(s, &mcp.Tool{ mcp.AddTool(s, &mcp.Tool{
Name: "crm_pending_actions", Name: "crm_pending_actions",
Description: "The CRM work Supermarket has queued for you: records to create in EspoCRM, and whether to copy recently " + Description: "The CRM work Supermarket has queued for you: records to create in EspoCRM, and whether to copy recently " +
@@ -292,3 +356,4 @@ func addTools(s *mcp.Server, d *db.DB) {
}}}, nil, nil }}}, nil, nil
}) })
} }
}
+228
View File
@@ -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
}
+107
View File
@@ -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")
}
}
+7 -6
View File
@@ -76,6 +76,7 @@ type User struct {
Kind Kind Kind Kind
Status Status Status Status
Title string Title string
Description string // an agent's: what it's for
TimeZone string TimeZone string
Photo string Photo string
Emails []string // the emails they want (the daily SEO email, …) 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 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) { func scanUser(row interface{ Scan(...any) error }) (*User, error) {
var u User var u User
var kind, status, emails, created, signedIn, locked, codes string var kind, status, emails, created, signedIn, locked, codes string
var twoFactor int 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) &u.FailedSignIns, &locked, &twoFactor, &u.totpStep, &codes)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound return nil, ErrNotFound
@@ -184,9 +185,9 @@ func Create(d *db.DB, u *User, now time.Time) error {
} }
emails, _ := json.Marshal(u.Emails) emails, _ := json.Marshal(u.Emails)
u.Created = now u.Created = now
u.ID, err = d.Insert(`INSERT INTO users (email, name, kind, status, password_hash, title, time_zone, photo, emails, created_at) u.ID, err = d.Insert(`INSERT INTO users (email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, 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.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 return err
} }
@@ -264,7 +265,7 @@ func Delete(d *db.DB, id int64) error {
defer tx.Rollback() defer tx.Rollback()
// Not left to ON DELETE CASCADE: SQLite enforces it only with // Not left to ON DELETE CASCADE: SQLite enforces it only with
// foreign_keys on, and an imported database may not have had them. // 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 { if _, err := tx.Exec(q, id); err != nil {
return err return err
} }
+2
View File
@@ -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", "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", "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", "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 { func actionLabel(a string) string {
+420
View File
@@ -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
}
+171
View File
@@ -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 ""
}
+7
View File
@@ -19,6 +19,13 @@ func newServerEdition(t *testing.T) (*Server, http.Handler) {
t.Helper() t.Helper()
s, h := newTestServer(t, nil) s, h := newTestServer(t, nil)
s.Config = &config.Config{Edition: config.Server} 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{} s.Mail = &appmail.Outbox{}
files, err := storage.Open(config.Storage{Dir: t.TempDir()}) files, err := storage.Open(config.Storage{Dir: t.TempDir()})
if err != nil { if err != nil {
+6
View File
@@ -344,6 +344,10 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /settings/about", s.aboutPage) mux.HandleFunc("GET /settings/about", s.aboutPage)
mux.HandleFunc("GET /settings/connections", s.connectionsPage) mux.HandleFunc("GET /settings/connections", s.connectionsPage)
mux.HandleFunc("GET /settings/activity", s.activityPage) 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("GET /settings/posting", s.postingPage)
mux.HandleFunc("POST /settings/posting", s.postingSave) mux.HandleFunc("POST /settings/posting", s.postingSave)
mux.HandleFunc("POST /settings/posting/{id}/remove", s.postingRemove) mux.HandleFunc("POST /settings/posting/{id}/remove", s.postingRemove)
@@ -698,6 +702,8 @@ var flashes = map[string]string{
"signed-out-user": "Signed out everywhere.", "signed-out-user": "Signed out everywhere.",
"removed": "Removed.", "removed": "Removed.",
"joined": "Welcome to Supermarket.", "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.", "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.", "own-account-connected": "Connected: you can post as it, and an admin can let others.",
"deleted": "Deleted.", "deleted": "Deleted.",
+4 -1
View File
@@ -54,9 +54,12 @@ func newTestServer(t *testing.T, c *core.Core) (*Server, http.Handler) {
s := &Server{ s := &Server{
DB: d, Secrets: sec, Core: c, DataDir: dir, DB: d, Secrets: sec, Core: c, DataDir: dir,
PublicURL: "http://localhost:8470", Version: "test", MCPToken: testToken, PublicURL: "http://localhost:8470", Version: "test", MCPToken: testToken,
MCP: mcpserver.Handler(d, testToken, "test"),
Log: slog.New(slog.NewTextHandler(io.Discard, nil)), 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() h, err := s.Handler()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
+17
View File
@@ -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 &lt;key&gt;</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}}
+49
View File
@@ -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}}
+33
View File
@@ -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 &lt;key&gt;</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}}
+17
View File
@@ -146,6 +146,7 @@
<a href="/settings/profile" {{if eq .Nav "settings/profile"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Profile</a> <a href="/settings/profile" {{if eq .Nav "settings/profile"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Profile</a>
<div class="nav-label">Connections</div> <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/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/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/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 &amp; Hermes</a> <a href="/settings/core" {{if eq .Nav "settings/core"}}aria-current="page"{{end}}>{{template "icon" "core"}}Core &amp; Hermes</a>
@@ -278,6 +279,22 @@
</section> </section>
{{end}} {{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). */}} {{/* 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}} {{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}}
+3
View File
@@ -116,6 +116,9 @@ func (s *Server) memberRows() ([]memberRow, error) {
now := time.Now() now := time.Now()
out := make([]memberRow, 0, len(list)) out := make([]memberRow, 0, len(list))
for _, m := range list { for _, m := range list {
if m.Kind == users.Agent {
continue // under Settings → Agents
}
row := memberRow{TeamUser: m, Access: accessText(m.Membership)} row := memberRow{TeamUser: m, Access: accessText(m.Membership)}
if m.Status == users.Invited { if m.Status == users.Invited {
if row.InviteEnd, err = users.LinkExpiry(s.DB, users.InviteLink, m.ID, now); err != nil { if row.InviteEnd, err = users.LinkExpiry(s.DB, users.InviteLink, m.ID, now); err != nil {