diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 246acc7..7f20b15 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -4,7 +4,10 @@ permissions: contents: read jobs: test: - runs-on: ubuntu-latest + strategy: + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..42609d4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +## 0.2.0 — 2026-11-07 + +- Support the 3.17 client prompt layout, with extraction checked against official 3.17.1 and 3.17.2 bundles. Read client versions from package/ASAR metadata or explicit `provision --app-version`. +- Replace retired billing/current discovery with billing/balance plans and capability buckets, preserving activation times and plan selection. +- Discover free grants from billing previews and explicit marketing banner/popup claim actions. Enable scheduled claims by default, with `ZCODE_AUTO_CLAIM=false` as an opt-out. +- Persist actual grant expiry and bounded retry holds so undated recurring offers are revisited. Respect provider server time, Retry-After, CAPTCHA, authentication and risk responses. +- Add `promos` for discovery without claims and `claim` for one maintenance cycle. Expose sanitized offers, campaigns and per-source failures through existing authenticated usage/plan APIs. +- Keep legacy private templates, encrypted account data and all existing API protocols compatible. No npm production dependencies added. + +Live verification covered current billing, marketing, process health and HTTP authentication. The available account had no active grant; successful live claims and inference with 3.17.2 were not verified. See [verification](docs/verification.md). diff --git a/README.en.md b/README.en.md index 4a62d28..7d075b3 100644 --- a/README.en.md +++ b/README.en.md @@ -4,7 +4,7 @@ Use your own ZCode Start Plan accounts through OpenAI and Anthropic-compatible APIs. This standalone Node.js gateway supports OAuth login, an encrypted multi-account vault, streamed model output and function-tool conversations. It can run behind OmniRoute or be used directly. -This is an independent integration with an undocumented ZCode endpoint. It is not affiliated with Z.ai. Compatibility was checked against ZCode desktop **3.16.3**, with **GLM-5.3** and **GLM-5.3-Flash** entitlements. Provider changes can break the integration. +This is an independent integration with an undocumented ZCode endpoint. It is not affiliated with Z.ai. Updated for the ZCode **3.17.2** client format, including prompt extraction, versioned requests, billing and campaign discovery. Extraction was also checked with **3.17.1**. See [verification notes](docs/verification.md) for live-test limits; provider changes can break the integration. ## Supported endpoints @@ -43,7 +43,9 @@ node --env-file=.env src/cli.ts provision 'C:\Program Files\ZCode\resources\glm\ `init` creates `.env` with independent random ZCODE_MASTER_KEY and ZCODE_API_KEYS values. For the API Key field in OmniRoute or another app, copy one value from `ZCODE_API_KEYS` in `.env`, without the `ZCODE_API_KEYS=` prefix. Do not use `ZCODE_MASTER_KEY` for API requests. Keep `.env` and `data/` out of Git. The server binds to `127.0.0.1:8080` by default. -Provisioning extracts only the supported prompt functions from your installed official client into `data/template.json`. It does not execute the installed application's entrypoint or modify ZCode. Vendor prompt text is **not distributed in this repository** and is not covered by this project's MIT license. The extractor fails when its expected bundle structure is absent; do not force it against another release without verification. +Provisioning extracts the supported private prompt sections from your installed official client into `data/template.json`. It does not execute the installed application's entrypoint or modify ZCode. Vendor prompt text is **not distributed in this repository** and is not covered by this project's MIT license. The extractor fails when its expected bundle structure is absent; do not force it against another release without verification. + +The app version is read from adjacent `package.json` or `app.asar` metadata and passed to OAuth, billing, claims and inference. Run `provision` again after updating the desktop app. For a standalone bundle without its metadata, use `provision /path/zcode.cjs --app-version 3.17.2` with its actual release version. Legacy 3.16.3 templates remain readable. Unknown prompt structures fail instead of guessing compatibility. The private template also records the provisioning machine's platform, shell, locale, timezone and working directory. Both upstream headers and environment context preserve those original values when the gateway moves to a VPS. This keeps the request consistent with the desktop profile being delegated; it does not grant the gateway access to that desktop's files or tools. Treat this metadata as private and regenerate the template when intentionally moving to a different client profile. @@ -74,15 +76,28 @@ node --env-file=.env src/cli.ts remove ACCOUNT_ID Selection rotates among enabled, model-entitled accounts, with one in-flight request per account. Quota, authentication and transient failures may try another account before any response content is sent. Risk-control rejection code 3012 pauses that account locally for 15 minutes and returns the error without trying to bypass its block. This delay is local policy, not an upstream reset guarantee. Streams are never replayed after output begins. Account credentials that fail authorization require a new login; the gateway does not pretend an undocumented refresh endpoint exists. -`quota` reads reported plan and balance data. Unknown counters remain unknown. The scheduler uses entitlements and provider errors, rather than guessing token balances from missing fields. Automatic claims are opt-in; see below. +`quota` reads reported plan and balance data. Unknown counters remain unknown. The scheduler uses entitlements and provider errors, rather than guessing token balances from missing fields. Automatic free-grant claims are enabled by default; see below. + +## Automatic promotions and events + +The worker runs at startup and every five minutes without inbound HTTP traffic. Automatic claims are **enabled by default**; set `ZCODE_AUTO_CLAIM=false` to opt out. An existing explicit false remains respected. `ZCODE_AUTO_CLAIM_INTERVAL_MS` defaults to `300000`, with a one-minute minimum. Restart the process or recreate the Compose service after changing settings. + +Two official channels are queried per eligible Start Plan account: billing preview model grants, and marketing touch banner/popup buttons with the explicit `claim_zcode_plan` action. Campaign names and grant IDs come from provider responses. Paid preview entries, external URLs, navigation, invitation and copy actions are never executed. Subscription accounts, disabled accounts and accounts requiring login are skipped. -## Automatic free-plan claims +Offers are deduplicated across channels. Real expiry from claim responses prevents successful undated previews from suppressing future periods forever. Unknown claim expiry uses a bounded retry hold. After claims, entitlement discovery reads **billing balance**, replacing the retired `billing/current` endpoint. Capability buckets are matched to active plan instances; future and expired entitlements are excluded. + +Stop `serve` before either one-shot command: + +```sh +node --env-file=.env src/cli.ts promos # Discover only; no claims +node --env-file=.env src/cli.ts claim # Run one free-grant claim cycle +``` -Set `ZCODE_AUTO_CLAIM=true` in `.env` and restart the service. `ZCODE_AUTO_CLAIM_INTERVAL_MS` defaults to `300000` (five minutes), with a one-minute minimum. Docker Compose forwards both settings; recreate the service after changing them. +Both commands persist discovery diagnostics in the encrypted vault. Authenticated `/api/usage` and `/api/plans` expose `accounts[].autoClaim`, including `sources`, `offers`, sanitized `campaigns`, claim results, grant expiry and retry times. `idle` means both channels were read successfully, including empty results; `discovery_partial` means a source was unavailable; `discovery_failed` means neither succeeded. Success codes without required payloads report `missing_data` instead of pretending discovery was complete. -The worker refreshes entitlements and checks provider previews at startup and periodically without inbound HTTP traffic. It considers unexpired model grants without payment fields, skips subscription accounts and accounts requiring login, and never purchases a paid plan. Successful claims and retry holds are persisted in the encrypted vault. Claims already held for the same period are skipped; a later period can reuse the same plan ID. Future activation does not prevent claiming, but model discovery waits for entitlement activation. +HTTP and provider error codes are checked separately, including numeric string codes and plain-text HTTP errors. `Retry-After` is honored. CAPTCHA, risk-control and login failures stop further claims for that account. The worker does not bypass verification, buy plans, open campaign links or send invitations. -Authenticated `/api/usage` and `/api/plans` expose per-account `autoClaim` status. An empty preview produces `idle`. Required or unknown CAPTCHA verification requires manual action, as does reauthorization. Availability and eligibility remain provider-controlled; a `one_time` grant does not promise daily refills. +Coverage is limited to the two verified official offer channels. Referral, payment or manual eligibility conditions remain provider-controlled. Unknown future endpoints are not automatically supported. A `daily` entitlement period does not guarantee a new offer every day, and a `one_time` grant does not promise refills. Model discovery refreshes before publishing the catalog or rejecting a missing model. During account cooldown, rate-limit failures retain their upstream status and safe error reason with `Retry-After` instead of becoming a generic no-account error. diff --git a/README.md b/README.md index 08c5428..3818a63 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Pakai model dari akun ZCode Anda di OmniRoute atau aplikasi yang mendukung API OpenAI dan Anthropic. Anda bisa menambahkan beberapa akun, melihat sisa kuota, dan memilih paket untuk tiap akun. -Sudah diuji dengan ZCode **3.16.3**, **GLM-5.3**, dan **GLM-5.3-Flash**. Proyek ini dibuat secara independen. Jika ZCode mengubah layanannya, integrasi ini mungkin perlu diperbarui. +Diperbarui untuk format klien ZCode **3.17.2**: template, versi request, billing, serta penawaran promo dan kampanye. Ekstraksi juga diperiksa pada **3.17.1**. Hasil dan batas uji langsung tercatat di [catatan pengujian](docs/verification.md). Proyek ini dibuat secara independen; perubahan layanan ZCode bisa memerlukan pembaruan integrasi. ## Mulai dari sini @@ -46,7 +46,15 @@ node --env-file=.env src/cli.ts provision "C:/Program Files/ZCode/resources/glm/ Ganti lokasi file jika ZCode Anda terpasang di folder lain. Untuk sistem lain, gunakan lokasi `resources/glm/zcode.cjs` dari instalasi ZCode Anda. -Perintah ini membuat `data/template.json` dari aplikasi ZCode yang terpasang. File ini diperlukan agar request bisa dikirim ke ZCode. Instalasi ZCode Anda tetap seperti semula. +Perintah ini membuat `data/template.json` dari aplikasi ZCode yang terpasang. Versi klien dibaca dari metadata aplikasi; header login, billing, klaim, dan inferensi memakai versi tersebut. Instalasi ZCode Anda tetap seperti semula. Jalankan `provision` lagi setelah memperbarui aplikasi. + +Jika hanya menyalin `zcode.cjs` tanpa metadata aplikasi, sertakan versi asalnya secara eksplisit: + +```sh +node --env-file=.env src/cli.ts provision /lokasi/zcode.cjs --app-version 3.17.2 +``` + +Template lama versi 3.16.3 tetap dapat dibaca. Ekstraktor akan menolak struktur prompt yang belum dikenali; tidak ada jaminan kompatibilitas dengan rilis yang belum diuji. ### 4. Tambahkan akun @@ -129,22 +137,38 @@ Ganti `ACCOUNT_ID` dengan ID dari perintah `accounts`. Menghapus akun di sini ti Request dibagi bergiliran ke akun aktif yang mendukung model tersebut. Setiap akun menangani satu request pada satu waktu. Jika satu akun gagal sebelum jawaban mulai dikirim, ZCode Gateway dapat mencoba akun lain. -## Klaim otomatis paket gratis +## Promo dan event otomatis -Klaim otomatis dapat diaktifkan untuk akun Start Plan yang terhubung dengan menambahkan pengaturan berikut ke `.env`, lalu memulai ulang layanan: +Pemeriksaan dan klaim grant gratis **aktif secara default** ketika `serve` berjalan. Gateway memeriksa saat mulai dan setiap lima menit, termasuk ketika tidak ada request API. Pengaturannya: ```dotenv ZCODE_AUTO_CLAIM=true ZCODE_AUTO_CLAIM_INTERVAL_MS=300000 ``` -Gateway memeriksa penawaran saat mulai dan setiap lima menit, tanpa menunggu request masuk. Interval minimum adalah satu menit. Untuk Docker Compose, jalankan ulang `docker compose up -d` setelah mengubah pengaturan. +Interval minimum satu menit. Isi `ZCODE_AUTO_CLAIM=false` untuk mematikannya. Nilai `false` yang sudah ada tetap dihormati. Restart layanan setelah mengubah `.env`; pada Docker, jalankan `docker compose up -d` untuk menerapkan pengaturan. + +Dua sumber resmi dibaca untuk setiap akun Start Plan aktif: + +- **Billing preview**: grant model yang ditawarkan akun, belum kedaluwarsa, dan tidak mencantumkan biaya. +- **Marketing touch**: kampanye banner dan popup dengan aksi eksplisit `claim_zcode_plan`. Nama event dan ID paket berasal dari respons provider; tidak dikunci ke daftar promo tertentu. + +Penawaran yang sama dari dua sumber hanya diproses sekali. Masa berlaku dari respons klaim disimpan agar preview tanpa tanggal tidak menghalangi klaim periode berikutnya. Setelah klaim, model dan kuota diperbarui dari **billing balance**, pengganti endpoint `billing/current` yang sudah tidak dipakai klien terbaru. Model menunggu waktu aktivasi entitlement. + +Untuk memeriksa tanpa mengklaim atau menjalankan satu siklus klaim, hentikan `serve` terlebih dahulu: + +```sh +node --env-file=.env src/cli.ts promos +node --env-file=.env src/cli.ts claim +``` + +`promos` hanya melakukan discovery; `claim` mencoba grant gratis yang ditawarkan. Keduanya menyimpan status pemeriksaan di vault. Akun yang dinonaktifkan, perlu login ulang, atau memakai route Coding Plan dilewati. -Hanya paket grant model yang ditawarkan endpoint preview, belum kedaluwarsa, dan tidak mencantumkan biaya yang diproses. Langganan berbayar tidak dibeli. Paket yang aktif pada periode yang sama serta klaim yang sudah berhasil tidak diulang; paket periode berikutnya tetap diperiksa meskipun ID-nya sama. Paket boleh diklaim sebelum waktu aktivasinya, tetapi model baru tersedia setelah entitlement aktif. +Respons berautentikasi `/api/usage` dan `/api/plans` memuat `accounts[].autoClaim`: `sources`, `offers`, ringkasan `campaigns`, hasil klaim, masa berlaku, dan waktu retry. `idle` berarti kedua kanal berhasil dibaca; `discovery_partial` berarti hanya sebagian sumber tersedia, sedangkan `discovery_failed` berarti discovery gagal. Kode sukses tanpa payload diberi alasan `missing_data`, bukan dianggap bukti bahwa seluruh promo kosong. Daftar kosong dapat tetap menghasilkan `idle`. -Status per akun tersedia pada `autoClaim` di respons berautentikasi `/api/usage` atau `/api/plans`. Jika penawaran kosong, statusnya `idle`. CAPTCHA atau login ulang yang diwajibkan provider memerlukan tindakan manual. Fitur ini tidak menjamin ada penawaran setiap hari; paket berperiode `one_time` tidak menjanjikan isi ulang kuota harian. +Rate limit mengikuti `Retry-After`. Respons CAPTCHA, login ulang, atau pembatasan risiko menghentikan klaim berikutnya pada akun itu dan menyimpan status tindakan yang diperlukan. Tidak ada pemecahan CAPTCHA, pembelian langganan, pembukaan tautan promosi, atau pengiriman undangan otomatis. -Daftar model juga disegarkan sebelum katalog ditampilkan dan sebelum model yang belum tercatat ditolak. Jika provider menolak request dengan rate limit, gateway mempertahankan penyebab penolakan serta header `Retry-After` selama masa jeda akun. +**Cakupan otomatis mengikuti kanal dan izin yang disediakan ZCode.** Event dengan syarat referral, pembelian, atau tindakan manual tetap membutuhkan syarat tersebut. Promo dari kanal lain atau endpoint baru tidak dijamin terambil. Label `daily` menunjukkan periode entitlement provider; gateway tidak membuat kuota baru dan tidak menjamin promo tersedia setiap hari. ## Ganti paket yang dipakai diff --git a/compose.yaml b/compose.yaml index d803dd4..3afc147 100644 --- a/compose.yaml +++ b/compose.yaml @@ -5,7 +5,7 @@ services: environment: ZCODE_MASTER_KEY: ${ZCODE_MASTER_KEY:?set master key} ZCODE_API_KEYS: ${ZCODE_API_KEYS:?set client keys} - ZCODE_AUTO_CLAIM: ${ZCODE_AUTO_CLAIM:-false} + ZCODE_AUTO_CLAIM: ${ZCODE_AUTO_CLAIM:-true} ZCODE_AUTO_CLAIM_INTERVAL_MS: ${ZCODE_AUTO_CLAIM_INTERVAL_MS:-300000} volumes: - ./data:/data diff --git a/docs/updates/2026-11-07-compatibility.md b/docs/updates/2026-11-07-compatibility.md new file mode 100644 index 0000000..067ab86 --- /dev/null +++ b/docs/updates/2026-11-07-compatibility.md @@ -0,0 +1,17 @@ +# ZCode 3.17 compatibility and automatic offers + +Scope: update the existing gateway for the official 3.17.2 client and automatically process provider-offered free grants. Keep Node 24.14+, the encrypted vault, existing protocols and legacy templates. No paid purchases, fabricated eligibility, referral creation or verification bypass. + +Evidence: official release v3.17.2, source commit a9fe401eede6e6e5e01be9048679c206fe6f02d9. The Windows release archive matches its published SHA256SUMS. The client uses billing preview/claim and marketing/touch; the old agent/configs CAPTCHA preflight is absent from the current claim flow. Preview grants may omit dates. Claim responses contain the actual grant period. Marketing buttons explicitly distinguish claim_zcode_plan from navigation and external URLs. + +Implementation plan: + +- [x] Add failing tests for modern template extraction, metadata version discovery and propagation to billing. +- [x] Read the app version from adjacent package metadata/ASAR (or explicit provision argument); extract modern prompt sections without depending on minified symbol names. Preserve legacy extraction and templates. +- [x] Add failing tests for marketing claims, repeated undated offers, grant expiry, HTTP errors, numeric string codes, per-source failures and server time. +- [x] Query billing preview and marketing touch independently. Merge only explicit claim actions and free model grants. Persist real claim expiry, provider retry holds and bounded diagnostic summaries. Refresh entitlements after claims. Stop on login/risk/verification requirements. +- [x] Expose authenticated offer status and add a one-shot claims CLI. Enable automatic claims for new installations, preserving an explicit false opt-out. +- [x] Run all tests and syntax checks, provision from the verified 3.17.2 archive, then perform available authenticated live checks without publishing credentials. +- [x] Update both guides, release notes and CI; publish the verified branch as a pull request and provide a source archive and patch. + +Coverage limit: automatically handles the two verified official offer channels. Invitations, paid plans, CAPTCHA, eligibility requirements and future unknown endpoints remain provider-controlled. An empty preview is not proof that no other promotion exists. diff --git a/docs/verification.md b/docs/verification.md index 8ad88c0..ae311e9 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -50,3 +50,19 @@ The subsequent owner instruction enabled per-key logging by default: all 13 exis The owner's local vault could not be opened with the current local master key; its original deployment key decrypted both saved accounts. The local configuration was backed up privately and restored without deleting the vault. Desktop import then succeeded for the existing second account, and live OAuth initialization succeeded. This confirms local vault recovery and flow initialization, not a new completed browser-consent flow. The CLI now explains vault authentication failures and refuses `init` when an existing vault has no matching environment file. Login opens the default browser, provides OSC 8 links in interactive terminals, and supports `--no-browser`. Twenty-six local tests passed, including wrong-key preservation, initialization refusal, launcher argument handling, terminal-link validation and browser-launch fallback. Syntax checks passed for ten source modules. Actual link click behavior depends on the terminal's OSC 8 support; browser-launch tests use an injected launcher. The Indonesian guide is available in `README.id.md`. + +## 2026-11-07 — ZCode 3.17 compatibility and promotions + +Version 0.2.0 was checked on Node.js 24.14.1 / Windows. `npm test`: 80 passed, zero failed. `npm run check`: 11 source modules passed. Git whitespace validation passed. CI now covers Ubuntu and Windows with Node 24. + +Template extraction succeeded against the installed official 3.17.1 bundle and the official 3.17.2 Windows x64 release. The latter installer SHA-256 matched the release's published SHA256SUMS: `2466b25b747918a8bdf8a2ef71419e377ede60541e9e8f3c88771de07855dc3d`. Its extracted zcode.cjs hash was `66c05fccbf354aee197427adcefe52893b32630ff18503a4973c740952bdf680`. No vendor prompt text or account data is included in the repository. + +Current API contracts were checked against [official release source a9fe401](https://github.com/zai-org/ZCode/tree/a9fe401eede6e6e5e01be9048679c206fe6f02d9), specifically billing balance, manual grant claims, marketing touch and the current prompt layout. The retired billing/current endpoint must not drive model discovery. Static startPlanPreview display information is not treated as an account-specific offer or claimed by guessing eligibility. + +New automated coverage includes renamed minified prompt identifiers, ASAR version metadata, executable interpolation rejection, version propagation, bucket-based discovery, activation/expiry/selected-plan filters, banner/popup claims, duplicate sources, undated recurring grants, actual claim expiry, short periods, provider time, partial discovery, HTTP and business errors, plain-text rate limits, retry persistence, one-shot CLI commands, and an end-to-end background claim that activates models and serves all three HTTP API formats through a fixture provider. Existing streaming, tool, OAuth, encrypted vault, cooldown and shutdown tests remain passing. + +Authenticated live checks used the available desktop login in an isolated, ignored gateway vault. Billing balance returned HTTP 200 with empty plans/balances; marketing touch returned code 0 with no deliveries. Billing preview returned HTTP 200/code 0 without data, reported as `sources.preview.reason=missing_data` and `discovery_partial`. The claim cycle made zero claim requests because neither source offered a grant. Live HTTP checks confirmed unauthenticated requests receive 401 and authenticated health, model catalog and usage requests succeed; background discovery ran without an incoming inference request. + +There was no currently entitled model on this account, so successful live claims, 3.17.2 inference, and genuine multi-account claim behavior were not verified. Fixture coverage does not replace those live checks. No paid purchase, invitation, browser login, CAPTCHA completion or production deployment was performed. + +Docker Compose configuration validation passed. A container build/run was not performed because the local Docker Linux daemon was not running. diff --git a/package.json b/package.json index e011c3c..4a1d374 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "zcode-gateway", - "version": "0.1.0", + "version": "0.2.0", "private": true, "type": "module", "description": "OAuth multi-account ZCode gateway with OpenAI and Anthropic protocol adapters", diff --git a/src/claims.ts b/src/claims.ts index affe607..a6b991e 100644 --- a/src/claims.ts +++ b/src/claims.ts @@ -1,73 +1,121 @@ +import { headers } from './upstream.ts'; + +const validId=(value:any)=>typeof value==='string'&&value.trim()===value&&value.length>0&&value.length<=200; +const seconds=(value:any)=>typeof value==='number'&&Number.isFinite(value)&&value>0?value*1000:undefined; +function freeOffer(plan:any) { + if(!validId(plan?.plan_id)||plan.requires_payment||plan.paid||plan.is_free===false)return false; + return [plan.price,plan.cost,plan.amount].every(value=>value==null||(typeof value==='number'&&value===0)); +} +function modelGrant(plan:any) { + return Array.isArray(plan.entitlements)&&plan.entitlements.some((e:any)=>Number(e?.grant_units)>0&&Array.isArray(e.capabilities)&&e.capabilities.some((c:any)=>typeof c==='string'&&c.startsWith('model:'))); +} + export function createAutoClaim(vault: any, template: any, refresh: any, options: any = {}) { const fetcher=options.fetcher || fetch,now=options.now || Date.now; const intervalMs=options.intervalMs ?? 300000; if(!Number.isFinite(intervalMs)||intervalMs<60000)throw new Error('Auto claim interval must be at least 60000 ms'); const log=options.log || (()=>{}),control=new AbortController(); - let pending:Promise|undefined,timer:ReturnType|undefined,stopped=false; - const base='https://zcode.z.ai',version=template.appVersion; - const platform=(template.context?.platform || process.platform)+'-'+(template.context?.arch || process.arch); - async function request(path:string,headers:any,body?:any){ - const response=await fetcher(base+path,{method:body?'POST':'GET',headers,body:body?JSON.stringify(body):undefined,redirect:'error',signal:AbortSignal.any([control.signal,AbortSignal.timeout(15000)])}); - const data=await response.json(); - return {ok:response.ok&&data.code===0,code:Number.isFinite(Number(data.code))?Number(data.code):response.status,data:data.data}; + let pending:Promise|undefined,timer:ReturnType|undefined,stopped=false,sequence=0; + const version=template.appVersion,platform=(template.context?.platform || process.platform)+'-'+(template.context?.arch || process.arch); + async function request(path:string,auth:any,body?:any) { + try { + const response=await fetcher('https://zcode.z.ai'+path,{method:body?'POST':'GET',headers:auth,body:body?JSON.stringify(body):undefined,redirect:'error',signal:AbortSignal.any([control.signal,AbortSignal.timeout(15000)])}); + const data=await response.json().catch(()=>undefined); + const raw=data?.code,code=typeof raw==='number'&&Number.isFinite(raw)?raw:typeof raw==='string'&&/^\d+$/.test(raw)?Number(raw):-1; + const retry=response.headers.get('retry-after'); + const delay=retry&&/^\d+$/.test(retry)?Number(retry)*1000:retry?Date.parse(retry)-now():0; + const effectiveCode=response.ok||[3007,3012].includes(code)?code:response.status; + return {ok:response.ok&&code===0,code:effectiveCode,data:data?.data,retryMs:Number.isFinite(delay)?Math.min(86400000,Math.max(0,delay)):0}; + } catch {return {ok:false,code:-1,data:undefined,retryMs:0};} } - function offeredGrant(plan:any,time:number){ - if(typeof plan?.plan_id!=='string'||!plan.plan_id||plan.plan_id.length>200)return false; - if(plan.requires_payment||plan.paid||plan.is_free===false)return false; - for(const value of [plan.price,plan.cost,plan.amount])if(value!=null&&(typeof value!=='number'||value!==0))return false; - if(plan.ends_at&&plan.ends_at*1000<=time)return false; - return Array.isArray(plan.entitlements)&&plan.entitlements.some((e:any)=>Number(e.grant_units)>0&&Array.isArray(e.capabilities)&&e.capabilities.some((c:any)=>typeof c==='string'&&c.startsWith('model:'))); - } - async function cycle(){ - await refresh(); - for(const a of vault.accounts){ + const statusFor=(code:number)=>({1003:'already_claimed',1004:'ineligible',1005:'quota_exhausted',3007:'captcha_required',401:'login_required',403:'login_required',3012:'risk_blocked',429:'rate_limited',503:'provider_unavailable'}[code] || 'failed'); + async function cycle() { + try {await refresh();}catch {log({event:'auto_claim',status:'entitlement_refresh_failed'});} + for(const a of vault.accounts) { if(stopped)break; if(!a.enabled||a.needsLogin||a.plan==='coding-plan')continue; const time=now(),state=a.autoClaim ||= {plans:[]}; - state.checkedAt=time;state.nextCheckAt=time+intervalMs;state.status='checking'; - const auth={Authorization:'Bearer '+a.token,...(a.deviceId?{'X-Device-Mid':a.deviceId}:{})}; - try{ + if(state.retryAt>time)continue; + state.checkedAt=time;state.nextCheckAt=time+intervalMs;state.status='checking';delete state.retryAt; + state.plans ||= [];state.sources={};state.campaigns=[];state.offers=[];state.offeredPlans=0; + const auth={...headers(a.token,version,template.context),...(a.deviceId?{'X-Device-Mid':a.deviceId}:{})}; + const candidates=new Map(),blocked=new Set(); + let changed=false; + function hold(code:number,retryMs=0) { + const status=statusFor(code); + if(['login_required','risk_blocked','captcha_required','rate_limited','provider_unavailable'].includes(status)) { + state.status=status;state.code=code; + state.retryAt=time+Math.max(retryMs,status==='risk_blocked'?900000:status==='captcha_required'?3600000:intervalMs); + state.nextCheckAt=state.retryAt; + if(status==='login_required')a.needsLogin=true; + return true; + } + return false; + } + try { const preview=await request('/api/v1/zcode-plan/billing/preview?app_version='+encodeURIComponent(version)+'&platform='+encodeURIComponent(platform),auth); - if(!preview.ok||!Array.isArray(preview.data?.plans)){state.status=preview.code===401?'login_required':'preview_failed';state.code=preview.code;continue;} - const candidates=preview.data.plans.filter((p:any)=>offeredGrant(p,time)); - state.status='idle';state.offeredPlans=candidates.length;delete state.code; - let captchaAllowed:boolean|undefined,changed=false; - for(const p of candidates){ + const previewOk=preview.ok&&Array.isArray(preview.data?.plans); + state.sources.preview={status:previewOk?'ok':'failed',code:preview.code,...preview.ok&&!previewOk?{reason:'missing_data'}:{}}; + if(!previewOk&&[401,403,3007,3012,429].includes(preview.code)&&hold(preview.code,preview.retryMs))continue; + const providerTime=seconds(preview.data?.server_time) ?? time; + for(const p of previewOk?preview.data.plans:[]) { + if(!freeOffer(p)){if(validId(p?.plan_id))blocked.add(p.plan_id);continue;} + if(p.ends_at!=null&&!seconds(p.ends_at)){blocked.add(p.plan_id);continue;} + if(p.ends_at&&seconds(p.ends_at)!<=providerTime){blocked.add(p.plan_id);continue;} + if(modelGrant(p))candidates.set(p.plan_id,{...p,source:'preview',providerTime}); + } + if(!stopped&&a.deviceId) { + const marketing=await request('/api/v1/marketing/touch?seq='+sequence++,{...auth,'X-Client-Language':template.context?.locale==='zh-CN'?'zh-CN':'en-US'}); + const marketingOk=marketing.ok&&Array.isArray(marketing.data?.deliveries); + state.sources.marketing={status:marketingOk?'ok':'failed',code:marketing.code,...marketing.ok&&!marketingOk?{reason:'missing_data'}:{}}; + if(!marketingOk&&[401,403,3007,3012,429].includes(marketing.code)&&hold(marketing.code,marketing.retryMs))continue; + const marketingTime=seconds(marketing.data?.server_time) ?? providerTime; + for(const d of marketingOk?marketing.data.deliveries.slice(0,32):[]) { + if(!validId(d?.campaign_id)||!['banner','popup'].includes(d.resource_position))continue; + const content=d[d.resource_position];if(!Array.isArray(content?.buttons))continue; + const actions=content.buttons.slice(0,4).map((b:any)=>b?.action).filter((x:any)=>x&&typeof x.type==='string'); + const planIds=actions.filter((x:any)=>x.type==='claim_zcode_plan'&&validId(x.args?.plan_id)).map((x:any)=>x.args.plan_id); + state.campaigns.push({campaignId:d.campaign_id,position:d.resource_position,title:typeof content.title?.content==='string'?content.title.content.slice(0,500):undefined,planIds,actionTypes:[...new Set(actions.map((x:any)=>['claim_zcode_plan','close','open_url','navigate','copy_text'].includes(x.type)?x.type:'unsupported'))],status:planIds.length?'claimable':'manual_action'}); + for(const id of planIds)if(!blocked.has(id)&&!candidates.has(id))candidates.set(id,{plan_id:id,source:'marketing',providerTime:marketingTime}); + } + } else state.sources.marketing={status:a.deviceId?'stopped':'device_required'}; + const marketingOk=state.sources.marketing.status==='ok'; + state.status=previewOk&&marketingOk?'idle':previewOk||marketingOk?'discovery_partial':'discovery_failed'; + state.offeredPlans=candidates.size;delete state.code;delete state.refreshFailed; + state.offers=[...candidates.values()].map(p=>({planId:p.plan_id,source:p.source,endsAt:seconds(p.ends_at)})); + if(options.discoverOnly)continue; + for(const p of candidates.values()) { if(stopped)break; - if((a.plans||[]).some((q:any)=>q.plan_id===p.plan_id&&q.status!=='expired'&&(!q.ends_at||q.ends_at*1000>time)&&q.ends_at===p.ends_at))continue; + if((a.plans||[]).some((q:any)=>q.plan_id===p.plan_id&&q.status!=='expired'&&(!q.ends_at||seconds(q.ends_at)!>p.providerTime)&&(!p.ends_at||q.ends_at===p.ends_at)))continue; const key=p.plan_id+':'+(p.ends_at || 0),previous=state.plans.find((r:any)=>r.key===key); - if(previous&&(previous.status==='claimed'||previous.status==='already_claimed'||previous.retryAt>time))continue; - const record={key,planId:p.plan_id,checkedAt:time,retryAt:time+3600000,status:'failed',code:0}; - if(captchaAllowed===undefined){ - const config=await request('/api/v1/agent/configs',auth); - const captcha=config.ok?config.data?.configs?.captcha:undefined; - captchaAllowed=captcha?.enabled===false||captcha?.skip_model_request===true; - } - if(!captchaAllowed){record.status='captcha_required';} - else{ - const response=await request('/api/v1/zcode-plan/billing/claim',{Authorization:auth.Authorization,'Content-Type':'application/json','X-ZCode-App-Version':version,'X-Platform':platform,...(a.deviceId?{'X-Device-Mid':a.deviceId}:{})},{plan_id:p.plan_id}); - record.code=response.code; - const claimed=response.data?.plan; - record.status=response.ok&&claimed&&typeof claimed==='object'&&(!claimed.plan_id||claimed.plan_id===p.plan_id)?'claimed':({1003:'already_claimed',1004:'ineligible',1005:'quota_exhausted',3007:'captcha_required',401:'login_required',403:'login_required',3012:'risk_blocked'}[response.code] || 'failed'); - changed ||= record.status==='claimed'||record.status==='already_claimed'; + if(previous) { + const activeUntil=previous.endsAt; + if(previous.retryAt>time)continue; + if(['claimed','already_claimed'].includes(previous.status)&&((activeUntil&&activeUntil>p.providerTime)||(p.ends_at&&seconds(p.ends_at)!>p.providerTime)))continue; } - state.plans=[...state.plans.filter((r:any)=>r.key!==key),record].slice(-50); - state.status=record.status; - vault.save(); - log({event:'auto_claim',accountId:a.id,planId:p.plan_id,status:record.status,code:record.code}); - if(['login_required','risk_blocked'].includes(record.status))break; + const response=await request('/api/v1/zcode-plan/billing/claim',auth,{plan_id:p.plan_id}); + const claimed=response.data?.plan; + const status=response.ok&&claimed&&typeof claimed==='object'&&!Array.isArray(claimed)&&(!claimed.plan_id||claimed.plan_id===p.plan_id)?'claimed':statusFor(response.code); + const endsAt=seconds(claimed?.ends_at),claimTime=seconds(response.data?.server_time) ?? p.providerTime; + const retryMs=status==='claimed'&&endsAt?Math.max(0,Math.min(3600000,endsAt-claimTime)):Math.max(3600000,response.retryMs); + const record={key,planId:p.plan_id,source:p.source,checkedAt:time,retryAt:time+retryMs,endsAt,status,code:response.code}; + state.plans=[...state.plans.filter((r:any)=>r.key!==key),record].slice(-200); + state.status=status;changed ||= status==='claimed'||status==='already_claimed'; + vault.save();log({event:'auto_claim',accountId:a.id,planId:p.plan_id,source:p.source,status,code:record.code}); + if(hold(response.code,response.retryMs))break; } - if(changed)await refresh({force:true}); - }catch{state.status=stopped?'stopped':'preview_failed';} - finally{vault.save();} + } finally { + if(changed&&!stopped)try {await refresh({force:true});}catch {state.refreshFailed=true;} + vault.save(); + } } } - function run():Promise{ + function run():Promise { if(stopped)return Promise.resolve(); if(!pending)pending=cycle().catch(()=>{log({event:'auto_claim',status:'maintenance_failed'});}).finally(()=>{pending=undefined;}); return pending; } - function start(){ + function start() { if(stopped||timer||pending)return; const tick=()=>{void run().finally(()=>{if(!stopped){timer=setTimeout(()=>{timer=undefined;tick();},intervalMs);timer.unref();}});}; tick(); diff --git a/src/cli.ts b/src/cli.ts index b86ca9c..5bb82bc 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -15,14 +15,14 @@ const args=process.argv.slice(2),command=args[0] || 'help'; const dir=resolve(process.env.ZCODE_DATA_DIR || './data'); function envSecret(name: string){return process.env[name+'_FILE']?readFileSync(process.env[name+'_FILE']!,'utf8').trim():process.env[name] || '';} function vault(){return new Vault(join(dir,'accounts.enc'),envSecret('ZCODE_MASTER_KEY'));} -function usage(){console.log(`ZCode Gateway\n\nnode src/cli.ts \n\n init Create local .env and data directory\n provision Extract private templates from ZCode 3.16.3\n login [zai|bigmodel] [label] Authorize and add/update one account\n import-desktop [label] Import this user's existing ZCode login\n accounts List account IDs and enabled models\n quota / plans Refresh account entitlements and balance\n plan start-plan Select the default promotional/trial route\n plan coding-plan --key-file PATH --models MODEL,MODEL\n Select a subscription with its own key\n enable / disable Change account eligibility\n remove Delete this local login (does not revoke upstream)\n serve Run authenticated HTTP service\n\nRun with node --env-file=.env src/cli.ts after init.\n`);} +function usage(){console.log(`ZCode Gateway\n\nnode src/cli.ts \n\n init Create local .env and data directory\n provision Extract private templates from an official ZCode client\n login [zai|bigmodel] [label] Authorize and add/update one account\n import-desktop [label] Import this user's existing ZCode login\n accounts List account IDs and enabled models\n quota / plans Refresh account entitlements and balance\n promos Discover offers and campaigns without claiming\n claim Claim offered free grants once\n plan start-plan Select the default promotional/trial route\n plan coding-plan --key-file PATH --models MODEL,MODEL\n Select a subscription with its own key\n enable / disable Change account eligibility\n remove Delete this local login (does not revoke upstream)\n serve Run authenticated HTTP service\n\nRun with node --env-file=.env src/cli.ts after init.\n`);} async function main(){ if(command==='help'){usage();console.log('Login opens your default browser; append --no-browser for SSH or manual authorization.');return;} if(command==='init'){ mkdirSync(dir,{recursive:true,mode:0o700}); if(existsSync('.env'))throw new Error('.env already exists'); if(existsSync(join(dir,'accounts.enc')))throw new Error('Found an existing account vault at '+join(dir,'accounts.enc')+'. Restore its original .env / ZCODE_MASTER_KEY instead of generating unrelated keys. No files were changed.'); - writeFileSync('.env',`ZCODE_MASTER_KEY=${randomBytes(32).toString('hex')}\nZCODE_API_KEYS=${randomBytes(32).toString('hex')}\nZCODE_DATA_DIR=./data\nHOST=127.0.0.1\nPORT=8080\n`,{mode:0o600,flag:'wx'}); + writeFileSync('.env',`ZCODE_MASTER_KEY=${randomBytes(32).toString('hex')}\nZCODE_API_KEYS=${randomBytes(32).toString('hex')}\nZCODE_DATA_DIR=./data\nZCODE_AUTO_CLAIM=true\nZCODE_AUTO_CLAIM_INTERVAL_MS=300000\nHOST=127.0.0.1\nPORT=8080\n`,{mode:0o600,flag:'wx'}); console.log('Created .env with private random keys. Keep it outside Git.');return; } mkdirSync(dir,{recursive:true,mode:0o700}); @@ -34,12 +34,16 @@ async function main(){ try{ if(command==='provision'){ if(!args[1])throw new Error('Provide an installed official zcode.cjs path'); - console.log(JSON.stringify(provision(resolve(args[1]),join(dir,'template.json'))));return; + const index=args.indexOf('--app-version'); + if(index>=0&&!args[index+1])throw Error('Provide --app-version X.Y.Z'); + console.log(JSON.stringify(provision(resolve(args[1]),join(dir,'template.json'),{appVersion:index>=0?args[index+1]:undefined})));return; } const v=vault(); + const template=existsSync(join(dir,'template.json'))?JSON.parse(readFileSync(join(dir,'template.json'),'utf8')):{}; + const refresh=(account:any)=>refreshAccount(account,fetch,template); if(command==='login'){ const loginArgs=args.slice(1).filter(arg=>arg!=='--no-browser'); - const flow=await beginLogin(loginArgs[0] || 'zai'); + const flow=await beginLogin(loginArgs[0] || 'zai',fetch,template.appVersion); const cancel=new AbortController();process.once('SIGINT',()=>cancel.abort()); console.log('Open this one-time OAuth URL in your browser. Choose the ZCode account to add:\n'+flow.authorizeUrl); if(process.stdout.isTTY&&process.env.TERM!=='dumb')console.log(loginLink(flow.authorizeUrl,true)); @@ -48,7 +52,7 @@ async function main(){ const context=JSON.parse(readFileSync(join(dir,'template.json'),'utf8')).context; account.deviceId=context?.deviceId || randomBytes(16).toString('hex'); const previous=v.accounts.find(a=>a.identity===account.identity); - const ready=await refreshAccount({...previous,...account});ready.label=loginArgs[1] || previous?.label || 'ZCode account'; + const ready=await refresh({...previous,...account});ready.label=loginArgs[1] || previous?.label || 'ZCode account'; const saved=v.upsert(ready);console.log(JSON.stringify({id:saved.id,label:saved.label,models:saved.models}));return; } if(command==='import-desktop'){ @@ -63,7 +67,7 @@ async function main(){ if(!claims.user_id)throw new Error('Desktop login omitted identity'); const context=JSON.parse(readFileSync(join(dir,'template.json'),'utf8')).context; const previous=v.accounts.find(a=>a.identity==='zai:'+claims.user_id); - const ready=await refreshAccount({...previous,identity:'zai:'+claims.user_id,token,needsLogin:false,provider:'zai',deviceId:context?.deviceId,models:[],label:args[1] || 'Desktop account'}); + const ready=await refresh({...previous,identity:'zai:'+claims.user_id,token,needsLogin:false,provider:'zai',deviceId:context?.deviceId,models:[],label:args[1] || 'Desktop account'}); const saved=v.upsert(ready);console.log(JSON.stringify({id:saved.id,label:saved.label,models:saved.models}));return; } if(command==='accounts'){console.log(JSON.stringify(v.publicAccounts(),null,2));return;} @@ -76,11 +80,11 @@ async function main(){ if(modelsIndex>=0&&args[modelsIndex+1])next.codingModels=args[modelsIndex+1].split(',').map(x=>x.trim().toLowerCase()); if(!next.codingModels?.length)throw new Error('Set the subscription model IDs with --models'); } - planSelection(next);v.upsert(await refreshAccount(next));console.log(JSON.stringify(v.publicAccounts(),null,2));return; + planSelection(next);v.upsert(await refresh(next));console.log(JSON.stringify(v.publicAccounts(),null,2));return; } if(command==='quota'||command==='plans'){ for(const a of [...v.accounts]){ - try{v.upsert(await refreshAccount(a));}catch{a.needsLogin=true;v.save();console.log('Account '+a.id+' needs reauthorization or quota refresh failed');} + try{v.upsert(await refresh(a));}catch{a.quota={checkedAt:Date.now(),reported:null,error:'Quota refresh failed'};v.save();console.log('Account '+a.id+' quota refresh failed');} } console.log(JSON.stringify(quotaSummary(v.accounts),null,2));return; } @@ -89,14 +93,18 @@ async function main(){ if(command==='remove')v.accounts.splice(v.accounts.indexOf(a),1);else a.enabled=command==='enable'; v.save();console.log('Account '+command+' completed');return; } - if(command!=='serve')throw new Error('Unknown command'); - const template=JSON.parse(readFileSync(join(dir,'template.json'),'utf8')); + if(!['serve','promos','claim'].includes(command))throw new Error('Unknown command'); + if(!template.appVersion)throw Error('Provision the installed ZCode client first'); for(const a of v.accounts)if(!a.deviceId&&template.context?.deviceId)a.deviceId=template.context.deviceId; v.save(); + const quota=createQuotaReader(v,{template}); + if(command==='promos'||command==='claim') { + maintenance=createAutoClaim(v,template,quota,{discoverOnly:command==='promos'}); + await maintenance.run();console.log(JSON.stringify(quotaSummary(v.accounts),null,2));return; + } const keys=envSecret('ZCODE_API_KEYS').split(',').map(x=>x.trim()).filter(Boolean); if(keys.some(k=>k.length<24))throw new Error('Every API key must contain at least 24 characters'); - const quota=createQuotaReader(v); - const autoClaim=maintenance=process.env.ZCODE_AUTO_CLAIM==='true'?createAutoClaim(v,template,quota,{intervalMs:Number(process.env.ZCODE_AUTO_CLAIM_INTERVAL_MS || 300000),log:event=>console.log(JSON.stringify(event))}):undefined; + const autoClaim=maintenance=process.env.ZCODE_AUTO_CLAIM!=='false'?createAutoClaim(v,template,quota,{intervalMs:Number(process.env.ZCODE_AUTO_CLAIM_INTERVAL_MS || 300000),log:event=>console.log(JSON.stringify(event))}):undefined; const server=createGateway({keys,models:()=>[...new Set(v.accounts.filter(a=>a.enabled&&!a.needsLogin).flatMap(a=>a.models))],generate:createUpstream(v,template),quota}); const host=process.env.HOST || '127.0.0.1',port=Number(process.env.PORT || 8080); server.listen(port,host,()=>console.log(JSON.stringify({event:'listening',host,port,accounts:v.accounts.length}))); diff --git a/src/oauth.ts b/src/oauth.ts index dd09b48..98e484a 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -2,7 +2,7 @@ import { randomBytes } from 'node:crypto'; import { setTimeout as pause } from 'node:timers/promises'; const origin = 'https://zcode.z.ai'; -export async function beginLogin(provider = 'zai', fetcher: any = fetch, version = '3.16.3') { +export async function beginLogin(provider = 'zai', fetcher: any = fetch, version = '3.17.2') { if (!['zai', 'bigmodel'].includes(provider)) throw new Error('Unknown OAuth provider'); const pollToken = randomBytes(32).toString('hex'); const response = await fetcher(origin + '/api/v1/oauth/cli/init', { method: 'POST', headers: { Authorization: 'Bearer '+pollToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ provider }), redirect: 'error', signal: AbortSignal.timeout(30000) }); diff --git a/src/plans.ts b/src/plans.ts index 9a968f4..8774fbe 100644 --- a/src/plans.ts +++ b/src/plans.ts @@ -31,7 +31,7 @@ export function quotaSummary(accounts: any[]) { } } const claim=a.autoClaim; - const autoClaim=claim?{checkedAt:claim.checkedAt,nextCheckAt:claim.nextCheckAt,status:claim.status,offeredPlans:claim.offeredPlans,plans:(claim.plans || []).map(({planId,status,code,checkedAt,retryAt}:any)=>({planId,status,code,checkedAt,retryAt}))}:null; + const autoClaim=claim?{checkedAt:claim.checkedAt,nextCheckAt:claim.nextCheckAt,status:claim.status,code:claim.code,retryAt:claim.retryAt,offeredPlans:claim.offeredPlans,offers:claim.offers,sources:claim.sources,campaigns:claim.campaigns,refreshFailed:claim.refreshFailed,plans:(claim.plans || []).map(({planId,source,status,code,checkedAt,retryAt,endsAt}:any)=>({planId,source,status,code,checkedAt,retryAt,endsAt}))}:null; publicAccounts.push({id:a.id,label:a.label,plan:a.plan || 'start-plan',selectedPlanId:a.selectedPlanId || null,plans,models:a.models,quotas:accountQuotas,quotaError:a.quota?.error || null,checkedAt:a.quota?.checkedAt || null,quotaKnown:buckets.length>0,needsLogin:!!a.needsLogin,autoClaim}); } const quotaBuckets=Object.fromEntries(Object.entries(quotas).map(([model,bucket])=>[model.replace(/[^a-z0-9]/g,'_'),bucket])); diff --git a/src/templates.ts b/src/templates.ts index 541a5b4..a5d44dc 100644 --- a/src/templates.ts +++ b/src/templates.ts @@ -1,4 +1,4 @@ -import { readFileSync, writeFileSync, existsSync } from 'node:fs'; +import { readFileSync, writeFileSync, existsSync, openSync, readSync, closeSync } from 'node:fs'; import { createHash } from 'node:crypto'; import vm from 'node:vm'; import os from 'node:os'; @@ -10,10 +10,80 @@ export function clientContext() { return { platform:process.platform,arch:os.arch(),release:os.release(),cwd:process.cwd(),shell:process.platform==='win32'?'pwsh.exe':path.basename(process.env.SHELL || 'sh'),locale:Intl.DateTimeFormat().resolvedOptions().locale,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,...deviceId?{deviceId}:{} }; } -// Only supported prompt-only functions are evaluated, in an empty VM. The -// installed application entrypoint and its initialization code never execute. -export function extractTemplate(file: string) { +function appVersion(file: string, explicit?: string) { + let version=explicit; + for(const root of [path.dirname(file),path.dirname(path.dirname(file))]) { + if(version)break; + const metadata=path.join(root,'package.json'),asar=path.join(root,'app.asar'); + if(existsSync(metadata))version=JSON.parse(readFileSync(metadata,'utf8')).version; + if(!version&&existsSync(asar)) { + const fd=openSync(asar,'r'); + try { + const prefix=Buffer.alloc(16);if(readSync(fd,prefix,0,16,0)!==16)throw Error('Invalid ASAR metadata'); + const size=prefix.readUInt32LE(12),offset=8+prefix.readUInt32LE(4); + if(size>32*1024*1024)throw Error('ASAR metadata is too large'); + const buffer=Buffer.alloc(size);readSync(fd,buffer,0,size,16); + const item=JSON.parse(buffer.toString()).files?.['package.json']; + if(!item||item.size>1024*1024)throw Error('Missing ASAR package metadata'); + const data=Buffer.alloc(item.size);readSync(fd,data,0,data.length,offset+Number(item.offset)); + version=JSON.parse(data.toString()).version; + } finally {closeSync(fd);} + } + } + if(typeof version!=='string'||!/^\d+\.\d+\.\d+(?:[-+][a-zA-Z0-9.-]+)?$/.test(version))throw Error('Cannot determine ZCode app version; supply provision --app-version X.Y.Z or keep adjacent application metadata'); + return version; +} + +function modernTemplate(s: string) { + function stringAt(source: string, start: number): {value:string,end:number} { + const quote=source[start];if(!['"',"'",'`'].includes(quote))throw Error('Unsupported prompt string'); + let end=start+1; + for(;end{ + return stringAt(no,0).value.replace(/\\/g,'\\\\').replace(/`/g,'\\`').replace(/\$/g,'\\$'); + }); + } + const values=[];let cursor=0; + while(cursorAs you answer the user's questions, you can use the following context:\n# currentDate\nToday's date is "+date+".\n\n IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task."}]}); + if(template.version===2)b.messages[0].content.unshift({type:'text',text:'\n'+env+'\n'}); for (const m of b.messages) for (const c of m.content || []) delete c.cache_control; const last = b.messages.at(-1)?.content?.at(-1); if(last && ['text','image','tool_result'].includes(last.type)) last.cache_control={type:'ephemeral'}; for (const t of b.tools || []) delete t.cache_control; diff --git a/src/upstream.ts b/src/upstream.ts index a838b96..9c6afff 100644 --- a/src/upstream.ts +++ b/src/upstream.ts @@ -5,24 +5,33 @@ import { Pool } from './accounts.ts'; import { planSelection, quotaSummary } from './plans.ts'; const base = 'https://zcode.z.ai'; -export function headers(token: string, version = '3.16.3', context: any = {}): Record { +export function headers(token: string, version = '3.17.2', context: any = {}): Record { const platform=context.platform || process.platform; return { Authorization:'Bearer '+token,'Content-Type':'application/json','anthropic-version':'2023-06-01','HTTP-Referer':base,'User-Agent':'ZCode/'+version,'X-ZCode-App-Version':version,'X-Title':'Z Code@electron','X-Release-Channel':'production','X-Client-Language':context.locale || Intl.DateTimeFormat().resolvedOptions().locale,'X-Client-Timezone':context.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,'X-ZCode-Agent':'glm','X-Platform':platform+'-'+(context.arch || os.arch()),'X-Os-Category':platform==='win32'?'windows':platform==='darwin'?'macos':'linux','X-Os-Version':context.release || os.release() }; } -export async function refreshAccount(account: any, fetcher: any = fetch) { +export async function refreshAccount(account: any, fetcher: any = fetch, template: any = {}) { if(account.plan==='coding-plan')return {...account,models:account.codingModels || [],quota:{checkedAt:Date.now(),reported:null,error:'Subscription quota requires its separate billing API; Start Plan balances are not subscription balances'}}; - const options = {headers:{...headers(account.token),...account.deviceId?{'X-Device-Mid':account.deviceId}:{}},redirect:'error',signal:AbortSignal.timeout(30000)}; - const response=await fetcher(base+'/api/v1/zcode-plan/billing/current',options); + const version=template.appVersion || '3.17.2'; + const options = {headers:{...headers(account.token,version,template.context),...account.deviceId?{'X-Device-Mid':account.deviceId}:{}},redirect:'error',signal:AbortSignal.timeout(30000)}; + const response=await fetcher(base+'/api/v1/zcode-plan/billing/balance?app_version='+encodeURIComponent(version),options); const data=await response.json(); - if(!response.ok || data.code!==0) throw new Error('Unable to read account plan: '+response.status); + if(!response.ok || ![0,'0'].includes(data.code)||!Array.isArray(data.data?.plans)||!Array.isArray(data.data?.balances))throw new Error('Unable to read account balance: '+response.status); + const reported=data.data,time=Number.isFinite(reported.server_time)?reported.server_time*1000:Date.now(); + const active=(p:any)=>p.status==='active'&&(!p.starts_at||Number(p.starts_at)*1000<=time)&&(!p.ends_at||Number(p.ends_at)*1000>time)&&(!account.selectedPlanId||p.plan_id===account.selectedPlanId); + const plans=reported.plans.filter(active); const models=new Set(); - for(const plan of data.data?.plans || []) if(plan.status==='active' && (!plan.starts_at || plan.starts_at*1000<=Date.now()) && (!plan.ends_at || plan.ends_at*1000>Date.now())&&(!account.selectedPlanId||plan.plan_id===account.selectedPlanId)) for(const entitlement of plan.entitlements || []) if(!entitlement.effective_at || entitlement.effective_at*1000<=Date.now()) for(const capability of entitlement.capabilities || []) if(capability.startsWith('model:')) models.add(capability.slice(6).toLowerCase()); - const updated={...account,models:[...models],plans:data.data?.plans || [],plan:account.plan || 'start-plan'}; - try{ - const balance=await fetcher(base+'/api/v1/zcode-plan/billing/balance?app_version=3.16.3',options); - const b=await balance.json();updated.quota={checkedAt:Date.now(),reported:balance.ok&&b.code===0?b.data:null,error:balance.ok&&b.code===0?null:'Provider quota unavailable'}; - }catch{updated.quota={checkedAt:Date.now(),reported:null};} - return updated; + const add=(capabilities:any)=>{for(const c of capabilities || [])if(typeof c==='string'&&c.toLowerCase().startsWith('model:')&&c.slice(6).trim())models.add(c.slice(6).trim().toLowerCase());}; + for(const plan of plans)for(const e of plan.entitlements || [])if(!e.effective_at||Number(e.effective_at)*1000<=time)add(e.capabilities); + for(const b of reported.balances) { + if((b.expires_at&&Number(b.expires_at)*1000<=time)||(b.period_start&&Number(b.period_start)*1000>time))continue; + const plan=plans.find((p:any)=>b.user_plan_id?p.user_plan_id===b.user_plan_id:b.plan_id?p.plan_id===b.plan_id:false); + if(!plan)continue; + const entitlement=(plan.entitlements || []).find((e:any)=>e.entitlement_id===b.entitlement_id); + if(entitlement?.effective_at&&Number(entitlement.effective_at)*1000>time)continue; + add(b.capabilities); + if(!b.capabilities?.length&&typeof b.show_name==='string'&&/^glm-[a-z0-9.-]+$/i.test(b.show_name.trim()))models.add(b.show_name.trim().toLowerCase()); + } + return {...account,models:[...models],plans:reported.plans,plan:account.plan || 'start-plan',quota:{checkedAt:Date.now(),reported,error:null}}; } export function createQuotaReader(vault: any, options: any = {}) { let expires=0,pending: Promise | undefined; @@ -31,7 +40,7 @@ export function createQuotaReader(vault: any, options: any = {}) { if(!force&&Date.now(){ for(const a of vault.accounts.filter(x=>x.enabled)){ - try{Object.assign(a,await refreshAccount(a,options.fetcher || fetch));}catch{a.quota={checkedAt:Date.now(),reported:null,error:'Quota refresh failed'};} + try{Object.assign(a,await refreshAccount(a,options.fetcher || fetch,options.template));}catch{a.quota={checkedAt:Date.now(),reported:null,error:'Quota refresh failed'};} } vault.save();expires=Date.now()+60000;return quotaSummary(vault.accounts); })().finally(()=>{pending=undefined;}); diff --git a/test/claims.test.mjs b/test/claims.test.mjs index 0e4dcf3..3b15075 100644 --- a/test/claims.test.mjs +++ b/test/claims.test.mjs @@ -12,7 +12,7 @@ function fixture(extra={},offers=[offer],config={enabled:false},claimCode=0){ const fetcher=async(url,init)=>{ calls.push({url,init}); if(url.includes('/preview?'))return Response.json({code:0,data:{plans:offers}}); - if(url.endsWith('/agent/configs'))return Response.json({code:0,data:{configs:config===null?{}:{captcha:config}}}); + if(url.includes('/marketing/touch?'))return Response.json({code:0,data:{deliveries:[]}}); if(url.endsWith('/claim'))return Response.json({code:claimCode,data:claimCode===0?{plan:{plan_id:JSON.parse(init.body).plan_id}}:{}}); throw Error('Unexpected endpoint'); }; @@ -71,11 +71,9 @@ test('already active account plans are not claimed again',async()=>{ const f=fixture({plans:[offer]});await f.runner.run();assert.equal(f.posts().length,0); }); -test('CAPTCHA enabled or unknown requires manual action without a claim request',async()=>{ - for(const config of [{enabled:true},null]){ - const f=fixture({},[offer],config);await f.runner.run(); - assert.equal(f.posts().length,0);assert.equal(f.a.autoClaim.plans[0].status,'captcha_required'); - } +test('provider CAPTCHA requirement is preserved without trying to bypass verification',async()=>{ + const f=fixture({},[offer],null,3007);await f.runner.run();await f.runner.run(); + assert.equal(f.posts().length,1);assert.equal(f.a.autoClaim.plans[0].status,'captcha_required'); }); test('provider CAPTCHA and ineligibility responses are recorded with a retry hold',async()=>{ @@ -95,7 +93,7 @@ test('failed preview leaves current models intact and stores no raw error or cre const f=fixture({models:['glm-5.3-flash']}); const runner=createAutoClaim(f.vault,template,async()=>{}, {now:()=>now,fetcher:async()=>{throw Error('private-token');},log:()=>{}}); await runner.run();assert.deepEqual(f.a.models,['glm-5.3-flash']); - assert.equal(f.a.autoClaim.status,'preview_failed');assert.doesNotMatch(JSON.stringify(f.a.autoClaim),/private-token/); + assert.equal(f.a.autoClaim.status,'discovery_failed');assert.doesNotMatch(JSON.stringify(f.a.autoClaim),/private-token/); }); test('stopped runner does not perform further network operations',async()=>{ diff --git a/test/cli.test.mjs b/test/cli.test.mjs index 288d510..19edba0 100644 --- a/test/cli.test.mjs +++ b/test/cli.test.mjs @@ -1,9 +1,9 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { mkdtempSync, readFileSync, existsSync, rmSync } from 'node:fs'; +import { mkdtempSync, readFileSync, writeFileSync, existsSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { spawnSync } from 'node:child_process'; import { Vault } from '../src/accounts.ts'; @@ -23,3 +23,34 @@ test('init refuses to generate unrelated keys over an existing vault', () => { assert.deepEqual(readFileSync(file), before); } finally { rmSync(dir, { recursive: true, force: true }); } }); + +test('fresh installations enable automatic promotion checks',()=>{ + const dir=mkdtempSync(join(tmpdir(),'zc-auto-init-')); + try { + const result=spawnSync(process.execPath,[cli,'init'],{cwd:dir,env:{...process.env,ZCODE_DATA_DIR:join(dir,'data')},encoding:'utf8'}); + assert.equal(result.status,0,result.stderr);assert.match(readFileSync(join(dir,'.env'),'utf8'),/ZCODE_AUTO_CLAIM=true/); + } finally {rmSync(dir,{recursive:true,force:true});} +}); + +for(const command of ['promos','claim'])test(command+' discovers real endpoint offers with the provisioned version',()=>{ + const dir=mkdtempSync(join(tmpdir(),'zc-cli-offers-')),key='k'.repeat(64); + try { + const file=join(dir,'accounts.enc');new Vault(file,key).upsert({identity:'fixture',token:'secret-fixture',deviceId:'fixture-device',models:[]}); + writeFileSync(join(dir,'template.json'),JSON.stringify({appVersion:'3.17.2',context:{platform:'darwin',arch:'arm64'}})); + const preload=join(dir,'fetch.mjs'); + writeFileSync(preload,`globalThis.fetch=async(url,init)=>{ + if(init.headers['X-ZCode-App-Version']!=='3.17.2')throw Error('wrong version'); + if(url.includes('/preview?'))return Response.json({code:0,data:{plans:[{plan_id:'fixture-free',entitlements:[{grant_units:10,capabilities:['model:fixture']}]}]}}); + if(url.includes('/marketing/touch?'))return Response.json({code:0,data:{deliveries:[]}}); + if(url.endsWith('/claim'))return Response.json({code:0,data:{plan:{plan_id:'fixture-free',ends_at:Date.now()/1000+3600}}}); + return Response.json({code:0,data:{plans:[],balances:[]}}); + };`); + const result=spawnSync(process.execPath,['--import',pathToFileURL(preload).href,cli,command],{cwd:dir,env:{...process.env,ZCODE_DATA_DIR:dir,ZCODE_MASTER_KEY:key},encoding:'utf8'}); + assert.equal(result.status,0,result.stderr); + const state=new Vault(file,key).accounts[0].autoClaim; + assert.equal(state.offeredPlans,1);assert.equal(state.offers[0].planId,'fixture-free'); + assert.equal(state.plans.length,command==='claim'?1:0); + assert.equal(existsSync(join(dir,'vault.lock')),false); + assert.doesNotMatch(result.stdout,/secret-fixture|fixture-device/); + } finally {rmSync(dir,{recursive:true,force:true});} +}); diff --git a/test/compatibility.test.mjs b/test/compatibility.test.mjs new file mode 100644 index 0000000..862b397 --- /dev/null +++ b/test/compatibility.test.mjs @@ -0,0 +1,99 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { extractTemplate, prepareRequest } from '../src/templates.ts'; +import { refreshAccount, createQuotaReader } from '../src/upstream.ts'; + +// Small synthetic prompt, with intentionally unrelated minified identifiers. +const bundle = `var boot=()=>{throw Error('application entrypoint executed')}; +var init=()=>{abc="You are ZCode, an interactive agent",def="You are an agent working with the user toward their goals, fixture.",sec="IMPORTANT: Assist with authorized security testing, fixture.",style='You are an interactive agent that helps users according to your "Output Style", fixture.'}; +function harness(flag=!0){return["# Harness"," - Fixture terminal guidance.",\` - \${flag?"System turns.":"Reminder tags."} Hook guidance.\`].join("\\n")} +var dyn=()=>{a="Write code that reads like the surrounding code: fixture.",b="When you use a pronoun for someone, fixture.",c="For actions that are hard to reverse or outward-facing, fixture.",d=["# Context management","When the conversation grows long, fixture."].join("\\n"),e="When you have enough information to act, act. Fixture."};`; + +test('modern extraction discovers renamed prompt symbols and reads adjacent application metadata',()=>{ + const dir=mkdtempSync(join(tmpdir(),'zc-modern-')); + try { + mkdirSync(join(dir,'glm'));writeFileSync(join(dir,'package.json'),JSON.stringify({version:'3.17.2'})); + const file=join(dir,'glm','zcode.cjs');writeFileSync(file,bundle); + const t=extractTemplate(file); + assert.equal(t.appVersion,'3.17.2');assert.equal(t.version,2); + assert.match(t.stable,/# Harness/);assert.match(t.stable,/Reminder tags/); + assert.match(t.before,/Write code/);assert.match(t.after,/# Context management/); + assert.doesNotMatch(JSON.stringify(t),/entrypoint executed/); + } finally {rmSync(dir,{recursive:true,force:true});} +}); + +test('provision accepts an explicit version for a standalone official bundle',()=>{ + const dir=mkdtempSync(join(tmpdir(),'zc-version-')); + try { + const file=join(dir,'zcode.cjs');writeFileSync(file,bundle); + assert.equal(extractTemplate(file,{appVersion:'3.17.2'}).appVersion,'3.17.2'); + assert.throws(()=>extractTemplate(file,{appVersion:'latest\r\nInjected: value'}),/version/i); + assert.throws(()=>extractTemplate(file),/version|metadata/i); + } finally {rmSync(dir,{recursive:true,force:true});} +}); + +test('modern extraction rejects executable template interpolation',()=>{ + const dir=mkdtempSync(join(tmpdir(),'zc-literal-')); + try { + const file=join(dir,'zcode.cjs'); + writeFileSync(file,bundle.replace('fixture.\",b=', 'fixture ${globalThis.process.exit()}.\",b=')); + assert.throws(()=>extractTemplate(file,{appVersion:'3.17.2'}),/interpolated/); + } finally {rmSync(dir,{recursive:true,force:true});} +}); + +test('application version can be read from an adjacent ASAR without loading its code',()=>{ + const dir=mkdtempSync(join(tmpdir(),'zc-asar-')); + try { + const file=join(dir,'zcode.cjs');writeFileSync(file,bundle); + const metadata=Buffer.from(JSON.stringify({version:'3.17.2'})); + const header=Buffer.from(JSON.stringify({files:{'package.json':{size:metadata.length,offset:'0'}}})); + const prefix=Buffer.alloc(16);prefix.writeUInt32LE(4,0);prefix.writeUInt32LE(header.length+8,4);prefix.writeUInt32LE(header.length+4,8);prefix.writeUInt32LE(header.length,12); + writeFileSync(join(dir,'app.asar'),Buffer.concat([prefix,header,metadata])); + assert.equal(extractTemplate(file).appVersion,'3.17.2'); + } finally {rmSync(dir,{recursive:true,force:true});} +}); + +test('modern request preserves application instructions and sends environment as user context',()=>{ + const t={version:2,prefix:'prefix',stable:'static',before:'behavior',after:'context',context:{platform:'win32',arch:'x64',timezone:'UTC',cwd:'fixture',shell:'pwsh',release:'test'}}; + const r=prepareRequest({model:'glm-fixture',system:'caller rules',messages:[{role:'user',content:[{type:'text',text:'hello'}]}]},t); + assert.match(r.system[1].text,/caller rules/); + assert.doesNotMatch(r.system[2].text,/# Environment/); + assert.match(r.messages[0].content[0].text,/# Environment/); + assert.match(r.messages[0].content[0].text,/glm-fixture/); + assert.equal(r.messages.at(-1).content[0].text,'hello'); +}); + +test('billing and balance requests carry the provisioned version and platform',async()=>{ + const calls=[];const template={appVersion:'3.17.2',context:{platform:'darwin',arch:'arm64'}}; + const fetcher=async(url,init)=>{calls.push({url,init});return Response.json({code:0,data:{plans:[],balances:[]}});}; + await refreshAccount({token:'fixture'},fetcher,template); + assert.equal(calls[0].init.headers['X-ZCode-App-Version'],'3.17.2'); + assert.equal(calls[0].init.headers['X-Platform'],'darwin-arm64'); + assert.match(calls[0].url,/app_version=3.17.2/); + calls.length=0; + await createQuotaReader({accounts:[{enabled:true,token:'fixture'}],save(){}},{fetcher,template})(); + assert.equal(calls[0].init.headers['X-ZCode-App-Version'],'3.17.2'); +}); + +test('current billing discovers models from authoritative balance buckets without calling retired current endpoint',async()=>{ + const calls=[]; + const r=await refreshAccount({token:'fixture'},async url=>{ + calls.push(url); + if(url.includes('/billing/current'))return Response.json({code:0}); + return Response.json({code:0,data:{server_time:1800000000,plans:[{user_plan_id:'instance',plan_id:'promo',status:'active',ends_at:1800003600,entitlements:[{entitlement_id:'e'}]}],balances:[ + {user_plan_id:'instance',entitlement_id:'e',capabilities:['model:glm-next'],remaining_units:100,expires_at:1800003600}, + ]}}); + }); + assert.deepEqual(r.models,['glm-next']);assert.equal(calls.length,1);assert.match(calls[0],/billing\/balance/); +}); + +test('balance model discovery excludes inactive, future and expired buckets and respects selected plan',async()=>{ + const r=await refreshAccount({token:'fixture',selectedPlanId:'selected'},async()=>Response.json({code:0,data:{server_time:1800000000, + plans:[{plan_id:'selected',status:'active',entitlements:[{entitlement_id:'future',effective_at:1800003600}]},{plan_id:'other',status:'active'},{plan_id:'old',status:'expired'}], + balances:[{plan_id:'selected',capabilities:['model:good']},{plan_id:'other',capabilities:['model:other']},{plan_id:'old',capabilities:['model:old']},{plan_id:'selected',capabilities:['model:expired'],expires_at:1799999999},{plan_id:'selected',entitlement_id:'future',capabilities:['model:future']}], + }})); + assert.deepEqual(r.models,['good']); +}); diff --git a/test/promotion-gateway.test.mjs b/test/promotion-gateway.test.mjs new file mode 100644 index 0000000..f09e749 --- /dev/null +++ b/test/promotion-gateway.test.mjs @@ -0,0 +1,41 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import { createAutoClaim } from '../src/claims.ts'; +import { createQuotaReader, createUpstream } from '../src/upstream.ts'; +import { createGateway } from '../src/server.ts'; + +test('background claim activates balance models and all three HTTP protocols use the modern template',async t=>{ + const template={version:2,appVersion:'3.17.2',prefix:'fixture prefix',stable:'fixture stable',before:'fixture behavior',after:'fixture context',context:{platform:'win32',arch:'x64',timezone:'UTC',cwd:'fixture',shell:'pwsh',release:'fixture'}}; + const a={id:'a',enabled:true,token:'private-upstream',deviceId:'private-device',models:[]}; + const vault={accounts:[a],save(){}};let claimed=false,posts=0;const inference=[]; + const expiry=Date.now()/1000+3600; + const fetcher=async(url,init)=>{ + assert.equal(init.headers['X-ZCode-App-Version'],'3.17.2'); + if(url.includes('/billing/balance?'))return Response.json({code:0,data:{plans:claimed?[{plan_id:'event',user_plan_id:'event-instance',status:'active',ends_at:expiry}]:[],balances:claimed?[{user_plan_id:'event-instance',capabilities:['model:glm-5.3-flash'],expires_at:expiry,total_units:100,used_units:0,remaining_units:100}]:[]}}); + if(url.includes('/billing/preview?'))return Response.json({code:0,data:{plans:[]}}); + if(url.includes('/marketing/touch?'))return Response.json({code:0,data:{deliveries:[{campaign_id:'event',resource_position:'banner',banner:{buttons:[{action:{type:'claim_zcode_plan',args:{plan_id:'event'}}}]}}]}}); + if(url.endsWith('/billing/claim')){claimed=true;posts++;return Response.json({code:0,data:{plan:{plan_id:'event',ends_at:expiry}}});} + if(url.endsWith('/messages')) { + const body=JSON.parse(init.body);inference.push(body); + return Response.json({id:'msg_fixture',type:'message',role:'assistant',model:body.model,content:[{type:'text',text:'fixture answer'}],stop_reason:'end_turn',usage:{input_tokens:10,output_tokens:3}}); + } + throw Error('Unexpected endpoint'); + }; + const quota=createQuotaReader(vault,{template,fetcher}); + const runner=createAutoClaim(vault,template,quota,{fetcher});t.after(()=>runner.stop()); + runner.start();await runner.run();assert.equal(posts,1);assert.deepEqual(a.models,['glm-5.3-flash']); + const key='fixture-client-key-24-characters'; + const server=createGateway({keys:[key],models:()=>a.models,quota,generate:createUpstream(vault,template,{fetcher})}); + server.listen(0,'127.0.0.1');await once(server,'listening');t.after(()=>new Promise(resolve=>server.close(resolve))); + const base='http://127.0.0.1:'+server.address().port,headers={Authorization:'Bearer '+key,'Content-Type':'application/json'}; + const catalog=await(await fetch(base+'/v1/models',{headers})).json();assert.equal(catalog.data[0].id,'glm-5.3-flash'); + for(const path of ['/v1/chat/completions','/v1/responses','/v1/messages']) { + const body={model:'glm-5.3-flash',max_tokens:32,...path.endsWith('/responses')?{input:'hello'}:{messages:[{role:'user',content:'hello'}]}}; + const response=await fetch(base+path,{method:'POST',headers,body:JSON.stringify(body)}); + assert.equal(response.status,200,await response.clone().text());assert.match(await response.text(),/fixture answer/); + } + assert.equal(inference.length,3); + for(const body of inference){assert.doesNotMatch(body.system[2].text,/# Environment/);assert.match(body.messages[0].content[0].text,/# Environment/);} + assert.equal(posts,1); +}); diff --git a/test/promotions.test.mjs b/test/promotions.test.mjs new file mode 100644 index 0000000..a3fe8ff --- /dev/null +++ b/test/promotions.test.mjs @@ -0,0 +1,119 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createAutoClaim } from '../src/claims.ts'; +import { quotaSummary } from '../src/plans.ts'; + +const time=1800000000000; +const grant={plan_id:'weekend',entitlements:[{capabilities:['model:glm-next'],grant_units:100}]}; +const action={type:'claim_zcode_plan',args:{plan_id:'event-grant'}}; +const delivery=(buttons=[action])=>({campaign_id:'weekend-event',priority:1,resource_position:'popup',popup:{title:{format:'plaintext',content:'Weekend event'},buttons:buttons.map(action=>({action}))}}); +function fixture(options={}) { + let clock=time,seq=0;const calls=[]; + const account={id:'a',token:'secret-token',deviceId:'original-device',enabled:true,models:[],...options.account}; + const fetcher=async(url,init)=>{ + calls.push({url,init}); + if(url.includes('/preview?'))return options.preview?.() || Response.json({code:0,data:{server_time:clock/1000,plans:options.offers??[grant]}}); + if(url.includes('/marketing/touch?'))return options.marketing?.() || Response.json({code:0,data:{server_time:clock/1000,deliveries:options.deliveries??[]}}); + if(url.endsWith('/claim'))return options.claim?.(++seq,init) || Response.json({code:'0',data:{plan:{plan_id:JSON.parse(init.body).plan_id,ends_at:clock/1000+3600}}}); + throw Error('Unexpected obsolete endpoint: '+url); + }; + const runner=createAutoClaim({accounts:[account],save(){}},{appVersion:'3.17.2',context:{platform:'win32',arch:'x64',locale:'id-ID'}},async()=>{}, {fetcher,now:()=>clock}); + return {runner,account,calls,advance(ms){clock+=ms;},posts:()=>calls.filter(c=>c.init.method==='POST')}; +} + +test('current official claim flow does not require the removed agent CAPTCHA configuration',async()=>{ + const f=fixture();await f.runner.run(); + assert.equal(f.posts().length,1);assert.equal(f.account.autoClaim.plans[0].status,'claimed'); + assert.equal(f.calls.some(c=>c.url.includes('/agent/configs')),false); +}); + +test('marketing popup and banner claim actions are discovered even without preview entitlements',async()=>{ + const banner={campaign_id:'banner',resource_position:'banner',banner:{buttons:[{action:{type:'claim_zcode_plan',args:{plan_id:'banner-grant'}}}]}}; + const f=fixture({offers:[],deliveries:[delivery(),banner]});await f.runner.run(); + assert.deepEqual(f.posts().map(c=>JSON.parse(c.init.body).plan_id),['event-grant','banner-grant']); + const query=f.calls.find(c=>c.url.includes('/marketing/touch?')); + assert.equal(query.init.headers['X-Device-Mid'],'original-device');assert.equal(query.init.headers['X-Client-Language'],'en-US'); + assert.equal(f.account.autoClaim.campaigns[0].title,'Weekend event'); +}); + +test('preview and marketing duplicates claim once; paid offers and unrelated actions never claim',async()=>{ + const paid={...grant,plan_id:'paid',price:5}; + const f=fixture({offers:[grant,paid],deliveries:[delivery([ + {type:'claim_zcode_plan',args:{plan_id:'weekend'}},{type:'claim_zcode_plan',args:{plan_id:'paid'}}, + {type:'open_url',args:{url:'https://example.com'}},{type:'navigate',args:{page:'rewards'}}, + ])]});await f.runner.run(); + assert.deepEqual(f.posts().map(c=>JSON.parse(c.init.body).plan_id),['weekend']); +}); + +test('undated recurring previews are retried after the claimed grant actually expires',async()=>{ + const f=fixture();await f.runner.run();await f.runner.run();assert.equal(f.posts().length,1); + f.advance(3600001);await f.runner.run();assert.equal(f.posts().length,2); +}); + +test('already-claimed response without grant dates does not suppress future periods forever',async()=>{ + const f=fixture({claim:()=>Response.json({code:1003,data:{}})}); + await f.runner.run();await f.runner.run();assert.equal(f.posts().length,1); + f.advance(3600001);await f.runner.run();assert.equal(f.posts().length,2); +}); + +test('HTTP failures cannot be mistaken for successful claims and Retry-After gates the whole account',async()=>{ + const f=fixture({offers:[grant,{...grant,plan_id:'second'}],claim:()=>Response.json({code:0,data:{plan:{}}},{status:429,headers:{'Retry-After':'7200'}})}); + await f.runner.run();assert.equal(f.posts().length,1);assert.equal(f.account.autoClaim.status,'rate_limited'); + await f.runner.run();assert.equal(f.posts().length,1); + f.advance(7200001);await f.runner.run();assert.equal(f.posts().length,2); +}); + +test('plain-text provider rate limits preserve HTTP status and Retry-After',async()=>{ + const f=fixture({claim:()=>new Response('Too many requests',{status:429,headers:{'Retry-After':'7200'}})}); + await f.runner.run();assert.equal(f.account.autoClaim.status,'rate_limited'); + assert.equal(f.account.autoClaim.retryAt,time+7200000); +}); + +test('missing preview data is reported as incomplete discovery rather than an empty success',async()=>{ + const f=fixture({preview:()=>Response.json({code:0})});await f.runner.run(); + assert.equal(f.account.autoClaim.sources.preview.reason,'missing_data'); + assert.equal(f.account.autoClaim.status,'discovery_partial'); +}); + +test('a successful short-lived grant is eligible again when its actual period ends',async()=>{ + const f=fixture({claim:()=>Response.json({code:0,data:{server_time:time/1000,plan:{plan_id:'weekend',ends_at:time/1000+120}}})}); + await f.runner.run();f.advance(120001);await f.runner.run();assert.equal(f.posts().length,2); +}); + +test('a failing preview does not hide marketing offers, and a failing marketing channel does not hide previews',async()=>{ + const f=fixture({preview:()=>Response.json({code:900},{status:503}),deliveries:[delivery()]});await f.runner.run(); + assert.equal(f.posts().length,1);assert.equal(f.account.autoClaim.sources.preview.status,'failed'); + const g=fixture({marketing:()=>Response.json({code:900},{status:503})});await g.runner.run();assert.equal(g.posts().length,1); + assert.equal(g.account.autoClaim.sources.marketing.status,'failed'); +}); + +test('provider server time, rather than a fast local clock, determines offer expiry',async()=>{ + const f=fixture({offers:[],preview:()=>Response.json({code:0,data:{server_time:time/1000-7200,plans:[{...grant,ends_at:time/1000-3600}]}})}); + await f.runner.run();assert.equal(f.posts().length,1); +}); + +test('provider verification, login and risk responses stop additional claims for that account',async()=>{ + for(const [code,status] of [[3007,'captcha_required'],[401,'login_required'],[403,'login_required'],[3012,'risk_blocked']]) { + const f=fixture({offers:[grant,{...grant,plan_id:'second'}],claim:()=>Response.json({code,data:{}})});await f.runner.run(); + assert.equal(f.posts().length,1);assert.equal(f.account.autoClaim.status,status); + } +}); + +test('risk and CAPTCHA business errors retain their meaning on non-success HTTP responses',async()=>{ + for(const [code,http,status] of [[3012,405,'risk_blocked'],[3007,400,'captcha_required']]) { + const f=fixture({offers:[grant,{...grant,plan_id:'second'}],claim:()=>Response.json({code,data:{}},{status:http})}); + await f.runner.run();assert.equal(f.posts().length,1);assert.equal(f.account.autoClaim.status,status); + } +}); + +test('malformed marketing deliveries do not abort remaining discovery or other accounts',async()=>{ + const f=fixture({offers:[],deliveries:[null,{},delivery()]});await f.runner.run(); + assert.equal(f.posts().length,1); +}); + +test('authenticated status includes sanitized campaign/source diagnostics without arbitrary payloads',async()=>{ + const f=fixture({deliveries:[{...delivery([{type:'open_url',args:{url:'https://example.com/?token=secret'}}]),raw:'secret-token'}]}); + await f.runner.run();const status=quotaSummary([f.account]).accounts[0].autoClaim; + assert.equal(status.campaigns[0].campaignId,'weekend-event');assert.equal(status.sources.marketing.status,'ok'); + assert.doesNotMatch(JSON.stringify(status),/secret-token|original-device|https:\/\//); +}); diff --git a/test/quota-refresh.test.mjs b/test/quota-refresh.test.mjs index 808d57b..31c2a8a 100644 --- a/test/quota-refresh.test.mjs +++ b/test/quota-refresh.test.mjs @@ -10,9 +10,9 @@ test('forced quota refresh discovers new grants despite the normal cache',async( calls++; return Response.json({code:0,data:{plans:available?[{status:'active',entitlements:[{capabilities:['model:glm-5.3-flash']}]}]:[],balances:[]}}); }}); - await quota();assert.deepEqual(a.models,[]);assert.equal(calls,2); - available=true;await quota();assert.deepEqual(a.models,[]);assert.equal(calls,2); - await quota({force:true});assert.deepEqual(a.models,['glm-5.3-flash']);assert.equal(calls,4); + await quota();assert.deepEqual(a.models,[]);assert.equal(calls,1); + available=true;await quota();assert.deepEqual(a.models,[]);assert.equal(calls,1); + await quota({force:true});assert.deepEqual(a.models,['glm-5.3-flash']);assert.equal(calls,2); }); test('quota reports auto-claim status without account credentials',()=>{ diff --git a/test/shutdown.test.mjs b/test/shutdown.test.mjs index 118754d..af1e25a 100644 --- a/test/shutdown.test.mjs +++ b/test/shutdown.test.mjs @@ -14,7 +14,7 @@ test('shutdown retains the vault lock until background quota refresh settles',as vault.upsert({identity:'fixture',token:'fixture',models:[],enabled:true}); writeFileSync(join(dir,'template.json'),JSON.stringify({appVersion:'test'})); const preload=join(dir,'preload.mjs'); - writeFileSync(preload,`globalThis.fetch=async url=>{if(url.includes('/billing/current')){process.stdout.write('refresh-start\\n');await new Promise(r=>setTimeout(r,1800));}return Response.json({code:0,data:{plans:[],balances:[]}});};process.stdin.on('data',()=>{process.emit('SIGTERM');process.stdout.write('signal-seen\\n');});`); + writeFileSync(preload,`globalThis.fetch=async url=>{if(url.includes('/billing/balance')){process.stdout.write('refresh-start\\n');await new Promise(r=>setTimeout(r,1800));}return Response.json({code:0,data:{plans:[],balances:[]}});};process.stdin.on('data',()=>{process.emit('SIGTERM');process.stdout.write('signal-seen\\n');});`); const child=spawn(process.execPath,['--import',pathToFileURL(preload).href,resolve('src/cli.ts'),'serve'],{env:{...process.env,ZCODE_DATA_DIR:dir,ZCODE_MASTER_KEY:key,ZCODE_API_KEYS:'fixture-client-key-24-characters',ZCODE_AUTO_CLAIM:'true',HOST:'127.0.0.1',PORT:'0'},stdio:['pipe','pipe','pipe']}); let output='';child.stdout.on('data',data=>{output+=data;});child.stderr.resume(); const exited=once(child,'exit');