middleware: onAccount can pass an account over for a request (bm_rabbit)

bm_rabbit (Discord) is building MOD_Probe, a middleware that tells
Codex accounts apart and needs to keep some requests off some of them.
onProvider could only change a try's body, never which account took
it.

A JS middleware may now export onAccount(account, ctx). The gateway
calls it before each try on a subscription account, at the top of the
candidate loop (accountSkipped). That is before anything of the try is
done: no Codex reset is spent, no body is built, nothing is sent.

account is {ref, provider, name, kind, model}. ref is 32 hex
characters: an HMAC-SHA256 of the middleware's name and the account's
agent, lower-cased user and plan. Its key is random, made once per
install in account-ref.key in magpie's config folder. It is written to
a temp file and linked into place, so it never writes over a key that
is there. The ref is the same on every request and after a restart,
and different for each middleware. The email can't be found from it
without the key. A key file that can't be read is never overwritten:
that process uses a key of its own and logs it.

{skip: true} passes the account over for this request. The next
candidate is asked, as past an account that can't be used. The call's
fallback gets a "passed over by middleware <name>" line, and the
account is not rested or held against. When the last candidate is
passed over, nothing is sent (no fail-open). The agent gets the
failure of a candidate asked before it, or, if there was none, the
usual 404 "none of <model>'s models is ready".

Anything else uses the account: undefined, {}, null, a throw, or going
past the 250ms limit. The last three count as failures. A key's try
asks no onAccount. ctx.account holds the same object for the hooks
after it on that try, and is taken away on a key's try. ownAsk clears
the Accounts runs with the Tried ones.

Note: the plan is part of the ref, so a plan change gives the account
a new ref.

Docs: docs/subsystems/gateway-middleware.md (runtime path step 4,
limits, fail open, verification), docs/reference.md,
docs/integrating.md, and site/public/docs/{,zh/,ja/}plugins.html (an
onAccount row in the hooks table). The Bun plugin host is unchanged:
middleware runs in moejs in the gateway, not in host.js.

Tests:
- internal/middleware TestOnAccount: the ref is stable across runs and
  a key reload; it differs between two middlewares, users, plans and
  kinds, and is the same when only case differs; no email or plan
  reaches the hook. {skip:true} names the middleware; undefined,
  {skip:false}, throw and null use the account (2 failures counted);
  ctx.account reaches onProvider; a key's try clears it.
- internal/middleware TestAccountRefKey: the key file is made at 0600,
  read back, never written over when unreadable, and no temp file is
  left behind.
- internal/gateway TestOnAccountSkipMovesToNextAccount: two Codex
  accounts, Ordered. The first is passed over, only acct-2 is sent
  the request, acct-1 doesn't rest, and the same holds on a second
  request.
- internal/gateway TestOnAccountSkipEveryAccount: every account passed
  over gives a 404 "…models is ready", nothing is sent, nobody rests.

Broken by hand, each on mote, each red, then restored:
- skip ignored in accountSkipped: both gateway tests red (acct-1
  reached; 200 instead of 404)
- fail open on the last candidate: SkipEveryAccount red (200)
- the skipped account rested: both gateway tests red (rests)
- a random key per ref: TestOnAccount (refs changed between requests)
  and TestAccountRefKey red
- the middleware name left out of the hash: TestOnAccount red (two
  middlewares told one ref)
- an unreadable key overwritten: TestAccountRefKey red

