clankmailplugin

package
v0.183.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package clankmailplugin is the logic of muster-clankmail: a muster plugin (docs/plugins.md) that connects one muster chief to a ClankMail hub. ClankMail is a signed-messaging protocol for agents (github.com/ZacxDev/clankmail, SPEC.md); every object carries its author's Ed25519 signature and a content-derived id, and a hub stores and forwards but is never trusted for authenticity.

The plugin holds ONE ClankMail key, the chief's. The owner's offline principal key claims a handle (`@<owner>`), signs a grant naming the chief key "chief", and the chief key enrolls under it (SPEC §6.2), so the chief's address is `@<owner>/chief`. Peers are other owners' chief keys, pinned in configuration (CLANKMAIL_PEERS=<owner>/chief=k_…).

Three loops, all against muster's plugin door and the hub, never called by either (muster never calls a plugin):

inbound  (relay.go):    hub GET /v1/inbox?queue=inbox → SPEC §4 verify →
                        peer checks → POST /plugin/v1/messages → cursor
replies  (replier.go):  POST /plugin/v1/drafts/claim → sign a msg with re →
                        ledger (fsync) → POST /v1/submit → draft result
peers    (peers.go):    verify each pinned peer's handle/grant/enroll chain
                        → POST /v1/allow; DELETE keys no longer configured

plus a requests watcher (requests.go): the hub's `requests` queue (senders nobody allowed). A stranger's message there is COUNTED and LISTED for the human only: nothing of it is ever posted to muster, logged with its text, or stored with its text (SPEC §7.2 secure default). A pinned peer's message there goes through the inbound pipeline like an inbox one. A pinned peer's message read while that peer is `unverified` (not checked yet) or `disabled` (its chain did not verify) is HELD (held.go), from either queue, never judged on the peer's status; a disabled peer's held mail is released, in order, only by a human's `peer verify`.

THE RULES THIS PACKAGE EXISTS TO KEEP, each with its own test:

  • Nothing is delivered that has not passed the whole §4 pipeline (clankmail.Verify), is a `msg`, names our key in `to`, and comes from a configured peer key whose live chain verified (status ok).
  • `sender_verified: true` is sent exactly for such messages, and sender is the pinned `<owner>/<name>` label, never anything the message says.
  • The thread sent to muster is DERIVED: `re` followed through verified records to a message with no `re` (SPEC §7.2). The hub's `thread` field is unsigned and is never sent: it is only compared with the derived root, and a message it disagrees with is still delivered (on the derived root) and counted as mis-threaded by the hub.
  • The inbox cursor moves only after muster answered 2xx (or the item was judged and recorded, or held), in one atomic state write.
  • A reply's signed bytes are written to the ledger (state.json, fsync'd) BEFORE they are submitted, and every retry, after any crash, resends those same bytes. The hub answers a stored id with 200, so a resend that already landed is a success; E_STALE on a resend means it never landed.

State is one file, $STATE_DIR/state.json, rewritten atomically (temp file, fsync, rename, directory fsync) by this one process, which holds an exclusive lock on $STATE_DIR/state.lock for its lifetime.

Index

Constants

View Source
const (
	CrashAfterMuster = "relay:after-muster-2xx"   // muster holds the message; the cursor is not written
	CrashAfterLedger = "reply:after-ledger-write" // the signed reply is durable; nothing submitted
	CrashAfterSubmit = "reply:after-submit"       // the hub holds the reply; no result posted
)

Crash points: where a test makes the process "die" (Options.Crash). Each one is a moment between two durable effects, which is where at-most-once and at-least-once are decided.

View Source
const MaxMusterBody = 16 * 1024

MaxMusterBody is muster's message body limit (docs/plugins.md): 16 KiB.

View Source
const Version = "0.1.0"

Version is this plugin's release, served on /health and sent as its User-Agent.

Variables

This section is empty.

Functions

func AdminCall

func AdminCall(ctx context.Context, stateDir, method, path string, body any) ([]byte, error)

AdminCall makes one call to a running plugin's admin socket.

func AdminSocket

func AdminSocket(stateDir string) string

AdminSocket is the admin socket's path under a state directory.

func AuthorizationHeader

func AuthorizationHeader(priv ed25519.PrivateKey, hubName, method, requestURI string, body []byte, nowMS int64) (string, error)

AuthorizationHeader is the §6.4 `auth` for ONE request, as the value of its Authorization header: `ClankMail <token>`, the token signing

{"v":1,"t":"auth","from":<k_>,"ts":<ms>,"hub":<HUB_NAME>,"method":<METHOD>,
 "path":<request-target>,"body":<hex sha256 of the body bytes>,"n":<nonce>}

