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>
229 lines
6.9 KiB
Go
229 lines
6.9 KiB
Go
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
|
|
}
|