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).
180 lines
5.1 KiB
Go
180 lines
5.1 KiB
Go
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
|
|
}
|