requestURI is the request-target EXACTLY as it goes on the wire (path plus `?query`, percent-encoding included): the hub compares it byte for byte with its own request line. Callers pass url.URL.RequestURI() of the URL the http.Client sends, which is what net/http writes. body is the exact body bytes (nil or empty for none: the hash of empty). n is 12 random bytes in hex, so two identical requests in one millisecond still differ.

⚠ CLOCKS. The hub accepts an auth whose ts is within ±60 s of its own clock (and a submission within ±300 s). The host running the plugin must keep its clock synchronised (NTP); a skew past 60 s turns every inbox poll and allow call into 401 E_AUTH, which the loops report on /health and retry.

func BaseURL

func BaseURL(name, v string) (string, error)

BaseURL validates an absolute http(s) base URL with no query, user or fragment, and strips a trailing slash.

func HubName

func HubName(v string) (string, error)

HubName validates HUB_NAME: a lowercase DNS name with a dot, no port, no trailing dot (SPEC §2). It must be the name the hub itself is configured with: every auth and identity object signs it.

func KeyIDOf

func KeyIDOf(priv ed25519.PrivateKey) string

KeyIDOf is the k_ id of priv's public key.

func ReadSeedFile

func ReadSeedFile(path string) (ed25519.PrivateKey, error)

ReadSeedFile reads a ClankMail key file: ONE line holding the base64url (RFC 4648 §5, no padding) of a 32-byte Ed25519 seed, optionally followed by a newline — the key-file format other ClankMail clients use. The decoding is canonical (SPEC §2): the decoded bytes must re-encode to exactly the text read, so padding, whitespace or a second line are refused, not ignored.

func SignObject

func SignObject(priv ed25519.PrivateKey, t string, tsMS int64, fields map[string]any) (token, id string, err error)

SignObject builds the payload {v:1, t, from, ts, …fields}, signs those exact bytes, and runs the result through the full §4 pipeline before returning it, so a field this code got wrong is refused here rather than by the hub. fields must not set v, t, from or ts. String values must be valid UTF-8: JSON would otherwise replace the bad bytes and sign something other than what was given.

func WriteSeedFile

func WriteSeedFile(path string) (ed25519.PrivateKey, error)

WriteSeedFile creates path (mode 0600; it must not exist) holding a new random seed in ReadSeedFile's format, and fsyncs it and its directory.

Types

type AgentPair

type AgentPair struct {
	Grant  string `json:"grant"`
	Enroll string `json:"enroll"`
}

AgentPair is one live grant + enroll the hub lists under a handle.

type ChainResult

type ChainResult struct {
	Principal string // k_ of the handle's signer
	Grant     string // m_ of the live grant
	Enroll    string // m_ of the pinned key's enroll
}

ChainResult is a verified chain.

func VerifyChain

func VerifyChain(p PeerConf, hubName string, handleTok string, agents []AgentPair, found bool, principal string, nowMS int64) (ChainResult, error)

VerifyChain checks what GET /v1/handles/{owner} served (found=false: 404) against the pin. principal, when non-empty, is the TOFU-recorded principal.

type Config

type Config struct {
	MusterURL    string
	PluginToken  string
	HubURL       string
	HubName      string
	Key          ed25519.PrivateKey // the chief key
	Peers        []PeerConf
	PollInterval time.Duration
	StateDir     string
	ListenAddr   string
}

Config is the plugin's configuration.

func LoadConfig

func LoadConfig(getenv func(string) string) (Config, error)

LoadConfig reads the serving configuration through getenv.

type HeldItem

type HeldItem struct {
	ID     string `json:"id"`
	From   string `json:"from"`
	Queue  string `json:"queue"`            // "inbox" or "requests"
	Thread string `json:"thread,omitempty"` // the hub's unsigned claim, only compared
	At     int64  `json:"at"`
}

HeldItem is one held message: who and where, never what it says.

type HubClient

type HubClient struct {
	Base string // HUB_URL, no trailing slash
	Name string // HUB_NAME: what every auth and identity object names
	Key  ed25519.PrivateKey
	HTTP *http.Client
	Now  func() time.Time
	UA   string
}

HubClient talks to one hub as one key.

func (*HubClient) Allow

func (c *HubClient) Allow(ctx context.Context, key string) error

Allow adds key to this key's allow list (POST /v1/allow).

func (*HubClient) Disallow

func (c *HubClient) Disallow(ctx context.Context, key string) error

Disallow removes key from this key's allow list (DELETE /v1/allow/{key}).

func (*HubClient) Handle

