gateway: a key's holder sees its own usage and setup at /me
zytszone on X runs one magpie's gateway for a whole department, whose people can't be given the admin's app. Each now opens the gateway's /me at the address they reach it at, types the gateway key they were given, and sees that key's own name, limits and what is spent of them, its usage over today, 7 and 30 days with its most used models, the models it may use, and copy-ready setup for Claude Code (settings.json env), Codex (config.toml provider, /v1, responses), any OpenAI-compatible client and a curl test. The base URL is the address the page was opened at, never 127.0.0.1; the key is a placeholder until "Put my key in the setup" is ticked. Strings in en, zh, zh-TW, ja and de. - GET /me (keypage.html, embedded) is the same bytes for everyone and holds no data, so lanGuard serves exactly GET/HEAD /me (no escaped path) to another machine without a key, after the allow list, the rebinding check and the not-shared 403, which still apply. Its CSP loads nothing from elsewhere, posts no form and forbids framing. - GET /v1/magpie/me (keyInfo) answers access.Caller's own key only. No key, a wrong one, one turned off and magpie's own token are 401 alike; ?key= is refused 400 so a key never sits in an address or a log. It names no account, other key, provider or secret; its models are /v1/models' for that key (keyAllowed), none for a read-only key. The page sends the key as Authorization to its own origin with credentials omitted and keeps it in sessionStorage only. - Both are in readOnlyRoutes, /me in clientPrefixes (magpie web's page port), and Gateway -> Gateway keys shows the page's address (MAGPIE_PUBLIC_URL, else the LAN address offered) with a Copy, while shared and with a key. Docs: gateway-routing.md, reference.md. Run: - mote: go build -tags nogui ./...; go vet -tags nogui gateway+gui; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway; go test -tags nogui -count=1 ./internal/gateway ./internal/gui: ok (gateway 732s). gofmt -l clean. Rebased onto18b63fe5fafter that; there: build, vet, and the KeyPage, read-only, client path, page port, LAN guard, caller usage and core script budget tests ok. - Key page Go tests, through the real lanGuard(Handler()) chain, from the network and from loopback: the key sees its own name, usage, top model, limits and allowed models and nothing of Bob, Bob's secret, the upstream key or magpie's token; no key, wrong key, turned-off key (Bearer and x-api-key), magpie's Token, ?key=, Origin null, an evil.localhost page, a foreign origin with a good key and a rebound Host all get nothing; the page opens without a key, not on POST, /me/x or /%6De, and not while unshared; a read-only key gets no models. - GUI, key-page.test.cjs: Chromium on mote and WebKit on the Linux box (magpie-desktop), 390px, all five languages, 24 of 24; i18n-keys ok. The 46 Gateway/caller-key GUI files and i18n-keys on the Linux box, both engines: 645 pass, 11 red at concurrency 4. Serially 6 stay red, and the same tests are red on origin/maina0cb8b646there: api-key-theme "system", gateway-key-limit webkit en/zh, connect-snippet-shell, gateway-key-models (#4120), phone-rows (#4218). Broken by hand, each red then restored: lanGuard's /me exemption removed (page 401); the KeyID check removed (no key/wrong/off/Token got data); keyAllowed dropped (Alice saw plan/m2); the RawPath check dropped (/%6De served); the ?key refusal dropped (200 with Alice's data). Not tried: a real Claude Code or Codex pointed at a shared gateway with the page's snippets; WebKit on macOS (every WebKit launch on mote hangs right now, for every session, a bare launch included); the whole GUI suite and a full go test ./... (one suite per machine; mote is running other sessions' suites).
This commit is contained in:
@@ -686,6 +686,14 @@ Usage page this way (#1547). Requests from
|
||||
this computer that send no gateway key are not limited; a gateway key used
|
||||
from this computer is.
|
||||
|
||||
A key's holder can also open **`/me`** in a browser at the address they
|
||||
reach the gateway at (for example `http://192.168.1.10:3999/me`), type
|
||||
their key, and see its own limits, its usage over today, 7 and 30 days, the
|
||||
models it may use, and copy-ready setup for Claude Code, Codex and any
|
||||
OpenAI-compatible client. It shows nothing of other keys, accounts or
|
||||
providers. Gateway → Gateway keys shows that address with a Copy button,
|
||||
so it can be handed out with the keys.
|
||||
|
||||
A gateway key can also be held to some **models** (#882): pick them with the
|
||||
**All models** badge on the key's row, or run `magpie gateway-key models <id>
|
||||
openai/gpt-5 anthropic/*` (`all` takes the restriction off). A pattern is
|
||||
|
||||
@@ -425,8 +425,8 @@ after `callerGuard`, so the key is known from loopback and from elsewhere,
|
||||
and before `withCaller` and `keyLimited`, so nothing is read, reserved or
|
||||
sent first. It judges the pattern `ServeMux.Handler` routes the request to
|
||||
against `readOnlyRoutes` (`GET /`, `/v1`, the quotas, their history and
|
||||
cards, the usage summary and its requests, the key's limit and the
|
||||
concurrency) and refuses every other with 403 `gateway_key_read_only`:
|
||||
cards, the usage summary and its requests, the key's limit, the key
|
||||
page and its data, and the concurrency) and refuses every other with 403 `gateway_key_read_only`:
|
||||
every model route, `count_tokens`, the Responses WebSocket's upgrade, every
|
||||
MCP server, Codex's and Gemini's backends, the catch-all and every write
|
||||
(`POST /v1/magpie/usage/requests`, the quotas' refresh). A route added later
|
||||
@@ -466,6 +466,33 @@ with it off, a key held to a limit gets 503 and nothing is sent. A local magpie
|
||||
asks it with each of its remote-magpie keys for that key's card on its
|
||||
Usage page (#1547), a window per limit's cap.
|
||||
|
||||
`GET /me` is the key page: a gateway key's holder opens it in a browser at
|
||||
the address they reach the gateway at, types their key, and sees that key's
|
||||
own name, limits, usage (today, 7 and 30 days, its most used models) and
|
||||
the models it may use, with the setup for Claude Code, Codex and an
|
||||
OpenAI-compatible client whose base URL is the address the page was opened
|
||||
at (zytszone on X: a department shares one magpie, whose app its people
|
||||
can't be given). The page itself (`keypage.html`, embedded) is the same
|
||||
bytes for everyone and holds no data, so `lanGuard` serves exactly `GET`
|
||||
or `HEAD /me` (`keyPageOpen`: no escaped path) to another machine without a
|
||||
key, after the allow list, the rebinding check and the not-shared refusal,
|
||||
which still apply. Its data is `GET /v1/magpie/me` (`keyInfo`), which takes
|
||||
the key as every route does (`Authorization` or `x-api-key`) and answers
|
||||
only `access.Caller`'s own: no key, a wrong one, one turned off and
|
||||
magpie's own token are 401 alike, and `?key=` is refused 400, so a key is
|
||||
never written into an address or a log. It names no account, no other key,
|
||||
no provider and no secret; its models are `/v1/models`' for that key
|
||||
(`keyAllowed`), none for a read-only key. The page loads nothing from
|
||||
elsewhere, posts no form and can't be framed (its CSP), keeps the key in
|
||||
the tab's `sessionStorage` only, and sends it to its own origin with
|
||||
`credentials: "omit"`. Gateway → Gateway keys shows the page's address
|
||||
(`MAGPIE_PUBLIC_URL`, else the LAN address offered) with a Copy, while
|
||||
shared and with a key (`gatewayKeyPage` in `keys.js`). `key_page.go`, and
|
||||
`TestKeyPageTellsAKeyItsOwn`, `TestKeyPageRefusesWithoutItsKey` and
|
||||
`TestKeyPageOpensWithoutAKey` in
|
||||
[`key_page_test.go`](../../internal/gateway/key_page_test.go);
|
||||
`internal/gui/tests/key-page.test.cjs` drives the page itself.
|
||||
|
||||
System One uses `RouteDecider` and `postDecide` in
|
||||
[`decide.go`](../../internal/gateway/decide.go), taking one provider prefix
|
||||
off at each hop and preserving the state, questions and vendor errors.
|
||||
|
||||
@@ -807,6 +807,8 @@ func (s *Server) routes() *routeMux {
|
||||
mux.HandleFunc("GET /v1/magpie/trace", s.gatewayTrace)
|
||||
mux.HandleFunc("GET /v1/magpie/concurrency", s.concurrency)
|
||||
mux.HandleFunc("GET /v1/magpie/limit", s.keyLimit)
|
||||
mux.HandleFunc("GET "+KeyPagePath, s.keyPage)
|
||||
mux.HandleFunc("GET "+keyPageData, s.keyInfo)
|
||||
// the Claude Code processes the Claude subscription runs, for magpie
|
||||
// claude-code runs (loopback only)
|
||||
mux.HandleFunc("GET "+ClaudeRunsPath, s.claudeRuns)
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"net/http"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/budget"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// KeyPagePath is the page a gateway key's holder opens in a browser at the
|
||||
// address they reach the gateway at (zytszone on X: magpie shared with a
|
||||
// whole department, whose people can't be given the admin's app). It asks
|
||||
// for their key and shows, from keyInfo, that key's own name, limits,
|
||||
// usage and models, and the setup to paste into Claude Code, Codex or an
|
||||
// OpenAI-compatible client, with the address it was opened at as the base
|
||||
// URL.
|
||||
const KeyPagePath = "/me"
|
||||
|
||||
// keyPageData is the key page's own route.
|
||||
const keyPageData = "/v1/magpie/me"
|
||||
|
||||
//go:embed keypage.html
|
||||
var keyPageHTML []byte
|
||||
|
||||
// keyPageOpen: r asks for the key page itself, which lanGuard serves to
|
||||
// another machine without a key while magpie is shared: it is the same
|
||||
// bytes for everyone and has no data in it. Its data (keyInfo) needs the
|
||||
// key as every other route does.
|
||||
func keyPageOpen(r *http.Request) bool {
|
||||
return r.URL.Path == KeyPagePath && r.URL.RawPath == "" && (r.Method == http.MethodGet || r.Method == http.MethodHead)
|
||||
}
|
||||
|
||||
// keyPage serves the key page. It loads nothing from anywhere else, posts
|
||||
// nothing and can't be framed, so a page that tricks a holder into
|
||||
// opening it can't read or steer what they type into it.
|
||||
func (s *Server) keyPage(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Content-Security-Policy", "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'")
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Referrer-Policy", "no-referrer")
|
||||
h.Set("Cache-Control", "no-cache")
|
||||
w.Write(keyPageHTML)
|
||||
}
|
||||
|
||||
// keyPageUsage are the periods the key page sums its key's calls over.
|
||||
var keyPageUsage = []usage.Period{usage.Today, usage.Week, usage.Month}
|
||||
|
||||
// keyInfo is what the calling gateway key may know of itself, for the key
|
||||
// page: its name, its limits and what it has spent of them, its calls
|
||||
// over today, 7 and 30 days and the models it called most, and the models
|
||||
// it may use. Nothing in it is another key's, an account's, a provider's
|
||||
// key or the admin's: no account names, no other key, no secret (the
|
||||
// holder typed theirs). No key, a wrong one, one turned off and magpie's
|
||||
// own token (which is no gateway key) are answered 401 alike.
|
||||
func (s *Server) keyInfo(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if r.URL.Query().Has("key") {
|
||||
writeError(w, provider.Chat, http.StatusBadRequest, "send the gateway key as Authorization: Bearer <key> or x-api-key, never in the address")
|
||||
return
|
||||
}
|
||||
who := access.Caller(r.Context())
|
||||
if who.KeyID == "" || who.KeyID == usage.NoCallerKey {
|
||||
writeError(w, provider.Chat, http.StatusUnauthorized, "send an enabled gateway key as Authorization: Bearer <key> or x-api-key")
|
||||
return
|
||||
}
|
||||
limits := budget.All(access.Key{ID: who.KeyID, Name: who.KeyName, Limit: who.Limit, More: who.More}, limitClock())
|
||||
if limits == nil {
|
||||
limits = []budget.Status{}
|
||||
}
|
||||
sums := map[string]keyPageTotals{}
|
||||
// the models it called most, as their vendors name them
|
||||
top := []keyPageModel{}
|
||||
for _, p := range keyPageUsage {
|
||||
page := usage.QueryPage(p, usage.Filter{CallerKey: who.KeyID}, 0, 1)
|
||||
sums[string(p)] = keyPageSum(page.Sum)
|
||||
if p != usage.Month {
|
||||
continue
|
||||
}
|
||||
for _, sh := range page.By["model"] {
|
||||
if len(top) < 8 {
|
||||
top = append(top, keyPageModel{ID: sh.ID, keyPageTotals: keyPageSum(sh.Totals)})
|
||||
}
|
||||
}
|
||||
}
|
||||
models := []map[string]string{}
|
||||
// a read-only key is refused every model (readOnlyGuard)
|
||||
if !who.ReadOnly {
|
||||
// as /v1/models tells this key, for no agent in particular
|
||||
shown, _ := provider.CatalogFor("")
|
||||
shown = keyAllowed(r, shown)
|
||||
labels := provider.Labels(shown)
|
||||
for i, e := range shown {
|
||||
models = append(models, map[string]string{"id": e.ID, "label": labels[i]})
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"name": who.KeyName,
|
||||
"readOnly": who.ReadOnly,
|
||||
"limits": limits,
|
||||
"usage": sums,
|
||||
"topModels": top,
|
||||
"models": models,
|
||||
"version": Version,
|
||||
})
|
||||
}
|
||||
|
||||
// keyPageTotals are the sums the key page shows of a key's calls.
|
||||
type keyPageTotals struct {
|
||||
Calls int `json:"calls"`
|
||||
Errors int `json:"errors"`
|
||||
Input int `json:"input"`
|
||||
Output int `json:"output"`
|
||||
CacheRead int `json:"cache_read"`
|
||||
CacheWrite int `json:"cache_write"`
|
||||
Cost float64 `json:"cost"`
|
||||
Unpriced int `json:"unpriced"`
|
||||
}
|
||||
|
||||
type keyPageModel struct {
|
||||
ID string `json:"id"`
|
||||
keyPageTotals
|
||||
}
|
||||
|
||||
func keyPageSum(t usage.Totals) keyPageTotals {
|
||||
return keyPageTotals{Calls: t.Calls, Errors: t.Errors, Input: t.Input, Output: t.Output, CacheRead: t.CacheRead, CacheWrite: t.CacheWrite, Cost: t.Cost, Unpriced: t.Unpriced}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/budget"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// keyPageGateway is a shared gateway with a plan of two models and two
|
||||
// keys, each with calls of its own: "Alice" held to plan/m1 and called
|
||||
// once, "Bob" held to a daily token limit and called twice.
|
||||
func keyPageGateway(t *testing.T) (http.Handler, []access.Key, []string) {
|
||||
t.Helper()
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
budget.Forget()
|
||||
pinLimitClock(t)
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":30,"completion_tokens":5}}`)
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1", "m2"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys, secrets := newCaller(t, "Alice", "Bob")
|
||||
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"plan/m1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
setLimit(t, keys[1].ID, &access.Limit{Period: "day", Tokens: 1000})
|
||||
h := lanGuard(New().Handler())
|
||||
for _, secret := range []string{secrets[0], secrets[1], secrets[1]} {
|
||||
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq))
|
||||
r.RemoteAddr = "192.168.1.9:5000"
|
||||
r.Header.Set("Authorization", "Bearer "+secret)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 200 {
|
||||
t.Fatal("call", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
return h, keys, secrets
|
||||
}
|
||||
|
||||
type keyPageReq struct {
|
||||
method, path, from, host string
|
||||
header map[string]string
|
||||
}
|
||||
|
||||
func (q keyPageReq) do(h http.Handler) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(q.method, q.path, nil)
|
||||
r.RemoteAddr = q.from
|
||||
if q.host != "" {
|
||||
r.Host = q.host
|
||||
}
|
||||
for k, v := range q.header {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
type keyPageInfo struct {
|
||||
Name string `json:"name"`
|
||||
ReadOnly bool `json:"readOnly"`
|
||||
Limits []budget.Status `json:"limits"`
|
||||
Usage map[string]keyPageTotals `json:"usage"`
|
||||
TopModels []keyPageModel `json:"topModels"`
|
||||
Models []struct{ ID, Label string }
|
||||
}
|
||||
|
||||
// zytszone on X: a department's people each have a gateway key and can't
|
||||
// be given the admin's app. The key page's data tells a key what is its
|
||||
// own: its name, limits, calls and models, from another machine, and
|
||||
// nothing of the other key, the provider's key or either secret.
|
||||
func TestKeyPageTellsAKeyItsOwn(t *testing.T) {
|
||||
h, keys, secrets := keyPageGateway(t)
|
||||
for i, secret := range secrets {
|
||||
w := keyPageReq{method: "GET", path: keyPageData, from: "192.168.1.9:5000", header: map[string]string{"Authorization": "Bearer " + secret}}.do(h)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
if cc := w.Header().Get("Cache-Control"); cc != "no-store" {
|
||||
t.Error("Cache-Control", cc)
|
||||
}
|
||||
body := w.Body.String()
|
||||
other := 1 - i
|
||||
for _, leak := range []string{keys[other].Name, keys[other].ID, secrets[other], secret, "upstream-secret", Token} {
|
||||
if strings.Contains(body, leak) {
|
||||
t.Errorf("key %s is told %q: %s", keys[i].Name, leak, body)
|
||||
}
|
||||
}
|
||||
var got keyPageInfo
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Name != keys[i].Name || got.ReadOnly {
|
||||
t.Errorf("name %q readOnly %v", got.Name, got.ReadOnly)
|
||||
}
|
||||
calls := []int{1, 2}[i]
|
||||
for _, p := range []string{"today", "7d", "30d"} {
|
||||
if u := got.Usage[p]; u.Calls != calls || u.Input != 30*calls || u.Output != 5*calls {
|
||||
t.Errorf("%s: %s usage %+v", keys[i].Name, p, u)
|
||||
}
|
||||
}
|
||||
if len(got.TopModels) != 1 || got.TopModels[0].ID != "m1" || got.TopModels[0].Calls != calls {
|
||||
t.Errorf("%s: top models %+v", keys[i].Name, got.TopModels)
|
||||
}
|
||||
var ids []string
|
||||
for _, m := range got.Models {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
if want := []string{"plan/m1", "plan/m1,plan/m2"}[i]; strings.Join(ids, ",") != want {
|
||||
t.Errorf("%s: models %v, want %s", keys[i].Name, ids, want)
|
||||
}
|
||||
if i == 0 && len(got.Limits) != 0 {
|
||||
t.Errorf("Alice has no limit: %+v", got.Limits)
|
||||
}
|
||||
if i == 1 && (len(got.Limits) != 1 || got.Limits[0].TokenLimit != 1000 || got.Limits[0].Tokens != 70) {
|
||||
t.Errorf("Bob's limit: %+v", got.Limits)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No key, a wrong one, one turned off or removed, magpie's own token and
|
||||
// a key in the address are all told nothing, from another machine and
|
||||
// from this one; and a page from elsewhere (Origin null, a *.localhost
|
||||
// name, another site, a rebound name) is refused as on every route.
|
||||
func TestKeyPageRefusesWithoutItsKey(t *testing.T) {
|
||||
h, keys, secrets := keyPageGateway(t)
|
||||
if _, err := access.Update("off-key", access.Change{Key: keys[1].ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote, here := "192.168.1.9:5000", "127.0.0.1:5000"
|
||||
bearer := func(k string) map[string]string { return map[string]string{"Authorization": "Bearer " + k} }
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
q keyPageReq
|
||||
want int
|
||||
}{
|
||||
{"no key", keyPageReq{from: remote}, 401},
|
||||
{"wrong key", keyPageReq{from: remote, header: bearer("sk-magpie-not-a-key")}, 401},
|
||||
{"turned off", keyPageReq{from: remote, header: bearer(secrets[1])}, 401},
|
||||
{"turned off, x-api-key", keyPageReq{from: remote, header: map[string]string{"x-api-key": secrets[1]}}, 401},
|
||||
{"key in the address", keyPageReq{from: remote, path: keyPageData + "?key=" + secrets[0]}, 400},
|
||||
{"here, no key", keyPageReq{from: here}, 401},
|
||||
{"here, wrong key", keyPageReq{from: here, header: bearer("sk-magpie-not-a-key")}, 401},
|
||||
{"here, turned off", keyPageReq{from: here, header: bearer(secrets[1])}, 401},
|
||||
{"here, magpie's token", keyPageReq{from: here, header: bearer(Token)}, 401},
|
||||
{"here, key in the address", keyPageReq{from: here, path: keyPageData + "?key=" + secrets[0]}, 400},
|
||||
{"Origin null", keyPageReq{from: here, header: map[string]string{"Origin": "null"}}, 403},
|
||||
{"a localhost subdomain", keyPageReq{from: here, header: map[string]string{"Origin": "http://evil.localhost"}}, 403},
|
||||
{"another site, with the key", keyPageReq{from: here, header: map[string]string{"Origin": "https://evil.example", "Authorization": "Bearer " + secrets[0]}}, 403},
|
||||
{"another site, remote, with the key", keyPageReq{from: remote, header: map[string]string{"Origin": "https://evil.example", "Authorization": "Bearer " + secrets[0]}}, 403},
|
||||
{"rebound name", keyPageReq{from: here, host: "evil.example:3425", header: map[string]string{"Sec-Fetch-Site": "same-origin"}}, 403},
|
||||
{"remote, Origin null, no key", keyPageReq{from: remote, header: map[string]string{"Origin": "null"}}, 401},
|
||||
} {
|
||||
c.q.method = "GET"
|
||||
if c.q.path == "" {
|
||||
c.q.path = keyPageData
|
||||
}
|
||||
w := c.q.do(h)
|
||||
if w.Code != c.want {
|
||||
t.Errorf("%s: %d, want %d: %s", c.name, w.Code, c.want, w.Body.String())
|
||||
}
|
||||
for _, k := range keys {
|
||||
if strings.Contains(w.Body.String(), k.Name) || strings.Contains(w.Body.String(), k.ID) {
|
||||
t.Errorf("%s: told %s: %s", c.name, k.Name, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
// and the key that works still does
|
||||
if w := (keyPageReq{method: "GET", path: keyPageData, from: remote, header: bearer(secrets[0])}).do(h); w.Code != 200 {
|
||||
t.Fatal("Alice", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// The page itself is opened before its key is typed: from another machine
|
||||
// without a key while magpie is shared, never framed, loading nothing
|
||||
// from elsewhere and never sending the key in an address. Not shared, it
|
||||
// isn't answered at all; a rebound name is refused it here.
|
||||
func TestKeyPageOpensWithoutAKey(t *testing.T) {
|
||||
h, _, _ := keyPageGateway(t)
|
||||
w := keyPageReq{method: "GET", path: KeyPagePath, from: "192.168.1.9:5000", header: map[string]string{"User-Agent": "Mozilla/5.0"}}.do(h)
|
||||
if w.Code != 200 || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/html") {
|
||||
t.Fatal(w.Code, w.Header())
|
||||
}
|
||||
csp := w.Header().Get("Content-Security-Policy")
|
||||
for _, want := range []string{"default-src 'none'", "connect-src 'self'", "frame-ancestors 'none'", "form-action 'none'"} {
|
||||
if !strings.Contains(csp, want) {
|
||||
t.Errorf("CSP %q lacks %q", csp, want)
|
||||
}
|
||||
}
|
||||
if w.Header().Get("X-Frame-Options") != "DENY" || w.Header().Get("Referrer-Policy") != "no-referrer" {
|
||||
t.Error(w.Header())
|
||||
}
|
||||
page := w.Body.String()
|
||||
if strings.Contains(page, "?key=") || strings.Contains(page, "&key=") || !strings.Contains(page, `Authorization: "Bearer " + k`) {
|
||||
t.Error("the page sends its key some other way than the Authorization header")
|
||||
}
|
||||
// a path that isn't the page's exactly, and any other method, needs
|
||||
// the key as every other route does
|
||||
for _, q := range []keyPageReq{{method: "POST", path: KeyPagePath}, {method: "GET", path: KeyPagePath + "/x"}, {method: "GET", path: "/%6De"}} {
|
||||
q.from = "192.168.1.9:5000"
|
||||
if w := q.do(h); w.Code != 401 {
|
||||
t.Errorf("%s %s: %d", q.method, q.path, w.Code)
|
||||
}
|
||||
}
|
||||
if w := (keyPageReq{method: "GET", path: KeyPagePath, from: "127.0.0.1:5000", host: "evil.example:3425", header: map[string]string{"User-Agent": "Mozilla/5.0"}}).do(h); w.Code != 403 {
|
||||
t.Error("rebound", w.Code)
|
||||
}
|
||||
s := settings.Load()
|
||||
s.LAN = false
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := (keyPageReq{method: "GET", path: KeyPagePath, from: "192.168.1.9:5000"}).do(h); w.Code != 403 {
|
||||
t.Error("not shared", w.Code)
|
||||
}
|
||||
if w := (keyPageReq{method: "GET", path: KeyPagePath, from: "127.0.0.1:5000"}).do(h); w.Code != 200 {
|
||||
t.Error("here", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// A read-only key opens the page and reads its own usage, and is told
|
||||
// no models, as it may call none.
|
||||
func TestKeyPageReadOnlyKey(t *testing.T) {
|
||||
h, keys, secrets := keyPageGateway(t)
|
||||
if _, err := access.Update("access-key", access.Change{Key: keys[0].ID, ReadOnly: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bearer := map[string]string{"Authorization": "Bearer " + secrets[0]}
|
||||
if w := (keyPageReq{method: "GET", path: KeyPagePath, from: "192.168.1.9:5000", header: bearer}).do(h); w.Code != 200 {
|
||||
t.Fatal("page", w.Code, w.Body.String())
|
||||
}
|
||||
w := keyPageReq{method: "GET", path: keyPageData, from: "192.168.1.9:5000", header: bearer}.do(h)
|
||||
var got keyPageInfo
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &got) != nil {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
if !got.ReadOnly || len(got.Models) != 0 || got.Usage["30d"].Calls != 1 {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<title>magpie key</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f5f7; --card: #fff; --text: #1d1d1f; --sub: #6e6e73; --line: #d2d2d7;
|
||||
--soft: #f0f0f2; --accent: #0071e3; --accent-text: #fff; --bad: #d70015; --warn: #b25000;
|
||||
--bar: #e3e3e8; --code: #f5f5f7;
|
||||
color-scheme: light dark;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #000; --card: #1c1c1e; --text: #f5f5f7; --sub: #98989d; --line: #38383a;
|
||||
--soft: #2c2c2e; --accent: #0a84ff; --accent-text: #fff; --bad: #ff453a; --warn: #ff9f0a;
|
||||
--bar: #3a3a3c; --code: #2c2c2e;
|
||||
}
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.45 -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "Helvetica Neue", "PingFang SC", "Hiragino Sans", "Microsoft YaHei", sans-serif; -webkit-font-smoothing: antialiased; }
|
||||
main { max-width: 680px; margin: 0 auto; padding: 40px 16px 64px; }
|
||||
h1 { font-size: 26px; font-weight: 600; margin: 0 0 6px; letter-spacing: -0.01em; overflow-wrap: anywhere; }
|
||||
h2 { font-size: 13px; font-weight: 600; color: var(--sub); margin: 28px 4px 8px; text-transform: none; }
|
||||
p { margin: 0; }
|
||||
.sub { color: var(--sub); }
|
||||
.card { background: var(--card); border-radius: 12px; padding: 16px; box-shadow: 0 0 0 0.5px var(--line); }
|
||||
.card + .card { margin-top: 10px; }
|
||||
.head { display: flex; align-items: flex-start; gap: 12px; }
|
||||
.head .grow { flex: 1; min-width: 0; }
|
||||
.row { display: flex; align-items: center; gap: 10px; }
|
||||
.grow { flex: 1; min-width: 0; }
|
||||
label.field { display: block; font-weight: 500; margin: 18px 0 6px; }
|
||||
input[type=password], input[type=text], input[type=search] { width: 100%; font: inherit; color: var(--text); background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 9px 11px; outline: none; }
|
||||
input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 25%, transparent); }
|
||||
button { font: inherit; cursor: pointer; border: 0; border-radius: 8px; padding: 8px 14px; background: var(--soft); color: var(--text); }
|
||||
button.primary { background: var(--accent); color: var(--accent-text); font-weight: 500; }
|
||||
button.link { background: none; color: var(--accent); padding: 4px 6px; }
|
||||
button:disabled { opacity: 0.5; cursor: default; }
|
||||
button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.form-row { display: flex; gap: 8px; }
|
||||
.form-row input { flex: 1; min-width: 0; }
|
||||
.note { color: var(--sub); font-size: 12px; margin-top: 8px; }
|
||||
.error { color: var(--bad); margin-top: 10px; }
|
||||
.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
|
||||
.stat .k { color: var(--sub); font-size: 12px; }
|
||||
.stat .v { font-size: 20px; font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||
.stat .s { color: var(--sub); font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
.limit + .limit { margin-top: 14px; }
|
||||
.bar { height: 6px; border-radius: 3px; background: var(--bar); overflow: hidden; margin: 6px 0 4px; }
|
||||
.bar > i { display: block; height: 100%; background: var(--accent); border-radius: 3px; }
|
||||
.bar.full > i { background: var(--bad); }
|
||||
.num { font-variant-numeric: tabular-nums; }
|
||||
.tag { font-size: 11px; padding: 1px 7px; border-radius: 10px; background: var(--soft); color: var(--sub); white-space: nowrap; }
|
||||
.tag.bad { color: var(--bad); }
|
||||
.list { margin: 0; padding: 0; list-style: none; }
|
||||
.list li { display: flex; gap: 10px; align-items: baseline; padding: 6px 0; }
|
||||
.list li + li { border-top: 0.5px solid var(--line); }
|
||||
.mono, code, pre { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 12.5px; }
|
||||
.list .mono { overflow-wrap: anywhere; }
|
||||
.segs { display: inline-flex; background: var(--soft); border-radius: 8px; padding: 2px; gap: 2px; flex-wrap: wrap; }
|
||||
.segs button { padding: 5px 12px; background: none; border-radius: 6px; font-size: 13px; }
|
||||
.segs button[aria-selected=true] { background: var(--card); box-shadow: 0 1px 2px rgba(0,0,0,0.12); font-weight: 500; }
|
||||
.snip { position: relative; margin-top: 12px; }
|
||||
.snip .file { color: var(--sub); font-size: 12px; margin-bottom: 4px; }
|
||||
pre { margin: 0; background: var(--code); border-radius: 8px; padding: 12px 14px; overflow-x: auto; white-space: pre; line-height: 1.5; }
|
||||
.kv { display: grid; grid-template-columns: max-content 1fr auto; gap: 8px 12px; align-items: center; margin-top: 12px; }
|
||||
.kv code { background: var(--code); border-radius: 6px; padding: 4px 8px; overflow-wrap: anywhere; }
|
||||
.copy { padding: 4px 10px; font-size: 12px; }
|
||||
.switch { display: inline-flex; align-items: center; gap: 8px; margin-top: 12px; cursor: pointer; user-select: none; }
|
||||
.switch input { accent-color: var(--accent); width: 16px; height: 16px; margin: 0; }
|
||||
.models { max-height: 280px; overflow-y: auto; margin-top: 8px; border-radius: 8px; }
|
||||
.models button { display: flex; width: 100%; text-align: left; gap: 10px; align-items: baseline; background: none; border-radius: 6px; padding: 7px 8px; }
|
||||
.models button:hover { background: var(--soft); }
|
||||
.models button .chk { width: 14px; flex: none; color: var(--accent); font-weight: 700; }
|
||||
.models button .lbl { color: var(--sub); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.models button .mono { overflow-wrap: anywhere; }
|
||||
.models button[aria-checked=true] { background: color-mix(in srgb, var(--accent) 12%, transparent); }
|
||||
.empty { color: var(--sub); padding: 6px 2px; }
|
||||
[hidden] { display: none !important; }
|
||||
@media (max-width: 480px) {
|
||||
main { padding-top: 24px; }
|
||||
.stats { grid-template-columns: 1fr 1fr 1fr; gap: 6px; }
|
||||
.stat .v { font-size: 17px; }
|
||||
.kv { grid-template-columns: 1fr auto; }
|
||||
.kv .k { grid-column: 1 / -1; margin-bottom: -4px; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<section id="signin">
|
||||
<h1 data-t="title">Your gateway key</h1>
|
||||
<p class="sub" data-t="intro">Enter the gateway key you were given to see what it has used, what it may use and how to set up your agents.</p>
|
||||
<form id="form" autocomplete="off">
|
||||
<label class="field" for="key" data-t="keyLabel">Gateway key</label>
|
||||
<div class="form-row">
|
||||
<input id="key" type="password" spellcheck="false" autocapitalize="off" autocomplete="off">
|
||||
<button class="primary" id="go" type="submit" data-t="go">Continue</button>
|
||||
</div>
|
||||
<p class="error" id="err" role="alert" hidden></p>
|
||||
<p class="note" data-t="kept">The key stays in this tab and is sent to this gateway alone.</p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section id="info" hidden>
|
||||
<div class="head">
|
||||
<div class="grow">
|
||||
<p class="sub" data-t="keyLabel">Gateway key</p>
|
||||
<h1 id="name"></h1>
|
||||
</div>
|
||||
<button class="link" id="refresh" type="button" data-t="refresh">Refresh</button>
|
||||
<button class="link" id="forget" type="button" data-t="forget">Forget key</button>
|
||||
</div>
|
||||
<p class="error" id="err2" role="alert" hidden></p>
|
||||
|
||||
<h2 data-t="limits">Limits</h2>
|
||||
<div class="card" id="limits"></div>
|
||||
|
||||
<h2 data-t="usage">Usage</h2>
|
||||
<div class="card">
|
||||
<div class="stats" id="stats"></div>
|
||||
</div>
|
||||
<div class="card" id="topCard">
|
||||
<p class="sub" data-t="top">Most used, last 30 days</p>
|
||||
<ul class="list" id="top"></ul>
|
||||
</div>
|
||||
|
||||
<div id="setupBlock">
|
||||
<h2 data-t="setup">Set up</h2>
|
||||
<div class="card">
|
||||
<div class="segs" role="tablist" id="tabs"></div>
|
||||
<p class="note" id="tabNote"></p>
|
||||
<div id="snip"></div>
|
||||
<label class="switch"><input type="checkbox" id="withKey"><span data-t="withKey">Put my key in the setup</span></label>
|
||||
</div>
|
||||
|
||||
<h2 data-t="models">Models this key can use</h2>
|
||||
<div class="card">
|
||||
<input type="search" id="filter" spellcheck="false">
|
||||
<div class="models" id="models" role="radiogroup"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card" id="readOnly" hidden><p data-t="readOnly">This key reads its usage only; it can't call models.</p></div>
|
||||
</section>
|
||||
</main>
|
||||
<script>
|
||||
"use strict";
|
||||
const STR = {
|
||||
en: {
|
||||
title: "Your gateway key", intro: "Enter the gateway key you were given to see what it has used, what it may use and how to set up your agents.",
|
||||
keyLabel: "Gateway key", go: "Continue", kept: "The key stays in this tab and is sent to this gateway alone.",
|
||||
bad: "This isn't an enabled gateway key here. Check it with whoever gave it to you.", net: "The gateway didn't answer. Check the address and try again.",
|
||||
many: "Too many tries. Wait a minute and try again.", notShared: "This gateway isn't shared right now.",
|
||||
refresh: "Refresh", forget: "Forget key", limits: "Limits", noLimit: "No limit on this key.",
|
||||
day: "Daily", week: "Weekly", month: "Monthly", days: "Every {n} days", hours: "Every {n} hours",
|
||||
tokensOf: "{a} of {b} tokens", costOf: "{a} of {b}", resets: "Resets {t}", spent: "Used up until it resets",
|
||||
usage: "Usage", today: "Today", d7: "7 days", d30: "30 days", calls: "{n} requests", tokens: "tokens", cost: "≈ {c}",
|
||||
top: "Most used, last 30 days", none: "Nothing yet.",
|
||||
setup: "Set up", withKey: "Put my key in the setup", models: "Models this key can use", filter: "Filter models",
|
||||
noModels: "This key can't use any model.", readOnly: "This key reads its usage only; it can't call models.",
|
||||
copy: "Copy", copied: "Copied",
|
||||
claudeNote: "Add this to ~/.claude/settings.json, then start claude.",
|
||||
codexNote: "Add this to ~/.codex/config.toml, then start codex.",
|
||||
oaiNote: "For any app or SDK that takes an OpenAI-compatible endpoint.",
|
||||
curlNote: "Run this in a terminal to check the key works.",
|
||||
base: "Base URL", apiKey: "API key", model: "Model", test: "Test", other: "OpenAI-compatible",
|
||||
pick: "The model is the one picked below.",
|
||||
},
|
||||
zh: {
|
||||
title: "你的网关密钥", intro: "输入你拿到的网关密钥,查看它的用量、可用的模型,以及怎样配置你的智能体。",
|
||||
keyLabel: "网关密钥", go: "继续", kept: "密钥只保存在这个标签页里,只会发给这个网关。",
|
||||
bad: "这不是此处可用的网关密钥。请向给你密钥的人确认。", net: "网关没有响应。请检查地址后重试。",
|
||||
many: "尝试次数过多。请等一分钟再试。", notShared: "这个网关目前没有共享。",
|
||||
refresh: "刷新", forget: "忘记密钥", limits: "额度", noLimit: "这个密钥没有额度限制。",
|
||||
day: "每天", week: "每周", month: "每月", days: "每 {n} 天", hours: "每 {n} 小时",
|
||||
tokensOf: "已用 {a} / {b} tokens", costOf: "已用 {a} / {b}", resets: "{t} 重置", spent: "已用完,重置后恢复",
|
||||
usage: "用量", today: "今天", d7: "7 天", d30: "30 天", calls: "{n} 次请求", tokens: "tokens", cost: "约 {c}",
|
||||
top: "最近 30 天最常用", none: "还没有用量。",
|
||||
setup: "配置", withKey: "在配置里填入我的密钥", models: "这个密钥可用的模型", filter: "筛选模型",
|
||||
noModels: "这个密钥不能使用任何模型。", readOnly: "这个密钥只能查看用量,不能调用模型。",
|
||||
copy: "复制", copied: "已复制",
|
||||
claudeNote: "加到 ~/.claude/settings.json 里,然后启动 claude。",
|
||||
codexNote: "加到 ~/.codex/config.toml 里,然后启动 codex。",
|
||||
oaiNote: "适用于任何支持 OpenAI 兼容接口的应用或 SDK。",
|
||||
curlNote: "在终端里运行,检查密钥能否使用。",
|
||||
base: "Base URL", apiKey: "API Key", model: "模型", test: "测试", other: "OpenAI 兼容",
|
||||
pick: "模型为下方选中的那个。",
|
||||
},
|
||||
"zh-TW": {
|
||||
title: "你的閘道金鑰", intro: "輸入你拿到的閘道金鑰,查看它的用量、可用的模型,以及如何設定你的代理程式。",
|
||||
keyLabel: "閘道金鑰", go: "繼續", kept: "金鑰只保存在這個分頁中,只會傳給這個閘道。",
|
||||
bad: "這不是此處可用的閘道金鑰。請向提供金鑰的人確認。", net: "閘道沒有回應。請檢查位址後再試。",
|
||||
many: "嘗試次數過多。請等一分鐘再試。", notShared: "這個閘道目前沒有共用。",
|
||||
refresh: "重新整理", forget: "忘記金鑰", limits: "額度", noLimit: "這個金鑰沒有額度限制。",
|
||||
day: "每天", week: "每週", month: "每月", days: "每 {n} 天", hours: "每 {n} 小時",
|
||||
tokensOf: "已用 {a} / {b} tokens", costOf: "已用 {a} / {b}", resets: "{t} 重設", spent: "已用完,重設後恢復",
|
||||
usage: "用量", today: "今天", d7: "7 天", d30: "30 天", calls: "{n} 次請求", tokens: "tokens", cost: "約 {c}",
|
||||
top: "最近 30 天最常用", none: "還沒有用量。",
|
||||
setup: "設定", withKey: "在設定中填入我的金鑰", models: "這個金鑰可用的模型", filter: "篩選模型",
|
||||
noModels: "這個金鑰不能使用任何模型。", readOnly: "這個金鑰只能查看用量,不能呼叫模型。",
|
||||
copy: "複製", copied: "已複製",
|
||||
claudeNote: "加到 ~/.claude/settings.json 中,然後啟動 claude。",
|
||||
codexNote: "加到 ~/.codex/config.toml 中,然後啟動 codex。",
|
||||
oaiNote: "適用於任何支援 OpenAI 相容介面的應用程式或 SDK。",
|
||||
curlNote: "在終端機中執行,檢查金鑰是否可用。",
|
||||
base: "Base URL", apiKey: "API Key", model: "模型", test: "測試", other: "OpenAI 相容",
|
||||
pick: "模型為下方選取的那個。",
|
||||
},
|
||||
ja: {
|
||||
title: "あなたのゲートウェイキー", intro: "受け取ったゲートウェイキーを入力すると、使用量、使えるモデル、エージェントの設定方法が表示されます。",
|
||||
keyLabel: "ゲートウェイキー", go: "続ける", kept: "キーはこのタブにだけ保存され、このゲートウェイにだけ送られます。",
|
||||
bad: "ここで有効なゲートウェイキーではありません。キーをくれた人に確認してください。", net: "ゲートウェイから応答がありません。アドレスを確認して、もう一度お試しください。",
|
||||
many: "試行回数が多すぎます。1 分待ってからお試しください。", notShared: "このゲートウェイは現在共有されていません。",
|
||||
refresh: "更新", forget: "キーを消去", limits: "上限", noLimit: "このキーに上限はありません。",
|
||||
day: "毎日", week: "毎週", month: "毎月", days: "{n} 日ごと", hours: "{n} 時間ごと",
|
||||
tokensOf: "{b} トークン中 {a}", costOf: "{b} 中 {a}", resets: "{t} にリセット", spent: "リセットまで使い切りました",
|
||||
usage: "使用量", today: "今日", d7: "7 日間", d30: "30 日間", calls: "{n} リクエスト", tokens: "トークン", cost: "約 {c}",
|
||||
top: "直近 30 日でよく使ったモデル", none: "まだありません。",
|
||||
setup: "設定", withKey: "設定にキーを入れる", models: "このキーで使えるモデル", filter: "モデルを絞り込む",
|
||||
noModels: "このキーで使えるモデルはありません。", readOnly: "このキーは使用量の閲覧専用で、モデルは呼び出せません。",
|
||||
copy: "コピー", copied: "コピーしました",
|
||||
claudeNote: "~/.claude/settings.json に追加してから claude を起動します。",
|
||||
codexNote: "~/.codex/config.toml に追加してから codex を起動します。",
|
||||
oaiNote: "OpenAI 互換のエンドポイントを使えるアプリや SDK 向けです。",
|
||||
curlNote: "ターミナルで実行して、キーが使えるか確かめます。",
|
||||
base: "Base URL", apiKey: "API キー", model: "モデル", test: "テスト", other: "OpenAI 互換",
|
||||
pick: "モデルは下で選んだものです。",
|
||||
},
|
||||
de: {
|
||||
title: "Ihr Zugangsschlüssel", intro: "Geben Sie den Zugangsschlüssel ein, den Sie bekommen haben, um seine Nutzung, die erlaubten Modelle und die Einrichtung Ihrer Agenten zu sehen.",
|
||||
keyLabel: "Zugangsschlüssel", go: "Weiter", kept: "Der Schlüssel bleibt in diesem Tab und wird nur an dieses Gateway gesendet.",
|
||||
bad: "Das ist hier kein aktiver Zugangsschlüssel. Fragen Sie, wer ihn Ihnen gegeben hat.", net: "Das Gateway antwortet nicht. Prüfen Sie die Adresse und versuchen Sie es erneut.",
|
||||
many: "Zu viele Versuche. Warten Sie eine Minute.", notShared: "Dieses Gateway ist gerade nicht freigegeben.",
|
||||
refresh: "Aktualisieren", forget: "Schlüssel vergessen", limits: "Limits", noLimit: "Dieser Schlüssel hat kein Limit.",
|
||||
day: "Täglich", week: "Wöchentlich", month: "Monatlich", days: "Alle {n} Tage", hours: "Alle {n} Stunden",
|
||||
tokensOf: "{a} von {b} Tokens", costOf: "{a} von {b}", resets: "Zurückgesetzt {t}", spent: "Aufgebraucht bis zum Zurücksetzen",
|
||||
usage: "Nutzung", today: "Heute", d7: "7 Tage", d30: "30 Tage", calls: "{n} Anfragen", tokens: "Tokens", cost: "≈ {c}",
|
||||
top: "Am meisten genutzt, letzte 30 Tage", none: "Noch nichts.",
|
||||
setup: "Einrichten", withKey: "Meinen Schlüssel einsetzen", models: "Modelle für diesen Schlüssel", filter: "Modelle filtern",
|
||||
noModels: "Dieser Schlüssel kann kein Modell nutzen.", readOnly: "Dieser Schlüssel liest nur seine Nutzung; er kann keine Modelle aufrufen.",
|
||||
copy: "Kopieren", copied: "Kopiert",
|
||||
claudeNote: "In ~/.claude/settings.json einfügen, dann claude starten.",
|
||||
codexNote: "In ~/.codex/config.toml einfügen, dann codex starten.",
|
||||
oaiNote: "Für jede App oder jedes SDK mit OpenAI-kompatiblem Endpunkt.",
|
||||
curlNote: "Im Terminal ausführen, um den Schlüssel zu prüfen.",
|
||||
base: "Base URL", apiKey: "API-Schlüssel", model: "Modell", test: "Test", other: "OpenAI-kompatibel",
|
||||
pick: "Das Modell ist das unten gewählte.",
|
||||
},
|
||||
};
|
||||
const LANG = (() => {
|
||||
for (const l of navigator.languages || [navigator.language || "en"]) {
|
||||
const s = String(l).toLowerCase();
|
||||
if (s.startsWith("zh")) return /hant|tw|hk|mo/.test(s) ? "zh-TW" : "zh";
|
||||
if (s.startsWith("ja")) return "ja";
|
||||
if (s.startsWith("de")) return "de";
|
||||
if (s.startsWith("en")) return "en";
|
||||
}
|
||||
return "en";
|
||||
})();
|
||||
const t = (k, v) => String(STR[LANG][k] ?? STR.en[k] ?? k).replace(/\{(\w+)\}/g, (_, n) => (v && n in v ? v[n] : ""));
|
||||
document.documentElement.lang = LANG;
|
||||
document.querySelectorAll("[data-t]").forEach((e) => { e.textContent = t(e.dataset.t); });
|
||||
document.title = t("title") + " · magpie";
|
||||
const $ = (id) => document.getElementById(id);
|
||||
$("filter").placeholder = t("filter");
|
||||
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
|
||||
|
||||
// the gateway's address is where this page was opened, less "/me": a
|
||||
// reverse proxy that serves magpie under a path keeps it
|
||||
const BASE = location.origin + location.pathname.replace(/\/me\/?$/, "");
|
||||
const PLACEHOLDER = "YOUR_GATEWAY_KEY";
|
||||
const STORE = "magpie-key";
|
||||
let key = "", data = null, model = "", tab = "claude";
|
||||
const store = {
|
||||
get() { try { return sessionStorage.getItem(STORE) || ""; } catch { return ""; } },
|
||||
set(v) { try { v ? sessionStorage.setItem(STORE, v) : sessionStorage.removeItem(STORE); } catch {} },
|
||||
};
|
||||
|
||||
const nf = new Intl.NumberFormat(LANG, { notation: "compact", maximumFractionDigits: 1 });
|
||||
const usd = (n) => "$" + (n >= 100 ? n.toFixed(0) : n.toFixed(2));
|
||||
const total = (u) => (u.input || 0) + (u.output || 0) + (u.cache_read || 0) + (u.cache_write || 0);
|
||||
const when = (s) => new Date(s).toLocaleString(LANG, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
async function load(k) {
|
||||
const res = await fetch(BASE + "/v1/magpie/me", { headers: { Authorization: "Bearer " + k }, cache: "no-store", credentials: "omit", referrerPolicy: "no-referrer" });
|
||||
if (res.ok) return { ok: true, body: await res.json() };
|
||||
return { ok: false, status: res.status };
|
||||
}
|
||||
function why(status) {
|
||||
if (status === 401) return t("bad");
|
||||
if (status === 429) return t("many");
|
||||
if (status === 403) return t("notShared");
|
||||
return t("net");
|
||||
}
|
||||
|
||||
$("form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const k = $("key").value.trim();
|
||||
if (!k) return $("key").focus();
|
||||
$("go").disabled = true;
|
||||
$("err").hidden = true;
|
||||
try {
|
||||
const r = await load(k);
|
||||
if (!r.ok) { $("err").textContent = why(r.status); $("err").hidden = false; return; }
|
||||
key = k; store.set(k); $("key").value = "";
|
||||
show(r.body);
|
||||
} catch { $("err").textContent = t("net"); $("err").hidden = false; }
|
||||
finally { $("go").disabled = false; }
|
||||
});
|
||||
$("forget").onclick = () => {
|
||||
key = ""; data = null; store.set("");
|
||||
$("info").hidden = true; $("signin").hidden = false; $("key").focus();
|
||||
};
|
||||
$("refresh").onclick = async () => {
|
||||
$("err2").hidden = true;
|
||||
try {
|
||||
const r = await load(key);
|
||||
if (r.ok) return show(r.body);
|
||||
if (r.status === 401) return $("forget").onclick();
|
||||
$("err2").textContent = why(r.status); $("err2").hidden = false;
|
||||
} catch { $("err2").textContent = t("net"); $("err2").hidden = false; }
|
||||
};
|
||||
$("withKey").onchange = () => drawSetup();
|
||||
$("filter").oninput = () => drawModels();
|
||||
|
||||
function show(d) {
|
||||
data = d;
|
||||
$("signin").hidden = true; $("info").hidden = false;
|
||||
$("name").textContent = d.name || "—";
|
||||
drawLimits(); drawUsage();
|
||||
const ids = (d.models || []).map((m) => m.id);
|
||||
// the one it called most (its vendor's name for it) is picked first
|
||||
const used = (d.topModels || []).map((s) => ids.find((id) => id === s.id || id.endsWith("/" + s.id))).find(Boolean);
|
||||
if (!ids.includes(model)) model = used || ids[0] || "";
|
||||
$("setupBlock").hidden = !!d.readOnly; $("readOnly").hidden = !d.readOnly;
|
||||
drawTabs(); drawSetup(); drawModels();
|
||||
}
|
||||
|
||||
function drawLimits() {
|
||||
const box = $("limits");
|
||||
box.replaceChildren();
|
||||
const ls = data.limits || [];
|
||||
if (!ls.length) return box.append(el("p", "sub", t("noLimit")));
|
||||
for (const l of ls) {
|
||||
const row = el("div", "limit");
|
||||
const head = el("div", "row");
|
||||
const name = l.period === "days" ? t("days", { n: l.days }) : l.period === "hours" ? t("hours", { n: l.hours }) : t(l.period);
|
||||
head.append(el("strong", "grow", name));
|
||||
if (l.spent) head.append(el("span", "tag bad", t("spent")));
|
||||
row.append(head);
|
||||
const caps = [];
|
||||
if (l.tokenLimit) caps.push([l.tokens / l.tokenLimit, t("tokensOf", { a: nf.format(l.tokens), b: nf.format(l.tokenLimit) })]);
|
||||
if (l.costLimit) caps.push([l.cost / l.costLimit, t("costOf", { a: usd(l.cost), b: usd(l.costLimit) })]);
|
||||
for (const [f, text] of caps) {
|
||||
const bar = el("div", "bar" + (f >= 1 ? " full" : ""));
|
||||
const fill = el("i");
|
||||
fill.style.width = Math.min(100, Math.max(0, f * 100)).toFixed(1) + "%";
|
||||
bar.append(fill);
|
||||
bar.setAttribute("role", "progressbar");
|
||||
bar.setAttribute("aria-valuenow", String(Math.round(Math.min(1, f) * 100)));
|
||||
row.append(bar, el("div", "sub num", text));
|
||||
}
|
||||
if (l.reset && !l.reset.startsWith("0001")) row.append(el("div", "note", t("resets", { t: when(l.reset) })));
|
||||
box.append(row);
|
||||
}
|
||||
}
|
||||
|
||||
function drawUsage() {
|
||||
const box = $("stats");
|
||||
box.replaceChildren();
|
||||
const u = data.usage || {};
|
||||
for (const [p, k] of [["today", "today"], ["7d", "d7"], ["30d", "d30"]]) {
|
||||
const s = u[p] || {};
|
||||
const c = el("div", "stat");
|
||||
c.append(el("div", "k", t(k)), el("div", "v", nf.format(total(s))), el("div", "s", t("tokens") + " · " + t("calls", { n: nf.format(s.calls || 0) })));
|
||||
if (s.cost) c.append(el("div", "s", t("cost", { c: usd(s.cost) })));
|
||||
box.append(c);
|
||||
}
|
||||
const top = $("top");
|
||||
top.replaceChildren();
|
||||
for (const s of data.topModels || []) {
|
||||
const li = el("li");
|
||||
li.append(el("span", "mono grow", s.id), el("span", "sub num", nf.format(total(s)) + " " + t("tokens")));
|
||||
top.append(li);
|
||||
}
|
||||
if (!top.children.length) top.append(el("li", "empty", t("none")));
|
||||
}
|
||||
|
||||
const TABS = [["claude", "Claude Code"], ["codex", "Codex"], ["openai", null], ["curl", null]];
|
||||
function drawTabs() {
|
||||
const box = $("tabs");
|
||||
box.replaceChildren();
|
||||
for (const [id, name] of TABS) {
|
||||
const b = el("button", "", name || t(id === "openai" ? "other" : "test"));
|
||||
b.type = "button";
|
||||
b.setAttribute("role", "tab");
|
||||
b.dataset.tab = id;
|
||||
b.setAttribute("aria-selected", String(id === tab));
|
||||
b.onclick = () => { tab = id; drawTabs(); drawSetup(); };
|
||||
box.append(b);
|
||||
}
|
||||
}
|
||||
|
||||
function copyBtn(text) {
|
||||
const b = el("button", "copy", t("copy"));
|
||||
b.type = "button";
|
||||
b.onclick = async () => {
|
||||
try { await navigator.clipboard.writeText(text); }
|
||||
catch {
|
||||
const a = el("textarea"); a.value = text; document.body.append(a); a.select();
|
||||
try { document.execCommand("copy"); } catch {}
|
||||
a.remove();
|
||||
}
|
||||
b.textContent = t("copied");
|
||||
setTimeout(() => { b.textContent = t("copy"); }, 1500);
|
||||
};
|
||||
return b;
|
||||
}
|
||||
|
||||
const q = (s) => JSON.stringify(s);
|
||||
function drawSetup() {
|
||||
const box = $("snip");
|
||||
box.replaceChildren();
|
||||
const k = $("withKey").checked ? key : PLACEHOLDER;
|
||||
const m = model || "MODEL_ID";
|
||||
const v1 = BASE + "/v1";
|
||||
const block = (file, text) => {
|
||||
const s = el("div", "snip");
|
||||
const h = el("div", "row");
|
||||
h.append(el("div", "file mono grow", file || ""), copyBtn(text));
|
||||
s.append(h, el("pre", "", text));
|
||||
box.append(s);
|
||||
};
|
||||
if (tab === "claude") {
|
||||
$("tabNote").textContent = t("claudeNote") + " " + t("pick");
|
||||
block("~/.claude/settings.json", JSON.stringify({ env: {
|
||||
ANTHROPIC_BASE_URL: BASE, ANTHROPIC_AUTH_TOKEN: k, ANTHROPIC_MODEL: m,
|
||||
ANTHROPIC_DEFAULT_OPUS_MODEL: m, ANTHROPIC_DEFAULT_SONNET_MODEL: m, ANTHROPIC_DEFAULT_HAIKU_MODEL: m,
|
||||
} }, null, 2));
|
||||
} else if (tab === "codex") {
|
||||
$("tabNote").textContent = t("codexNote") + " " + t("pick");
|
||||
block("~/.codex/config.toml", [
|
||||
"model = " + q(m), 'model_provider = "magpie"', "",
|
||||
"[model_providers.magpie]", 'name = "magpie"', "base_url = " + q(v1), 'wire_api = "responses"', "experimental_bearer_token = " + q(k),
|
||||
].join("\n"));
|
||||
} else if (tab === "openai") {
|
||||
$("tabNote").textContent = t("oaiNote");
|
||||
const kv = el("div", "kv");
|
||||
for (const [name, v] of [[t("base"), v1], [t("apiKey"), k], [t("model"), m]]) kv.append(el("span", "k sub", name), el("code", "", v), copyBtn(v));
|
||||
box.append(kv);
|
||||
} else {
|
||||
$("tabNote").textContent = t("curlNote");
|
||||
const body = JSON.stringify({ model: m, messages: [{ role: "user", content: "Say hi" }] });
|
||||
block("", "curl " + v1 + "/chat/completions \\\n -H " + sh("Authorization: Bearer " + k) + " \\\n -H 'Content-Type: application/json' \\\n -d " + sh(body));
|
||||
}
|
||||
}
|
||||
const sh = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
|
||||
|
||||
function drawModels() {
|
||||
const box = $("models");
|
||||
box.replaceChildren();
|
||||
const all = data?.models || [];
|
||||
if (!all.length) return box.append(el("div", "empty", t("noModels")));
|
||||
const f = $("filter").value.trim().toLowerCase();
|
||||
for (const mo of all) {
|
||||
if (f && !mo.id.toLowerCase().includes(f) && !(mo.label || "").toLowerCase().includes(f)) continue;
|
||||
const b = el("button");
|
||||
b.type = "button";
|
||||
b.setAttribute("role", "radio");
|
||||
b.setAttribute("aria-checked", String(mo.id === model));
|
||||
b.dataset.id = mo.id;
|
||||
const txt = el("span", "grow");
|
||||
txt.append(el("div", "mono", mo.id));
|
||||
if (mo.label && mo.label !== mo.id) txt.append(el("div", "lbl", mo.label));
|
||||
b.append(el("span", "chk", mo.id === model ? "✓" : ""), txt);
|
||||
b.onclick = () => { model = mo.id; drawModels(); drawSetup(); };
|
||||
box.append(b);
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const k = store.get();
|
||||
if (!k) return $("key").focus();
|
||||
try {
|
||||
const r = await load(k);
|
||||
if (r.ok) { key = k; return show(r.body); }
|
||||
if (r.status === 401) store.set("");
|
||||
} catch {}
|
||||
$("key").focus();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -367,6 +367,12 @@ func lanGuard(next http.Handler) http.Handler {
|
||||
http.Error(w, "magpie isn't shared on the local network", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// the key page itself is the same bytes for everyone, so it is
|
||||
// opened before the key it asks for is typed; its data isn't
|
||||
if remote && keyPageOpen(r) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if remote || managedKey(r) {
|
||||
var ok bool
|
||||
r, ok = identifyCaller(w, r)
|
||||
|
||||
@@ -28,6 +28,9 @@ var clientPrefixes = []string{
|
||||
"/models", "/chat/completions", "/responses", "/messages",
|
||||
"/images", "/embeddings", "/rerank", "/audio", "/videos",
|
||||
"/muse-code/models", CodexPath, AlphaSearchPath, "/mcp",
|
||||
// the key page (KeyPagePath): a key's holder opens it at the address
|
||||
// they give their agents
|
||||
KeyPagePath,
|
||||
}
|
||||
|
||||
// ClientPath: p is one of the gateway's client routes, which `magpie web`
|
||||
|
||||
@@ -34,6 +34,8 @@ var readOnlyRoutes = map[string]bool{
|
||||
"GET /v1/magpie/usage/requests": true,
|
||||
"GET /v1/magpie/limit": true,
|
||||
"GET /v1/magpie/concurrency": true,
|
||||
"GET " + KeyPagePath: true,
|
||||
"GET " + keyPageData: true,
|
||||
}
|
||||
|
||||
// ReadOnlyCode is the error code a read-only key is refused a route with.
|
||||
|
||||
@@ -444,6 +444,8 @@ const I18N = {
|
||||
"Gateway key rotated. Update clients on other computers.": "网关密钥已轮换,请更新其他电脑上的客户端。",
|
||||
"Add gateway key": "添加网关密钥",
|
||||
"Create a gateway key for each client. Usage is counted separately for each key.": "为每个客户端创建一个网关密钥,分别统计用量。",
|
||||
"Key holders see their usage and setup at": "密钥持有人可在此查看自己的用量和配置方法:",
|
||||
"Key page": "密钥页面",
|
||||
"Gateway keys are for other computers, and for a tunnel to this one such as Cloudflare Tunnel: they are added here once Share on local network is on. Agents on this computer need none.": "网关密钥给其他电脑用,也给连到这台电脑的隧道(如 Cloudflare Tunnel)用:打开「局域网共享」后在这里添加。这台电脑上的 Agent 不需要密钥。",
|
||||
"Gateway key name": "网关密钥名称",
|
||||
"Key name, e.g. Laptop": "密钥名称,例如笔记本",
|
||||
@@ -4645,6 +4647,8 @@ const I18N = {
|
||||
"Gateway key rotated. Update clients on other computers.": "閘道金鑰已輪換,請更新其他電腦上的用戶端。",
|
||||
"Add gateway key": "新增閘道金鑰",
|
||||
"Create a gateway key for each client. Usage is counted separately for each key.": "為每個用戶端建立一個閘道金鑰,分別統計用量。",
|
||||
"Key holders see their usage and setup at": "金鑰持有人可在此查看自己的用量和設定方法:",
|
||||
"Key page": "金鑰頁面",
|
||||
"Gateway keys are for other computers, and for a tunnel to this one such as Cloudflare Tunnel: they are added here once Share on local network is on. Agents on this computer need none.": "閘道金鑰給其他電腦用,也給連到這臺電腦的通道(如 Cloudflare Tunnel)用:開啟「區域網共享」後在這裡新增。這臺電腦上的 Agent 不需要金鑰。",
|
||||
"Gateway key name": "閘道金鑰名稱",
|
||||
"Key name, e.g. Laptop": "金鑰名稱,例如筆記本",
|
||||
@@ -8808,6 +8812,8 @@ const I18N = {
|
||||
"Gateway key rotated. Update clients on other computers.": "ゲートウェイキーを更新しました。他のコンピュータのクライアントを更新してください。",
|
||||
"Add gateway key": "ゲートウェイキーを追加",
|
||||
"Create a gateway key for each client. Usage is counted separately for each key.": "クライアントごとにゲートウェイキーを作成してください。使用量はキーごとに集計されます。",
|
||||
"Key holders see their usage and setup at": "キーの持ち主はここで自分の使用量と設定方法を確認できます:",
|
||||
"Key page": "キーのページ",
|
||||
"Gateway keys are for other computers, and for a tunnel to this one such as Cloudflare Tunnel: they are added here once Share on local network is on. Agents on this computer need none.": "ゲートウェイキーは他のコンピュータや、Cloudflare Tunnel などこのコンピュータへのトンネル用です。「ローカルネットワークで共有」をオンにするとここで追加できます。このコンピュータのエージェントには不要です。",
|
||||
"Gateway key name": "ゲートウェイキー名",
|
||||
"Key name, e.g. Laptop": "キー名(例:ノートPC)",
|
||||
@@ -12988,6 +12994,8 @@ const I18N = {
|
||||
"Gateway key rotated. Update clients on other computers.": "Zugangsschlüssel erneuert. Aktualisieren Sie die Clients auf anderen Computern.",
|
||||
"Add gateway key": "Zugangsschlüssel hinzufügen",
|
||||
"Create a gateway key for each client. Usage is counted separately for each key.": "Erstellen Sie für jeden Client einen Zugangsschlüssel. Die Nutzung wird je Schlüssel getrennt gezählt.",
|
||||
"Key holders see their usage and setup at": "Wer einen Schlüssel hat, sieht Nutzung und Einrichtung hier:",
|
||||
"Key page": "Schlüsselseite",
|
||||
"Gateway keys are for other computers, and for a tunnel to this one such as Cloudflare Tunnel: they are added here once Share on local network is on. Agents on this computer need none.": "Zugangsschlüssel sind für andere Computer und für einen Tunnel zu diesem Computer wie Cloudflare Tunnel: Sie werden hier hinzugefügt, sobald „Im lokalen Netzwerk freigeben“ an ist. Agenten auf diesem Computer brauchen keinen.",
|
||||
"Gateway key name": "Name des Zugangsschlüssels",
|
||||
"Key name, e.g. Laptop": "Schlüsselname, z. B. Laptop",
|
||||
|
||||
@@ -230,6 +230,22 @@ function renderGatewayKeys() {
|
||||
if (gatewayKeyDraft !== null) list.append(gatewayKeyForm());
|
||||
else if (!gatewayKeys.length) list.append(el("div", "none", t("No gateway keys yet")));
|
||||
box.append(list);
|
||||
const page = gatewayKeyPage();
|
||||
if (page) box.append(page);
|
||||
}
|
||||
|
||||
// the key page (the gateway's /me): where a key's holder, with their key
|
||||
// alone, sees what it has used and may use and the setup for their agents
|
||||
// (zytszone on X: a department shares one magpie, whose app its people
|
||||
// can't be given). Its address is the one other machines reach.
|
||||
function gatewayKeyPage() {
|
||||
const g = providers?.gateway, lan = g?.lanURLs || [];
|
||||
const at = g?.publicURL || (lan.includes(connectURL) ? connectURL : lan[0]);
|
||||
if (!at || !gatewayKeys?.length) return null;
|
||||
const url = at.replace(/\/+$/, "") + "/me";
|
||||
const p = el("div", "usage-note gw-key-page");
|
||||
p.append(el("span", "", t("Key holders see their usage and setup at")), " ", el("code", "", url), copyBtn(url, t("Key page")));
|
||||
return p;
|
||||
}
|
||||
|
||||
const ROTATE_GLYPH = "M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3.25h-3.25";
|
||||
|
||||
@@ -47,6 +47,18 @@ a live gateway.
|
||||
|
||||
## Gateway Caller Keys
|
||||
|
||||
`key-page.test.cjs` drives the gateway's key page (`/me`,
|
||||
`internal/gateway/keypage.html`, under the gateway's CSP) at 390px in
|
||||
Chromium and WebKit and every language: a wrong key is told so in the
|
||||
page's language and shows nothing; the right one shows its limit, its
|
||||
usage and most used model, picks that model, and gives Claude Code, Codex,
|
||||
OpenAI-compatible and curl setup at the address the page was opened at,
|
||||
with a placeholder until "Put my key in the setup" is ticked. A reload
|
||||
keeps the key in the tab, Forget takes it away, and no request carries the
|
||||
key in its address. A read-only key gets no setup. Gateway → Gateway keys
|
||||
shows the page's address (the LAN one, or `MAGPIE_PUBLIC_URL`) with a
|
||||
Copy, translated, and nothing with no key.
|
||||
|
||||
`gateway-keys-empty.test.cjs` checks the Gateway page with no gateway key
|
||||
yet, as magpie web on a 390px phone: "No gateway keys yet" sits inside the
|
||||
list's card, inset from its edges, in the muted colour and size of Recent
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { fixture } = require("./fixtures/caller-keys.cjs");
|
||||
|
||||
// zytszone on X: magpie shared with a whole department, whose people can't
|
||||
// be given the admin's app. Each opens the gateway's /me with their own
|
||||
// gateway key and sees that key's limits, usage and models, and the setup
|
||||
// for Claude Code, Codex and an OpenAI-compatible client with the address
|
||||
// they opened it at. The page is the gateway's own file
|
||||
// (internal/gateway/keypage.html), served as the gateway serves it, under
|
||||
// its Content-Security-Policy; its data is a fixture that answers only the
|
||||
// key sent as Authorization, never in the address.
|
||||
const html = fs.readFileSync(path.resolve(__dirname, "../../gateway/keypage.html"), "utf8");
|
||||
const CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
||||
const KEY = "sk-magpie-alice-0123456789";
|
||||
const BASE = "http://gw.test:3999";
|
||||
const ME = {
|
||||
name: "Alice", readOnly: false, version: "dev",
|
||||
limits: [{ period: "day", start: "2026-10-30T00:00:00Z", reset: "2026-10-31T00:00:00Z", calls: 4, tokens: 750, cost: 0, tokenLimit: 1000, tokensLeft: 250, costLeft: 0, spent: false }],
|
||||
usage: {
|
||||
today: { calls: 4, errors: 0, input: 600, output: 150, cache_read: 0, cache_write: 0, cost: 0.12, unpriced: 0 },
|
||||
"7d": { calls: 9, errors: 0, input: 1200, output: 300, cache_read: 0, cache_write: 0, cost: 0.3, unpriced: 0 },
|
||||
"30d": { calls: 20, errors: 1, input: 3000, output: 700, cache_read: 500, cache_write: 0, cost: 0.8, unpriced: 0 },
|
||||
},
|
||||
topModels: [{ id: "m2", calls: 12, errors: 0, input: 2000, output: 500, cache_read: 0, cache_write: 0, cost: 0.5, unpriced: 0 }],
|
||||
models: [{ id: "plan/m1", label: "m1 · Plan" }, { id: "plan/m2", label: "m2 · Plan" }],
|
||||
};
|
||||
const TITLE = { en: "Your gateway key", zh: "你的网关密钥", "zh-TW": "你的閘道金鑰", ja: "あなたのゲートウェイキー", de: "Ihr Zugangsschlüssel" };
|
||||
const LOCALE = { en: "en-US", zh: "zh-CN", "zh-TW": "zh-TW", ja: "ja-JP", de: "de-DE" };
|
||||
|
||||
async function open(engine, lang, me = ME) {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width: 390, height: 844 }, locale: LOCALE[lang], reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
const seen = { urls: [], errors: [] };
|
||||
page.on("pageerror", (e) => seen.errors.push(e.message));
|
||||
page.on("request", (r) => seen.urls.push(r.url()));
|
||||
await page.route("**/*", (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
if (url.pathname === "/me") return route.fulfill({ contentType: "text/html; charset=utf-8", headers: { "Content-Security-Policy": CSP }, body: html });
|
||||
if (url.pathname === "/v1/magpie/me") {
|
||||
if (url.searchParams.has("key")) return route.fulfill({ status: 400, json: {} });
|
||||
if (req.headers().authorization !== "Bearer " + KEY) return route.fulfill({ status: 401, json: { error: { message: "no" } } });
|
||||
return route.fulfill({ json: me });
|
||||
}
|
||||
return route.fulfill({ status: 404, body: "" });
|
||||
});
|
||||
await page.goto(BASE + "/me");
|
||||
return { browser, page, seen };
|
||||
}
|
||||
|
||||
const signIn = async (page, key) => {
|
||||
await page.fill("#key", key);
|
||||
await page.click("#go");
|
||||
};
|
||||
const snippet = (page) => page.locator("#snip pre").first().textContent();
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
test(`${engine} ${lang}: a key's holder sees their own key and its setup`, async (t) => {
|
||||
const { browser, page, seen } = await open(engine, lang);
|
||||
t.after(() => browser.close());
|
||||
assert.equal(await page.locator("#signin h1").textContent(), TITLE[lang]);
|
||||
// a wrong key is told so, in the page's language, and shows nothing
|
||||
await signIn(page, "sk-magpie-wrong");
|
||||
await page.locator("#err").waitFor();
|
||||
const err = await page.locator("#err").textContent();
|
||||
assert.ok(err.length > 10, err);
|
||||
if (lang !== "en") assert.doesNotMatch(err, /enabled gateway key/);
|
||||
assert.equal(await page.locator("#info").isHidden(), true);
|
||||
await signIn(page, KEY);
|
||||
await page.locator("#info").waitFor();
|
||||
assert.equal(await page.locator("#name").textContent(), "Alice");
|
||||
assert.equal(await page.locator("#key").inputValue(), "", "the key is taken out of the field");
|
||||
// its limit, with how much is used
|
||||
assert.equal(await page.locator("#limits .bar").count(), 1);
|
||||
assert.equal(await page.locator("#limits .bar").getAttribute("aria-valuenow"), "75");
|
||||
// its usage: three periods
|
||||
assert.equal(await page.locator("#stats .stat").count(), 3);
|
||||
assert.match(await page.locator("#top").textContent(), /m2/);
|
||||
// the model it called most is picked; the setup has the address it
|
||||
// was opened at and a placeholder, not the key
|
||||
assert.equal(await page.locator('#models button[aria-checked="true"]').getAttribute("data-id"), "plan/m2");
|
||||
let s = await snippet(page);
|
||||
const claude = JSON.parse(s);
|
||||
assert.equal(claude.env.ANTHROPIC_BASE_URL, BASE);
|
||||
assert.equal(claude.env.ANTHROPIC_MODEL, "plan/m2");
|
||||
assert.equal(claude.env.ANTHROPIC_AUTH_TOKEN, "YOUR_GATEWAY_KEY");
|
||||
await page.check("#withKey");
|
||||
assert.equal(JSON.parse(await snippet(page)).env.ANTHROPIC_AUTH_TOKEN, KEY);
|
||||
// Codex: its provider at /v1, the picked model
|
||||
await page.click('#tabs [data-tab="codex"]');
|
||||
await page.click('#models [data-id="plan/m1"]');
|
||||
s = await snippet(page);
|
||||
assert.match(s, /^model = "plan\/m1"\nmodel_provider = "magpie"\n/);
|
||||
assert.match(s, /base_url = "http:\/\/gw\.test:3999\/v1"/);
|
||||
assert.match(s, /wire_api = "responses"/);
|
||||
assert.match(s, new RegExp(`experimental_bearer_token = "${KEY}"`));
|
||||
await page.click('#tabs [data-tab="openai"]');
|
||||
assert.deepEqual(await page.locator("#snip .kv code").allTextContents(), [BASE + "/v1", KEY, "plan/m1"]);
|
||||
await page.click('#tabs [data-tab="curl"]');
|
||||
assert.match(await snippet(page), /curl http:\/\/gw\.test:3999\/v1\/chat\/completions/);
|
||||
// filtering the models
|
||||
await page.fill("#filter", "m1");
|
||||
assert.equal(await page.locator("#models button").count(), 1);
|
||||
// nothing sideways at a phone's width
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
|
||||
// a reload in the tab keeps it; Forget takes it away
|
||||
await page.reload();
|
||||
await page.locator("#info").waitFor();
|
||||
await page.click("#forget");
|
||||
await page.locator("#signin").waitFor();
|
||||
assert.equal(await page.evaluate(() => sessionStorage.getItem("magpie-key")), null);
|
||||
await page.reload();
|
||||
await page.locator("#signin").waitFor();
|
||||
assert.equal(await page.locator("#info").isHidden(), true);
|
||||
// the key never went in an address
|
||||
assert.deepEqual(seen.urls.filter((u) => u.includes("alice") || u.includes("key=")), []);
|
||||
assert.deepEqual(seen.errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
test(`${engine}: a read-only key is shown its usage and no setup`, async (t) => {
|
||||
const { browser, page } = await open(engine, "en", { ...ME, readOnly: true, models: [], limits: [] });
|
||||
t.after(() => browser.close());
|
||||
await signIn(page, KEY);
|
||||
await page.locator("#info").waitFor();
|
||||
assert.equal(await page.locator("#setupBlock").isHidden(), true);
|
||||
assert.equal(await page.locator("#readOnly").isVisible(), true);
|
||||
assert.equal(await page.locator("#limits").textContent(), "No limit on this key.");
|
||||
});
|
||||
|
||||
// the admin finds the page's address under the gateway keys, the one
|
||||
// other machines reach, and copies it
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
test(`${engine} ${lang}: the gateway keys say where their holders look`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width: 390, height: 844 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", fixture(lang, "light", [], { lan: true, web: true }));
|
||||
await page.goto("http://magpie.test/?view=gateway");
|
||||
const line = page.locator("#gatewayKeys .gw-key-page");
|
||||
await line.waitFor();
|
||||
assert.equal(await line.locator("code").textContent(), "http://192.168.1.10:3999/me");
|
||||
const text = await line.locator("span").first().textContent();
|
||||
if (lang === "en") assert.equal(text, "Key holders see their usage and setup at");
|
||||
else assert.notEqual(text, "Key holders see their usage and setup at");
|
||||
assert.equal(await line.locator("button.copy").count(), 1);
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
test(`${engine}: MAGPIE_PUBLIC_URL is the address given, and no keys gives none`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const ctx = await browser.newContext({ viewport: { width: 1000, height: 800 }, reducedMotion: "reduce" });
|
||||
let page = await ctx.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.route("**/*", fixture("en", "light", [], { lan: true, web: true, publicURL: "https://ai.corp.example" }));
|
||||
await page.goto("http://magpie.test/?view=gateway");
|
||||
await page.locator("#gatewayKeys .gw-key-page").waitFor();
|
||||
assert.equal(await page.locator("#gatewayKeys .gw-key-page code").textContent(), "https://ai.corp.example/me");
|
||||
page = await ctx.newPage();
|
||||
await page.route("**/*", fixture("en", "light", [], { lan: true, web: true, keys: [] }));
|
||||
await page.goto("http://magpie.test/?view=gateway");
|
||||
await page.locator("#gatewayKeys .none").waitFor();
|
||||
assert.equal(await page.locator("#gatewayKeys .gw-key-page").count(), 0);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user