codeburn/tests/quota-zcode.test.ts
Resham Joshi 5d9d7a0b2f
fix(quota): one keychain prompt per action, exact ZCode token boundary, expired Gemini login reported once (#1904)
* fix(quota): stop at the first keychain Deny instead of prompting again for the same item

A refused or unanswered lookup on the user account fell through to the
service-only lookup, which matches the same item and raised a second
prompt. An unanswered dialog then waited twice, past the quota timeout,
and ended as "Timed out." The reader now returns accessDenied at the
first refusal; only a genuine miss tries the next account. The CLI row
says the access was denied or not answered.

* fix(quota): end the ZCode token at its journal frame length

The token was read greedily up to the first non-token byte, so when the
login ended a write batch the next record's checksum bytes could be
appended to it, and every poll sent a corrupted token and reported a
false "Login expired". The reader now decodes the value's varint length
and slices exactly the string after the encoding flag.

* fix(quota): report an expired Gemini login as needing the user

Without a refresh client an expired Gemini CLI token was sent as-is and
the 401 read as a transient failure on every poll, so the row stayed
"Temporarily unavailable" and never said what to do. A 401 on a token
whose expiry has passed and that nothing refreshed is now terminal, with
a footer to run Gemini CLI once, as Claude already does.

* fix(quota): stop only at a keychain Deny or unanswered prompt, and remember it for the run

An error that showed no prompt (an I/O failure, interaction not allowed) moves on to the next account again, as before. A Deny or a prompt left open until the timeout ends the lookup, and the CLI keeps that refusal for the rest of the process, so a second read of the same service answers without a prompt. Nothing is persisted, so the next run asks once. The Claude row now says which it was: denied, or not answered.

* fix(quota): treat a rejected Gemini login without a refresher as terminal

The stored expiry can be missing or skewed, so it no longer decides: with no client credentials or refresh token nothing here can mint a new token, and the 401 needs the user to run Gemini CLI. With a refresher configured the 401 stays transient.

* fix(quota): pick the newest ZCode login by journal position across encodings

Latin-1 matches were preferred over UTF-16LE ones, so a rotation that changed the string encoding returned the older token. The last write by offset now wins regardless of encoding.

* fix(quota): remember a keychain refusal per account and classify only our own timeout as unanswered

The run's refusal memo is keyed by service and account, so denying one account no longer hides another account's item. Only the kill from our own timeout counts as an unanswered prompt; any other signal is an ordinary error that moves on. A string exit code is normalised, so "128" is a Deny like 128.

* fix(quota): report a ZCode login the app cleared as expired

An empty newest write for the key means the app cleared the login. It used to be skipped, so an older token in the same or an older journal was sent instead. It now reads as an expired login without a request.

* fix(quota): skip a refused keychain account, time prompts with our own timer, and remember refusals in the desktop app

A refusal remembered for one account now skips that account (and the service-only lookup, which can match the same item) and goes on to the next named account, instead of ending the read. An unanswered prompt is now only our own 90 s timer firing: the lookup runs under an AbortSignal whose timer sets a flag, and a kill or signal we did not cause is an ordinary error that moves on. The desktop app keeps the same service-plus-account refusals; a keychain-allowed refresh, which is the user acting again, clears them, so one action asks at most once per item.

* fix(quota): treat a malformed newest ZCode write as unreadable, not as the older token

Only the newest write of the key is read now. If its frame does not parse (no length, zero length, a length past the end of the file, an unknown flag, or bytes that are not a token) the poll reports a transient failure without a request, instead of falling back to an older token the app already replaced. This cannot be narrowed to in-progress writes: the leveldb log splits a record that crosses a 32 KiB block boundary with a 7-byte header, so a complete write can also fail to parse as one contiguous frame, and a torn tail after a crash looks the same. Both are treated as unreadable for this poll.

* fix(quota): count only real leveldb records of the ZCode key as writes

The newest write was the last place the key name appeared, so another entry whose value mentions the key (a settings blob, say) was read as a newer, malformed write and the login was reported unreadable. A token value itself cannot hold the key, since ':' is outside the token alphabet. An occurrence now counts only when it ends the key of a leveldb record: tag, varint key length, then `_`, origin, NUL, string flag and the name. A delete record of the key reads as a cleared login.

* fix(desktop): say whether the Claude keychain prompt was denied or left unanswered

The desktop keychain reader now carries the same refusal reason as the CLI's, and the Claude adapter turns it into the same footer line. The Plans card and the Settings row show that line in place of the generic keychain message for an access-denied row, keeping the generic copy when no reason is known.

* fix(quota): read the ZCode key only under its own origin and reject odd UTF-16 frames

A record now counts as a write of the login only when its key is ZCode's own origin prefix (`_https://zcode.z.ai`, a NUL, the string flag) followed by the key name, as in the recorded journal from #1347 (tag 01, key length 2b, `_https://zcode.z.ai`, 00 01, `oauth:zai:access_token`); the same key under another origin is ignored. A UTF-16 value with an odd byte count was trimmed by the decoder and could still look like a token; it is now read as unreadable for this poll, with no request and no older token.

Not changed: a counterfeit record header embedded inside another entry's value. The journal is ZCode's own local storage on the user's machine, not input from anyone else; whoever can write those bytes already holds the account, and with the origin check a forged record would also have to carry ZCode's exact origin prefix and a matching key length.

* fix(quota): skip a later service-only keychain lookup once an account of the service was refused

A service-only lookup can match the item the user just refused, so a refusal for any account now also marks the service-only lookup as refused for the run. A later read with only the service-only candidate answers from memory instead of prompting again. Named accounts that were not refused are still read.

Not changed: a Deny for one account still ends that read without trying the next account. That is deliberate: the consent policy is stop at Deny, and prompting for the next account right after the user declined is the double prompt this branch exists to remove.
2026-11-06 17:11:44 +01:00

252 lines
12 KiB
TypeScript

// Fixture-driven coverage for the ZCode quota adapter (the z.ai coding-plan
// login the ZCode desktop app keeps in its coding-plan webview's Local Storage
// journal). Tokens are synthetic; no test reaches the network or a real login.
import { describe, expect, it, vi } from 'vitest'
import { decodeZcodeUsage, fetchZcodeQuota, zcodeAccessToken } from '../src/quota/zcode.js'
import type { ZcodeDeps } from '../src/quota/zcode.js'
const neverFetch = (() => { throw new Error('the test must not reach the network') }) as unknown as typeof fetch
const TOKEN = 'eyJhbGciOiJIUzU1MiJ9.synthetic-zcode-login-with-no-meaning.sig'
const STORAGE_KEY = 'oauth:zai:access_token'
/** Shape and values mirror the recorded 200 response posted (redacted — it
* carries no account identity to begin with, only limits and the plan level)
* in the #1347 review thread. */
const successBody = {
code: 200,
data: {
level: 'pro',
limits: [
{ type: 'CREDIT_LIMIT', unit: 3, number: 5, usage: 12000, currentValue: 1853, percentage: 15, nextResetTime: 1_789_312_697_938 },
{ type: 'CREDIT_LIMIT', unit: 6, number: 1, usage: 60000, currentValue: 1853, percentage: 3, nextResetTime: 1_789_899_227_973 },
],
},
}
/** Byte-faithful to a recorded ZCode journal (redacted hexdump in the #1347
* review thread), framed as a leveldb put record: tag 0x01, the key length,
* the key (`_` + origin, a NUL, the 0x01 one-byte-string flag and the key
* name), then a varint length covering the same flag plus the value's Latin-1
* bytes. The recorded login's frame length encodes as `fb 0a` (1,403). */
function varint(n: number): Buffer {
const out: number[] = []
for (; n >= 0x80; n = Math.floor(n / 0x80)) out.push((n % 0x80) | 0x80)
out.push(n)
return Buffer.from(out)
}
/** A put record's tag, key length and key, in the key name's encoding. */
function recordHead(key: string, encoding: 'latin1' | 'utf16le' = 'latin1', origin = 'https://zcode.z.ai'): Buffer {
const dbKey = Buffer.concat([
Buffer.from(`_${origin}`, 'latin1'),
Buffer.from([0x00, encoding === 'latin1' ? 0x01 : 0x00]),
Buffer.from(key, encoding),
])
return Buffer.concat([Buffer.from([0x01]), varint(dbKey.length), dbKey])
}
function journalEntry(key: string, value: string, encoding: 'latin1' | 'utf16le' = 'latin1'): Buffer {
const bytes = Buffer.from(value, encoding)
return Buffer.concat([
recordHead(key, encoding),
varint(bytes.length + 1),
Buffer.from([encoding === 'latin1' ? 0x01 : 0x00]),
bytes,
])
}
function deps(files: Record<string, Buffer | null>, dir = '/mock/leveldb'): ZcodeDeps {
return {
fetch: vi.fn(),
storageDir: dir,
readDir: vi.fn(async () => Object.keys(files)),
readJournal: vi.fn(async (filePath: string) => files[filePath.slice(dir.length + 1)] ?? null),
env: {},
}
}
function jsonResponse(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', ...headers } })
}
describe('ZCode credential discovery', () => {
it('reads the login out of the newest Local Storage journal', async () => {
const base = deps({ '000003.log': journalEntry(STORAGE_KEY, TOKEN) })
await expect(zcodeAccessToken(base)).resolves.toBe(TOKEN)
})
it('ends the token at its frame length, not at the next record\'s checksum bytes', async () => {
const login = 'eyJhbGciOiJIUzUxMiJ9.' + 'a'.repeat(1377) + '.sig'
const journal = Buffer.concat([
journalEntry(STORAGE_KEY, login),
// The next physical record's header: a CRC whose first bytes read as "Az3", length, type.
Buffer.from([0x41, 0x7a, 0x33, 0x9c, 0x20, 0x00, 0x01]),
])
expect(journal.includes(Buffer.from([0xfb, 0x0a, 0x01]))).toBe(true)
await expect(zcodeAccessToken(deps({ '000003.log': journal }))).resolves.toBe(login)
})
it('keeps the most recent write when the rotation changed the string encoding', async () => {
const renewed = 'eyJhbGciOiJIUzU1MiJ9.synthetic-zcode-renewal-with-no-meaning.sig'
const journal = Buffer.concat([
journalEntry(STORAGE_KEY, TOKEN),
journalEntry(STORAGE_KEY, renewed, 'utf16le'),
])
await expect(zcodeAccessToken(deps({ '000003.log': journal }))).resolves.toBe(renewed)
})
it('reports a login the newest write cleared as expired, not the older token', async () => {
const files = { '000003.log': journalEntry(STORAGE_KEY, TOKEN), '000005.log': journalEntry(STORAGE_KEY, '') }
await expect(zcodeAccessToken(deps(files))).resolves.toBe('')
const sameFile = Buffer.concat([journalEntry(STORAGE_KEY, TOKEN), journalEntry(STORAGE_KEY, '')])
const result = await fetchZcodeQuota({ ...deps({ '000003.log': sameFile }), fetch: neverFetch })
expect(result.quota.connection).toBe('terminalFailure')
expect(result.quota.footerLines).toEqual(['Login expired. Open the ZCode app and sign in again, then refresh.'])
})
it('reads a malformed newest write as unreadable for this poll, never as the older token', async () => {
const older = journalEntry(STORAGE_KEY, TOKEN)
const head = recordHead(STORAGE_KEY)
const malformed = [
Buffer.concat([older, head, varint(5000), Buffer.from([0x01]), Buffer.from('eyJhbGciOiJIUzU1MiJ9.cut', 'latin1')]),
Buffer.concat([older, head, varint(0)]),
]
for (const journal of malformed) {
const fetchMock = vi.fn()
await expect(zcodeAccessToken(deps({ '000003.log': journal }))).rejects.toThrow('could not be read')
const result = await fetchZcodeQuota({ ...deps({ '000003.log': journal }), fetch: fetchMock as unknown as typeof fetch })
expect(result.quota.connection).toBe('transientFailure')
expect(fetchMock).not.toHaveBeenCalled()
}
})
it('reads past the key name inside a later entry\'s value, which is not a write of the key', async () => {
const journal = Buffer.concat([
journalEntry(STORAGE_KEY, TOKEN),
journalEntry('zcode:settings', `{"tokenKey":"${STORAGE_KEY}","theme":"dark"}`),
])
await expect(zcodeAccessToken(deps({ '000003.log': journal }))).resolves.toBe(TOKEN)
})
it('ignores the same key written under another origin', async () => {
const other = 'eyJhbGciOiJIUzU1MiJ9.synthetic-login-of-another-origin.sig'
const journal = Buffer.concat([
journalEntry(STORAGE_KEY, TOKEN),
recordHead(STORAGE_KEY, 'latin1', 'https://chat.z.ai'), varint(other.length + 1), Buffer.from([0x01]), Buffer.from(other, 'latin1'),
])
await expect(zcodeAccessToken(deps({ '000003.log': journal }))).resolves.toBe(TOKEN)
})
it('reads an odd-length UTF-16 newest write as unreadable, never as a trimmed token', async () => {
const bytes = Buffer.concat([Buffer.from('eyJhbGciOiJIUzU1MiJ9.synthetic-zcode-renewal.sig', 'utf16le'), Buffer.from([0x41])])
const journal = Buffer.concat([
journalEntry(STORAGE_KEY, TOKEN),
recordHead(STORAGE_KEY, 'utf16le'), varint(bytes.length + 1), Buffer.from([0x00]), bytes,
])
await expect(zcodeAccessToken(deps({ '000003.log': journal }))).rejects.toThrow('could not be read')
const fetchMock = vi.fn()
const result = await fetchZcodeQuota({ ...deps({ '000003.log': journal }), fetch: fetchMock as unknown as typeof fetch })
expect(result.quota.connection).toBe('transientFailure')
expect(fetchMock).not.toHaveBeenCalled()
})
it('reads a deleted key as a cleared login', async () => {
const dbKey = recordHead(STORAGE_KEY).subarray(1)
const journal = Buffer.concat([journalEntry(STORAGE_KEY, TOKEN), Buffer.from([0x00]), dbKey])
await expect(zcodeAccessToken(deps({ '000003.log': journal }))).resolves.toBe('')
})
it('keeps the most recent write when the key was rotated in place', async () => {
const journal = Buffer.concat([
journalEntry(STORAGE_KEY, TOKEN),
journalEntry(STORAGE_KEY, 'eyJhbGciOiJIUzU1MiJ9.synthetic-zcode-renewal-with-no-meaning.sig'),
])
await expect(zcodeAccessToken(deps({ '000003.log': journal }))).resolves.toBe('eyJhbGciOiJIUzU1MiJ9.synthetic-zcode-renewal-with-no-meaning.sig')
})
it('reports no token when the storage directory is missing', async () => {
const base = deps({})
base.readDir = vi.fn(async () => { throw new Error('ENOENT') })
await expect(zcodeAccessToken(base)).resolves.toBeNull()
})
})
describe('ZCode quota decoding', () => {
it('maps the credit windows with the plan level', () => {
const quota = decodeZcodeUsage(successBody)
expect(quota).not.toBe('rejected')
if (quota === null || quota === 'rejected') throw new Error('expected a decoded provider')
expect(quota.connection).toBe('connected')
expect(quota.planLabel).toBe('Pro')
expect(quota.details.map(row => row.label)).toEqual(['5-hour', 'Weekly'])
expect(quota.primary).toEqual({ label: 'Weekly', percent: 0.03, resetsAt: '2026-09-20T10:13:47.973Z' })
expect(quota.footerLines).toEqual(['Source: Z.ai Coding Plan'])
})
it('still reads string-typed token windows and derives the percentage', () => {
const quota = decodeZcodeUsage({
data: { limits: [{ type: 'TOKENS_LIMIT', unit: '3', number: '5', usage: '2000', currentValue: '500', nextResetTime: '1800000000' }] },
})
if (quota === null || quota === 'rejected') throw new Error('expected a decoded provider')
expect(quota.details).toEqual([{ label: '5-hour', percent: 0.25, resetsAt: '2027-01-15T08:00:00.000Z' }])
})
it('reads an authentication code in the body as a rejection', () => {
for (const code of [401, 403]) {
expect(decodeZcodeUsage({ code, msg: 'token expired or incorrect', success: false })).toBe('rejected')
}
})
it('rejects a payload with no usable window', () => {
expect(decodeZcodeUsage({ code: 500, success: false })).toBeNull()
expect(decodeZcodeUsage({ data: {} })).toBeNull()
expect(decodeZcodeUsage({ data: { limits: [] } })).toBeNull()
expect(decodeZcodeUsage({ data: { limits: [{ type: 'CREDIT_LIMIT', unit: 3, number: 5 }] } })).toBeNull()
expect(decodeZcodeUsage({ data: { limits: [{ type: 'CREDIT_LIMIT', unit: 9, number: 2, percentage: 5 }] } })).toBeNull()
})
})
describe('ZCode HTTP failures', () => {
it('reports disconnected with no login anywhere and never fetches', async () => {
const result = await fetchZcodeQuota({ ...deps({}), fetch: neverFetch })
expect(result.quota.connection).toBe('disconnected')
})
it('keeps the terminal and retryable classifications', async () => {
const respond = async (status: number, headers: Record<string, string> = {}) => fetchZcodeQuota({
...deps({ '000003.log': journalEntry(STORAGE_KEY, TOKEN) }),
fetch: (async () => jsonResponse({}, status, headers)) as unknown as typeof fetch,
})
expect((await respond(401)).quota.footerLines).toEqual(['Login expired. Open the ZCode app and sign in again, then refresh.'])
const limited = await respond(429, { 'Retry-After': '90' })
expect(limited.quota.rateLimited).toBe(true)
expect(limited.retryAfterSeconds).toBe(90)
expect((await respond(503)).quota.footerLines).toEqual(['Z.ai is temporarily unavailable.'])
expect((await respond(404)).quota.footerLines).toEqual(['Z.ai returned an unrecognized quota response.'])
})
it('turns a body-level authentication failure into a terminal state', async () => {
const result = await fetchZcodeQuota({
...deps({ '000003.log': journalEntry(STORAGE_KEY, TOKEN) }),
fetch: (async () => jsonResponse({ code: 401, success: false })) as unknown as typeof fetch,
})
expect(result.quota.connection).toBe('terminalFailure')
expect(result.quota.footerLines).toEqual(['Login expired. Open the ZCode app and sign in again, then refresh.'])
})
it('sends the journal token as a bearer to the usage endpoint', async () => {
const seen: Record<string, string>[] = []
const result = await fetchZcodeQuota({
...deps({ '000003.log': journalEntry(STORAGE_KEY, TOKEN) }),
fetch: (async (url: string, init: RequestInit) => {
expect(url).toBe('https://api.z.ai/api/monitor/usage/quota/limit')
seen.push(init.headers as Record<string, string>)
return jsonResponse(successBody)
}) as unknown as typeof fetch,
})
expect(result.quota.connection).toBe('connected')
expect(seen[0]!['Authorization']).toBe(`Bearer ${TOKEN}`)
})
})