diff --git a/packages/kimi-work/README.md b/packages/kimi-work/README.md index 6de8fe1..517cf96 100644 --- a/packages/kimi-work/README.md +++ b/packages/kimi-work/README.md @@ -25,17 +25,21 @@ Every reasoning-effort value returned by `/models` is retained, including `STAND ## Sign-in and local files -The plugin reads only the desktop app's `daimon/config.json` in its `daimon-share` folder. That folder is where Kimi's own `daimon-storage.json` points (`shareDir`), or, with no such file, `daimon-share` itself, in Kimi's data folder: +The plugin reads only the desktop app's `daimon/config.json`, and since 0.1.13 its `daimon/kimi-code-key.json`, in its `daimon-share` folder. That folder is where Kimi's own `daimon-storage.json` points (`shareDir`), or, with no such file, `daimon-share` itself, in Kimi's data folder: - Windows: `%APPDATA%/kimi-desktop/` - macOS: `~/Library/Application Support/kimi-desktop/` - Linux: `~/.config/kimi-desktop/` -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. +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`. `credentials.kimiWeb` supplies the membership sign-in. The plugin rejects missing credentials and other origins. It saves only a hashed account reference in Magpie/OpenCode's auth store; the actual tokens remain in Kimi's own file and are reread on each operation. It never reads Magpie's credential files, writes Kimi configuration, consumes refresh tokens, or stores copies of desktop credentials. +The internal Work credential is named `credentials.kimiCode`, but its origin must be exactly `https://agent-gw.kimi.com/coding/v1`. `credentials.kimiWeb` supplies the membership sign-in. The plugin rejects missing credentials and other origins. It saves only a hashed account reference in Magpie/OpenCode's auth store; the actual tokens remain in Kimi's own files (`config.json`, and `kimi-code-key.json` for an account Kimi has switched away from) and are reread on each operation. It never reads Magpie's credential files, writes Kimi configuration, consumes refresh tokens, or stores copies of desktop credentials. -Kimi desktop remains responsible for refreshing its sign-in. If it expires, sign in there and reconnect this provider. Changing the desktop account requires reconnecting, so requests do not silently switch accounts. Each synced device must have its own Kimi desktop sign-in. +Kimi desktop remains responsible for refreshing its sign-in. If it expires, sign in there and reconnect this provider. Each synced device must have its own Kimi desktop sign-in. + +### Several Kimi accounts + +Since 0.1.13 each Kimi user signed in here is an account of its own (named `Kimi Work · ` and the start of its hashed id), and requests never switch silently from one to another. To add a second one, switch Kimi desktop to that user, open Work once, and sign in to this provider again. Both keep working after Kimi switches back and forth: Kimi keeps one minted Work key per user in `daimon/kimi-code-key.json` (`{"v":2,"keys":[{userId,apiKey,keyId?}]}`, Kimi 3.2.21) and reuses a user's key when it switches back to them; it drops one only when the Work gateway refuses it. The account Kimi is signed in to uses `config.json`'s key; any other uses its key from that file. Only the user Kimi is signed in to has a web sign-in, so the shared membership allowance can be read only for that account; the others show that they need switching to in Kimi, and chat is unaffected. An account whose key is no longer in Kimi's file, or whose key the gateway refuses, is marked signed out (`kimi_work_account_not_here`) until Kimi is switched to it and opens Work. Kimi signed out entirely (no Work sign-in in `config.json`) serves none of them. Accounts signed in before 0.1.13 are named `Kimi Work (local)`; signing in to the same user again adds it under the new name, and the old entry can be removed. ## Origin and provider-id conflict diff --git a/packages/kimi-work/index.mjs b/packages/kimi-work/index.mjs index 48bf15c..037400e 100644 --- a/packages/kimi-work/index.mjs +++ b/packages/kimi-work/index.mjs @@ -43,6 +43,20 @@ function workHeaders(deviceId) { 'X-Msh-Platform':'kimi-code-cli','X-Msh-Version':KIMI_CODE_VERSION,'X-Msh-Daimon-Version':DAIMON_VERSION}; } const expired = () => Object.assign(Error('请先在本机 Kimi 桌面版登录 Work,再重新连接 Kimi Work 供应商。'), {signIn:'expired',code:'kimi_work_login_expired'}); +// Kimi's daimon-share itself is gone (moved, deleted, a drive not mounted): +// the sign-in in it isn't known to have lapsed, so the account is not marked +// signed out ("kept"), and the message names the folder (#444). Kimi makes +// the folder again only when it starts, so signing in again in a running +// Kimi doesn't bring it back; putting it back does, at once. +const shareMissing = dir => Object.assign(Error('Kimi Work 的数据目录不存在:' + dir + + '。如果移动或删除过它,把它放回原处即可恢复,无需重新登录;否则请完全退出并重新打开 Kimi 桌面版(它会重建这个目录),再登录 Work。'), + {signIn:'kept',code:'kimi_work_share_missing',file:dir,shareMissing:true}); +// An account signed in here that Kimi has since switched away from, with no +// Work key of its own left in Kimi's key store (#440). +const notHere = (revoked=false) => Object.assign(Error(revoked + ? '这个 Kimi Work 账号在本机的 Work 密钥已失效。请在 Kimi 桌面版切换到这个账号进入一次 Work,Kimi 会换一把新的。' + : '这个 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 percent = x => typeof x === 'number' && Number.isFinite(x) ? Math.max(0,Math.min(100,x*100)) : undefined; @@ -247,11 +261,40 @@ function readDeviceId(file) { } catch {return undefined;} } +const accountUid = userId => createHash('sha256').update('kimi-work-account\0'+userId).digest('hex'); +// The Work keys Kimi minted, one per Kimi user that has used Work on this +// computer: /kimi-code-key.json, {"v":2,"keys":[{userId,apiKey, +// keyId?}]}, the user in use first (Kimi 3.2.21's DaimonProvision). Kimi +// keeps a user's entry when it switches to another user, and reuses it when +// it switches back; it drops one only when agent-gw answers it 401. So an +// account Kimi has switched away from still has its key here (#440). Read +// as Kimi reads it: any other version, or an entry without both strings, +// is none. Keyed by the account's hashed uid; the first entry for a user +// wins, as Kimi's find does. +function readKeys(file) { + const out=Object.create(null); + try { + if(fs.statSync(file).size>1024*1024)return out; + const doc=JSON.parse(fs.readFileSync(file,'utf8').replace(/^\uFEFF/,'')); + if(doc?.v!==2||!Array.isArray(doc.keys))return out; + for(const k of doc.keys) + if(typeof k?.userId==='string'&&k.userId&&typeof k.apiKey==='string'&&k.apiKey)out[accountUid(k.userId)]??=k.apiKey; + } catch {} + return out; +} + +// 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 the live Work sign-in, including after rotation. Never consume its // refresh token or write the desktop app's configuration. The internal field // is called kimiCode, but this credential is issued for agent-gw (Work). function readDesktop(file=desktopFile()) { - if(!fs.existsSync(file))throw Object.assign(expired(),{file,missing:true}); + const P=pathOf(file),daimon=P.dirname(file),share=P.dirname(daimon); + if(!fs.existsSync(file)) { + if(!fs.existsSync(share))throw shareMissing(share); + throw Object.assign(expired(),{file,missing:true}); + } try { const st=fs.statSync(file); if(!st.isFile() || st.size>8*1024*1024) throw expired(); @@ -260,7 +303,7 @@ function readDesktop(file=desktopFile()) { 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), - uid:createHash('sha256').update('kimi-work-account\0'+web.userId).digest('hex')}; + uid:accountUid(web.userId),keys:readKeys(P.join(daimon,'kimi-code-key.json'))}; } catch {throw Object.assign(expired(),{file});} } @@ -336,10 +379,17 @@ function workConfigRows(payload) { } function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platform=process.platform}={}) { + // 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 + // 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'||auth.uid!==session.uid)throw expired(); - return session; + if(auth?.source!=='kimi-work-desktop')throw expired(); + if(auth.uid===session.uid)return session; + const key=typeof auth.uid==='string'?session.keys?.[auth.uid]:undefined; + if(!key)throw notHere(); + return {workToken:key,webToken:'',deviceId:session.deviceId,uid:auth.uid,away:true}; }; async function jsonRequest(url,token,body,signal,deviceId) { const response=await fetchImpl(url,{method:body===undefined?'GET':'POST', @@ -398,6 +448,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo catch(error){ // Which file was read goes in the message, so a report says // where Kimi's sign-in was looked for (#425); never a value. + if(error?.shareMissing)return {type:'failed',error:error.message}; return {type:'failed',error:'没有可用的本机 Kimi Work 登录,请先打开 Kimi 并登录 Work。' +(error?.file?(error.missing?'(未找到 ':'(无法读取 ')+error.file+')':'')}; } @@ -408,9 +459,13 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo return {type:'failed',error:'已找到本机 Kimi Work 登录,但连接 Kimi Work 失败('+why+'),请检查网络后再试。'}; } // Only an account reference is saved in Magpie. Actual credentials - // stay in Kimi's own file and are reread for every operation. + // stay in Kimi's own files and are reread for every operation. + // Each Kimi user is an account of its own, named by the start of + // its hashed uid, so a second one signed in sits beside the first + // (magpie keeps one per accountId and uid) and the two are told + // apart (#440). return {type:'success',access:'',refresh:'',expires:0,source:'kimi-work-desktop', - accountId:'Kimi Work (local)',uid:s.uid}; + accountId:'Kimi Work · '+s.uid.slice(0,6),uid:s.uid}; }, })}], loader:async getAuth=>({ @@ -442,7 +497,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 expired(); } + if(response.status===401) { await response.body?.cancel(); throw s.away?notHere(true):expired(); } // Magpie classifies rate vs quota from the upstream response. Keep // its wording, reset details and Retry-After instead of guessing. return response; @@ -459,6 +514,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo usage:async getAuth=>{ const s=current(await getAuth()); const plan='Kimi Work · 会员共享额度'; + if(s.away)return {plan,windows:[],error:'这个账号不是 Kimi 桌面版当前登录的账号,切换到它后才能读取会员额度(对话不受影响)',signIn:'kept'}; let j; try {j=await jsonRequest(MEMBER+'GetSubscriptionStats',s.webToken,{});} catch(error) { @@ -493,4 +549,4 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo } export default async function KimiWorkProvider(){return createPlugin();} -export const _internal={createPlugin,moonshotTools,moonshotSchema,readDesktop,desktopFile,shareDir,userDataDir,modelRows,workConfigRows,BASE,MEMBER,CONFIG,UA,workHeaders,webHeaders,readDeviceId}; +export const _internal={createPlugin,moonshotTools,moonshotSchema,readDesktop,readKeys,desktopFile,shareDir,userDataDir,modelRows,workConfigRows,BASE,MEMBER,CONFIG,UA,workHeaders,webHeaders,readDeviceId}; diff --git a/packages/kimi-work/package.json b/packages/kimi-work/package.json index 6f3dad2..f8726d8 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.12", + "version": "0.1.13", "type": "module", "main": "./index.mjs", "files": [ diff --git a/packages/kimi-work/tests/accounts.test.mjs b/packages/kimi-work/tests/accounts.test.mjs new file mode 100644 index 0000000..dfaecfd --- /dev/null +++ b/packages/kimi-work/tests/accounts.test.mjs @@ -0,0 +1,137 @@ +import {test,expect} from 'bun:test'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {_internal as I} from '../index.mjs'; + +// Kimi's own files, as Kimi 3.2.21 writes them: /config.json with +// the signed-in user's Work key and web sign-in, and /kimi-code-key.json, +// one minted Work key per Kimi user that has used Work here, the user in +// use first ({"v":2,"keys":[{userId,apiKey,keyId?}]}). +function kimiHome() { + const home=fs.mkdtempSync(path.join(os.tmpdir(),'kimi-work-acct-')); + const platform=process.platform==='win32'?'win32':process.platform==='darwin'?'darwin':'linux'; + const opts={home,platform,appdata:path.join(home,'AppData','Roaming')}; + const data=I.userDataDir(opts),share=path.join(home,'KimiData','daimon-share'),daimon=path.join(share,'daimon'); + fs.mkdirSync(daimon,{recursive:true});fs.mkdirSync(data,{recursive:true}); + // the pointer Kimi writes for an install on another drive (#425, #444) + fs.writeFileSync(path.join(data,'daimon-storage.json'),JSON.stringify({version:1,shareDir:share})); + const signIn=(userId,keys)=>{ + fs.writeFileSync(path.join(daimon,'config.json'),JSON.stringify({credentials:{ + kimiCode:{apiKey:keys[0].apiKey,baseUrl:I.BASE},kimiWeb:{accessToken:'web-'+userId,userId}}})); + fs.writeFileSync(path.join(daimon,'kimi-code-key.json'),JSON.stringify({v:2,keys})); + }; + return {home,opts,share,daimon,signIn,read:()=>I.readDesktop(I.desktopFile(opts)),done:()=>fs.rmSync(home,{recursive:true,force:true})}; +} +const chat=loader=>loader.fetch(I.BASE+'/chat/completions',{method:'POST',body:'{"model":"k3-agent","messages":[]}'}); + +// #444 (kongbai01203): daimon-storage.json readable, the folder it names +// moved or deleted afterwards. 0.1.12 called that a lapsed sign-in. +test('a share folder that is gone says which folder, leaves the sign-in unmarked, and comes back when the folder does',async()=>{ + const k=kimiHome(); + try { + k.signIn('user-a',[{userId:'user-a',apiKey:'key-a'}]); + let calls=0; + const p=I.createPlugin({readSession:k.read,fetchImpl:async()=>{calls++;return new Response('{}');}}); + const a=await (await p.auth.methods[0].authorize()).callback(); + expect(a.type).toBe('success'); + const loader=await p.auth.loader(async()=>a); + calls=0; + const moved=k.share+'.moved'; + fs.renameSync(k.share,moved); + let err; + try {await chat(loader);} catch(e) {err=e;} + expect(err?.code).toBe('kimi_work_share_missing'); + expect(err?.signIn).toBe('kept'); + expect(err?.message).toContain(k.share); + expect(err?.message).toContain('放回原处'); + expect(calls).toBe(0); + await expect(p.auth.usage(async()=>a)).rejects.toMatchObject({code:'kimi_work_share_missing',signIn:'kept'}); + const again=await (await p.auth.methods[0].authorize()).callback(); + expect(again.type).toBe('failed'); + expect(again.error).toContain(k.share); + expect(again.error).not.toContain('没有可用'); + // put back: the same account works with no new sign-in + fs.renameSync(moved,k.share); + expect((await chat(loader)).status).toBe(200); + expect(calls).toBe(1); + } finally {k.done();} +}); + +test('the reporter\'s Windows path: D:\\KimiData\\daimon-share gone is named as the folder',()=>{ + let err; + try {I.readDesktop('D:\\KimiData\\daimon-share\\daimon\\config.json');} catch(e) {err=e;} + expect(err?.code).toBe('kimi_work_share_missing'); + expect(err?.message).toContain('D:\\KimiData\\daimon-share'); +}); + +test('a share folder with no sign-in in it is still a missing sign-in',()=>{ + const k=kimiHome(); + try { + let err; + try {k.read();} catch(e) {err=e;} + expect(err?.code).toBe('kimi_work_login_expired'); + expect(err?.missing).toBe(true); + } finally {k.done();} +}); + +// #440 (kongbai01203): a second Kimi user signed in made the first one's +// account fail, since only the user Kimi is signed in to was served. +test('two Kimi users signed in one after the other are both served, each with its own Work key',async()=>{ + const k=kimiHome(); + try { + const calls=[]; + const p=I.createPlugin({readSession:k.read,fetchImpl:async(url,init)=>{calls.push({url:String(url),auth:new Headers(init.headers).get('authorization')});return new Response('{}');}}); + k.signIn('user-a',[{userId:'user-a',apiKey:'key-a',keyId:'id-a'}]); + const a=await (await p.auth.methods[0].authorize()).callback(); + // Kimi switched to user B: B's key minted and put first, A's kept + k.signIn('user-b',[{userId:'user-b',apiKey:'key-b'},{userId:'user-a',apiKey:'key-a',keyId:'id-a'}]); + const b=await (await p.auth.methods[0].authorize()).callback(); + expect(a.type).toBe('success');expect(b.type).toBe('success'); + expect(a.uid).not.toBe(b.uid); + expect(a.accountId).not.toBe(b.accountId); + calls.length=0; + await chat(await p.auth.loader(async()=>a)); + await chat(await p.auth.loader(async()=>b)); + expect(calls.map(c=>c.auth)).toEqual(['Bearer key-a','Bearer key-b']); + // A's allowance needs A's web sign-in, which Kimi no longer holds + calls.length=0; + const u=await p.auth.usage(async()=>a); + expect(u.signIn).toBe('kept'); + expect(u.error).toContain('切换到它'); + expect(calls).toHaveLength(0); + // A's key gone from Kimi's store (agent-gw refused it): A can't be served + k.signIn('user-b',[{userId:'user-b',apiKey:'key-b'}]); + await expect(chat(await p.auth.loader(async()=>a))).rejects.toMatchObject({signIn:'expired',code:'kimi_work_account_not_here'}); + expect(calls).toHaveLength(0); + } finally {k.done();} +}); + +test('an away account\'s key the gateway refuses says to switch to it in Kimi',async()=>{ + const k=kimiHome(); + try { + k.signIn('user-b',[{userId:'user-b',apiKey:'key-b'},{userId:'user-a',apiKey:'key-a'}]); + const p=I.createPlugin({readSession:k.read,fetchImpl:async()=>new Response('{}',{status:401})}); + const uidA=I.readKeys(path.join(k.daimon,'kimi-code-key.json')); + const a=Object.keys(uidA).find(u=>uidA[u]==='key-a'); + const auth={type:'oauth',source:'kimi-work-desktop',uid:a}; + let err; + try {await chat(await p.auth.loader(async()=>auth));} catch(e) {err=e;} + expect(err?.code).toBe('kimi_work_account_not_here'); + expect(err?.message).toContain('失效'); + } finally {k.done();} +}); + +test('the key store is read as Kimi reads it',()=>{ + const k=kimiHome(); + try { + const f=path.join(k.daimon,'kimi-code-key.json'); + for(const body of ['not json','{}',JSON.stringify({v:1,keys:[{userId:'u',apiKey:'k'}]}),JSON.stringify({v:2,keys:{}})]) { + fs.writeFileSync(f,body); + expect(Object.keys(I.readKeys(f))).toHaveLength(0); + } + fs.writeFileSync(f,JSON.stringify({v:2,keys:[{userId:'u',apiKey:'first'},{userId:'u',apiKey:'second'},{userId:'',apiKey:'x'},{userId:'w'},null]})); + expect(Object.values(I.readKeys(f))).toEqual(['first']); + expect(Object.keys(I.readKeys(path.join(k.daimon,'none.json')))).toHaveLength(0); + } finally {k.done();} +}); diff --git a/packages/kimi-work/tests/desktop-path.test.mjs b/packages/kimi-work/tests/desktop-path.test.mjs index 4deff07..2243a67 100644 --- a/packages/kimi-work/tests/desktop-path.test.mjs +++ b/packages/kimi-work/tests/desktop-path.test.mjs @@ -64,7 +64,8 @@ test('a failed sign-in says which file it looked for, and a failed Work check is const missing=I.createPlugin({readSession:()=>I.readDesktop('/nowhere/kimi-desktop/daimon-share/daimon/config.json')}); const a=await (await missing.auth.methods[0].authorize()).callback(); expect(a.type).toBe('failed'); - expect(a.error).toContain('/nowhere/kimi-desktop/daimon-share/daimon/config.json'); + // the share folder itself is gone, so it is the folder that is named (#444) + expect(a.error).toContain('/nowhere/kimi-desktop/daimon-share'); const session={uid:'u',workToken:'synthetic-work-token',webToken:'w'}; const down=I.createPlugin({readSession:()=>session,fetchImpl:async()=>{throw Object.assign(TypeError('fetch failed'),{cause:{code:'ECONNRESET'}});}}); const b=await (await down.auth.methods[0].authorize()).callback();