Run at this commit's tree (rebased on origin/main 6a900e0d0):
- gofmt -l: clean
- mote-run go vet -tags nogui ./internal/... ./plugins/...,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok
- mote-run go test -tags nogui -count=1 -timeout 45m ./... (log kept
  whole): every package ok except three. internal/middleware's
  TestPointsLoadErrors was mine: its load-error text now names
  onAccount. The test is fixed in this commit, and the package and
  plugins/middleware were rerun ok at this tree. The other two are red
  on main and already filed: internal/cli TestLibraryMCPHub (#4140,
  TempDir cleanup) and internal/gui TestSettingsSaveKeepsWhatItDoesNotSend
  (#4514, SearchAll from b09349d17)
- Rebased again on origin/main 20482d71f (it changed
  internal/gateway/affinity.go): mote-run go test -tags nogui -count=1
  ./internal/middleware ./internal/gateway ./plugins/middleware: all ok
  (gateway 846s)

Not tried: a real MOD_Probe against real Codex accounts. Not changed:
probe keys can still reach deactivated accounts (out of scope).
This commit is contained in:
yetone
2026-11-01 02:19:26 +08:00
parent 80af3b86a4
commit e40675cc19
14 changed files with 550 additions and 26 deletions
+1 -1
View File
@@ -141,7 +141,7 @@ kinds ([plugin guide](https://usemagpie.ai/docs/plugins)):
source of models, such as a subscription magpie doesn't sign in to
itself. They sign in, list models and make requests.
- **Gateway middleware**: rewrites requests and replies as they pass
(`onRequest`, `onProvider`, `onEvent`, `onResponse`).
(`onRequest`, `onAccount`, `onProvider`, `onEvent`, `onResponse`).
A plugin can't add a row to the Agents page or write another app's
config, so it is not how an app registers itself.
+4 -1
View File
@@ -1123,7 +1123,10 @@ A plugin can also be gateway middleware: `onRequest(body, ctx)` sees each
request an agent sends before it is routed, `onProvider(body, ctx)` the
body each provider it is tried on is sent (`ctx.provider` has its `id`,
`name`, `account` and `model`; each try starts from what `onRequest`
left), `onEvent(event, ctx)` each
left), `onAccount(account, ctx)` each subscription account a try is
about to go to (`account.ref` is an anonymous id, stable per install and
per middleware; `{skip: true}` passes the account over for that request),
`onEvent(event, ctx)` each
event of a streamed reply and `onResponse(body, ctx)` a whole one, all in
the agent's own API. A hook returns the changed object, or nothing to
leave it; `onEvent` returns `null` to drop an event, and
+7 -5
View File
@@ -24,8 +24,9 @@ plugins.json is the source of truth for which middleware is installed and on, in
1. `serveAgent` establishes the [gateway session identity and optional recording](gateway-sessions.md), runs any [asynchronous request hooks](gateway-request-hooks.md) through Bun, then calls `Begin` on each registered `gwmw.Agent` (the JS chain's is `middleware.Begin`) with the request's protocol, model, stream flag, path and agent. With no middleware it calls `serve` directly.
2. `Run.Request` passes the agent's body, in its own API, to each `onRequest` in turn. An object returned is the body the next middleware and the gateway get; `undefined` keeps the bytes as they were. `ctx.reject(status, message)` stops the chain, and the agent gets that error in its API's shape (`writeError`).
3. `Run.Tried` runs each `onProvider` on the body each time `serve` tries it on a provider, just before that try is sent (`triedOn` in the candidate loop of `gateway.go`; `serveAgent` puts the runs that are `gwmw.Tried` on the request's context). `ctx.provider` says which: `id`, `name`, `account` (the subscription's kind, as `accountAgent` gives it: `claude`, `antigravity`, …; absent for a key) and `model`, the model's id there. Every try starts again from the body `onRequest` left, so what one provider is sent changes no other try's: this is how a plugin acts on one vendor only, for an agent such as Claude Desktop whose model names say nothing of where they go. `null` and `ctx.reject` turn nothing away here; the request has been routed.
4. `Run.Wrap` wraps the response writer when some middleware has `onEvent` or `onResponse`. An SSE reply is split into events. Each event whose data is a JSON object goes to every `onEvent` that wants its name (`export const events`): an object replaces it, `null` drops it, and `undefined` writes the original bytes. `data: [DONE]` and other non-object data pass by. A whole JSON reply is buffered for `onResponse`, with `ctx.status` set. A reply with a `Content-Encoding` passes as-is.
5. `Run.End` returns the runtimes to their pools.
4. `Run.Account` runs each `onAccount(account, ctx)` before each try on a subscription account, at the top of the candidate loop in `gateway.go` (`accountSkipped`; `serveAgent` puts the runs that are `gwmw.Accounts` on the request's context beside the `gwmw.Tried` ones), before anything of the try is done: no Codex reset is spent (`resetBeforeCredits`), no body is built and nothing is sent. `account` is `{ref, provider, name, kind, model}`; `ref` is an HMAC-SHA256 (first 16 bytes, hex) of the middleware's name (`plugin.Name`: a package's name without its version, a file's path) and the account's agent, user and plan, lower-cased, keyed by a random key made once per install in `account-ref.key` in magpie's config folder (`accountRef`, `refKey` in [`account.go`](../../internal/middleware/account.go)). So it is the same on every request and after a restart, different for each middleware, and the email can't be found from it without that key, even by someone who knows the email to try. The plan is part of who the account is, so a plan change gives a new ref. A key file that can't be read is never written over: that process makes refs with a key of its own and logs it. `{skip: true}` passes the account over for this request: the next candidate is asked, as past an account that can't be used, with a `passed over by middleware <name>` line in the call's fallback, and the account isn't rested, held or counted against. When the last candidate is passed over, nothing is sent (no fail-open): the agent gets the failure of a candidate asked before it, or, with none, the 404 "none of <model>'s models is ready" a request with no member ready gets. The first `{skip: true}` wins, and the middleware after it isn't asked. A try on a key asks no `onAccount`. `ctx.account` is set to the same object for that middleware's later hooks of the try (`onProvider`, `onEvent`, `onResponse`), and taken away on a key's try.
5. `Run.Wrap` wraps the response writer when some middleware has `onEvent` or `onResponse`. An SSE reply is split into events. Each event whose data is a JSON object goes to every `onEvent` that wants its name (`export const events`): an object replaces it, `null` drops it, and `undefined` writes the original bytes. `data: [DONE]` and other non-object data pass by. A whole JSON reply is buffered for `onResponse`, with `ctx.status` set. A reply with a `Content-Encoding` passes as-is.
6. `Run.End` returns the runtimes to their pools.
Each middleware gets one runtime for the whole request, so its hooks share `ctx.state`. Runtimes come from a per-middleware `sync.Pool` and modules are compiled once per load. Compiling a plugin's module (imports kept inside the plugin) is [`internal/jsmod`](../../internal/jsmod/jsmod.go), which agent plugins ([Agent wiring](agent-wiring.md)) share.
@@ -42,8 +43,8 @@ Only requests agents send go through `serveAgent`. magpie's own requests (thread
## Constraints and failure behavior
- Limits: 250ms for `onRequest`, each `onProvider` and `onResponse`, 50ms for each `onEvent`, 1s to load. A hook past its limit is interrupted.
- Fail open: a hook that throws, returns something that is neither an object, `null` nor `undefined` (an `onProvider` returning `null` too), or is interrupted leaves the request or event as it was. The failure is counted and kept as the last error, and logged at most 60 lines a minute.
- Limits: 250ms for `onRequest`, each `onAccount`, each `onProvider` and `onResponse`, 50ms for each `onEvent`, 1s to load. A hook past its limit is interrupted.
- Fail open: a hook that throws, returns something that is neither an object, `null` nor `undefined` (an `onProvider` returning `null` too), or is interrupted leaves the request or event as it was. An `onAccount` that fails, or returns `null`, uses the account; only `{skip: true}` passes it over. The failure is counted and kept as the last error, and logged at most 60 lines a minute.
- A middleware imports only relative files; packages must be bundled into it.
- Reload: a change to plugins.json or to a middleware file is picked up by the next request at most a second later (`stamp`).
- A strategy has 20ms, waiting for its runtime included; one that throws, runs out of time or returns what isn't an order of the seats leaves them in their listed order (fail open), counted and logged as a failure. `onUsage` has 250ms and fails open the same way. A request never waits for `onUsage`.
@@ -59,7 +60,8 @@ go test -tags nogui -run 'TestParseRouting|TestPluginListSaysMiddleware' ./inter
go test -tags nogui -run TestPluginRoutingKept ./internal/provider
go test -tags nogui -run TestOnServesStrategies ./plugins/middleware
node --test internal/gui/tests/routing-js.test.cjs
go test -tags nogui -run 'TestMiddlewareThroughGateway|TestMiddlewareOnProviderPerTry|WithoutTheAgentsMiddleware' ./internal/gateway
go test -tags nogui -run 'TestMiddlewareThroughGateway|TestMiddlewareOnProviderPerTry|WithoutTheAgentsMiddleware|TestOnAccountSkip' ./internal/gateway
go test -tags nogui -run 'TestOnAccount|TestAccountRefKey' ./internal/middleware
go test -tags nogui -run TestPluginListSaysMiddleware .
go test -tags nogui -run "TestSetOptionsShortName|TestBuiltinMarket" ./internal/plugin
go test -tags nogui -bench Event ./internal/middleware
+75
View File
@@ -0,0 +1,75 @@
package gateway
import (
"net/http"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A middleware's onAccount passing the first of two Codex accounts over
// (bm_rabbit's MOD_Probe): the request goes to the second, the first is
// never sent it, and nothing is held against the first, which the next
// request is asked of again.
func TestOnAccountSkipMovesToNextAccount(t *testing.T) {
codexSignedIn(t, "spare@example.com")
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
t.Fatal(err)
}
var tried []string
chatgptRefusing(t, &tried, func(w http.ResponseWriter) { t.Error("acct-1 refused stand-in reached") })
onMiddleware(t, `
export function onAccount(account, ctx) {
if (ctx.state.passed) return;
ctx.state.passed = account.ref;
return {skip: true};
}`)
s := New()
code, body := codexAskOn(s, `{"model":"gpt-5.5","stream":true,"input":"ping"}`)
if code != 200 || !strings.Contains(body, "pong") {
t.Fatalf("status %d: %s", code, body)
}
if strings.Join(tried, ",") != "acct-2" {
t.Fatalf("tried %v, not the second account alone", tried)
}
if r, ok := restOf("codex@me@example.com"); ok {
t.Fatalf("the account passed over rests: %+v", r)
}
restingUntil.Lock()
n := len(restingUntil.m)
restingUntil.Unlock()
if n != 0 {
t.Fatalf("%d accounts rest", n)
}
// the next request passes the first over again, by its ref: still
// nothing against it, and the turn goes on to the second as before
tried = nil
if code, body := codexAskOn(s, `{"model":"gpt-5.5","stream":true,"input":"ping"}`); code != 200 || strings.Join(tried, ",") != "acct-2" {
t.Fatalf("second request: %d %s tried %v", code, body, tried)
}
}
// Every account passed over: the agent is told none is ready, as with no
// account to ask, and none is sent the request (no fail-open) or rests.
func TestOnAccountSkipEveryAccount(t *testing.T) {
codexSignedIn(t, "spare@example.com")
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
t.Fatal(err)
}
var tried []string
chatgptRefusing(t, &tried, func(w http.ResponseWriter) {})
onMiddleware(t, `export function onAccount() { return {skip: true}; }`)
code, body := codexAskOn(New(), `{"model":"gpt-5.5","stream":true,"input":"ping"}`)
if code != 404 || !strings.Contains(body, "gpt-5.5's models is ready") {
t.Fatalf("status %d: %s", code, body)
}
if len(tried) != 0 {
t.Fatalf("sent to %v though every account was passed over", tried)
}
for _, id := range []string{"codex@me@example.com", "codex@spare@example.com"} {
if r, ok := restOf(id); ok {
t.Fatalf("%s rests: %+v", id, r)
}
}
}
+23
View File
@@ -2774,6 +2774,29 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
cands = cands[:i+1]
}
}
if by := accountSkipped(r.Context(), c.p, c.model); by != "" {
// a middleware's onAccount passed the account over for this
// request: the next is asked, as past one that can't be used,
// before anything of this try is done (no reset spent, no rest,
// nothing held against it)
skipped = append(skipped, c.label()+": passed over by middleware "+by)
if i < len(cands)-1 {
continue
}
// every one left was passed over: never sent to one all the
// same (no fail-open). The agent is told the failure of one
// asked before, else what it is told with none ready
msg := ""
switch {
case other != nil:
call.Status, call.Error = other.Status, other.Error
case call.Status < 400:
call.Status, call.Error = 404, "every account passed over by a middleware"
msg = fmt.Sprintf("none of %s's models is ready", call.Model)
}
failTo(w, kept, from, call.Status, cmp.Or(msg, call.Error))
break
}
if !autoReset && c.onCredits() {
// going to the account on its credits, its week used up: a
// reset it spends by itself when the week runs out goes
+40 -8
View File
@@ -44,7 +44,7 @@ func (s *Server) serveAgent(w http.ResponseWriter, r *http.Request, from provide
return
}
info := gwmw.Info{Protocol: string(from), Model: modelOf(body), Stream: streamOf(body), Path: r.URL.Path, Agent: agentOf(r)}
var tried []gwmw.Tried
var runs mwRuns
for _, a := range agents {
// the user's middleware runs before a route is begun: a wait
// magpie knows of (unrouted.go)
@@ -56,7 +56,10 @@ func (s *Server) serveAgent(w http.ResponseWriter, r *http.Request, from provide
}
defer run.End()
if t, ok := run.(gwmw.Tried); ok {
tried = append(tried, t)
runs.tried = append(runs.tried, t)
}
if t, ok := run.(gwmw.Accounts); ok {
runs.accounts = append(runs.accounts, t)
}
var turned *gwmw.Reject
body, turned = run.Request(body)
@@ -69,30 +72,59 @@ func (s *Server) serveAgent(w http.ResponseWriter, r *http.Request, from provide
w, done = run.Wrap(w)
defer done()
}
if len(tried) > 0 {
r = r.WithContext(context.WithValue(r.Context(), triedKey{}, tried))
if len(runs.tried) > 0 || len(runs.accounts) > 0 {
r = r.WithContext(context.WithValue(r.Context(), triedKey{}, runs))
}
s.serve(w, r, from, body)
}
type triedKey struct{}
// mwRuns are the middleware of an agent's request that are asked again on
// each try: tried change its body (onProvider), accounts may pass its
// account over (onAccount).
type mwRuns struct {
tried []gwmw.Tried
accounts []gwmw.Accounts
}
// triedOn is body as it goes to model on p, in the agent's API: what each
// middleware of the request that is also gwmw.Tried (the JS chain's
// onProvider) made of it for that provider. Each try starts from the body
// it is given, so a change for one provider never reaches another's.
func triedOn(ctx context.Context, p provider.Provider, model string, body []byte) []byte {
tried, _ := ctx.Value(triedKey{}).([]gwmw.Tried)
if len(tried) == 0 {
runs, _ := ctx.Value(triedKey{}).(mwRuns)
if len(runs.tried) == 0 {
return body
}
to := gwmw.To{ID: p.ID, Name: p.Name, Account: accountAgent(p), Model: model}
for _, t := range tried {
for _, t := range runs.tried {
body = t.Tried(body, to)
}
return body
}
// accountSkipped asks the request's middleware with onAccount whether the
// account p is may be used for this try of model, before anything of the
// try is done: by is the middleware that passed it over, "" when none did.
// A try on a key asks none, and tells them it is no account's.
func accountSkipped(ctx context.Context, p provider.Provider, model string) (by string) {
runs, _ := ctx.Value(triedKey{}).(mwRuns)
if len(runs.accounts) == 0 {
return ""
}
a := gwmw.Account{ID: p.ID, Name: p.Name, Model: model}
if p.Account != nil {
a.Agent, a.User, a.Plan = p.Account.Agent, p.Account.User, p.Account.Plan
}
for _, t := range runs.accounts {
if skip, who := t.Account(a); skip {
return who
}
}
return ""
}
// ownAsk is ctx for a request magpie asks of its own gateway while it
// serves an agent's (a web search, an image's description): the agent's
// middleware isn't run on it, as on magpie's other own requests. Its
@@ -106,7 +138,7 @@ func triedOn(ctx context.Context, p provider.Provider, model string, body []byte
// is it the agent's turn, which a model set for requests masking would
// change takes (maskRouteFor): it is masked as magpie's own asks are.
func ownAsk(ctx context.Context) context.Context {
return context.WithValue(context.WithValue(ctx, triedKey{}, []gwmw.Tried(nil)), agentTurnKey{}, false)
return context.WithValue(context.WithValue(ctx, triedKey{}, mwRuns{}), agentTurnKey{}, false)
}
// middlewareWanted: plugins.json has a JS middleware on, so plugins/middleware
+20 -1
View File
@@ -8,7 +8,8 @@
// middleware (internal/middleware) is the one there, registered by
// plugins/middleware. It fails open: a middleware that fails leaves the
// request as it was. A Run that is also Tried changes the body again
// for each provider the gateway tries the request on.
// for each provider the gateway tries the request on, and one that is
// also Accounts can have an account passed over for the request.
// - Masker: what magpie sends to a vendor, masked as the settings say,
// and what the vendor answers with the values back. The redact plugin
// registers it. It fails closed: when the settings ask for masking and
@@ -73,6 +74,24 @@ type Tried interface {
Tried(body []byte, to To) []byte
}
// Account is the subscription account a request is about to be tried on,
// as the gateway knows it. Agent, User and Plan are who it is
// (provider.Account) and never reach a middleware: a middleware is told a
// ref made from them (internal/middleware's accountRef). A zero Agent is
// a try on a key, no account.
type Account struct {
Agent, User, Plan string
ID, Name, Model string // the provider, and the model asked of it there
}
// Accounts is a Run asked, before each try, whether the account it goes
// to may be used for this request: skip says it may not, and the gateway
// goes on to the next as it does past an account that can't be used,
// resting nothing. by names the middleware that said so.
type Accounts interface {
Account(a Account) (skip bool, by string)
}
// Masker masks what magpie sends to a vendor and puts the values back in
// what comes back. It reads its settings itself; Wanted is the core's
// reading of whether any are asked for.
+179
View File
@@ -0,0 +1,179 @@
package middleware
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"sync"
"github.com/MoeForge/moejs"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/gwmw"
)
// account is what onAccount, and ctx.account after it, are told of the
// account a try goes to: never its email, login or id, only a ref.
type account struct {
Ref string `json:"ref"`
Provider string `json:"provider"` // the provider's id
Name string `json:"name"` // and its name
Kind string `json:"kind"` // the subscription's kind: codex, claude, …
Model string `json:"model"` // the model asked of it, by its id there
}
// Account runs each onAccount before a try goes to a, in turn, with
// a as an account (above) and ctx.account set to it; ctx.account stays for
// the hooks after it, onProvider, onEvent and onResponse, until the next
// try. The first that returns {skip: true} has the account passed over for
// this request: the hooks after it aren't asked, and the gateway goes on
// to the next account (skip, and by naming that middleware). A hook that
// throws, takes too long or returns what isn't an object or undefined
// skips nothing (fail open), counted as a failure. A try on a key (a.Agent
// "") asks no hook, and takes ctx.account away.
func (r *Run) Account(a gwmw.Account) (skip bool, by string) {
if r == nil {
return false, ""
}
defer r.letGo()
for i, m := range r.set.list {
if !m.hasAcct {
continue
}
if a.Agent == "" {
if in := r.insts[i]; in != nil {
realm := in.rt.Realm()
realm.SetV(r.ctxs[i], realm.KeyFromGoString("account"), moejs.Undefined())
}
continue
}
b, _ := json.Marshal(account{Ref: accountRef(m.name, a), Provider: a.ID, Name: a.Name, Kind: a.Agent, Model: a.Model})
in, ctx, err := r.acquire(i)
if err == nil {
var v moejs.Value
if v, err = in.rt.ParseJSON(b); err == nil {
realm := in.rt.Realm()
err = realm.SetV(ctx, realm.KeyFromGoString("account"), v)
}
}
if err != nil {
m.fail("onAccount", err)
continue
}
out, err := r.apply(i, m.onAcct, requestLimit, b, nil)
switch {
case errors.Is(err, errDropped):
m.fail("onAccount", errors.New("returned null; return {skip: true} to pass the account over"))
case err != nil:
m.fail("onAccount", err)
case out != nil:
var said struct {
Skip bool `json:"skip"`
}
if json.Unmarshal(out, &said) == nil && said.Skip {
return true, m.name
}
}
}
return false, ""
}
// accountRef is the account a, as middleware name is told it: a keyed hash
// of who the account is (its kind, user and plan), the same for every
// request and every start of magpie, different for each middleware, and
// one nobody can turn back into the email without this computer's key,
// even knowing the email to try.
func accountRef(name string, a gwmw.Account) string {
mac := hmac.New(sha256.New, refKey())
for _, s := range []string{"magpie account ref v1", name, a.Agent, strings.ToLower(a.User), strings.ToLower(a.Plan)} {
mac.Write([]byte(s))
mac.Write([]byte{0})
}
return hex.EncodeToString(mac.Sum(nil)[:16])
}
var refKeys = struct {
sync.Mutex
m map[string][]byte // by file
}{m: map[string][]byte{}}
// refKey is the key refs are made with: random, made the first time and
// kept in magpie's folder (account-ref.key), so a ref is the same after a
// restart. A key that can't be read is never written over, as every ref a
// middleware kept would change: this process makes do with one of its own
// and says so.
func refKey() []byte {
p := filepath.Join(appdir.Config(), "account-ref.key")
refKeys.Lock()
defer refKeys.Unlock()
if k, ok := refKeys.m[p]; ok {
return k
}
k, err := readRefKey(p)
if errors.Is(err, fs.ErrNotExist) {
k, err = makeRefKey(p)
}
if err != nil {
log.Printf("middleware: account refs are this run's only: %v", err)
k = make([]byte, 32)
rand.Read(k)
}
refKeys.m[p] = k
return k
}
func readRefKey(p string) ([]byte, error) {
b, err := os.ReadFile(p)
if err != nil {
return nil, err
}
k, err := hex.DecodeString(strings.TrimSpace(string(b)))
if err != nil || len(k) != 32 {
return nil, errors.New(p + " isn't a key")
}
return k, nil
}
// makeRefKey writes a new key to p, unless another process has just
// written one, which is then the key: written whole to a file of its own
// first and linked into place, which never writes over one there.
func makeRefKey(p string) ([]byte, error) {
k := make([]byte, 32)
if _, err := rand.Read(k); err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
return nil, err
}
tmp, err := os.CreateTemp(filepath.Dir(p), ".account-ref-*")
if err != nil {
return nil, err
}
defer os.Remove(tmp.Name())
_, err = tmp.WriteString(hex.EncodeToString(k) + "\n")
if err == nil {
err = tmp.Sync()
}
if cerr := tmp.Close(); err == nil {
err = cerr
}
if err != nil {
return nil, err
}
if err := os.Link(tmp.Name(), p); err != nil {
if errors.Is(err, fs.ErrExist) {
// another process made it a moment ago, whole as this one's
return readRefKey(p)
}
return nil, err
}
return k, nil
}
+184
View File
@@ -0,0 +1,184 @@
package middleware
import (
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/gwmw"
)
// forgetRefKeys makes the next ref read its key from the file again, as a
// new start of magpie does.
func forgetRefKeys() {
refKeys.Lock()
clear(refKeys.m)
refKeys.Unlock()
}
// what onProvider was told of the account after onAccount: each
// middleware's ctx.account, "none" when it had none
type told struct {
A any `json:"a"`
B string `json:"b"`
}
func triedAfter(t *testing.T, r *Run, a gwmw.Account) (skip bool, by string, got told) {
t.Helper()
skip, by = r.Account(a)
if !skip {
json.Unmarshal(r.Tried([]byte(`{}`), gwmw.To{ID: a.ID, Model: a.Model}), &got)
}
return
}
// onAccount is told a ref for the account, never its email, the same on
// every request and after magpie starts again, and a different one for
// each middleware; {skip: true} passes the account over, naming the
// middleware, and anything else, a throw and null among them, uses it.
func TestOnAccount(t *testing.T) {
forgetRefKeys()
t.Cleanup(forgetRefKeys)
a := file(t, `
export function onAccount(account, ctx) {
if (account.provider === "throw") throw new Error("bad");
if (account.provider === "null") return null;
if (account.provider === "undef") return;
if (account.provider === "skip") return {skip: true};
if (account.provider === "no") return {skip: false};
return {};
}
export function onProvider(body, ctx) { body.a = ctx.account === undefined ? "none" : ctx.account; return body; }`)
b := file(t, `
export function onAccount(account) {}
export function onProvider(body, ctx) { body.b = ctx.account === undefined ? "none" : ctx.account.ref; return body; }`)
use(t, a, b)
me := gwmw.Account{Agent: "codex", User: "me@example.com", Plan: "plus", ID: "codex", Name: "Codex", Model: "gpt-5.5"}
refs := func() (string, string) {
t.Helper()
r := Begin(info())
if r == nil {
t.Fatal("no run")
}
defer r.End()
skip, _, got := triedAfter(t, r, me)
if skip {
t.Fatal("skipped")
}
raw, _ := json.Marshal(got)
if strings.Contains(strings.ToLower(string(raw)), "example.com") || strings.Contains(string(raw), "plus") {
t.Fatalf("the account's email or plan reached a middleware: %s", raw)
}
ac, _ := got.A.(map[string]any)
if ac["provider"] != "codex" || ac["name"] != "Codex" || ac["kind"] != "codex" || ac["model"] != "gpt-5.5" {
t.Fatalf("ctx.account %s", raw)
}
ref, _ := ac["ref"].(string)
if _, err := hex.DecodeString(ref); err != nil || len(ref) != 32 {
t.Fatalf("ref %q", ref)
}
return ref, got.B
}
refA, refB := refs()
if refA == refB {
t.Fatalf("two middlewares told one ref %s", refA)
}
// another request, and magpie started again: the same refs
if a2, b2 := refs(); a2 != refA || b2 != refB {
t.Fatalf("refs changed between requests: %s %s, then %s %s", refA, refB, a2, b2)
}
forgetRefKeys()
if a2, b2 := refs(); a2 != refA || b2 != refB {
t.Fatalf("refs changed after a restart: %s %s, then %s %s", refA, refB, a2, b2)
}
// the same account written in another case is the same account;
// another user, or the plan changed, is another
if got := accountRef(a.Spec, gwmw.Account{Agent: "codex", User: "ME@Example.com", Plan: "Plus"}); got != refA {
t.Fatalf("case changed the ref: %s, %s", got, refA)
}
for _, o := range []gwmw.Account{
{Agent: "codex", User: "spare@example.com", Plan: "plus"},
{Agent: "codex", User: "me@example.com", Plan: "pro"},
{Agent: "claude", User: "me@example.com", Plan: "plus"},
} {
if accountRef(a.Spec, o) == refA {
t.Fatalf("%+v has me's ref", o)
}
}
r := Begin(info())
defer r.End()
for _, c := range []struct {
id string
skip bool
}{{"skip", true}, {"no", false}, {"undef", false}, {"throw", false}, {"null", false}, {"ok", false}} {
acct := me
acct.ID = c.id
skip, by, got := triedAfter(t, r, acct)
if skip != c.skip {
t.Fatalf("%s: skip %v", c.id, skip)
}
if skip && by != a.Spec {
t.Fatalf("%s: passed over by %q, not %q", c.id, by, a.Spec)
}
if !skip && got.B != refB {
t.Fatalf("%s: the next middleware wasn't told the account: %+v", c.id, got)
}
}
if st := States()[a.Spec]; st.Failures != 2 || !strings.Contains(st.Last, "null") || !strings.Contains(strings.Join(st.Hooks, ","), "onAccount") {
t.Fatalf("state %+v", st)
}
// a try on a key asks no onAccount, and the account before it is gone
// from ctx
if skip, _, got := triedAfter(t, r, gwmw.Account{ID: "skip", Model: "m1"}); skip || got.A != "none" || got.B != "none" {
t.Fatalf("a key's try: skip %v, told %+v", skip, got)
}
var none *Run
if skip, _ := none.Account(me); skip {
t.Fatal("a nil Run skipped")
}
}
// The key refs are made with is kept: made once, read after, and one that
// can't be read is never written over, as every ref a middleware kept
// would change with it.
func TestAccountRefKey(t *testing.T) {
forgetRefKeys()
t.Cleanup(forgetRefKeys)
p := filepath.Join(appdir.Config(), "account-ref.key")
os.Remove(p)
acct := gwmw.Account{Agent: "codex", User: "me@example.com"}
first := accountRef("m", acct)
b, err := os.ReadFile(p)
if err != nil || len(strings.TrimSpace(string(b))) != 64 {
t.Fatalf("key file %q %v", b, err)
}
if fi, _ := os.Stat(p); fi != nil && fi.Mode().Perm()&0o077 != 0 && os.PathSeparator == '/' {
t.Fatalf("key file mode %v", fi.Mode())
}
forgetRefKeys()
if accountRef("m", acct) != first {
t.Fatal("the kept key wasn't read back")
}
// a key of its own makes other refs: the file is what keeps them
forgetRefKeys()
os.Remove(p)
if accountRef("m", acct) == first {
t.Fatal("a new key made the same ref")
}
forgetRefKeys()
os.WriteFile(p, []byte("not a key\n"), 0o600)
accountRef("m", acct)
if b, _ := os.ReadFile(p); string(b) != "not a key\n" {
t.Fatalf("a key that couldn't be read was written over: %q", b)
}
if left, _ := filepath.Glob(filepath.Join(appdir.Config(), ".account-ref-*")); len(left) > 0 {
t.Fatalf("temp files left: %v", left)
}
os.Remove(p)
}
+13 -9
View File
@@ -1,7 +1,8 @@
// Package middleware runs the gateway middleware plugins declare: a
// module with onRequest, onProvider, onEvent and onResponse hooks that the
// gateway calls on every request an agent sends it, each provider it tries
// the request on, every event of the reply's stream and every whole reply.
// module with onRequest, onAccount, onProvider, onEvent and onResponse
// hooks that the gateway calls on every request an agent sends it, each
// account and provider it tries the request on, every event of the reply's
// stream and every whole reply.
//
// It runs in the gateway's own process, in moejs, a JavaScript engine
// written in Go: a hook on one streamed event costs about a microsecond,
@@ -46,10 +47,12 @@ type mw struct {
mod *moejs.Module
onReq moejs.Hook
onProv moejs.Hook
onAcct moejs.Hook
onEv moejs.Hook
onResp moejs.Hook
hasReq bool
hasProv bool
hasAcct bool
hasEv bool
hasResp bool
// events are the stream events onEvent is called for, by name; nil
@@ -75,8 +78,8 @@ type set struct {
stamp string
list []*mw
errs map[string]string // by spec: why it didn't load
// hooked: some module of list has onRequest, onProvider, onEvent or
// onResponse
// hooked: some module of list has onRequest, onAccount, onProvider,
// onEvent or onResponse
hooked bool
droppedSaid atomic.Int64
}
@@ -163,7 +166,7 @@ func load(st string) *set {
continue
}
s.list = append(s.list, m)
s.hooked = s.hooked || m.hasReq || m.hasProv || m.hasEv || m.hasResp
s.hooked = s.hooked || m.hasReq || m.hasAcct || m.hasProv || m.hasEv || m.hasResp
}
return s
}
@@ -193,13 +196,14 @@ func compile(e plugin.Entry, file string) (*mw, error) {
}
m.onReq, m.hasReq = in.hook("onRequest")
m.onProv, m.hasProv = in.hook("onProvider")
m.onAcct, m.hasAcct = in.hook("onAccount")
m.onEv, m.hasEv = in.hook("onEvent")
m.onResp, m.hasResp = in.hook("onResponse")
if err := m.discover(in); err != nil {
return nil, err
}
if !m.hasReq && !m.hasProv && !m.hasEv && !m.hasResp && len(m.strats) == 0 && !m.hasUse {
return nil, errors.New("exports none of onRequest, onProvider, onEvent, onResponse, strategies and onUsage")
if !m.hasReq && !m.hasAcct && !m.hasProv && !m.hasEv && !m.hasResp && len(m.strats) == 0 && !m.hasUse {
return nil, errors.New("exports none of onRequest, onAccount, onProvider, onEvent, onResponse, strategies and onUsage")
}
if names, ok := in.strings("events"); ok {
m.events = map[string]bool{}
@@ -451,7 +455,7 @@ func States() map[string]State {
for _, h := range []struct {
ok bool
name string
}{{m.hasReq, "onRequest"}, {m.hasProv, "onProvider"}, {m.hasEv, "onEvent"}, {m.hasResp, "onResponse"}} {
}{{m.hasReq, "onRequest"}, {m.hasAcct, "onAccount"}, {m.hasProv, "onProvider"}, {m.hasEv, "onEvent"}, {m.hasResp, "onResponse"}} {
if h.ok {
st.Hooks = append(st.Hooks, h.name)
}
+1 -1
View File
@@ -313,7 +313,7 @@ func TestPointsLoadErrors(t *testing.T) {
def := file(t, `export default { strategies: { d: { order: (p, s) => s.map((_, i) => i) } } };`)
use(t, none, badName, notFn, notObj, def)
st := States()
if !strings.Contains(st[none.Spec].Error, "onRequest, onProvider, onEvent, onResponse, strategies and onUsage") {
if !strings.Contains(st[none.Spec].Error, "onRequest, onAccount, onProvider, onEvent, onResponse, strategies and onUsage") {
t.Fatal(st[none.Spec].Error)
}
for _, e := range []plugin.Entry{badName, notFn, notObj} {
+1
View File
@@ -709,6 +709,7 @@ magpie plugin options model-map '{"mapping": {"fast": "deepseek/deepseek-chat"}}
<div class="table-wrap"><table>
<tr><th>フック</th><th>渡されるもの</th><th>戻り値</th></tr>
<tr><td><code>onRequest(body, ctx)</code></td><td>ルーティング前のリクエスト本文。<code>model</code> を変えると別の宛先にルーティングされます。</td><td>本文、または何も返さない。<code>ctx.reject(status, message)</code> はリクエストを断り、そのエラーをエージェントの API の形式で返します(ステータスを省くと 403)。</td></tr>
<tr><td><code>onAccount(account, ctx)</code></td><td>試行が送られようとしているサブスクリプションのアカウント。まだ何も送っていません。<code>account</code> には <code>ref</code>、<code>provider</code>、<code>name</code>、<code>kind</code>(<code>codex</code> や <code>claude</code> など)と <code>model</code> があります。<code>ref</code> はアカウントを名指しせずに表す 16 進 32 文字で、どのリクエストでも magpie を再起動しても同じ、ミドルウェアごとに異なります。ミドルウェアはメールアドレスや id を知らないままアカウントを覚えておけます。プランが変わると <code>ref</code> も変わります。API キーでは呼ばれません。その試行の後のフックでは <code>ctx.account</code> が同じオブジェクトです。</td><td><code>{skip: true}</code> を返すと、このリクエストではそのアカウントを飛ばし、次のアカウントかキーを試します。そのアカウントは休ませず、失敗にも数えません。すべて飛ばされたときは、使えるものがないという通常のエラーがエージェントに返り、何も送られません。それ以外か何も返さなければ、そのアカウントを使います。</td></tr>
<tr><td><code>onProvider(body, ctx)</code></td><td>あるプロバイダに送る直前のリクエスト本文。<code>ctx.provider</code> にはその <code>id</code>、<code>name</code>、<code>account</code>(サブスクリプションの種類。<code>claude</code> や <code>antigravity</code> など。API キーにはありません)と <code>model</code> があります。リクエストを試すプロバイダごとに呼ばれ、毎回 <code>onRequest</code> が残した本文を受け取るので、あるプロバイダ向けの変更は他のプロバイダに届きません。</td><td>本文、または何も返さない。この時点でルーティングは済んでいるので、拒否も行き先の変更もできません。</td></tr>
<tr><td><code>onEvent(event, ctx)</code></td><td>ストリーム応答の各イベントの <code>data:</code> JSON。</td><td>イベント、何も返さない、またはイベントを落とす <code>null</code>。</td></tr>
<tr><td><code>onResponse(body, ctx)</code></td><td>ストリームでない応答の全体。<code>ctx.status</code> がそのステータスです。</td><td>本文、または何も返さない。</td></tr>
+1
View File
@@ -709,6 +709,7 @@ magpie plugin options model-map '{"mapping": {"fast": "deepseek/deepseek-chat"}}
<div class="table-wrap"><table>
<tr><th>Hook</th><th>Is given</th><th>Returns</th></tr>
<tr><td><code>onRequest(body, ctx)</code></td><td>The request body, before routing: a new <code>model</code> routes it elsewhere.</td><td>The body, or nothing. <code>ctx.reject(status, message)</code> turns the request away with that error, in the agent’s API (403 when no status is given).</td></tr>
<tr><td><code>onAccount(account, ctx)</code></td><td>The subscription account a try is about to go to, before anything is sent: <code>account</code> has <code>ref</code>, <code>provider</code>, <code>name</code>, <code>kind</code> (such as <code>codex</code> or <code>claude</code>) and <code>model</code>. <code>ref</code> stands for the account without naming it: 32 hex characters, the same on every request and after magpie restarts, and different for each middleware, so a middleware can remember an account without ever being told its email or id. A new plan gives the account a new <code>ref</code>. Not called for an API key. <code>ctx.account</code> is the same object in the hooks after it for that try.</td><td><code>{skip: true}</code> passes the account over for this request: the next account or key is tried, and the account isn’t rested or held against. When every one is passed over, the agent gets the usual error that none is ready, and nothing is sent. Anything else, or nothing, uses the account.</td></tr>
<tr><td><code>onProvider(body, ctx)</code></td><td>The request body as it is about to go to one provider; <code>ctx.provider</code> has its <code>id</code>, <code>name</code>, <code>account</code> (the subscription’s kind, such as <code>claude</code> or <code>antigravity</code>; absent for an API key) and <code>model</code>. It is called again for each provider a request is tried on, each time with the body <code>onRequest</code> left, so a change for one provider reaches no other.</td><td>The body, or nothing. The request is routed by now: it can’t be turned away or sent elsewhere.</td></tr>
<tr><td><code>onEvent(event, ctx)</code></td><td>Each event of a streamed reply: its <code>data:</code> JSON.</td><td>The event, nothing, or <code>null</code> to leave the event out.</td></tr>
<tr><td><code>onResponse(body, ctx)</code></td><td>A reply that isn’t streamed, whole; <code>ctx.status</code> is its status.</td><td>The body, or nothing.</td></tr>
+1
View File
@@ -709,6 +709,7 @@ magpie plugin options model-map '{"mapping": {"fast": "deepseek/deepseek-chat"}}
<div class="table-wrap"><table>
<tr><th>钩子</th><th>拿到的内容</th><th>返回</th></tr>
<tr><td><code>onRequest(body, ctx)</code></td><td>路由之前的请求体:改了 <code>model</code>,请求就会路由到别处。</td><td>请求体,或者不返回。<code>ctx.reject(status, message)</code> 会拒绝这个请求,并用 agent 的 API 格式返回这个错误(不给状态码时是 403)。</td></tr>
<tr><td><code>onAccount(account, ctx)</code></td><td>一次尝试即将发往的订阅账号,此时还什么都没发:<code>account</code> 有 <code>ref</code>、<code>provider</code>、<code>name</code>、<code>kind</code>(比如 <code>codex</code> 或 <code>claude</code>)和 <code>model</code>。<code>ref</code> 代表这个账号但不透露它:32 个十六进制字符,每次请求、magpie 重启后都一样,每个中间件拿到的都不同,所以中间件能记住一个账号,却永远拿不到它的邮箱或 id。换了套餐,账号的 <code>ref</code> 也会变。API 密钥不调用它。这次尝试后面的钩子里,<code>ctx.account</code> 是同一个对象。</td><td>返回 <code>{skip: true}</code> 就在这次请求里跳过这个账号:改试下一个账号或密钥,这个账号不会被休息,也不记它的错。全部被跳过时,智能体收到平常那个“没有可用的”错误,什么都不会发出去。返回别的或不返回,就用这个账号。</td></tr>
<tr><td><code>onProvider(body, ctx)</code></td><td>请求即将发给某个供应商时的请求体;<code>ctx.provider</code> 有它的 <code>id</code>、<code>name</code>、<code>account</code>(订阅的种类,比如 <code>claude</code> 或 <code>antigravity</code>;API 密钥没有这一项)和 <code>model</code>。请求每换一个供应商尝试就再调用一次,每次拿到的都是 <code>onRequest</code> 处理后的请求体,所以为一个供应商做的改动不会带到别的供应商。</td><td>请求体,或者不返回。这时请求已经路由好了:不能再拒绝,也不能改发别处。</td></tr>
<tr><td><code>onEvent(event, ctx)</code></td><td>流式回复里的每个事件:它的 <code>data:</code> JSON。</td><td>事件、不返回,或者 <code>null</code> 表示丢掉这个事件。</td></tr>
<tr><td><code>onResponse(body, ctx)</code></td><td>非流式的完整回复;<code>ctx.status</code> 是它的状态码。</td><td>回复体,或者不返回。</td></tr>