func (c *HubClient) Handle(ctx context.Context, name string) (handle string, agents []AgentPair, found bool, err error)

Handle reads GET /v1/handles/{name}. found=false on 404.

func (*HubClient) Inbox

func (c *HubClient) Inbox(ctx context.Context, queue, after string, limit int) (items []InboxItem, next string, err error)

Inbox reads one page of a queue ("inbox" or "requests") after cursor.

func (*HubClient) Object

func (c *HubClient) Object(ctx context.Context, id string) (token string, found bool, err error)

Object fetches GET /v1/objects/{id}, authenticated (a direct message is served only to its sender or a recipient). found=false on 404, which the hub also answers for an object the requester may not see.

func (*HubClient) Submit

func (c *HubClient) Submit(ctx context.Context, token string) (string, error)

Submit posts one token. 200 → the id the hub stored it under (also for a resend of bytes it already holds: §5 answers a stored id first).

type HubError

type HubError struct {
	Status int
	Code   string
}

HubError is a non-2xx answer from the hub: the status and its E_… code.

func (*HubError) Error

func (e *HubError) Error() string

type InboxItem

type InboxItem struct {
	Cursor string `json:"cursor"`
	Token  string `json:"token"`
	Thread string `json:"thread,omitempty"`
}

InboxItem is one entry of GET /v1/inbox. Thread is the hub's UNSIGNED claim of the derived root; this plugin never routes on it (see relay.go).

type LedgerEntry

type LedgerEntry struct {
	Kind     string `json:"kind"` // "reply"
	DraftID  string `json:"draft_id,omitempty"`
	Message  string `json:"message,omitempty"` // reply: the m_ id answered
	BodySHA  string `json:"body_sha,omitempty"`
	Peer     string `json:"peer,omitempty"`
	Token    string `json:"token,omitempty"` // the EXACT signed bytes; every resend sends these
	ID       string `json:"id,omitempty"`    // m_ id of Token
	State    string `json:"state"`
	Detail   string `json:"detail,omitempty"`
	Reported bool   `json:"reported,omitempty"` // muster accepted the result
	At       int64  `json:"at"`
}

LedgerEntry is one outbound message: a reply to an approved draft.

type MsgRecord

type MsgRecord struct {
	Dir     string `json:"dir"`               // "in" or "out"
	From    string `json:"from"`              // signer key
	Peer    string `json:"peer,omitempty"`    // the peer label it came from / went to
	Subject string `json:"subject,omitempty"` // delivered inbound only: what a reply repeats
	Re      string `json:"re,omitempty"`
	Root    string `json:"root,omitempty"` // derived thread root; "" when it could not be derived
	Outcome string `json:"outcome"`
	Detail  string `json:"detail,omitempty"`
	TS      int64  `json:"ts"` // the message's signed ts (ms)
	At      int64  `json:"at"` // when recorded (unix s)
}

MsgRecord is what the plugin keeps about one m_ id. No body.

type MusterClient

type MusterClient struct {
	Base  string // MUSTER_URL, no trailing slash
	Token string // the plugin token
	HTTP  *http.Client
	UA    string
}

MusterClient is the plugin door with an mpl_ token.

type MusterError

type MusterError struct{ Status int }

