diff --git a/.agents/notes/implemented/feature/2026-11-20-kimi-work-credential-import.md b/.agents/notes/implemented/feature/2026-11-20-kimi-work-credential-import.md new file mode 100644 index 0000000..d965f87 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-20-kimi-work-credential-import.md @@ -0,0 +1,33 @@ +# Agent Note: Kimi Work 凭据文件导入 + +Status: implemented + +## Problem + +Kimi Work 的对话密钥与会员令牌是两套凭据。原实现只把会员令牌保存到宿主认证库,每次对话仍从运行 Magpie 的本机 `daimon-share` 读取 Work 密钥,因此没有安装 Kimi 或没有挂载该目录的机器无法使用已有 Work 登录。 + +## Decision + +使用 Magpie 已有的 `auth.import` 文件导入协议,让用户选择已登录 Work 的 Kimi 桌面版 `daimon/config.json`。导入时复用本机文件的字段校验和官方 Work origin 限制,并用文件中的 Work 密钥请求 `/models` 验证后才返回成功账号。 + +导入账号在同一宿主账号项中显式保存 `workToken`、会员 access/refresh token、UID 和 `imported: true`。请求、模型发现和额度读取遇到这种账号时只使用已保存凭据,不调用 `readDesktop()`。原有本机及 reference-only 账号不自动迁移,仍按原路径读取桌面文件。 + +会员令牌继续由现有 `auth.refresh` 续期。Work 密钥没有续期接口,导入后的 Work 401 明确要求重新选择新文件,不能把会员续期误当成 Work 密钥续期。文件内容、Work 密钥和会员令牌不得写入错误信息或日志。 + +## Consequences + +用户可以把可信机器上的 Work 凭据导入未安装 Kimi 的 Magpie,省去手工粘贴 JSON 的专用界面,并复用宿主的文件选择、代理、取消和账号保存流程。代价是 Work 密钥现在会按用户显式操作保存在宿主明文认证库中;文件仍须由某台已登录 Kimi 桌面版的机器生成,跨设备有效期和撤销策略仍由 Kimi 控制。 + +该入口是 Magpie 扩展,OpenCode 会忽略 `auth.import`,因此不宣称 OpenCode 也支持文件选择登录。 + +## Alternatives considered + +独立浏览器登录最接近 WorkBuddy 的体验,但当前源码没有 Kimi 服务端为插件独立签发 Work 密钥的流程,不能通过仿照 WorkBuddy 请求凭空实现。 + +只导入会员 access/refresh token 改动更小,却无法对话,因为推理使用的是独立的 `credentials.kimiCode.apiKey`,所以导入必须同时保存 Work 密钥。 + +自动把现有本机账号改为复制 Work 密钥可以减少一次用户操作,但会改变既有账号的凭据存储边界,并失去桌面重新签发密钥后自动读取新密钥的能力,因此保留原行为,只让显式文件导入复制密钥。 + +## Verification + +合成 `config.json` 测试覆盖导入声明、合法文件验证、导入后无桌面读取的对话/模型/额度请求、无 refresh token 的文件、无效 JSON/字段/origin、失效 Work 密钥和重新导入提示。既有测试继续约束本机登录不复制 Work 密钥及 reference-only 行为。未使用真实账号或真实凭据测试跨设备登录。 diff --git a/README.md b/README.md index a9b24b4..e3a70f5 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ vendor service and makes its requests. The packages work in OpenCode and in | [joycode](packages/joycode) | JoyCode IDE credits with JD account browser sign-in, live models and credit multipliers (unofficial) | `joycode` | | [doubao-work](packages/doubao-work) | Doubao Work (豆包工作), whose agent runs in the cloud with no API, through the Doubao desktop app driven the way a person uses it (macOS, Windows) | `doubao-work` | | [gemini-web](packages/gemini-web) | The Gemini web app (gemini.google.com), not Google's API: your Google account signed in through a browser window of its own, or as a visitor; one streamed call to the app's own endpoint per request | `gemini-web` | -| [kimi-work](packages/kimi-work) | Ordinary Kimi desktop Work subscription, through the desktop app's local sign-in; separate from Kimi Code | `kimi-work` | +| [kimi-work](packages/kimi-work) | Ordinary Kimi desktop Work subscription, through the desktop app's local sign-in or an imported credentials file; separate from Kimi Code | `kimi-work` | | [kiro](packages/kiro) | Kiro (Free, Pro, Pro+, Power), with Kiro's sign-in, kiro-cli's or the IDE's, or an API key | `kiro` | | [loomy](packages/loomy) | iFlytek's Loomy (loomyad.xunfei.cn), with SMS sign-in | `loomy` | | [mclaw](packages/mclaw) | China Mobile Cloud's MClaw agent (ai.yun.139.com), with a browser sign-in that harvests the ticket and auto-fetches the llm key: live models with token multipliers, aitokens pool usage, auto renewal (unofficial) | `mclaw` | diff --git a/packages/kimi-work/COMPATIBILITY.md b/packages/kimi-work/COMPATIBILITY.md index ae60db5..7ac6cd1 100644 --- a/packages/kimi-work/COMPATIBILITY.md +++ b/packages/kimi-work/COMPATIBILITY.md @@ -64,6 +64,6 @@ The historical live sequence above covers one shared-lineage cycle. Its temporar ## Limits -The monthly meter reports `subscriptionBalance.amountUsedRatio`; Code's share is text from `subscriptionBalance.kimiCodeUsedRatio`, never a second allowance. Expiration fields are not asserted to be reset times. Inference continues to read the local desktop Work key and enforce its exact gateway origin/account binding. Membership renewal does not replace a revoked Work key. +The monthly meter reports `subscriptionBalance.amountUsedRatio`; Code's share is text from `subscriptionBalance.kimiCodeUsedRatio`, never a second allowance. Expiration fields are not asserted to be reset times. Local accounts continue to read the desktop Work key; explicitly imported accounts use their saved copy. Both enforce its exact gateway origin/account binding. Membership renewal does not replace a revoked Work key. The historical live test covered renewal and read-only membership/model access, not an inference or desktop UI conversation at the current revision. Previous macOS and Windows streaming checks are historical coverage. Windows refresh, Linux, Intel macOS, long sleep/offline intervals, months of continuous renewal and future server revocation policy remain unverified. Automatic renewal does not guarantee a permanent session. diff --git a/packages/kimi-work/README.md b/packages/kimi-work/README.md index 87c005a..7252bf2 100644 --- a/packages/kimi-work/README.md +++ b/packages/kimi-work/README.md @@ -9,6 +9,10 @@ magpie plugin login kimi-work Open Kimi desktop and sign in to Work on the same computer first. Choose **使用本机 Kimi Work 登录** in the provider's sign-in menu. If the desktop provides a membership access/refresh pair, explicit sign-in imports it into the host's auth store and Magpie renews it directly with Kimi near expiry, including while the browser and desktop app are closed. Older desktops without a refresh token still sign in as reference-only accounts and read membership access from the desktop file. This package does not capture browser cookies or offer an API-key fallback. +Version **0.1.18** adds **Import accounts from a file…** in Magpie. Choose `daimon/config.json` from a trusted computer signed in to Kimi Work. Unlike local sign-in, this explicitly imports both the Work key and membership credentials, so the computer running Magpie does not need Kimi installed or the desktop data folder mounted. The file's `credentials.kimiCode`, `credentials.kimiWeb` and exact official Work origin are checked, then the Work key is verified with `/models` before the account is saved. Existing local/reference accounts are unchanged and are not migrated. This import hook is Magpie-only; OpenCode ignores it. + +The imported file contains sensitive Work and membership credentials, which are saved in Magpie's private plaintext `plugin-auth.json` (mode `0600`, not an encrypted vault). Import only into a trusted Magpie instance. Membership renewal continues as below, but it cannot renew the Work key: a Work 401 asks for a fresh `config.json` import. No desktop device ID or `kimi-code-key.json` is needed for an imported account. + Version **0.1.15** adds membership renewal and a single shared monthly meter to upstream 0.1.14. It retains the storage-pointer and sign-in diagnostics fixes (#425/#444), distinct account IDs and per-user Work keys (#440), and spent-quota 403→429 handling (#465), alongside the earlier menu/header fixes. **Existing reference-only accounts through 0.1.14 continue to read quota without reconnecting.** They do not silently migrate or spend the desktop refresh token. Explicitly reconnect only to opt into host-managed renewal when a desktop refresh token is available. Accounts already saved with a pair keep their format. Request-body buffering for schema conversion also follows the caller's abort signal: cancelling while a stream is still being read cancels that read and returns the original cancellation reason before any upstream request is sent. @@ -31,7 +35,7 @@ The account's models and reasoning options come from the two lists Kimi's deskto Version 0.1.4 preserves the calling agent's shared instructions, prompts, history and tools unchanged. Since 0.1.5 one exception: tool schemas Kimi's "moonshot flavored json schema" check refuses are rewritten to an equivalent it takes (#287). A `$ref` beside a `type`, as zod writes a schema derived from a reused one, gets its target written in; a `type` beside an `anyOf` is left out; an untyped `enum`, `const` or `$ref` target gets the type its values or keywords say. A request with none of these goes byte for byte. Instructions, MCP and skills are assigned to that agent in Magpie's Library; the provider does not create a second target or enable resources on its own. The ordinary Kimi agent's Library support starts at `@magpie-community/agent-kimi-desktop` 0.1.1. -An inference HTTP 401 marks the provider sign-in as expired (`kimi_work_login_expired`). Sign in to desktop Work if needed, then **reconnect Kimi Work in Magpie** (or run `magpie plugin login kimi-work`); signing in to the desktop alone does not reconnect the provider. A 403 whose body says the allowance is spent (Kimi's "You've reached your usage limit for this billing cycle", `resource_exhausted` "insufficient balance") goes to Magpie as a 429 with Kimi's body and headers, so Magpie rests that account until its allowance is back and asks another one (#465); any other 403 passes through as a 403. Other HTTP errors, including 429 and 5xx, pass through unchanged with Kimi's status, headers, body and Retry-After. This preserves the distinction between concurrency limits and exhausted allowance, including any upstream reset details. Network failures use `kimi_work_connection_failed` and retain the underlying cause code or fetch error message for diagnosis. Rate limits and service failures do not invalidate the desktop sign-in. Cancellation stays cancellation. No automatic retry sends a conversation twice or falls back to Code. +An inference HTTP 401 marks the provider sign-in as expired (`kimi_work_login_expired`). For a local account, sign in to desktop Work if needed, then **reconnect Kimi Work in Magpie** (or run `magpie plugin login kimi-work`); signing in to the desktop alone does not reconnect the provider. For an imported account, choose a fresh `config.json` through **Import accounts from a file…**. A 403 whose body says the allowance is spent (Kimi's "You've reached your usage limit for this billing cycle", `resource_exhausted` "insufficient balance") goes to Magpie as a 429 with Kimi's body and headers, so Magpie rests that account until its allowance is back and asks another one (#465); any other 403 passes through as a 403. Other HTTP errors, including 429 and 5xx, pass through unchanged with Kimi's status, headers, body and Retry-After. This preserves the distinction between concurrency limits and exhausted allowance, including any upstream reset details. Network failures use `kimi_work_connection_failed` and retain the underlying cause code or fetch error message for diagnosis. Rate limits and service failures do not invalidate the desktop sign-in. Cancellation stays cancellation. No automatic retry sends a conversation twice or falls back to Code. Models use standard context, capped at 262,144 tokens, rather than silently enabling the higher-priced XL context. The reply limit is the menu's `maxTokens` (32,768 for every model it lists today). Until the signed-in account's live catalog is read, and when it can't be, the models offered are `kimi-work/k3-agent` and `kimi-work/k2d8-preview`, the two ids Work's `/models` has listed; the live catalog replaces them, so a model Kimi adds to the account (such as K3.1 Pro) shows under the id the menu gives it. Since 0.1.6 a model whose reasoning levels come in a shape not seen before keeps the levels that can be read, rather than the whole catalog failing over to the fallback. @@ -43,7 +47,7 @@ Every reasoning-effort value returned by `/models` is retained, including `STAND ## Sign-in and local files -The plugin reads Kimi's `daimon/config.json`, `daimon/kimi-code-key.json` and optional `daimon/runtime/kimi-code/home/device_id` in its `daimon-share` folder. That folder is where Kimi's own `daimon-storage.json` points (`shareDir`), or, without a valid pointer, `daimon-share` inside Kimi's data folder: +For local sign-in, the plugin reads Kimi's `daimon/config.json`, `daimon/kimi-code-key.json` and optional `daimon/runtime/kimi-code/home/device_id` in its `daimon-share` folder. That folder is where Kimi's own `daimon-storage.json` points (`shareDir`), or, without a valid pointer, `daimon-share` inside Kimi's data folder: - Windows: `%APPDATA%/kimi-desktop/` - macOS: `~/Library/Application Support/kimi-desktop/` @@ -51,7 +55,7 @@ The plugin reads Kimi's `daimon/config.json`, `daimon/kimi-code-key.json` and op Kimi 3.2.21 on Windows, installed on another drive than `%APPDATA%`'s, keeps it there (`D:\KimiData\daimon-share` for an install on D:), and Kimi writes the same pointer on any system when its storage is moved. When the sign-in can't be found, the error names the file it looked for. Since 0.1.13, when the `daimon-share` folder itself is gone (moved, deleted, or on a drive that isn't mounted), the error names that folder instead (`kimi_work_share_missing`) and does not mark the account signed out: the sign-in in it isn't known to have lapsed. Putting the folder back makes the account work again at once, with no new sign-in. Kimi makes the folder again only when it starts, so signing in again in a running Kimi doesn't bring it back; quit and reopen Kimi, then sign in to Work. -The internal Work credential is named `credentials.kimiCode`, but its origin must be exactly `https://agent-gw.kimi.com/coding/v1`. Work credentials stay in Kimi's files and are reread for inference/model discovery. `credentials.kimiWeb.accessToken`, optional `refreshToken` and `userId` supply membership access. Only explicit sign-in can copy a complete membership pair to the host. The plugin never writes Kimi's configuration or creates a separate credential file. +The internal Work credential is named `credentials.kimiCode`, but its origin must be exactly `https://agent-gw.kimi.com/coding/v1`. For local accounts, Work credentials stay in Kimi's files and are reread for inference/model discovery. Imported accounts instead keep the explicitly imported Work key in the host's auth store and never read the desktop files. `credentials.kimiWeb.accessToken`, optional `refreshToken` and `userId` supply membership access. Explicit local sign-in can copy a complete membership pair to the host; file import copies the Work key too. The plugin never writes Kimi's configuration or creates a separate credential file. Reference-only accounts continue to read the desktop webToken on each quota request, after checking the saved account reference. They never consume a desktop refresh token or write auth state. A legacy membership 401 tells the user to open Kimi desktop to refresh membership access and keeps the Work sign-in. Paired accounts use their own saved access without reading desktop membership state; a membership 401 shows a reconnect hint while leaving Work usable. HTTP failures, timeouts and missing membership balances are reported on the quota card, rather than being treated as a revoked Work key. @@ -61,13 +65,13 @@ Since 0.1.13 each Kimi user signed in here has a distinct account ID (`Kimi Work ## Membership renewal and storage -When explicitly imported, the membership pair is saved by Magpie in its account-scoped `plugin-auth.json`, using flushed atomic writes and mode `0600`; OpenCode owns its own auth store. This is a private credential file, not an encrypted vault. No separate token file or desktop credential backup is created. Host-managed renewal is optional for reference-only accounts; a desktop without refresh continues to work in reference mode. +When explicitly imported, the membership pair is saved by Magpie in its account-scoped `plugin-auth.json`, using flushed atomic writes and mode `0600`; an imported Work key is saved in the same account entry. OpenCode owns its own auth store. This is a private credential file, not an encrypted vault. No separate token file or desktop credential backup is created. Host-managed renewal is optional for reference-only accounts; a desktop without refresh continues to work in reference mode. Magpie calls `auth.refresh` before models, usage and requests when access is within one minute of its JWT expiry. The hook returns rotated access/refresh fields. **Magpie owns the commit:** under its auth-store lock it checks that the original pair still stands before saving, so a late renewal cannot restore logout or overwrite a replacement login. The plugin never calls `client.auth.set` from renewal or usage. Pending work and cached rotations use exact credentials, keeping independent same-user reconnects separate. A failed host save can retry the rotated pair in the same plugin process; restarting before it is saved may require reconnecting. A rejected membership refresh gives a reconnect hint and keeps the Work sign-in; it throws a membership-only failure so the host retains retry backoff without marking the provider account expired. Network/429/5xx failures retain the stored login. RefreshToken uses its own observed desktop User-Agent/platform/version/timezone/language headers, with Connect JSON and no Authorization or Cookie. Browser device/session identifiers and ShieldData are not copied. Work requests keep upstream's Kimi Code 0.36.0/daimon 0.6.10 headers; www.kimi.com keeps upstream's desktop-menu metadata. The [compatibility record](COMPATIBILITY.md) compares the requests and preserves the dated 2026-10-24 single-cycle coexistence evidence; this revision does not claim a second real coexistence cycle. -Usage never rotates, writes or silently imports credentials, for either account format. `auth.refresh` and `auth.usage` are Magpie hooks ignored by OpenCode. Inference still depends on a valid per-account local Work key; membership renewal cannot replace a revoked Work key. Server expiry/revocation can require human sign-in, and automatic renewal does not guarantee a permanent session. +Usage never rotates, writes or silently imports credentials, for any account format. `auth.refresh`, `auth.usage` and `auth.import` are Magpie hooks ignored by OpenCode. Inference still depends on a valid per-account local or imported Work key; membership renewal cannot replace a revoked Work key. Server expiry/revocation can require human sign-in or a fresh file import, and automatic renewal does not guarantee a permanent session. ## Origin and provider-id conflict diff --git a/packages/kimi-work/import.test.mjs b/packages/kimi-work/import.test.mjs new file mode 100644 index 0000000..02f4475 --- /dev/null +++ b/packages/kimi-work/import.test.mjs @@ -0,0 +1,139 @@ +import {test,expect} from 'bun:test'; +import {_internal as I} from './index.mjs'; + +const NOW=1900000000000; +const jwt=(sub,exp,tag='fixture')=>'fixture.'+Buffer.from(JSON.stringify({sub,exp:exp/1000,tag})).toString('base64url')+'.fixture'; +const userId='synthetic-user'; +const workToken='synthetic-imported-work-key'; +const webToken=jwt(userId,NOW+3600000); +const file=({refresh='synthetic-membership-refresh',origin=I.BASE}={})=>JSON.stringify({credentials:{ + kimiCode:{apiKey:workToken,baseUrl:origin}, + kimiWeb:{accessToken:webToken,refreshToken:refresh,userId}, +}}); +const menu={models:[{requestParams:{modelId:'k3-agent',maxTokens:32768},display:{displayName:'K3'},daimonModelConfig:{maxContextSize:262144}}]}; +const catalog={data:[{id:'k3-agent',display_name:'K3',context_length:262144}]}; +const stats={subscriptionBalance:{amountUsedRatio:0.25}}; +function fixture(fetchImpl) { + let desktopReads=0; + const p=I.createPlugin({now:()=>NOW,fetchImpl,readSession:()=>{desktopReads++;throw Error('desktop files must not be read');}}); + return {p,desktopReads:()=>desktopReads}; +} +const chat=loader=>loader.fetch(I.BASE+'/chat/completions',{method:'POST',body:'{"model":"k3-agent","messages":[]}'}); + +test('magpie offers a guided config.json import in every window language',async()=>{ + const {p}=fixture(async()=>{throw Error('no network expected');}); + expect(typeof p.auth.import).toBe('function'); + expect(p.auth.importFrom).toContain('daimon/config.json'); + for(const lang of ['zh','zh-TW','ja','de'])expect(p.auth.importFroms[lang]).toContain('daimon/config.json'); +}); + +test('a selected config.json is validated and explicitly imports both Work and membership credentials',async()=>{ + const calls=[]; + const {p,desktopReads}=fixture(async(url,init)=>{ + calls.push({url:String(url),headers:new Headers(init.headers)}); + return Response.json(catalog); + }); + const [auth]=await p.auth.import(['\uFEFF'+file()]); + expect(auth).toMatchObject({type:'success',source:'kimi-work-desktop',imported:true,workToken, + access:webToken,refresh:'synthetic-membership-refresh',expires:NOW+3600000}); + expect(auth.accountId).toMatch(/^Kimi Work · [0-9a-f]{6}$/); + expect(calls).toHaveLength(1); + expect(calls[0].url).toBe(I.BASE+'/models'); + expect(calls[0].headers.get('authorization')).toBe('Bearer '+workToken); + expect(desktopReads()).toBe(0); +}); + +test('an imported account lists models, reads usage and chats without any desktop file or device id',async()=>{ + const calls=[]; + const {p,desktopReads}=fixture(async(url,init)=>{ + calls.push({url:String(url),headers:new Headers(init.headers)}); + if(url===I.BASE+'/models')return Response.json(catalog); + if(url===I.CONFIG)return Response.json(menu); + if(url===I.MEMBER+'GetSubscriptionStats')return Response.json(stats); + if(url===I.BASE+'/chat/completions')return Response.json({choices:[]}); + throw Error('unexpected request '+url); + }); + const [auth]=await p.auth.import([file()]); + calls.length=0; + expect(await p.auth.refresh(auth)).toBeUndefined(); + const models=await p.provider.models({models:{}},{auth}); + expect(Object.keys(models)).toEqual(['k3-agent']); + expect(await p.auth.usage(async()=>auth)).toEqual({plan:'月度共享额度',windows:[{name:'本月',used:25}]}); + expect((await chat(await p.auth.loader(async()=>auth))).status).toBe(200); + expect(desktopReads()).toBe(0); + expect(calls.find(c=>c.url===I.CONFIG).headers.get('authorization')).toBe('Bearer '+webToken); + expect(calls.find(c=>c.url===I.MEMBER+'GetSubscriptionStats').headers.get('authorization')).toBe('Bearer '+webToken); + for(const c of calls.filter(c=>c.url.startsWith(I.BASE))) { + expect(c.headers.get('authorization')).toBe('Bearer '+workToken); + expect(c.headers.has('x-msh-device-id')).toBe(false); + } +}); + +test('a config.json without a membership refresh token still works independently as an access-only import',async()=>{ + const sent=[]; + const {p,desktopReads}=fixture(async(url,init)=>{ + sent.push({url:String(url),authorization:new Headers(init.headers).get('authorization')}); + return Response.json(url===I.BASE+'/models'?catalog:stats); + }); + const [auth]=await p.auth.import([file({refresh:''})]); + expect(auth).toMatchObject({type:'success',imported:true,workToken,access:webToken,refresh:''}); + expect(await p.auth.refresh(auth)).toBeUndefined(); + expect((await p.auth.usage(async()=>auth)).windows[0].used).toBe(25); + expect((await chat(await p.auth.loader(async()=>auth))).status).toBe(200); + expect(sent.at(-1).authorization).toBe('Bearer '+workToken); + expect(desktopReads()).toBe(0); +}); + +test('bad JSON, missing credentials and a non-Work origin are refused without a request or secret leakage',async()=>{ + let calls=0; + const {p,desktopReads}=fixture(async()=>{calls++;return Response.json(catalog);}); + const results=await p.auth.import(['not json','{}',file({origin:'https://api.kimi.com/coding/v1'})]); + expect(results.map(r=>r.type)).toEqual(['failed','failed','failed']); + for(const r of results)expect(r.error).toContain('daimon/config.json'); + expect(JSON.stringify(results)).not.toContain(workToken); + expect(JSON.stringify(results)).not.toContain(webToken); + expect(calls).toBe(0); + expect(desktopReads()).toBe(0); +}); + +test('a Work key refused during import fails sign-in and names the fresh file to choose',async()=>{ + const {p,desktopReads}=fixture(async()=>new Response('{}',{status:401})); + const [auth]=await p.auth.import([file()]); + expect(auth.type).toBe('failed'); + expect(auth.error).toContain('新的 config.json'); + expect(auth.error).not.toContain(workToken); + expect(desktopReads()).toBe(0); +}); + +test('a Work 401 after import asks for reimport instead of a desktop path or membership renewal',async()=>{ + const {p,desktopReads}=fixture(async url=>String(url)===I.BASE+'/models'?Response.json(catalog):new Response('{}',{status:401})); + const [auth]=await p.auth.import([file()]); + const error=await chat(await p.auth.loader(async()=>auth)).catch(error=>error); + expect(error).toMatchObject({signIn:'expired',code:'kimi_work_login_expired'}); + expect(error.message).toContain('重新选择'); + expect(error.message).toContain('daimon/config.json'); + expect(error.message).not.toContain('magpie plugin login'); + expect(desktopReads()).toBe(0); +}); + +test('membership renewal changes only the membership pair and preserves the imported Work key',async()=>{ + const calls=[]; + const {p,desktopReads}=fixture(async(url,init)=>{ + calls.push({url:String(url),init}); + if(url===I.BASE+'/models')return Response.json(catalog); + if(url===I.REFRESH)return Response.json({access_token:jwt(userId,NOW+7200000,'rotated'),refresh_token:'synthetic-rotated-refresh'}); + if(url===I.BASE+'/chat/completions')return Response.json({choices:[]}); + throw Error('unexpected request '+url); + }); + const expiredFile=file().replace(webToken,jwt(userId,NOW-1000)); + const [auth]=await p.auth.import([expiredFile]); + const rotated=await p.auth.refresh(auth); + expect(rotated).toMatchObject({refresh:'synthetic-rotated-refresh',expires:NOW+7200000}); + const saved={...auth,...rotated}; + expect(saved.workToken).toBe(workToken); + expect(saved.imported).toBe(true); + await chat(await p.auth.loader(async()=>saved)); + const work=calls.at(-1); + expect(new Headers(work.init.headers).get('authorization')).toBe('Bearer '+workToken); + expect(desktopReads()).toBe(0); +}); diff --git a/packages/kimi-work/index.mjs b/packages/kimi-work/index.mjs index eda93ad..09572ea 100644 --- a/packages/kimi-work/index.mjs +++ b/packages/kimi-work/index.mjs @@ -84,6 +84,16 @@ const notHere = (revoked=false) => Object.assign(Error(revoked : '这个 Kimi Work 账号已不是 Kimi 桌面版当前登录的账号,本机也没有它的 Work 密钥。请在 Kimi 桌面版切换到这个账号进入一次 Work,之后切回别的账号它也能继续用。'), {signIn:'expired',code:'kimi_work_account_not_here'}); const unavailable = error => Object.assign(Error('Kimi Work 连接失败:' + (error?.cause?.code || error?.message || '未知网络错误'), {cause:error}), {code:'kimi_work_connection_failed'}); +const importExpired = () => Object.assign(Error('导入的 Kimi Work 密钥已失效,请重新选择 Kimi 桌面版的 daimon/config.json 导入。'), {signIn:'expired',code:'kimi_work_login_expired'}); +const IMPORT_FROM = { + en: "Choose Kimi desktop's daimon/config.json from a computer signed in to Work. The imported account works here without Kimi installed. Its credentials are kept in magpie's auth store; import it again if its Work key expires.", + froms: { + zh: '选择已登录 Work 的 Kimi 桌面版 daimon/config.json。导入后本机无需安装 Kimi。文件包含敏感凭据,会保存在 magpie 认证库中;Work 密钥失效后需重新导入。', + 'zh-TW': '選擇已登入 Work 的 Kimi 桌面版 daimon/config.json。匯入後本機無需安裝 Kimi。檔案包含敏感憑證,會保存在 magpie 認證庫中;Work 金鑰失效後需重新匯入。', + ja: 'Work にサインインした Kimi デスクトップの daimon/config.json を選択します。インポート後、このPCに Kimi は不要です。機密情報は magpie の認証ストアに保存されます。Work キーが失効したら再インポートしてください。', + de: 'Wähle daimon/config.json eines bei Work angemeldeten Kimi-Desktops. Danach ist Kimi hier nicht nötig. Die sensiblen Zugangsdaten werden in magpies Auth-Speicher abgelegt; nach Ablauf des Work-Schlüssels erneut importieren.', + }, +}; // spentQuota is a 403 body saying the account's allowance is used up, not // that the token or the model is refused (#465). const spentQuota = text => /resource_exhausted|usage limit|billing cycle|insufficient balance|quota/i.test(String(text??'')); @@ -377,8 +387,15 @@ function readKeys(file) { // A Windows path is taken apart as one wherever the plugin runs (tests). const pathOf = f => /^(?:[A-Za-z]:[\\/]|\\\\)/.test(f)?path.win32:path; -// Read Work credentials live. Only explicit sign-in can import the web pair; -// usage of a reference-only account just rereads its web access token. +function desktopCredentials(doc) { + const work=doc?.credentials?.kimiCode, web=doc?.credentials?.kimiWeb; + if(typeof work?.apiKey!=='string'||!work.apiKey || typeof web?.accessToken!=='string'||!web.accessToken + || typeof web.userId!=='string'||!web.userId || work.baseUrl?.replace(/\/$/,'')!==BASE) throw expired(); + return {workToken:work.apiKey,webToken:web.accessToken, + webRefresh:typeof web.refreshToken==='string' ? web.refreshToken : '',uid:accountUid(web.userId)}; +} +// Read a local account's Work credentials live. Only explicit sign-in or file +// import copies credentials; reference-only usage rereads its web access token. // Kimi owns these files; this plugin never writes them. function readDesktop(file=desktopFile()) { const P=pathOf(file),daimon=P.dirname(file),share=P.dirname(daimon); @@ -390,14 +407,15 @@ function readDesktop(file=desktopFile()) { const st=fs.statSync(file); if(!st.isFile() || st.size>8*1024*1024) throw expired(); const doc=JSON.parse(fs.readFileSync(file,'utf8').replace(/^\uFEFF/,'')); - const work=doc.credentials?.kimiCode, web=doc.credentials?.kimiWeb; - if(typeof work?.apiKey!=='string'||!work.apiKey || typeof web?.accessToken!=='string'||!web.accessToken - || typeof web.userId!=='string'||!web.userId || work.baseUrl?.replace(/\/$/,'')!==BASE) throw expired(); - return {workToken:work.apiKey,webToken:web.accessToken,deviceId:readDeviceId(file), - webRefresh:typeof web.refreshToken==='string' ? web.refreshToken : '', - uid:accountUid(web.userId),keys:readKeys(P.join(daimon,'kimi-code-key.json'))}; + return {...desktopCredentials(doc),deviceId:readDeviceId(file),keys:readKeys(P.join(daimon,'kimi-code-key.json'))}; } catch {throw Object.assign(expired(),{file});} } +function parseDesktopImport(text) { + try { + if(typeof text!=='string'||Buffer.byteLength(text)>8*1024*1024)throw Error('invalid import'); + return desktopCredentials(JSON.parse(text.replace(/^\uFEFF/,''))); + } catch {throw Error('文件不是有效的 Kimi Work daimon/config.json,未找到可用的 Work 和会员凭据。');} +} function modelRows(payload) { if(!Array.isArray(payload?.data)||payload.has_more||payload.data.length>100) throw Error('Kimi Work 模型目录暂不可用。'); @@ -482,13 +500,17 @@ function workConfigRows(payload) { } function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platform=process.platform,now=Date.now}={}) { - // The account's session: Kimi's own sign-in when the account is the one - // Kimi is signed in to, else its Work key from Kimi's key store, with no + // An imported account uses its saved Work key. A local account uses Kimi's + // own sign-in when current, else its Work key from Kimi's key store, with no // web sign-in (Kimi keeps only the current user's), so its allowance // can't be read (#440). const current=auth=>{ - const session=readSession(); if(auth?.source!=='kimi-work-desktop')throw expired(); + if(auth.imported===true) { + if(typeof auth.workToken!=='string'||!auth.workToken)throw importExpired(); + return {workToken:auth.workToken,webToken:typeof auth.access==='string'?auth.access:'',uid:auth.uid,imported:true}; + } + const session=readSession(); if(auth.uid===session.uid)return session; const key=typeof auth.uid==='string'?session.keys?.[auth.uid]:undefined; if(!key)throw notHere(); @@ -605,6 +627,34 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo offered.set(s.uid,ids); return ids; } + function signedIn(s,imported=false) { + const pair=s.webRefresh + ? {access:s.webToken,refresh:s.webRefresh,expires:expiry(s.webToken)} + : imported ? {access:s.webToken,refresh:'',expires:expiry(s.webToken)} : {access:'',refresh:'',expires:0}; + return {type:'success',...pair,source:'kimi-work-desktop', + accountId:'Kimi Work · '+s.uid.slice(0,6),uid:s.uid, + ...(imported?{imported:true,workToken:s.workToken}:{})}; + } + async function importFile(text,signal) { + let s; + try{s=parseDesktopImport(text);} + catch(error){return {type:'failed',error:error.message};} + try{await jsonRequest(BASE+'/models',s.workToken,undefined,signal);} + catch(error){ + if(error?.status===401)return {type:'failed',error:'文件中的 Kimi Work 密钥已失效,请在 Kimi 桌面版重新进入 Work 后选择新的 config.json。'}; + const why=error?.status?'HTTP '+error.status:error?.name==='TimeoutError'?'超时':error?.cause?.code||error?.message||'未知网络错误'; + return {type:'failed',error:'已读取文件中的 Kimi Work 登录,但连接 Kimi Work 失败('+why+'),请检查网络后再试。'}; + } + return signedIn(s,true); + } + async function importFiles(texts,signal) { + const out=[]; + for(const text of Array.isArray(texts)?texts:[texts]) { + signal?.throwIfAborted(); + out.push(await importFile(text,signal)); + } + return out; + } return { config:async cfg=>{ cfg.provider??={}; @@ -617,6 +667,9 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo auth:{ provider:ID, maxConcurrency:1, + importFrom:IMPORT_FROM.en, + importFroms:IMPORT_FROM.froms, + import:(texts,{signal}={})=>importFiles(texts,signal), methods:[{type:'oauth',label:'使用本机 Kimi Work 登录',authorize:async()=>({ url:'',method:'auto',instructions:'读取本机 Kimi Work 登录;支持会员续期,不修改桌面配置。', callback:async()=>{ @@ -637,11 +690,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo } // A user keeps a separate account id (#440). Import a complete web // pair when available; older desktops still get a reference account. - const pair=typeof s.webRefresh==='string'&&s.webRefresh - ? {access:s.webToken,refresh:s.webRefresh,expires:expiry(s.webToken)} - : {access:'',refresh:'',expires:0}; - return {type:'success',...pair,source:'kimi-work-desktop', - accountId:'Kimi Work · '+s.uid.slice(0,6),uid:s.uid}; + return signedIn(s); }, })}], refreshLead:REFRESH_LEAD, @@ -685,7 +734,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo let response; try { response=await fetchImpl(BASE+'/chat/completions',{...options,method:'POST',headers,redirect:'error'}); } catch(error) { if(options.signal?.aborted)throw error; throw unavailable(error); } - if(response.status===401) { await response.body?.cancel(); throw s.away?notHere(true):expired(); } + if(response.status===401) { await response.body?.cancel(); throw s.imported?importExpired():s.away?notHere(true):expired(); } // Kimi says a spent allowance with a 403 ("You've reached your // usage limit for this billing cycle", resource_exhausted // "insufficient balance"), which magpie reads as a key fault and diff --git a/packages/kimi-work/package.json b/packages/kimi-work/package.json index fe1ab33..d890607 100644 --- a/packages/kimi-work/package.json +++ b/packages/kimi-work/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kimi-work-auth", - "version": "0.1.17", + "version": "0.1.18", "type": "module", "main": "./opencode.mjs", "files": [ diff --git a/registry.json b/registry.json index 9dab6f5..f9319b7 100644 --- a/registry.json +++ b/registry.json @@ -29,7 +29,7 @@ "summary": { "en": "Unofficial JoyCode provider: JD account browser sign-in, live models and credit multipliers, plan credits and streaming tool calls.", "zh": "非官方 JoyCode 插件:京东账号浏览器登录,动态模型与积分倍率、套餐额度及流式工具调用。" } }, {"package": "@magpie-community/opencode-doubao-work-auth", "name": "豆包工作", "icon": "doubao-color", "providers": ["doubao-work"], "community": true, "summary": {"en": "Not a model API: Doubao Work has none for other clients. This drives its desktop app (or Doubao's) the way a person does, so each request is one run of Doubao's cloud agent in a new task, with the client's tools asked for as text. macOS and Windows; unofficial.", "zh": "不是模型接口:豆包工作没有给第三方客户端用的模型接口。本插件像人一样操作豆包工作(或豆包)桌面版,每个请求是豆包云端智能体在一个新任务里的一次执行,客户端的工具以文本方式调用。macOS 和 Windows;非官方。"}}, {"package": "@magpie-community/opencode-gemini-web-auth", "name": "Gemini 网页版", "icon": "gemini-color", "providers": ["gemini-web"], "community": true, "summary": {"en": "Not Google's API: the Gemini web app (gemini.google.com), with your Google account signed in through a browser window of its own, or as a visitor without one. Each request is one streamed call to the app's own endpoint, in a temporary chat, with the client's tools asked for as text. Unofficial.", "zh": "不是 Google 的 API:Gemini 网页版(gemini.google.com),在插件自己的浏览器窗口里登录 Google 账号,或不登录以访客使用。每个请求是对网页版自己接口的一次流式调用(临时对话,不进历史),客户端的工具以文本方式调用。非官方。"}}, - {"package": "@magpie-community/opencode-kimi-work-auth", "name": "Kimi Work", "icon": "kimi", "providers": ["kimi-work"], "community": true, "summary": {"en": "Kimi desktop Work subscription through its local sign-in, with live Work models and shared membership usage. Separate from Kimi Code.", "zh": "使用本机普通 Kimi 桌面版的 Work 登录,自动读取 Work 模型和会员共享用量;独立于 Kimi Code。"}}, + {"package": "@magpie-community/opencode-kimi-work-auth", "name": "Kimi Work", "icon": "kimi", "providers": ["kimi-work"], "community": true, "summary": {"en": "Kimi desktop Work subscription through its local sign-in or an imported credentials file, with live Work models and shared membership usage. Separate from Kimi Code.", "zh": "使用本机普通 Kimi 桌面版的 Work 登录或导入凭据文件,自动读取 Work 模型和会员共享用量;独立于 Kimi Code。"}}, { "package": "@magpie-community/opencode-zen-free-auth", "name": "OpenCode Zen Free", "icon": "opencode", "providers": ["opencode-zen-free"], "community": true, "summary": { "en": "OpenCode Zen's free models with the public credential, automatic discovery and native streaming protocols.", "zh": "使用 public 凭证接入 OpenCode Zen 免费模型,自动发现模型并支持原生流式协议。" } }, { "package": "@magpie-community/opencode-zcode-auth", "name": "ZCode", "icon": "zcode", "providers": ["zcode"], "community": true, "replaces": "zcode",