fix: review fixes, GitHub Releases update check (0.1.1)
- Wallet/subscription/window exhaustion skips a key for 10 minutes instead of disabling it; a balance read showing money brings it back. Only the gateway's own key refusals and a used-up key cap still disable a key. - Classify by sub2api's exact wording; a bare 401 or upstream text no longer retires a key; 'No available accounts' is capacity, not coverage. - Hosts keep only an https origin (no doubled /v1); timeouts and HTTP answers no longer set a host aside; hand edits are re-probed. - Balance: inactive subscriptions, per-plan subscription pooling, key caps kept out of the total, rate windows shown. - Endpoint editor no longer empties itself after Save. - Update check reads GitHub Releases and installs the release tarball; release workflow replaces npm publishing. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
86b8e4d24f
commit
f4f4ce55b3
34 files changed
+953
-521
No files matched your search
@@ -253,7 +253,7 @@ test('an official-CLI refusal from a key without a Claude group blames the key,
|
||||
runner: {
|
||||
async *stream() {
|
||||
yield { type: 'key', label: 'no-cc', model: 'claude-opus-5-5', groups: ['codex'], required: ['cc'], covers: false }
|
||||
throw new Error('Claude Code CLI failed: API Error: 400 当前令牌未覆盖供应商 "Anthropic"(模型=claude-opus-5-5,已选分组=[codex]) (request id: r2)')
|
||||
throw new Error("Claude Code CLI failed: API Error: 400 Model 'claude-opus-5-5' is not available. Use GET /v1/models to see supported models. (request id: r2)")
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
+27
-21
@@ -5,6 +5,7 @@ import { isQuotaExceededError } from '@deepseek-ai/dsh-llm'
|
||||
|
||||
import {
|
||||
CLIENT_POLICY_FAILURE,
|
||||
EXHAUSTED_FAILURE,
|
||||
INVALID_KEY_FAILURE,
|
||||
QUOTA_FAILURE,
|
||||
classifyCapacity,
|
||||
@@ -30,41 +31,47 @@ const OTHER_CLASSES = [
|
||||
/\b(?:network|connection|socket|fetch)\b|\bECONN[A-Z]+\b|\bterminated\b|premature close/iu,
|
||||
]
|
||||
|
||||
test('recognizes an exhausted key from the gateway wording', () => {
|
||||
assert.equal(classifyGatewayFailure('402 {"error":{"message":"当前令牌额度已用完"}}'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('insufficient quota'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('余额不足,请充值'), QUOTA_FAILURE)
|
||||
test('money that comes back is exhausted, a used-up key cap is quota', () => {
|
||||
assert.equal(classifyGatewayFailure('403 {"error":{"code":"INSUFFICIENT_BALANCE","message":"余额不足,请充值"}}'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('429 daily usage limit exceeded'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('429 api key 日限额已用完'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('429 api key 5小时限额已用完'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('429 Daily usage quota exhausted for this platform.'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"SUBSCRIPTION_NOT_FOUND","message":"No active subscription found for this group"}'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('429 {"code":"API_KEY_QUOTA_EXHAUSTED","message":"API key 额度已用完"}'), QUOTA_FAILURE)
|
||||
})
|
||||
|
||||
test('recognizes a rejected key from its status or wording', () => {
|
||||
assert.equal(classifyGatewayFailure('401 {"error":{"message":"无效的令牌"}}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('invalid api key'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('api key is invalid'), INVALID_KEY_FAILURE)
|
||||
test('only the gateway\'s own words reject a key; a bare 401 or upstream wording does not', () => {
|
||||
assert.equal(classifyGatewayFailure('401 {"code":"INVALID_API_KEY","message":"Invalid API key"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('401 Unauthorized'), undefined)
|
||||
assert.equal(classifyGatewayFailure('502 upstream said: 401 {"error":{"type":"authentication_error"}}'), undefined)
|
||||
assert.equal(classifyGatewayFailure('429 {"error":{"type":"insufficient_quota","message":"You exceeded your current quota"}}'), undefined)
|
||||
assert.equal(classifyGatewayFailure('当前令牌额度已用完'), undefined)
|
||||
})
|
||||
|
||||
test('leaves transient gateway faults to the key it already used', () => {
|
||||
const channelFault = '400 {"error":{"code":"model_not_found","message":"当前令牌未覆盖供应商 \\"Anthropic\\"(模型=claude-opus-5-5)"}}'
|
||||
assert.equal(classifyGatewayFailure(channelFault), undefined)
|
||||
assert.equal(classifyGatewayFailure('503 {"error":{"message":"分组 cc-sale 下模型 claude-opus-5-5 无可用渠道"}}'), undefined)
|
||||
assert.equal(classifyGatewayFailure('503 {"error":{"message":"No available accounts"}}'), undefined)
|
||||
assert.equal(classifyGatewayFailure('502 Upstream service temporarily unavailable'), undefined)
|
||||
assert.equal(classifyGatewayFailure(''), undefined)
|
||||
assert.equal(classifyGatewayFailure(undefined), undefined)
|
||||
})
|
||||
|
||||
test('a normalized quota failure lands in the harness quota category', () => {
|
||||
const raw = '403 {"error":{"message":"当前令牌额度已用完 (request id: 01M4)"}}'
|
||||
const raw = '403 {"error":{"code":"INSUFFICIENT_BALANCE","message":"余额不足,请充值"}}'
|
||||
const kind = classifyGatewayFailure(raw)
|
||||
assert.equal(kind, QUOTA_FAILURE)
|
||||
assert.equal(kind, EXHAUSTED_FAILURE)
|
||||
const normalized = normalizeFailureMessage(raw, kind)
|
||||
assert.equal(isQuotaExceededError(normalized), true)
|
||||
// The gateway's 403 must not send this into the auth category first.
|
||||
assert.equal(AUTH_STATUS.test(normalized), false)
|
||||
// The gateway's own sentence survives, so the user sees what happened.
|
||||
assert.match(normalized, /当前令牌额度已用完/u)
|
||||
assert.match(normalized, /余额不足,请充值/u)
|
||||
assert.match(normalized, /trying the next key/u)
|
||||
assert.equal(isQuotaExceededError(normalizeFailureMessage('429 API key 额度已用完', QUOTA_FAILURE)), true)
|
||||
})
|
||||
|
||||
test('a normalized key rejection lands in the harness auth category', () => {
|
||||
const raw = '{"error":{"message":"无效的令牌 (request id: 01M4)"}}'
|
||||
const raw = '{"error":{"code":"INVALID_API_KEY","message":"Invalid API key"}}'
|
||||
const kind = classifyGatewayFailure(raw)
|
||||
assert.equal(kind, INVALID_KEY_FAILURE)
|
||||
const normalized = normalizeFailureMessage(raw, kind)
|
||||
@@ -75,8 +82,7 @@ test('a normalized key rejection lands in the harness auth category', () => {
|
||||
|
||||
test('a client-policy refusal is never blamed on the key', () => {
|
||||
const claude = '403 {"error":{"type":"geek2api_api_error","message":"This API endpoint is only accessible via the official Claude CLI (request id: 01M4Q6FJ05BX8Z4SWZ01RXSNSS)"}}'
|
||||
const codex = '403 {"error":{"message":"我们检测到您的客户端存在异常,请使用标准 Codex 客户端请求,请避免任何基于我方 API 二次分发的 API 转接接入。"}}'
|
||||
for (const raw of [claude, codex]) {
|
||||
for (const raw of [claude]) {
|
||||
assert.equal(classifyClientPolicy(raw), true)
|
||||
// Not a key fault: nothing may disable or rotate a key for this.
|
||||
assert.equal(classifyGatewayFailure(raw), undefined)
|
||||
@@ -106,7 +112,8 @@ test('a busy gateway is told apart from key, quota, and client faults', () => {
|
||||
assert.equal(classifyCapacity('API Error: 503 {"error":{"type":"geek2api_concurrency_queue_full","message":"账号并发排队已满,请稍后重试。"}}'), true)
|
||||
assert.equal(classifyCapacity('API Error: 429 rate_limit_error'), true)
|
||||
assert.equal(classifyCapacity('API Error: 529 overloaded_error'), true)
|
||||
assert.equal(classifyCapacity('API Error: 401 无效的令牌'), false)
|
||||
assert.equal(classifyCapacity('API Error: 401 Invalid API key'), false)
|
||||
assert.equal(classifyCapacity('API Error: 503 No available accounts'), true)
|
||||
assert.equal(classifyCapacity('Request blocked: official Claude Code CLI only'), false)
|
||||
const text = explainCliCapacityFailure('Claude Code CLI failed: API Error: 503 queue full', 10)
|
||||
assert.match(text, /已自动重试 10 次/u)
|
||||
@@ -121,14 +128,13 @@ test('classifies the sub2api gateway wording', () => {
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"API_KEY_EXPIRED","message":"API key 已过期"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"message":"API Key 所属分组已删除"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"GROUP_NOT_ALLOWED","message":"API Key 所属专属分组不再允许当前用户使用"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"INSUFFICIENT_BALANCE","message":"余额不足,请充值"}'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"SUBSCRIPTION_NOT_FOUND","message":"No active subscription found for this group"}'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"INSUFFICIENT_BALANCE","message":"余额不足,请充值"}'), EXHAUSTED_FAILURE)
|
||||
|
||||
// A model the key's group does not serve is coverage, never a key fault.
|
||||
const missing = `400 {"error":{"message":"Model 'kimi-k3' is not available. Use GET /v1/models to see supported models.","type":"invalid_request_error"}}`
|
||||
assert.equal(classifyGatewayFailure(missing), undefined)
|
||||
assert.equal(classifyCoverage(missing), true)
|
||||
assert.equal(classifyCoverage('503 No available accounts'), true)
|
||||
assert.equal(classifyCoverage('503 No available accounts'), false, 'a busy pool is not coverage')
|
||||
assert.equal(classifyCoverage('Model is not allowed'), true)
|
||||
assert.equal(classifyCoverage('500 upstream exploded'), false)
|
||||
})
|
||||
|
||||
@@ -7,9 +7,11 @@ import test from 'node:test'
|
||||
|
||||
import {
|
||||
compareSemver,
|
||||
classifySpec,
|
||||
createGeek2APIPluginManager,
|
||||
NPM_REGISTRY_LATEST_URL,
|
||||
GITHUB_LATEST_RELEASE_URL,
|
||||
PACKAGE_NAME,
|
||||
parseLatestRelease,
|
||||
parseSemver,
|
||||
resolvePnpm,
|
||||
} from '../src/plugin-version.js'
|
||||
@@ -43,7 +45,27 @@ async function linkInstall(root, version = '1.0.3') {
|
||||
return pathToFileURL(join(checkout, 'package.json'))
|
||||
}
|
||||
|
||||
const registryOk = version => async () => ({ ok: true, status: 200, async json() { return { version } } })
|
||||
const tarballUrl = version => `https://github.com/CoderKuo/dsh-geek2api/releases/download/v${version}/${PACKAGE_NAME}-${version}.tgz`
|
||||
const releasePage = version => `https://github.com/CoderKuo/dsh-geek2api/releases/tag/v${version}`
|
||||
/** The GitHub "latest release" body for `version`, with its tarball asset. */
|
||||
const releaseBody = version => ({
|
||||
tag_name: `v${version}`,
|
||||
html_url: releasePage(version),
|
||||
draft: false,
|
||||
prerelease: false,
|
||||
assets: [{ name: `${PACKAGE_NAME}-${version}.tgz`, browser_download_url: tarballUrl(version) }],
|
||||
})
|
||||
const registryOk = version => async () => ({ ok: true, status: 200, async json() { return releaseBody(version) } })
|
||||
|
||||
/** Fake DSH home whose `web` profile installed a release tarball. */
|
||||
async function releaseInstall(root, version = '1.0.3') {
|
||||
const installedDir = join(root, 'profiles', 'web', 'node_modules', PACKAGE_NAME)
|
||||
await writeManifest(join(root, 'profiles', 'web', 'package.json'), {
|
||||
dependencies: { [PACKAGE_NAME]: tarballUrl(version) },
|
||||
})
|
||||
await writeManifest(join(installedDir, 'package.json'), { name: PACKAGE_NAME, version })
|
||||
return pathToFileURL(join(installedDir, 'package.json'))
|
||||
}
|
||||
|
||||
const rpc = pluginManager => createGeek2APIRpc({
|
||||
ring: {},
|
||||
@@ -63,7 +85,27 @@ test('semver parsing and comparison drive the update badge', () => {
|
||||
assert.equal(compareSemver('not-a-version', '1.0.3'), undefined)
|
||||
})
|
||||
|
||||
test('version check asks the registry for an uncompressed document', async () => {
|
||||
test('install specs: release tarballs and registry versions update in place, checkouts do not', () => {
|
||||
assert.equal(classifySpec(tarballUrl('1.0.3')), 'release')
|
||||
assert.equal(classifySpec('file:C:/Downloads/dsh-geek2api-1.0.3.tgz'), 'release')
|
||||
assert.equal(classifySpec('link:../../checkout'), 'link')
|
||||
assert.equal(classifySpec('file:../checkout'), 'link')
|
||||
assert.equal(classifySpec('1.0.3'), 'npm')
|
||||
assert.equal(classifySpec('github:someone/else'), 'unknown')
|
||||
})
|
||||
|
||||
test('the latest release names its version, tarball, and page; drafts and foreign links are ignored', () => {
|
||||
assert.deepEqual(parseLatestRelease(releaseBody('1.0.4')), { version: '1.0.4', tarballUrl: tarballUrl('1.0.4'), releaseUrl: releasePage('1.0.4') })
|
||||
assert.equal(parseLatestRelease({ ...releaseBody('1.0.4'), draft: true }), undefined)
|
||||
assert.equal(parseLatestRelease({ ...releaseBody('1.0.4'), prerelease: true }), undefined)
|
||||
assert.equal(parseLatestRelease({ ...releaseBody('1.0.4'), tag_name: 'latest' }), undefined)
|
||||
const foreign = parseLatestRelease({ ...releaseBody('1.0.4'), assets: [{ name: `${PACKAGE_NAME}-1.0.4.tgz`, browser_download_url: 'https://evil.example/x.tgz' }] })
|
||||
assert.deepEqual(foreign, { version: '1.0.4', releaseUrl: releasePage('1.0.4') })
|
||||
const wrongAsset = parseLatestRelease({ ...releaseBody('1.0.4'), assets: [{ name: `${PACKAGE_NAME}-1.0.3.tgz`, browser_download_url: tarballUrl('1.0.3') }] })
|
||||
assert.equal(wrongAsset.tarballUrl, undefined)
|
||||
})
|
||||
|
||||
test('version check asks GitHub for an uncompressed document', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-encoding-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root, '1.0.3')
|
||||
const original = globalThis.fetch
|
||||
@@ -73,7 +115,7 @@ test('version check asks the registry for an uncompressed document', async () =>
|
||||
if (acceptEncoding !== 'identity') {
|
||||
return { ok: true, status: 200, async json() { throw new SyntaxError('gzip body') } }
|
||||
}
|
||||
return { ok: true, status: 200, async json() { return { version: '1.0.3' } } }
|
||||
return { ok: true, status: 200, async json() { return releaseBody('1.0.3') } }
|
||||
}
|
||||
try {
|
||||
const value = await createGeek2APIPluginManager({
|
||||
@@ -88,7 +130,7 @@ test('version check asks the registry for an uncompressed document', async () =>
|
||||
}
|
||||
})
|
||||
|
||||
test('version read combines own manifest, registry latest, and the owning npm profile', async () => {
|
||||
test('version read combines own manifest, the latest release, and the owning profile', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-npm-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root)
|
||||
let requests = 0
|
||||
@@ -108,11 +150,13 @@ test('version read combines own manifest, registry latest, and the owning npm pr
|
||||
assert.deepEqual(first, {
|
||||
current: '1.0.3',
|
||||
latest: '1.0.4',
|
||||
releaseUrl: releasePage('1.0.4'),
|
||||
updateAvailable: true,
|
||||
updatable: true,
|
||||
install: { kind: 'npm', profile: 'web' },
|
||||
fetchedAt: 1000,
|
||||
})
|
||||
assert.deepEqual(observed, { url: NPM_REGISTRY_LATEST_URL, redirect: 'error' })
|
||||
assert.deepEqual(observed, { url: GITHUB_LATEST_RELEASE_URL, redirect: 'error' })
|
||||
await manager.read()
|
||||
assert.equal(requests, 1, 'fresh cached reads stay off the network')
|
||||
await manager.read({ force: true })
|
||||
@@ -131,7 +175,7 @@ test('registry failures and malformed payloads surface one sanitized error', asy
|
||||
const malformed = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
fetchImpl: async () => ({ ok: true, status: 200, async json() { return { version: 'not-a-version' } } }),
|
||||
fetchImpl: async () => ({ ok: true, status: 200, async json() { return { tag_name: 'not-a-version' } } }),
|
||||
})
|
||||
await assert.rejects(() => malformed.read(), /^Error: Geek2API plugin version check failed$/u)
|
||||
})
|
||||
@@ -184,14 +228,14 @@ async function desktopRuntime(root) {
|
||||
const installRecorder = async ({ args, cwd }) => {
|
||||
await writeManifest(join(cwd, 'node_modules', PACKAGE_NAME, 'package.json'), {
|
||||
name: PACKAGE_NAME,
|
||||
version: args.at(-1).split('@').at(-1),
|
||||
version: /-(\d+\.\d+\.\d+)\.tgz$/u.exec(args.at(-1))[1],
|
||||
})
|
||||
return { code: 0, stdout: '', stderr: '' }
|
||||
}
|
||||
|
||||
test('update installs the exact version into the owning profile, pinned and age-free', async () => {
|
||||
test('update installs the release tarball into the owning profile, age-free', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-update-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root)
|
||||
const ownPackageJsonUrl = await releaseInstall(root)
|
||||
const calls = []
|
||||
let registryRequests = 0
|
||||
const manager = createGeek2APIPluginManager({
|
||||
@@ -212,7 +256,7 @@ test('update installs the exact version into the owning profile, pinned and age-
|
||||
assert.deepEqual(updated, { version: '1.0.4', profile: 'web' })
|
||||
assert.equal(calls[0].command, 'pnpm')
|
||||
assert.deepEqual(calls[0].args, [
|
||||
'add', '--save-exact', '--config.minimumReleaseAge=0', `${PACKAGE_NAME}@1.0.4`,
|
||||
'add', '--config.minimumReleaseAge=0', `${PACKAGE_NAME}@${tarballUrl('1.0.4')}`,
|
||||
])
|
||||
assert.equal(calls[0].cwd, join(root, 'profiles', 'web'))
|
||||
await manager.read()
|
||||
@@ -240,7 +284,7 @@ test('desktop hosts install with the bundled pnpm, never by launching the deskto
|
||||
const [call] = calls
|
||||
assert.equal(call.command, '/Applications/DeepSeek Harness')
|
||||
assert.deepEqual(call.args, [
|
||||
runtime.pnpm, 'add', '--save-exact', '--config.minimumReleaseAge=0', `${PACKAGE_NAME}@1.0.4`,
|
||||
runtime.pnpm, 'add', '--config.minimumReleaseAge=0', `${PACKAGE_NAME}@${tarballUrl('1.0.4')}`,
|
||||
])
|
||||
const flattened = JSON.stringify(call)
|
||||
assert.equal(flattened.includes(runtime.hostEntry), false)
|
||||
@@ -359,3 +403,20 @@ test('loopback RPC exposes version and update endpoints with sanitized errors',
|
||||
error: { code: 'geek2api/request-failed', message: 'Geek2API plugin version is unavailable', details: {} },
|
||||
})
|
||||
})
|
||||
|
||||
test('a release without its tarball is reported but not installed', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-noasset-'))
|
||||
const ownPackageJsonUrl = await releaseInstall(root, '1.0.3')
|
||||
const manager = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
fetchImpl: async () => ({ ok: true, status: 200, async json() { return { ...releaseBody('1.0.4'), assets: [] } } }),
|
||||
runCommand: async () => {
|
||||
throw new Error('runCommand must not run without a tarball')
|
||||
},
|
||||
})
|
||||
const info = await manager.read()
|
||||
assert.equal(info.updateAvailable, true)
|
||||
assert.equal(info.updatable, false)
|
||||
await assert.rejects(() => manager.update(), /^Error: Geek2API plugin release has no package to install$/u)
|
||||
})
|
||||
@@ -35,7 +35,7 @@ test('a terminal quota event moves the ring and is rewritten for the classifier'
|
||||
const failures = []
|
||||
const event = {
|
||||
type: 'error',
|
||||
error: { errorMessage: '403 {"error":{"message":"当前令牌额度已用完"}}' },
|
||||
error: { errorMessage: '429 {"error":{"code":"API_KEY_QUOTA_EXHAUSTED","message":"API key 额度已用完"}}' },
|
||||
}
|
||||
const guarded = guardKeyRotation(fakeStream([event]), {
|
||||
key: 'sk-aaaaaaaaaaaaaaaa',
|
||||
@@ -55,7 +55,7 @@ test('a terminal quota event moves the ring and is rewritten for the classifier'
|
||||
test('a rejected key reported as a terminal event normalizes to auth', async () => {
|
||||
const failures = []
|
||||
const guarded = guardKeyRotation(fakeStream([
|
||||
{ type: 'done', message: { errorMessage: '401 {"error":{"message":"无效的令牌"}}' } },
|
||||
{ type: 'done', message: { errorMessage: '401 {"error":{"code":"INVALID_API_KEY","message":"Invalid API key"}}' } },
|
||||
]), { key: 'sk-bbbbbbbbbbbbbbbbbb', onKeyFailure: (...args) => failures.push(args) })
|
||||
const received = []
|
||||
for await (const item of guarded) received.push(item)
|
||||
@@ -216,7 +216,8 @@ test('sub2api key faults move the ring: invalid, disabled, deleted group, and em
|
||||
['401 {"error":{"message":"Invalid API key"}}', 'invalid-key'],
|
||||
['401 {"error":{"message":"API key is disabled"}}', 'invalid-key'],
|
||||
['403 {"error":{"message":"API Key 所属分组已删除"}}', 'invalid-key'],
|
||||
['403 {"error":{"message":"余额不足,请充值"}}', 'quota'],
|
||||
['403 {"error":{"message":"余额不足,请充值"}}', 'exhausted'],
|
||||
['429 {"error":{"message":"API key 额度已用完"}}', 'quota'],
|
||||
]
|
||||
for (const [message, kind] of cases) {
|
||||
const failures = []
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import test from 'node:test'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
|
||||
async function preflight(exchangeStatus) {
|
||||
const workflow = await readFile(new URL('../.github/workflows/publish.yml', import.meta.url), 'utf8')
|
||||
const step = workflow.split('- name: Show the OIDC identity npm will match')[1]?.split('- name: Publish')[0]
|
||||
const code = /node <<'EOF'\n([\s\S]*?)\n\s*EOF/u.exec(step ?? '')?.[1]
|
||||
assert.ok(code, 'the trusted-publisher preflight must contain its actual Node program')
|
||||
const lines = []
|
||||
const calls = []
|
||||
const token = `fixture-secret-${'x'.repeat(2_000)}`
|
||||
const claims = {
|
||||
repository: 'BaronCyrus/dsh-geek2api',
|
||||
repository_owner: 'BaronCyrus',
|
||||
workflow: 'Publish',
|
||||
workflow_ref: 'BaronCyrus/dsh-geek2api/.github/workflows/publish.yml@refs/heads/main',
|
||||
ref: 'refs/heads/main',
|
||||
aud: 'npm:registry.npmjs.org',
|
||||
iss: 'https://token.actions.githubusercontent.com',
|
||||
}
|
||||
const oidc = `header.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.signature`
|
||||
const promise = runInNewContext(code, {
|
||||
URL,
|
||||
Buffer,
|
||||
console: { log: value => lines.push(String(value)), error: value => lines.push(String(value)) },
|
||||
process: {
|
||||
env: { ACTIONS_ID_TOKEN_REQUEST_URL: 'https://actions.example/oidc?existing=true', ACTIONS_ID_TOKEN_REQUEST_TOKEN: 'fixture-request-capability' },
|
||||
exit: code => { throw new Error(`EXIT_${code}`) },
|
||||
},
|
||||
fetch: async (url, options) => {
|
||||
calls.push({ url: String(url), options })
|
||||
if (calls.length === 1) return { ok: true, json: async () => ({ value: oidc }) }
|
||||
assert.equal(String(url), 'https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/dsh-geek2api')
|
||||
assert.equal(options.method, 'POST')
|
||||
assert.equal(options.headers.Authorization, `Bearer ${oidc}`)
|
||||
return { ok: exchangeStatus >= 200 && exchangeStatus < 300, status: exchangeStatus, arrayBuffer: async () => Buffer.from(JSON.stringify({ token })) }
|
||||
},
|
||||
})
|
||||
return { promise, lines, calls, token }
|
||||
}
|
||||
|
||||
test('publisher preflight prints safe identity claims, never an exchange credential or its truncated prefix', async () => {
|
||||
const run = await preflight(200)
|
||||
await run.promise
|
||||
assert.ok(run.lines.includes('repository=BaronCyrus/dsh-geek2api'))
|
||||
assert.ok(run.lines.includes('environment='))
|
||||
assert.ok(run.lines.includes('exchange_status=200'))
|
||||
assert.equal(new URL(run.calls[0].url).searchParams.get('audience'), 'npm:registry.npmjs.org')
|
||||
assert.equal(run.lines.join('\n').includes(run.token.slice(0, 50)), false)
|
||||
assert.equal(run.lines.join('\n').includes('fixture-request-capability'), false)
|
||||
})
|
||||
|
||||
test('publisher preflight accepts the real registry exchange Created response', async () => {
|
||||
const run = await preflight(201)
|
||||
await run.promise
|
||||
assert.ok(run.lines.includes('exchange_status=201'))
|
||||
assert.equal(run.lines.join('\n').includes(run.token.slice(0, 50)), false)
|
||||
})
|
||||
|
||||
test('tag publication uses the verified versioned tarball, not a separately packed workspace', async () => {
|
||||
const workflow = await readFile(new URL('../.github/workflows/publish.yml', import.meta.url), 'utf8')
|
||||
assert.ok(workflow.includes('run: pnpm pack --pack-destination .artifacts'))
|
||||
assert.ok(workflow.includes('artifact=".artifacts/dsh-geek2api-${version:?}.tgz"'))
|
||||
assert.ok(workflow.includes('npm publish "${artifact:?}" --access public'))
|
||||
assert.ok(workflow.includes('if [ ! -f "$artifact" ]; then'))
|
||||
})
|
||||
|
||||
test('publisher preflight fails closed when npm rejects the configured publisher', async () => {
|
||||
const run = await preflight(403)
|
||||
await assert.rejects(run.promise, /EXIT_1/u)
|
||||
assert.ok(run.lines.includes('exchange_status=403'))
|
||||
assert.equal(run.lines.join('\n').includes(run.token.slice(0, 50)), false)
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { parseKeyUsage } from '../src/balance.js'
|
||||
import { isTransportFailure, normalizeHost, normalizeHostList } from '../src/hosts.js'
|
||||
import { createKeyChooser } from '../src/key-chooser.js'
|
||||
import { Geek2APIKeyRing } from '../src/key-ring.js'
|
||||
import { TransportError } from '../src/request.js'
|
||||
|
||||
function fakeCredentials() {
|
||||
let record
|
||||
let chain = Promise.resolve()
|
||||
return {
|
||||
async readRecord() {
|
||||
return record
|
||||
},
|
||||
modifyRecord(_key, mutate) {
|
||||
const run = chain.then(async () => {
|
||||
const next = await mutate(record)
|
||||
if (next !== undefined) record = next
|
||||
return record
|
||||
})
|
||||
chain = run.then(() => undefined, () => undefined)
|
||||
return run
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const NO_GROUPS = Object.freeze({
|
||||
read: async () => ({ keys: [] }),
|
||||
hasReading: () => true,
|
||||
covers: () => undefined,
|
||||
groupsOf: () => undefined,
|
||||
requiredGroups: () => undefined,
|
||||
})
|
||||
|
||||
async function chooserWith(clock) {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add('sk-first-0000000000000000', 'first')
|
||||
await ring.add('sk-second-000000000000000', 'second')
|
||||
const keys = createKeyChooser({ ring, groups: NO_GROUPS, now: () => clock.now, skipMs: 1_000 })
|
||||
return { ring, keys }
|
||||
}
|
||||
|
||||
test('an empty wallet skips the key for a while and never disables it', async () => {
|
||||
const clock = { now: 10_000 }
|
||||
const { ring, keys } = await chooserWith(clock)
|
||||
const first = await keys.active()
|
||||
assert.equal(first.label, 'first')
|
||||
|
||||
keys.onKeyFailure('exhausted', '余额不足,请充值', first.key)
|
||||
assert.equal((await keys.active()).label, 'second', 'the next key serves the retry')
|
||||
const state = await ring.list()
|
||||
assert.equal(state.keys.every(entry => entry.disabled !== true), true, 'nothing was disabled')
|
||||
assert.deepEqual(Object.keys(keys.skipped()), [first.id])
|
||||
|
||||
clock.now += 1_001
|
||||
assert.equal((await keys.active()).label, 'first', 'the skip ends by itself')
|
||||
})
|
||||
|
||||
test('with every key out of money the active key still answers, so the failure speaks', async () => {
|
||||
const clock = { now: 10_000 }
|
||||
const { keys } = await chooserWith(clock)
|
||||
const first = await keys.active()
|
||||
keys.onKeyFailure('exhausted', 'x', first.key)
|
||||
const second = await keys.active()
|
||||
keys.onKeyFailure('exhausted', 'x', second.key)
|
||||
assert.equal((await keys.active()).label, 'first')
|
||||
})
|
||||
|
||||
test('a balance read showing money brings a skipped key back at once', async () => {
|
||||
const clock = { now: 10_000 }
|
||||
const { keys } = await chooserWith(clock)
|
||||
const first = await keys.active()
|
||||
keys.onKeyFailure('exhausted', 'x', first.key)
|
||||
keys.noteBalances([{ id: first.id, usage: { availableUsd: 0 } }])
|
||||
assert.equal((await keys.active()).label, 'second', 'still empty: still skipped')
|
||||
keys.noteBalances([{ id: first.id, usage: { availableUsd: 12 }, stale: { fetchedAt: 1 } }])
|
||||
assert.equal((await keys.active()).label, 'second', 'a stale reading is no evidence')
|
||||
keys.noteBalances([{ id: first.id, usage: { availableUsd: 12 } }])
|
||||
assert.equal((await keys.active()).label, 'first')
|
||||
})
|
||||
|
||||
test('a used-up key cap or a rejected key is still disabled', async () => {
|
||||
const clock = { now: 10_000 }
|
||||
const { ring, keys } = await chooserWith(clock)
|
||||
const first = await keys.active()
|
||||
keys.onKeyFailure('quota', 'API key 额度已用完', first.key)
|
||||
await new Promise(resolve => { setTimeout(resolve, 10) })
|
||||
assert.equal((await ring.list()).keys.find(entry => entry.id === first.id).disabled, true)
|
||||
})
|
||||
|
||||
test('hosts keep only an https origin; plain http only on loopback', () => {
|
||||
assert.equal(normalizeHost('https://hk.geek2api.com/v1', undefined), 'https://hk.geek2api.com')
|
||||
assert.equal(normalizeHost('https://hk.geek2api.com/v1/', undefined), 'https://hk.geek2api.com')
|
||||
assert.equal(normalizeHost('http://hk.geek2api.com', undefined), undefined)
|
||||
assert.equal(normalizeHost('http://127.0.0.1:8080/x', undefined), 'http://127.0.0.1:8080')
|
||||
assert.equal(normalizeHost('http://localhost:3000', undefined), 'http://localhost:3000')
|
||||
assert.deepEqual(normalizeHostList(['https://a.example/v1', 'https://a.example', 'http://evil.example']), ['https://a.example'])
|
||||
})
|
||||
|
||||
test('a timeout or an HTTP answer does not set a host aside', () => {
|
||||
const timedOut = new TransportError(new Error('aborted'), { aborted: false, timedOut: true, timeoutMs: 1000 })
|
||||
assert.equal(isTransportFailure(timedOut), false)
|
||||
assert.equal(isTransportFailure('OpenAI API error (502): TLS handshake timeout'), false)
|
||||
assert.equal(isTransportFailure('502 Bad Gateway: certificate error upstream'), false)
|
||||
assert.equal(isTransportFailure('fetch failed'), true)
|
||||
assert.equal(isTransportFailure('Connection error.'), true)
|
||||
})
|
||||
|
||||
test('an inactive subscription is shown as such, not as an unrecognized payload', () => {
|
||||
const usage = parseKeyUsage({ mode: 'unrestricted', isValid: true, planName: 'Plus', unit: 'USD', key: { name: 'k' } })
|
||||
assert.equal(usage.mode, 'subscription')
|
||||
assert.equal(usage.inactive, true)
|
||||
assert.equal(usage.availableUsd, 0)
|
||||
assert.equal(usage.planName, 'Plus')
|
||||
})
|
||||
|
||||
test('a key with only rate windows is not called unlimited', () => {
|
||||
const usage = parseKeyUsage({ mode: 'quota_limited', isValid: true, status: 'active', rate_limits: [{ window: '5h', limit: 5, used: 1, remaining: 4 }] })
|
||||
assert.equal(usage.unlimitedQuota, false)
|
||||
assert.equal(usage.availableUsd, undefined)
|
||||
assert.deepEqual(usage.rateLimits, [{ window: '5h', limitUsd: 5, usedUsd: 1, remainingUsd: 4 }])
|
||||
})
|
||||
@@ -197,7 +197,7 @@ test('an exhausted key moves aside through the shared sink and the next key answ
|
||||
assert.equal(result.sources.length, 2)
|
||||
assert.deepEqual(used, ['sk-first-key-0001', 'sk-second-key-0002'])
|
||||
assert.equal(failures.length, 1)
|
||||
assert.equal(failures[0].kind, 'quota')
|
||||
assert.equal(failures[0].kind, 'exhausted')
|
||||
assert.equal(failures[0].key, 'sk-first-key-0001')
|
||||
assert.equal(typeof failures[0].id, 'string')
|
||||
})
|
||||
@@ -234,7 +234,7 @@ test('a client-policy refusal is explained and blames no key', async () => {
|
||||
ring,
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
onKeyFailure: kind => failures.push(kind),
|
||||
fetchImpl: async () => json(403, { error: { message: '请使用标准 codex 客户端' } }),
|
||||
fetchImpl: async () => json(403, { error: { message: 'This API endpoint is only accessible via the official Claude CLI' } }),
|
||||
})
|
||||
await assert.rejects(provider.search({ query: 'q' }), /拒绝了这个客户端/u)
|
||||
assert.deepEqual(failures, [])
|
||||
|
||||
+20
-7
@@ -3,20 +3,32 @@ import test from 'node:test'
|
||||
|
||||
import { sumBalances } from '../src/totals.js'
|
||||
|
||||
test('adds the per-key quotas a balance read returned', () => {
|
||||
test('a key quota is a cap on the wallet, not money: it stays out of the sums', () => {
|
||||
const rows = [
|
||||
{ id: 'a', usage: { mode: 'quota', availableUsd: 499.07, usedUsd: 0.93, limitUsd: 500 } },
|
||||
{ id: 'b', usage: { mode: 'subscription', planName: 'Plus', availableUsd: 500, usedUsd: 0, limitUsd: 500, resetPeriod: 'monthly' } },
|
||||
]
|
||||
const totals = sumBalances(rows)
|
||||
assert.equal(totals.counted, 2)
|
||||
assert.equal(Math.round(totals.remainingUsd * 100) / 100, 999.07)
|
||||
assert.equal(Math.round(totals.usedUsd * 100) / 100, 0.93)
|
||||
assert.equal(totals.limitUsd, 1000)
|
||||
assert.equal(totals.capped, 1)
|
||||
assert.equal(totals.remainingUsd, 500)
|
||||
assert.equal(totals.usedUsd, 0)
|
||||
assert.equal(totals.limitUsd, 500)
|
||||
assert.equal(totals.unread, 0)
|
||||
assert.equal(totals.unlimited, 0)
|
||||
})
|
||||
|
||||
test('keys on the same subscription plan count it once', () => {
|
||||
const totals = sumBalances([
|
||||
{ id: 'a', usage: { mode: 'subscription', planName: 'Plus', availableUsd: 30, usedUsd: 20, limitUsd: 50 } },
|
||||
{ id: 'b', usage: { mode: 'subscription', planName: 'Plus', availableUsd: 30, usedUsd: 20, limitUsd: 50 } },
|
||||
{ id: 'c', usage: { mode: 'subscription', planName: 'Max', availableUsd: 100, usedUsd: 0, limitUsd: 100 } },
|
||||
])
|
||||
assert.equal(totals.shared, 1)
|
||||
assert.equal(totals.remainingUsd, 130)
|
||||
assert.equal(totals.limitUsd, 150)
|
||||
})
|
||||
|
||||
test('counts only what it can read and reports the rest', () => {
|
||||
const rows = [
|
||||
{ id: 'a', usage: { availableUsd: 10, usedUsd: 1, limitUsd: 11 } },
|
||||
@@ -46,7 +58,7 @@ test('a key without a period limit contributes only what it reports', () => {
|
||||
})
|
||||
|
||||
test('an empty or malformed row list totals to zero', () => {
|
||||
assert.deepEqual(sumBalances([]), { keys: 0, counted: 0, unread: 0, unlimited: 0, shared: 0, remainingUsd: 0, usedUsd: 0, limitUsd: 0 })
|
||||
assert.deepEqual(sumBalances([]), { keys: 0, counted: 0, unread: 0, unlimited: 0, shared: 0, capped: 0, remainingUsd: 0, usedUsd: 0, limitUsd: 0 })
|
||||
assert.equal(sumBalances(undefined).keys, 0)
|
||||
assert.equal(sumBalances([null, 7]).keys, 2)
|
||||
assert.equal(sumBalances([null, 7]).counted, 0)
|
||||
@@ -72,6 +84,7 @@ test('without an account reference, wallets with the same balance are the same w
|
||||
{ id: 'd', usage: { mode: 'quota', availableUsd: 4226.232196, limitUsd: 5000 } },
|
||||
])
|
||||
assert.equal(totals.shared, 1)
|
||||
assert.equal(Math.round((totals.remainingUsd) * 1e6) / 1e6, Math.round((4226.232196 * 2 + 12.5) * 1e6) / 1e6, 'a key quota is its own money')
|
||||
assert.equal(totals.limitUsd, 5000)
|
||||
assert.equal(Math.round((totals.remainingUsd) * 1e6) / 1e6, Math.round((4226.232196 + 12.5) * 1e6) / 1e6, 'one wallet, counted once; the key cap is not money')
|
||||
assert.equal(totals.capped, 1)
|
||||
assert.equal(totals.limitUsd, 0)
|
||||
})
|
||||
Reference in new issue
Block a user