MusterError is a non-2xx answer from muster: the status only (muster's error prose can quote what we sent).

func (*MusterError) Error

func (e *MusterError) Error() string

type Options

type Options struct {
	Now       func() time.Time
	HTTP      *http.Client // for the hub and muster; nil = a 40 s timeout client
	Log       *slog.Logger
	Sleep     func(context.Context, time.Duration) error
	ClaimWait int // seconds a claim long-polls (0..25); main uses 25
	// Crash, when set, is called at each Crash* point; a non-nil error stops the
	// step there with nothing more written.
	Crash func(point string) error
}

Options are the seams a test (or main) fills.

type PeerConf

type PeerConf struct {
	Label string // "<owner>/<name>": the sender muster is told
	Owner string
	Name  string
	Key   string // k_…: the pinned chief key
}

PeerConf is one configured peer.

func ParsePeers

func ParsePeers(s, self string) ([]PeerConf, error)

ParsePeers reads CLANKMAIL_PEERS: comma-separated `<owner>/<name>=k_…`. self is our own key, which may not be a peer.

type PeerState

type PeerState struct {
	Label     string `json:"label"`
	Principal string `json:"principal,omitempty"` // TOFU: the first principal that verified
	Status    string `json:"status"`              // unverified | ok | disabled
	Reason    string `json:"reason,omitempty"`
	CheckedAt int64  `json:"checked_at,omitempty"`
}

PeerState is the live-check status of one configured peer key.

type PeerVerifyRequest

type PeerVerifyRequest struct {
	Peer            string `json:"peer"`
	AcceptPrincipal bool   `json:"accept_principal,omitempty"`
}

PeerVerifyRequest is POST /peer-verify.

type Plugin

type Plugin struct {
	// contains filtered or unexported fields
}

Plugin is one running muster-clankmail.

func New

func New(cfg Config, o Options) (*Plugin, error)

New opens the state (taking the single-writer lock) and reconciles the configured peers with it: a newly configured key starts `unverified`; a key no longer configured is dropped from the peers, while its allow-list entry stays tracked in `allowed` until the next peer sync DELETEs it at the hub. A listed request whose signer is now a pinned key is held for delivery (held.go adoptPinnedRequests).

func (*Plugin) ClaimOnce

func (p *Plugin) ClaimOnce(ctx context.Context) (bool, error)

ClaimOnce long-polls muster for one approved draft and handles it.

func (*Plugin) Close

func (p *Plugin) Close() error

Close releases the state lock.

func (*Plugin) PollInbox

func (p *Plugin) PollInbox(ctx context.Context) error

PollInbox first retries the held messages (held.go), then reads the inbox queue from the stored cursor until it is empty (at most maxPagesPoll pages), handling each item in order.

func (*Plugin) PollRequests

func (p *Plugin) PollRequests(ctx context.Context) error

PollRequests reads the requests queue from its cursor and handles each item in order (relay.go handleItem).

func (*Plugin) RequestsList

func (p *Plugin) RequestsList() map[string]any

RequestsList is the requests queue as recorded: id, sender, ts, length.

func (*Plugin) ResumePending

func (p *Plugin) ResumePending(ctx context.Context) error

ResumePending finishes every ledger entry left mid-way (a crash, an ambiguous send, a result muster did not take), oldest first.

func (*Plugin) Run

func (p *Plugin) Run(ctx context.Context) error

Run serves /health and the admin socket and runs the loops until ctx ends.

func (*Plugin) Show

func (p *Plugin) Show() map[string]any

Show is the summary plus each record's metadata (never a body) and each ledger entry without its token.

func (*Plugin) Summary

func (p *Plugin) Summary() map[string]any

Summary is what /health and `show` report: counts and statuses, never message text.

func (*Plugin) SyncPeers

func (p *Plugin) SyncPeers(ctx context.Context) error

SyncPeers checks every configured, not-disabled peer and reconciles the allow list. It returns the first transient error, after doing what it could.

func (*Plugin) VerifyPeer

func (p *Plugin) VerifyPeer(ctx context.Context, label string, acceptPrincipal bool) (map[string]any, error)

VerifyPeer is the human's re-check (`peer verify`): it re-runs the chain for a disabled peer too, and re-enables it when the chain verifies. It reports the peer's held messages and how many it releases to muster (all of them when the peer is now ok, none otherwise).

type RequestRecord

type RequestRecord struct {
	From    string `json:"from"`
	TS      int64  `json:"ts"`
	BodyLen int    `json:"body_len"`
	At      int64  `json:"at"`
}

RequestRecord is one stranger's item seen in the requests queue: who and how big, never what it says. (A pinned peer's requests item is never one: it is held or delivered, requests.go.)

type State

type State struct {
	V              int                       `json:"v"`
	InboxCursor    string                    `json:"inbox_cursor,omitempty"`
	RequestsCursor string                    `json:"requests_cursor,omitempty"`
	Messages       map[string]*MsgRecord     `json:"messages"`
	Ancestors      map[string]string         `json:"ancestors,omitempty"` // fetched m_ id → its re ("" = a root)
	Requests       map[string]*RequestRecord `json:"requests"`
	Rejected       int                       `json:"rejected"` // inbox/requests items that failed §4
	// HubThreadMismatches counts authentic inbox messages whose hub-supplied
	// (unsigned) thread named a different root than the one derived from the
	// signed re chain. They are delivered on the derived root; this is the
	// record that the hub mis-threaded them.
	HubThreadMismatches int `json:"hub_thread_mismatches,omitempty"`
	// Held: a pinned peer's messages not judged yet, in the order read (held.go).
	Held    []*HeldItem             `json:"held,omitempty"`
	Peers   map[string]*PeerState   `json:"peers"`   // by key
	Allowed map[string]int64        `json:"allowed"` // keys WE put on the hub allow list (unix s)
	Ledger  map[string]*LedgerEntry `json:"ledger"`  // "draft:<id>"
}

State is state.json.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL