gateway-key: rotating a key can give it a value of the user's own (isaac_bai)

isaac_bai on Discord: a gateway key's value is random, and only rotate
changes it, to another random one; they want to set one easy to pass on.
Adding a key could take an own value since 6b6113aa; an existing key
couldn't.

- access: rotate-key takes Change.Secret. Given, it is checked as an
  added key's own value (ownSecret: 8-256 printable ASCII, no space, not
  sk-magpie-, no other key's value; its own current value is allowed);
  empty, magpie makes one as before. The key keeps its id, name, limits,
  models and accounts, and Named counts a request from this computer
  with it as that key.
- ownSecret now refuses a value that is one of the user's provider keys
  (a provider's Key or any of its Keys, constant-time), for add-key too:
  a client sending it would spend that provider directly.
- CLI: `magpie gateway-key rotate <id> --key <value|->`; docs/reference.md.
- GUI (plugins/gateway/keys.js, outside the core budget): the Rotate key
  dialog has a hidden "Your own key (optional)" field; Enter rotates,
  Escape cancels; an own value says "Gateway key changed. Clients that
  send this key reach magpie now." Strings in zh, zh-TW, ja, de.

Tests: TestRotateToOwnValue (bad values refused, old value still works
after a refusal, trimmed own value authenticates as the same key, is
Named, listed masked; empty makes a new key; add-key refuses a provider
key). TestRotatedOwnValueKeepsTheKeysLimit: after rotating to an own
value the old one is 401 from another computer, the own one 200 from
another computer and from 127.0.0.1, and a 700-token day limit stops
the third request from either (429), every record under the key.
gateway-key-own-rotate.test.cjs: chromium and webkit, en/zh/zh-TW/ja/de,
1000 and 400px.

Run (mote): at the pushed head: TestCoreScriptBudget ok, ./internal/access ok, the
own-key/caller-key gateway tests ok. At f37742e14 with this change (no file the rebase touched):
gofmt -l clean; go vet GOOS=linux and windows (./internal/access ./internal/gateway, cli with
-tags nogui on linux) ok; ./internal/cli red on TestEveryRouteHasACommandOrIsNamed only,
/api/context/reply (#5026, 0872bc2a0, the same at main); GUI: gateway-key-own-rotate 20/20,
every gateway-key-*, redact-*, masking-*, privacy-* file and i18n-keys pass.
Broken by hand: the rotate own-value path off made TestRotateToOwnValue and
TestRotatedOwnValueKeepsTheKeysLimit red (401 from another computer); the provider-key check off
made TestRotateToOwnValue red ("accepted upstream-first-key").
Not run: the whole GUI suite (two runs lost: one to another run of this tree, one to mote
rebooting mid-run); it runs after the push. Not tried: a real client on another computer with
the own value, the real app.
This commit is contained in:
yetone
2026-11-03 20:17:00 +08:00
parent 7d022bdb63
commit d136d0fe98
10 changed files with 256 additions and 16 deletions
+6 -2
View File
@@ -620,8 +620,11 @@ starting with `sk-magpie-`, unlike any other key); left empty, magpie makes
one. The list shows only its last four characters, and it is counted,
limited and restricted as any other key, from this computer too.
Rename, disable, rotate or remove keys independently; rotation and removal
ask for confirmation. Rotation keeps the name, enabled state and usage
history; other keys are unchanged. While sharing is on, **Gateway → Connect**
ask for confirmation. Rotation keeps the name, enabled state, limits and usage
history; other keys are unchanged. Its dialog takes an optional value of
your own, checked as a new key's is (8–256 printable ASCII characters, no
spaces, not starting with `sk-magpie-`, no other gateway key's and none of
your providers' API keys); left empty, magpie makes one. While sharing is on, **Gateway → Connect**
offers loopback and shared addresses, plus enabled gateway keys, for all
connection examples. With sharing off, Connect keeps the original **API key**
field and local `magpie` token, without a gateway-key picker. Its arbitrary
@@ -634,6 +637,7 @@ magpie gateway-key add "Remote laptop" # prints the new credential once
magpie gateway-key add Family --key - # keeps a key clients already send, read from stdin
magpie gateway-key list # ids, names, enabled state and masked keys
magpie gateway-key rotate <id> # prints the replacement; identity stays the same
magpie gateway-key rotate <id> --key - # gives it a value of your own instead, read from stdin
magpie gateway-key remove <id> # revokes remote access
magpie gateway-key limit <id> week --tokens 2m --cost 5 # its own limit
magpie gateway-key limit <id> list # each limit, used, left and reset
+35 -6
View File
@@ -21,6 +21,7 @@ import (
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/filelock"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
@@ -105,9 +106,28 @@ func ownSecret(secret string, keys []Key) (string, error) {
return "", errors.New("Another gateway key already has this key")
}
}
if upstreamKey(secret) {
return "", errors.New("This is one of your providers' API keys: give the gateway key a value of its own")
}
return secret, nil
}
// upstreamKey: secret is a key magpie sends a provider, which a gateway
// key handed to others must never be.
func upstreamKey(secret string) bool {
for _, p := range provider.All() {
if p.Key != "" && subtle.ConstantTimeCompare([]byte(secret), []byte(p.Key)) == 1 {
return true
}
for _, k := range p.Keys {
if k.Key != "" && subtle.ConstantTimeCompare([]byte(secret), []byte(k.Key)) == 1 {
return true
}
}
}
return false
}
type Key struct {
ID string `json:"id"`
Name string `json:"name"`
@@ -347,8 +367,8 @@ type Change struct {
// keys under itself (Key.Issues).
Issues bool `json:"issues,omitempty"`
// Secret is the value "add-key" gives the new key, one its clients
// already send (love1sbug on X: keys handed out from another gateway);
// "" for one magpie makes.
// already send (love1sbug on X: keys handed out from another gateway),
// or "rotate-key" gives the key; "" for one magpie makes.
Secret string `json:"secret,omitempty"`
}
@@ -399,11 +419,20 @@ func Update(action string, in Change) (string, error) {
}
switch action {
case "rotate-key":
token, err := random(24)
if err != nil {
return "", err
// a value of the user's own (isaac_bai on Discord: one easy to
// remember and pass on), checked as add-key's is; none, a new
// one magpie makes
if in.Secret != "" {
if secret, err = ownSecret(in.Secret, slices.Delete(slices.Clone(keys), i, i+1)); err != nil {
return "", err
}
} else {
token, err := random(24)
if err != nil {
return "", err
}
secret = Prefix + token
}
secret = Prefix + token
keys[i].Secret = secret
case "rename-key":
keys[i].Name = name
+54
View File
@@ -9,6 +9,7 @@ import (
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
@@ -408,3 +409,56 @@ func TestAuthenticateTellsTheDefaultKey(t *testing.T) {
}
})
}
// A key magpie made can be given a value of the user's own when it is
// rotated (isaac_bai on Discord: one easy to remember and pass on),
// checked as add-key's is, and never a key magpie sends a provider.
func TestRotateToOwnValue(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
made, err := Update("add-key", Change{Name: "Family"})
if err != nil {
t.Fatal(err)
}
if _, err := Update("add-key", Change{Name: "Other", Secret: "other-key-of-mine"}); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-first-key", Keys: []provider.KeyAccount{{Key: "upstream-second-key"}}, Chat: "http://127.0.0.1:1/v1", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
keys, _ := List()
id := keys[0].ID
for _, bad := range []string{"short", "has a space in it", "非ascii-key-value", "sk-magpie-key-mine-1234", "other-key-of-mine", "upstream-first-key", "upstream-second-key", strings.Repeat("k", 257)} {
if _, err := Update("rotate-key", Change{Key: id, Secret: bad}); err == nil {
t.Fatalf("accepted %q", bad)
}
}
if who, ok := Authenticate(made); !ok || who.KeyName != "Family" {
t.Fatal("a refused value changed the key", who, ok)
}
const own = "family-easy-to-share"
got, err := Update("rotate-key", Change{Key: id, Secret: " " + own + "\n"})
if err != nil || got != own {
t.Fatal(got, err)
}
if who, ok := Authenticate(own); !ok || who.KeyName != "Family" || who.KeyID != id {
t.Fatal(who, ok)
}
if _, ok := Authenticate(made); ok || !Named(own) {
t.Fatal("the old value still works, or the new one isn't named")
}
if keys, _ := List(); keys[0].Masked != "…hare" || keys[0].Secret != "" {
t.Fatal(keys[0])
}
// its own value again is no other key's
if _, err := Update("rotate-key", Change{Key: id, Secret: own}); err != nil {
t.Fatal(err)
}
// none: magpie makes one again
if again, err := Update("rotate-key", Change{Key: id}); err != nil || !strings.HasPrefix(again, Prefix) {
t.Fatal(again, err)
}
// a new key can't take a provider's key either
if _, err := Update("add-key", Change{Name: "Leak", Secret: "upstream-first-key"}); err == nil {
t.Fatal("add-key took a provider's key")
}
}
+7 -3
View File
@@ -73,10 +73,11 @@ func gatewayKeysTo(out io.Writer, args []string) error {
}
}
// add <name> --key <value>: the key keeps a value its clients already
// send (love1sbug on X); "--key -" reads it from stdin, out of the
// send (love1sbug on X); rotate <id> --key <value> gives a key one
// (isaac_bai on Discord); "--key -" reads it from stdin, out of the
// shell's history
var own string
if action == "add" && len(args) == 4 && args[2] == "--key" {
if (action == "add" || action == "rotate") && len(args) == 4 && args[2] == "--key" {
own = args[3]
if own == "-" {
b, err := io.ReadAll(io.LimitReader(os.Stdin, 4096))
@@ -91,7 +92,7 @@ func gatewayKeysTo(out io.Writer, args []string) error {
args = args[:2]
}
if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) {
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] [--read-only] | rotate <id> | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off] | access <id> [read-only | full] | move <id> <place> | issue --ttl <duration> [--name <name>] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] | issuer <id> [on | off] | oidc [list | add --key <id> --repo owner/name … | remove <rule id>]")
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] [--read-only] | rotate <id> [--key <value> | --key -] | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off] | access <id> [read-only | full] | move <id> <place> | issue --ttl <duration> [--name <name>] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] | issuer <id> [on | off] | oidc [list | add --key <id> --repo owner/name … | remove <rule id>]")
}
switch action {
case "list", "add", "rotate", "remove":
@@ -148,6 +149,9 @@ func gatewayKeysTo(out io.Writer, args []string) error {
return w.Flush()
}
in := access.Change{Key: args[1]}
if action == "rotate" {
in.Secret = own
}
if action == "add" {
in = access.Change{Name: args[1], Secret: own, ReadOnly: readOnly}
}
+1 -1
View File
@@ -128,7 +128,7 @@ const usage = `magpie — one place to pick every agent's model
magpie cpu [<file>] [--seconds N] a Go CPU profile of the running magpie over 30s (5..120) while you use it, for a report of it using too much CPU
magpie goroutines [<file>] every goroutine of the running magpie, its stack and how long it waited, for a report of it stuck at something
magpie log [--path] [-n N] [-f] where magpie's logs are, to send with a report: the app's (app.log), the service's; -n prints the app log's last N lines, -f follows it
magpie gateway-key list|add <name> [--read-only]|rotate <id>|remove <id> manage the keys clients use to call a shared gateway
magpie gateway-key list|add <name> [--read-only]|rotate <id> [--key -]|remove <id> manage the keys clients use to call a shared gateway
magpie gateway-key limit <id> [list|off|reset [n]|remove <n>|[add] day|week|month|<N>d|<N>h --tokens N --cost USD --cache-reads] a key's own limits, and what it used
magpie gateway-key models <id> [all|<provider>/<model>|<provider>/* ...] the models a key may use, every one unless it names some
magpie gateway-key quotas <id> [on|off] whether a key held to a budget, models or accounts is told the quotas of what it may use
+51
View File
@@ -9,6 +9,7 @@ import (
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
@@ -77,3 +78,53 @@ func TestOwnKeyValueIsTheKey(t *testing.T) {
t.Fatal("a disabled key from another computer", code)
}
}
// A key magpie made, rotated to a value of the user's own (isaac_bai on
// Discord), is still that key: from another computer and from this one
// it is let in, counted as it and held to its limit, and its old value
// is refused.
func TestRotatedOwnValueKeepsTheKeysLimit(t *testing.T) {
fresh(t)
budget.Forget()
pinLimitClock(t)
calls := limitedUpstream(t, 0)
keys, secrets := newCaller(t, "Family")
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 700})
const own = "family-easy-to-share"
if _, err := access.Update("rotate-key", access.Change{Key: keys[0].ID, Secret: own}); err != nil {
t.Fatal(err)
}
h := lanGuard(New().Handler())
call := func(from, key string) int {
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq))
r.RemoteAddr = from
r.Header.Set("Authorization", "Bearer "+key)
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code
}
if code := call("192.0.2.7:4000", secrets[0]); code != http.StatusUnauthorized {
t.Fatal("the value it had", code)
}
if code := call("192.0.2.7:4000", own); code != 200 {
t.Fatal("from another computer", code)
}
if code := call("127.0.0.1:4000", own); code != 200 {
t.Fatal("from this computer", code)
}
// 700 tokens, 350 a call: the third is refused, from either computer
if code := call("192.0.2.7:4000", own); code != http.StatusTooManyRequests {
t.Fatal("past its limit from another computer", code)
}
if code := call("127.0.0.1:4000", own); code != http.StatusTooManyRequests {
t.Fatal("past its limit from this computer", code)
}
if calls.Load() != 2 {
t.Fatal("calls reached the provider:", calls.Load())
}
for _, rec := range usage.Load(time.Time{}) {
if rec.CallerKeyID != keys[0].ID {
t.Fatalf("not counted as the key: %+v", rec)
}
}
}
+8
View File
@@ -524,6 +524,8 @@ const I18N = {
"A key can have only letters, digits and ASCII symbols, no spaces": "密钥只能包含字母、数字和 ASCII 符号,不能有空格",
"A key of your own can't start with sk-magpie-: leave the key empty and magpie makes one": "自定义密钥不能以 sk-magpie- 开头:留空即可由 magpie 生成",
"Another gateway key already has this key": "已有其他网关密钥使用了这个密钥",
"This is one of your providers' API keys: give the gateway key a value of its own": "这是你某个供应商的 API 密钥:请给网关密钥另设一个值",
"Gateway key changed. Clients that send this key reach magpie now.": "网关密钥已修改,发送这个密钥的客户端现在就能连接 magpie。",
"Gateway key created. Use Copy on its row to connect a client.": "网关密钥已创建,用该行的复制按钮配置客户端。",
"Copy gateway key": "复制网关密钥",
"Rotate key": "轮换密钥",
@@ -5092,6 +5094,8 @@ const I18N = {
"A key can have only letters, digits and ASCII symbols, no spaces": "金鑰只能包含字母、數字和 ASCII 符號,不能有空格",
"A key of your own can't start with sk-magpie-: leave the key empty and magpie makes one": "自定義金鑰不能以 sk-magpie- 開頭:留空即可由 magpie 生成",
"Another gateway key already has this key": "已有其他閘道金鑰使用了這個金鑰",
"This is one of your providers' API keys: give the gateway key a value of its own": "這是你某個供應商的 API 金鑰:請給閘道金鑰另設一個值",
"Gateway key changed. Clients that send this key reach magpie now.": "閘道金鑰已修改,傳送這個金鑰的用戶端現在就能連線 magpie。",
"Gateway key created. Use Copy on its row to connect a client.": "閘道金鑰已建立,用該行的複製按鈕設定用戶端。",
"Copy gateway key": "複製閘道金鑰",
"Rotate key": "輪換金鑰",
@@ -9621,6 +9625,8 @@ const I18N = {
"A key can have only letters, digits and ASCII symbols, no spaces": "キーに使えるのは英数字と ASCII 記号だけで、空白は使えません",
"A key of your own can't start with sk-magpie-: leave the key empty and magpie makes one": "独自のキーは sk-magpie- で始められません。空欄にすると magpie が作成します",
"Another gateway key already has this key": "このキーは別のゲートウェイキーで使われています",
"This is one of your providers' API keys: give the gateway key a value of its own": "これはプロバイダの API キーです。ゲートウェイキーには別の値を設定してください",
"Gateway key changed. Clients that send this key reach magpie now.": "ゲートウェイキーを変更しました。このキーを送るクライアントはそのまま magpie に接続できます。",
"Gateway key created. Use Copy on its row to connect a client.": "ゲートウェイキーを作成しました。行のコピーを使ってクライアントを接続してください。",
"Copy gateway key": "ゲートウェイキーをコピー",
"Rotate key": "キーを再発行",
@@ -14168,6 +14174,8 @@ const I18N = {
"A key can have only letters, digits and ASCII symbols, no spaces": "Ein Schlüssel darf nur Buchstaben, Ziffern und ASCII-Zeichen enthalten, keine Leerzeichen",
"A key of your own can't start with sk-magpie-: leave the key empty and magpie makes one": "Ein eigener Schlüssel darf nicht mit sk-magpie- beginnen: leer lassen, dann erzeugt magpie einen",
"Another gateway key already has this key": "Ein anderer Zugangsschlüssel hat diesen Schlüssel schon",
"This is one of your providers' API keys: give the gateway key a value of its own": "Das ist ein API-Schlüssel eines Ihrer Anbieter: Geben Sie dem Zugangsschlüssel einen eigenen Wert",
"Gateway key changed. Clients that send this key reach magpie now.": "Zugangsschlüssel geändert. Clients, die diesen Schlüssel senden, erreichen magpie jetzt.",
"Gateway key created. Use Copy on its row to connect a client.": "Zugangsschlüssel erstellt. Mit „Kopieren“ in seiner Zeile einen Client verbinden.",
"Copy gateway key": "Zugangsschlüssel kopieren",
"Rotate key": "Schlüssel erneuern",
+13 -2
View File
@@ -356,6 +356,16 @@ function askGatewayKey(k, rotate) {
ed.append(head, el("p", "lib-confirm", t(rotate
? "Clients using {name} will need the new key. Its name and usage history stay the same."
: "Clients using {name} will lose access from other computers. Its usage history is kept.", { name: k.name })));
// a value of one's own in place of the one magpie makes (isaac_bai on
// Discord: one easy to remember and pass on)
let own = null;
if (rotate) {
own = input("", t("Your own key (optional)"), "password");
own.setAttribute("aria-label", t("Gateway key value"));
own.title = t("Leave empty and magpie makes a key. Or enter one your clients already send, from another gateway, so they keep working.");
own.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") go.click(); else if (e.key === "Escape") closeConfirmAsk(); };
ed.append(el("label", "", t("Gateway key")), own);
}
const bar = el("div", "bar");
const cancel = el("button", "text", t("Cancel"));
cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); };
@@ -364,10 +374,11 @@ function askGatewayKey(k, rotate) {
e.stopPropagation();
if (go.disabled) return;
go.disabled = true;
const out = await gatewayKeyAction(rotate ? "rotate-key" : "remove-key", { key: k.id });
const mine = !!own?.value.trim();
const out = await gatewayKeyAction(rotate ? "rotate-key" : "remove-key", mine ? { key: k.id, secret: own.value } : { key: k.id });
if (!out) { go.disabled = false; return; }
closeConfirmAsk();
if (rotate) status(t("Gateway key rotated. Update clients on other computers."), "ok");
if (rotate) status(t(mine ? "Gateway key changed. Clients that send this key reach magpie now." : "Gateway key rotated. Update clients on other computers."), "ok");
};
bar.append(el("span", "grow"), cancel, go);
ed.append(bar);
+4 -2
View File
@@ -140,10 +140,12 @@ function fixture(lang, theme, events, options = {}) {
}
if (action === "rename-key") k.name = body.name;
if (action === "rotate-key") {
secret = "fixture-rotated-" + (++rotations);
// a value of the user's own, checked as access.ownSecret does
if (body.secret !== undefined && body.secret.trim().length < 8) return route.fulfill({ status: 400, json: { error: "Use a key between 8 and 256 characters" } });
secret = body.secret?.trim() || "fixture-rotated-" + (++rotations);
secrets.set(k.id, secret);
if (k.id === lanKeyID) lanSecret = secret;
k.masked = "sk-magpie-key-…" + secret.slice(-6);
k.masked = body.secret ? "…" + secret.slice(-4) : "sk-magpie-key-…" + secret.slice(-6);
}
if (action === "remove-key") keys = keys.filter((v) => v !== k);
if (action === "on-key" || action === "off-key") k.off = action === "off-key";
@@ -0,0 +1,77 @@
// Rotating a gateway key can give it a value of the user's own in place of
// the one magpie makes (isaac_bai on Discord: one easy to remember and
// pass on), typed hidden, checked as a new key's is; left empty, magpie
// makes one as before.
const assert = require("node:assert/strict");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { fixture, keyAction } = require("./fixtures/caller-keys.cjs");
const words = {
en: { rotate: "Rotate key", own: "Gateway key value", placeholder: "Your own key (optional)", label: "Gateway key", changed: "Gateway key changed. Clients that send this key reach magpie now.", rotated: "Gateway key rotated. Update clients on other computers.", short: "Use a key between 8 and 256 characters" },
zh: { rotate: "轮换密钥", own: "网关密钥的值", placeholder: "自定义密钥(可选)", label: "网关密钥", changed: "网关密钥已修改,发送这个密钥的客户端现在就能连接 magpie。", rotated: "网关密钥已轮换,请更新其他电脑上的客户端。", short: "密钥长度需在 8 到 256 个字符之间" },
"zh-TW": { rotate: "輪換金鑰", own: "閘道金鑰的值", placeholder: "自定義金鑰(可選)", label: "閘道金鑰", changed: "閘道金鑰已修改,傳送這個金鑰的用戶端現在就能連線 magpie。", rotated: "閘道金鑰已輪換,請更新其他電腦上的用戶端。", short: "金鑰長度需在 8 到 256 個字元之間" },
ja: { rotate: "キーを再発行", own: "ゲートウェイキーの値", placeholder: "独自のキー(任意)", label: "ゲートウェイキー", changed: "ゲートウェイキーを変更しました。このキーを送るクライアントはそのまま magpie に接続できます。", rotated: "ゲートウェイキーを更新しました。他のコンピュータのクライアントを更新してください。", short: "キーは 8〜256 文字にしてください" },
de: { rotate: "Schlüssel erneuern", own: "Wert des Zugangsschlüssels", placeholder: "Eigener Schlüssel (optional)", label: "Zugangsschlüssel", changed: "Zugangsschlüssel geändert. Clients, die diesen Schlüssel senden, erreichen magpie jetzt.", rotated: "Zugangsschlüssel erneuert. Aktualisieren Sie die Clients auf anderen Computern.", short: "Der Schlüssel muss 8 bis 256 Zeichen lang sein" },
};
const said = (page, m) => page.waitForFunction((m) => document.body.textContent.includes(m), m);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
for (const width of [1000, 400]) {
test(`${engine} ${lang} ${width}px: rotate a gateway key to a value of one's own`, async (t) => {
const w = words[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(6000);
page.setDefaultNavigationTimeout(60000);
const events = [], errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", fixture(lang, "light", events, { lan: true }));
await page.goto("http://magpie.test/?view=gateway");
const row = page.locator('#gatewayKeys .acc[data-key="laptop"]');
await row.waitFor();
await keyAction(page, row, w.rotate);
const modal = page.locator("#modal");
const own = modal.locator('input[type="password"]');
await own.waitFor();
assert.equal(await own.getAttribute("placeholder"), w.placeholder);
assert.equal(await own.getAttribute("aria-label"), w.own);
assert.equal(await modal.locator(".editor .ebody > label").textContent(), w.label);
// the field fits the dialog, wide enough to type in, at either width
const box = await own.boundingBox(), dlg = await modal.locator(".editor").boundingBox();
assert(box.width >= 140, `field ${box.width}px wide`);
assert(box.x >= dlg.x && box.x + box.width <= dlg.x + dlg.width + 0.5, "field inside the dialog");
// a short value is refused and the dialog stays, with what was typed
await own.fill("short");
await own.press("Enter");
await said(page, w.short);
assert(await modal.isVisible(), "the dialog stays");
assert.equal(await own.inputValue(), "short");
assert.equal(events.filter((e) => e.action === "rotate-key").length, 1);
await own.fill("family-easy-to-share");
await modal.getByRole("button", { name: w.rotate, exact: true }).click();
await modal.waitFor({ state: "hidden" });
assert.deepEqual(events.filter((e) => e.action === "rotate-key").at(-1).body, { key: "laptop", secret: "family-easy-to-share" });
await said(page, w.changed);
await page.waitForFunction(() => document.querySelector('#gatewayKeys .acc[data-key="laptop"]')?.textContent.includes("…hare"));
assert.doesNotMatch(await page.locator("#gatewayKeys").textContent(), /family-easy/);
// the next rotation starts empty: magpie makes the key
await keyAction(page, row, w.rotate);
assert.equal(await own.inputValue(), "");
await modal.getByRole("button", { name: w.rotate, exact: true }).click();
await modal.waitFor({ state: "hidden" });
assert.deepEqual(events.filter((e) => e.action === "rotate-key").at(-1).body, { key: "laptop" });
await said(page, w.rotated);
// Remove asks with no field
await row.locator(".gw-key-more").click();
await page.locator(".row-menu [role=menuitem]").last().click();
await modal.locator(".editor").waitFor();
assert.equal(await modal.locator("input").count(), 0);
assert.deepEqual(errors, []);
});
}
}
}