Files
plugins/packages/inkstone/keys.test.mjs
T
我是一条没有名字的区 e7004d9354 inkstone 0.1.0: Intern InkStone (书生·端砚) Token Plan, browser sign-in, credit card and ink-* key chat (#775)
New package @magpie-community/opencode-inkstone-auth 0.1.0 for Intern
InkStone (书生·端砚, Shanghai AI Lab) Token Plan, provider id
`intern-inkstone`. Community package by yunwang2442-creator.

What it does:
- Browser sign-in (Edge/Chrome, its own profile under
  $XDG_CONFIG_HOME or ~/.config/magpie/inkstone-browser, or
  %LOCALAPPDATA%\magpie\inkstone-browser). The login window has no
  debugging port. A headless CDP read takes the uaa-token cookie, and the
  same read renews it silently later.
- Usage card: ink-credit balance, 5-hour and 7-day windows, credit packs.
- Chat: a pasted ink-* API key, or one the sign-in creates, named
  ink-<host4>-<acct4>-<rand4> (18 of the console's 20 characters). An
  idempotency clash (-15109) retries with a fresh name, up to three times.
  Pruning is on by default. It only touches this machine's and account's
  prefix, keeps the newest two and the key this sign-in created, and never
  deletes manual keys or keys of unknown age.
- Closing on Unix: SIGTERM, then SIGKILL only after a 15s grace. Leftover
  browsers are matched by --user-data-dir=<escaped profile>, and Windows
  uses .Contains().
- The login wait comes from an injected waitForLogin in tests. No env
  hook is left in production code.
- Hosts: discovery.intern-ai.org.cn, discovery-api.intern-ai.org.cn,
  127.0.0.1 (CDP).

Outside the package: scripts/opencode2.mjs lets a prompt with
`required: false` stay optional (`p.required !== false`). Every package's
copy is synced byte for byte, so all 39 copies in the merged tree are blob
afe074cb. No other package sets `required: false` on a prompt, so this
changes nothing for them. Also a root README row and a registry entry.

Review at 36412a15, on mote, HOME=$(mktemp -d), Bun 1.4.2:
- bun test packages/inkstone: 68 pass, 0 fail in Asia/Shanghai, UTC,
  America/Los_Angeles and Pacific/Kiritimati.
- bun scripts/check.mjs inkstone and bun scripts/check.mjs: ok.
- bun test (repo), on 36412a15 merged with origin/main e7cb9dc5:
  6743 pass, 20 skip, 0 fail. main has since moved by cline 0.1.14 and
  zcode 0.1.55 only, and none of the adapter copies changed.
- Broken by hand, each red: no protectName protection; prune_keys default
  off; no post-sign-in prune; no SIGTERM on close; the -15109 retry keeping
  its name.

Not tried: a real InkStone account sign-in on macOS, Linux or Windows (no
account here); a live chat request; magpie end to end with the plugin.
2026-11-07 15:07:06 +08:00

210 lines
8.6 KiB
JavaScript

// API-key lifecycle: the 20-character name, create on a blank prompt, the
// ten-key guard, optional pruning that never touches manual keys, and the
// one-time plaintext rule.
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { KEY_LIMIT, fingerprint } from "./lib/protocol.mjs"
import { HOST_TAG, ensureKey, keyNameFor, keyPrefixFor, pruneKeys } from "./lib/keys.mjs"
import { fakeInkStone, json, ok, fail } from "./fake.mjs"
let f
afterEach(() => f?.close())
const now = (n) => new Date(Date.UTC(2026, 10, 1, 0, 0, n)).toISOString()
function serveKeys(initial = []) {
const keys = initial.map((k) => ({ ...k }))
f.route("GET /v1/models", () => json({ object: "list", data: [] }))
f.route("GET /api/tokenplan/v1/keys", () => ok({ total: keys.length, items: keys }))
f.route("POST /api/tokenplan/v1/keys", (r) => {
const name = r.json?.name
keys.push({ id: `id-${keys.length + 1}`, name, status: "active", created_at: now(keys.length + 1) })
return ok({ key: "sk-new" })
})
return keys
}
test("a key name fits the console's 20-character limit and carries this host and account", () => {
const name = keyNameFor("u")
expect(name.length).toBeLessThanOrEqual(20)
expect(name.startsWith(keyPrefixFor("u"))).toBe(true)
expect(keyPrefixFor("u").startsWith("ink-")).toBe(true)
// the host segment comes from os.hostname() (4 hex — environment variables
// are absent in macOS GUI processes), the account segment is 4 hex, and the
// random tail is 4 hex: 1 byte only gave 256 names and two keys of one
// account collided
expect(keyPrefixFor("u")).toBe(`ink-${HOST_TAG}-${fingerprint("u").slice(0, 4)}-`)
expect(HOST_TAG).toHaveLength(4)
expect(fingerprint("u").slice(0, 4)).toHaveLength(4)
expect(name.length).toBe(keyPrefixFor("u").length + 4)
})
test("a pasted key is probed and used as-is, with no key created", async () => {
f = fakeInkStone()
serveKeys([])
expect(await ensureKey("uaa", "u", { apiKey: "sk-pasted", create: true })).toBe("sk-pasted")
expect(f.seen.some((r) => r.method === "POST" && r.path.endsWith("/keys"))).toBe(false)
})
test("a blank prompt creates one key with an idempotency key", async () => {
f = fakeInkStone()
serveKeys([])
expect(await ensureKey("uaa", "u", { create: true })).toBe("sk-new")
const post = f.seen.find((r) => r.method === "POST" && r.path.endsWith("/keys"))
expect(post.json.name.startsWith(keyPrefixFor("u"))).toBe(true)
expect(post.headers.get("idempotency-key")).toBeTruthy()
expect(post.json.name.length).toBeLessThanOrEqual(20)
})
test("an account at the ten-key limit is refused unless pruning is on", async () => {
f = fakeInkStone()
const keys = serveKeys(
Array.from({ length: KEY_LIMIT }, (_, i) => ({
id: `k${i}`,
name: `manual-${i}`,
status: "active",
created_at: now(i + 1),
})),
)
await expect(ensureKey("uaa", "u", { create: true })).rejects.toMatchObject({ code: "key_limit" })
expect(keys.length).toBe(KEY_LIMIT)
})
test("pruning frees a slot for a new key and deletes only this machine's old keys", async () => {
f = fakeInkStone()
const prefix = keyPrefixFor("u")
const keys = serveKeys([
{ id: "old", name: `${prefix}aaaa`, status: "active", created_at: now(1) },
{ id: "keep1", name: `${prefix}bbbb`, status: "active", created_at: now(2) },
{ id: "keep2", name: `${prefix}cccc`, status: "active", created_at: now(3) },
{ id: "manual", name: "my-own-key", status: "active", created_at: now(4) },
{ id: "unknown", name: `${prefix}dddd`, status: "active", created_at: "" },
])
const deleted = []
for (const k of keys) {
f.route("DELETE /api/tokenplan/v1/keys/" + k.id, () => {
deleted.push(k.id)
const i = keys.findIndex((x) => x.id === k.id)
if (i >= 0) keys.splice(i, 1)
return ok({})
})
}
const n = await pruneKeys("uaa", "u", { freeSlots: 0 })
expect(n).toBe(1)
expect(deleted).toEqual(["old"])
expect(keys.some((k) => k.id === "manual")).toBe(true)
expect(keys.some((k) => k.id === "unknown")).toBe(true)
})
test("pruning never deletes a key whose age is unknown, including created_at 0", async () => {
f = fakeInkStone()
const prefix = keyPrefixFor("u")
const keys = serveKeys([
{ id: "zero", name: `${prefix}aaaa`, status: "active", created_at: 0 },
{ id: "empty", name: `${prefix}bbbb`, status: "active", created_at: "" },
{ id: "keep1", name: `${prefix}cccc`, status: "active", created_at: now(1) },
])
const deleted = []
for (const k of keys) {
f.route("DELETE /api/tokenplan/v1/keys/" + k.id, () => {
deleted.push(k.id)
const i = keys.findIndex((x) => x.id === k.id)
if (i >= 0) keys.splice(i, 1)
return ok({})
})
}
const n = await pruneKeys("uaa", "u", { freeSlots: 0 })
expect(n).toBe(0)
expect(deleted).toEqual([])
expect(keys.length).toBe(3)
})
test("a freshly created key is protected by NAME even when it is the oldest of three", async () => {
f = fakeInkStone()
const prefix = keyPrefixFor("u")
// the newest two are newer; the protected one is the OLDEST — so keep:2
// alone could not save it, and only protectName does
const inUse = "oldest-in-use"
const keys = serveKeys([
{ id: "oldest", name: `${prefix}${inUse}`, status: "active", created_at: now(1) },
{ id: "mid", name: `${prefix}bbbb`, status: "active", created_at: now(2) },
{ id: "newest", name: `${prefix}cccc`, status: "active", created_at: now(3) },
])
const deleted = []
for (const k of keys) {
f.route("DELETE /api/tokenplan/v1/keys/" + k.id, () => {
deleted.push(k.id)
const i = keys.findIndex((x) => x.id === k.id)
if (i >= 0) keys.splice(i, 1)
return ok({})
})
}
const n = await pruneKeys("uaa", "u", { freeSlots: 0, protectName: `${prefix}${inUse}` })
// the protected key and the two newest survive; nothing older remains to delete
expect(n).toBe(0)
expect(deleted).toEqual([])
expect(keys.some((k) => k.id === "oldest")).toBe(true)
})
test("pruneKeys with a protected name really deletes the others when it should", async () => {
f = fakeInkStone()
const prefix = keyPrefixFor("u")
const keys = serveKeys([
{ id: "old1", name: `${prefix}aaaa`, status: "active", created_at: now(1) },
{ id: "old2", name: `${prefix}bbbb`, status: "active", created_at: now(2) },
{ id: "protected", name: `${prefix}cccc`, status: "active", created_at: now(3) },
{ id: "newest", name: `${prefix}dddd`, status: "active", created_at: now(4) },
])
const deleted = []
for (const k of keys) {
f.route("DELETE /api/tokenplan/v1/keys/" + k.id, () => {
deleted.push(k.id)
const i = keys.findIndex((x) => x.id === k.id)
if (i >= 0) keys.splice(i, 1)
return ok({})
})
}
const n = await pruneKeys("uaa", "u", { freeSlots: 0, protectName: `${prefix}aaaa` })
// keep:2 protects "newest" and "protected"; protectName adds "old1";
// only "old2" is a candidate. Drop protectName and this deletes 2 keys.
expect(n).toBe(1)
expect(deleted).toEqual(["old2"])
expect(keys.some((k) => k.id === "old1")).toBe(true)
})
test("a key created without a plaintext is a clear failure, not a silent empty key", async () => {
f = fakeInkStone()
f.route("GET /v1/models", () => json({ object: "list", data: [] }))
f.route("GET /api/tokenplan/v1/keys", () => ok({ total: 0, items: [] }))
f.route("POST /api/tokenplan/v1/keys", () => fail(-15108, "created but hidden"))
await expect(ensureKey("uaa", "u", { create: true })).rejects.toThrow(/plaintext|did not return/i)
})
test("an idempotency clash retries with a FRESH name and returns the key string", async () => {
f = fakeInkStone()
f.route("GET /v1/models", () => json({ object: "list", data: [] }))
f.route("GET /api/tokenplan/v1/keys", () => ok({ total: 0, items: [] }))
const posted = []
// the console refuses the first name only: a retry that kept the same name
// would keep hitting the clash, so the test goes red if the name is stale
let refusedName = ""
f.route("POST /api/tokenplan/v1/keys", (r) => {
const name = r.json?.name
posted.push(name)
if (refusedName === "") {
refusedName = name
return fail(-15109, "name clash")
}
if (name === refusedName) return fail(-15109, "name clash")
return ok({ key: "sk-retried" })
})
const key = await ensureKey("uaa", "u", { create: true })
// must be the plaintext string; an envelope object would become
// "Bearer [object Object]" for every later request
expect(typeof key).toBe("string")
expect(key).toBe("sk-retried")
expect(posted).toHaveLength(2)
expect(posted[1]).not.toBe(posted[0])
expect(posted[0]).toBe(refusedName)
})