Files
plugins/packages/inkstone/lib/protocol.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

216 lines
7.6 KiB
JavaScript

// The platform's endpoints, its console APIs, and the OpenAI-compatible
// catalogue. ENDPOINTS is a mutable object on purpose: the tests point it
// at a local fake (the same shape fake.mjs uses), so no test can reach the
// real platform. Production code reads the values at call time.
import { createHash } from "node:crypto"
export const ENDPOINTS = {
console: "https://discovery.intern-ai.org.cn",
api: "https://discovery-api.intern-ai.org.cn/v1",
}
export const PUBLIC_MODELS_PATH = "/api/tokenplan/v1/public/models"
export const CONSOLE_API = "/api/tokenplan/v1"
const UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36"
const TIMEOUT_MS = 20_000
export const KEY_LIMIT = 10
export const KEY_NAME_LIMIT = 20
// Vendor text goes into logs and the account card, so it must not carry a
// credential. Only token-shaped runs are masked; the diagnostic words stay.
const SECRETISH =
/(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9._-]{10,}[A-Za-z0-9._-]*|Bearer\s+[A-Za-z0-9._~+/-]{12,}|(?:uaa[-_]?token|refresh[-_]?token|access[-_]?token|id[-_]?token)\s*[=:]\s*[A-Za-z0-9._~+/-]{12,}|sk-[A-Za-z0-9-]{8,})/gi
export function cleanDetail(value) {
return String(value ?? "").replace(SECRETISH, "***")
}
export class ProtocolError extends Error {
constructor(message, { status = 0, code = 0 } = {}) {
super(message)
this.name = "ProtocolError"
this.status = status
this.code = code
}
}
/** Trim a pasted key: spaces, a stray `Bearer `, and wrapping quotes. */
export function normalizeApiKey(value) {
let s = String(value ?? "").trim()
if (/^bearer\s+/i.test(s)) s = s.replace(/^bearer\s+/i, "")
return s.replace(/^["'`]|["'`]$/g, "").trim()
}
function clientHints() {
return {
"user-agent": UA,
"sec-ch-ua": '"Chromium";v="152", "Not;A=Brand";v="24", "Google Chrome";v="152"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
}
/** The console APIs' browser-shaped headers (the platform's WAF expects them). */
export function consoleHeaders(token, extra = {}) {
return {
authorization: `Bearer ${token}`,
accept: "application/json",
"accept-language": "zh-CN",
origin: ENDPOINTS.console,
referer: `${ENDPOINTS.console}/token-plan/home`,
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
...clientHints(),
...extra,
}
}
async function readJson(res, what) {
const text = await res.text().catch(() => "")
let json = null
try {
json = text ? JSON.parse(text) : null
} catch {
/* a non-JSON body is handled by its status */
}
if (!res.ok) {
const detail = cleanDetail(
json?.msg || json?.message || json?.error?.message || text.slice(0, 200).trim() || `HTTP ${res.status}`,
)
throw new ProtocolError(`${what}: ${detail}`, { status: res.status, code: json?.code })
}
if (!json || typeof json !== "object") {
throw new ProtocolError(`${what}: non-JSON reply`, { status: res.status })
}
// The console answers {code:0,...} on success and a non-zero code with
// HTTP 200 when the account or the request is the problem: surface that
// as an error the caller can tell from a network failure.
if (typeof json.code === "number" && json.code !== 0) {
throw new ProtocolError(`${what}: ${cleanDetail(json.msg || `code ${json.code}`)}`, {
status: res.status,
code: json.code,
})
}
return json
}
async function consoleFetch(url, token, init, what, timeoutMs = TIMEOUT_MS) {
let res
try {
res = await fetch(url, {
...init,
headers: consoleHeaders(token, init?.headers),
signal: AbortSignal.timeout(timeoutMs),
})
} catch (e) {
throw new ProtocolError(`${what}: ${cleanDetail(e?.message ?? e)}`)
}
return readJson(res, what)
}
/** GET a console API. `query` is an object of search params. */
export function consoleGet(path, token, { query, timeoutMs } = {}) {
const q = query ? `?${new URLSearchParams(query)}` : ""
return consoleFetch(`${ENDPOINTS.console}${path}${q}`, token, { method: "GET" }, path, timeoutMs)
}
/** POST/PUT/DELETE a console API. */
export function consoleSend(path, token, { method = "POST", body, headers, timeoutMs } = {}) {
return consoleFetch(
`${ENDPOINTS.console}${path}`,
token,
{
method,
body: body === undefined ? undefined : JSON.stringify(body),
headers: body === undefined ? headers : { "content-type": "application/json", ...headers },
},
path,
timeoutMs,
)
}
/** The public model metadata: no credential, the page loads it signed out. */
export async function publicModels({ timeoutMs } = {}) {
let res
try {
res = await fetch(`${ENDPOINTS.console}${PUBLIC_MODELS_PATH}?page=1&page_size=50`, {
headers: { accept: "application/json", "accept-language": "zh-CN", "user-agent": UA },
signal: AbortSignal.timeout(timeoutMs ?? TIMEOUT_MS),
})
} catch (e) {
throw new ProtocolError(`public models: ${cleanDetail(e?.message ?? e)}`)
}
return readJson(res, "public models")
}
/** The catalogue the key is served: free, read-only, and it costs no credits. */
export async function apiModels(apiKey, { timeoutMs } = {}) {
let res
try {
res = await fetch(`${ENDPOINTS.api}/models`, {
headers: { authorization: `Bearer ${apiKey}`, accept: "application/json" },
signal: AbortSignal.timeout(timeoutMs ?? TIMEOUT_MS),
})
} catch (e) {
throw new ProtocolError(`model catalogue: ${cleanDetail(e?.message ?? e)}`)
}
if (res.status === 401 || res.status === 403) {
throw Object.assign(new ProtocolError(`TokenPlan refused the API key (HTTP ${res.status})`, { status: res.status }), {
refused: true,
})
}
// The raw envelope: the caller normalizes (live rows carry more than the
// doc example shows, and the caller wants the whole body).
return readJson(res, "model catalogue")
}
/** A best-effort key check: only 401/403 says the key is invalid. */
export async function probeApiKey(apiKey, { timeoutMs = 10_000 } = {}) {
let res
try {
res = await fetch(`${ENDPOINTS.api}/models`, {
headers: { authorization: `Bearer ${apiKey}`, accept: "application/json" },
signal: AbortSignal.timeout(timeoutMs),
})
} catch (e) {
throw new ProtocolError(`API key probe: ${cleanDetail(e?.message ?? e)}`)
}
if (res.status === 401 || res.status === 403) {
throw new ProtocolError(`API key refused (HTTP ${res.status})`, { status: res.status })
}
return res.ok
}
/* ------------------------------------------------------- console endpoints */
export const creditsBalance = (token, o) => consoleGet(`${CONSOLE_API}/credits/balance`, token, o)
export const creditPackages = (token, o) => consoleGet(`${CONSOLE_API}/credits/packages`, token, o)
export const usersValidate = (token, o) => consoleGet(`${CONSOLE_API}/users/validate`, token, o)
/** Claims the month's free ink points. Idempotent: has_received says so. */
export const freeGrant = (token, o) => consoleSend(`${CONSOLE_API}/users/free-grant`, token, { ...o })
export function listKeys(token, o) {
return consoleGet(`${CONSOLE_API}/keys`, token, o)
}
export function createKey(token, name, idempotencyKey, o) {
return consoleSend(`${CONSOLE_API}/keys`, token, {
body: { name },
headers: { "Idempotency-Key": idempotencyKey },
...o,
})
}
export function deleteKey(token, id, o) {
return consoleSend(`${CONSOLE_API}/keys/${encodeURIComponent(id)}`, token, { method: "DELETE", ...o })
}
/** A stable short fingerprint for names and cache buckets. */
export function fingerprint(value) {
return createHash("sha256").update(String(value ?? "")).digest("hex").slice(0, 12)
}