larkmate 0.1.31 → 0.1.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/INSTALL.md CHANGED
@@ -28,6 +28,8 @@ larkmate --help
28
28
 
29
29
  ### 2. 配置登录态
30
30
 
31
+ 支持 Unix 文件权限的系统可以运行 `larkmate login-qr`,用飞书扫描命令返回的二维码并在手机上确认。Agent 可直接读取二维码与登录状态,按 Skill 的登录恢复说明完成操作。
32
+
31
33
  macOS Chrome 用户可以运行 `larkmate login`,在打开的飞书页面完成登录,CLI 会验证并导入当前浏览器配置的登录态。已有账号信息无法确认时,按命令提示核对账号;具体步骤见 Skill 的登录恢复说明。
32
34
 
33
35
  其他环境可按下面的方式手动配置:
package/README.md CHANGED
@@ -38,6 +38,7 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
38
38
  已勾选表示已实现,未勾选表示暂不支持;具体使用仍受当前用户权限限制。
39
39
 
40
40
  - 登录
41
+ - [x] 直接生成飞书扫码登录二维码,输出 Agent 可读取的登录状态
41
42
  - [x] 通过飞书网页登录并导入个人登录态(macOS Chrome)
42
43
  - [x] 按需刷新会话及尝试从已登录的浏览器恢复
43
44
  - 会话
package/bin/larkmate.js CHANGED
@@ -26,6 +26,8 @@ import { startApiService } from '../src/api-service.js';
26
26
  import { refreshCredentials, refreshWithRecovery } from '../src/auth.js';
27
27
  import { browserLogin, FEISHU_LOGIN_URL } from '../src/browser-login.js';
28
28
  import { setTimeout as delay } from 'node:timers/promises';
29
+ import { createInterface } from 'node:readline';
30
+ import { qrLogin } from '../src/qr-login.js';
29
31
 
30
32
  const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
31
33
  const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
@@ -186,6 +188,17 @@ program.command('login').description('Open Feishu login in macOS Chrome and impo
186
188
  .action(async o=>{requireDirectAuth();if(program.opts().credentialsFile)throw new FeishuError('UNSUPPORTED_MODE','Browser login updates the default credentials file only.');
187
189
  process.stderr.write(`Sign in to Feishu in Chrome: ${FEISHU_LOGIN_URL}\n`);
188
190
  output(await browserLogin({credentialsFile:serviceAccountFile(),profile:o.profile,expectedUserId:o.expectUserId,timeoutSeconds:Number(o.timeout),openBrowser:o.open}));});
191
+ program.command('login-qr').description('Create a QR login and emit newline-delimited status events.')
192
+ .option('--output <path>', 'save the QR PNG to a new file; default is a private temporary file')
193
+ .option('--expect-user-id <id>', 'expected numeric user ID')
194
+ .option('--timeout <seconds>', 'login deadline, 10 to 900 seconds', '180')
195
+ .action(async o=>{requireDirectAuth();const controller=new AbortController(),stop=()=>controller.abort();process.once('SIGINT',stop);process.once('SIGTERM',stop);
196
+ const emit=event=>process.stdout.write(`${JSON.stringify({ok:true,...event})}\n`);
197
+ const confirmAccount=(user,signal)=>new Promise(resolve=>{const input=createInterface({input:process.stdin,crlfDelay:Infinity});let done=false;
198
+ const finish=value=>{if(done)return;done=true;signal.removeEventListener('abort',aborted);input.close();resolve(value)};
199
+ const aborted=()=>finish(false);signal.addEventListener('abort',aborted,{once:true});input.once('close',()=>finish(false));input.once('line',line=>{try{const data=JSON.parse(line);finish(line.length<=4096&&data?.confirmUserId===user.id)}catch{finish(false)}});if(signal.aborted)finish(false)});
200
+ try{await qrLogin({credentialsFile:serviceAccountFile(),outputPath:o.output,expectedUserId:o.expectUserId,timeoutSeconds:Number(o.timeout),signal:controller.signal,emit,confirmAccount});}
201
+ finally{process.off('SIGINT',stop);process.off('SIGTERM',stop)}});
189
202
  program.command('auth-refresh').description('Refresh cookies returned by Feishu for the current account.')
190
203
  .action(async()=>{requireDirectAuth();output(await refreshCredentials(serviceAccountFile()));});
191
204
  program.command('auth-keepalive').description('Periodically refresh the current session until interrupted.')
@@ -28,7 +28,7 @@
28
28
 
29
29
  未使用系统用户委托或受限代理时,LarkMate 默认从 `~/.larkmate/credentials.json` 读取 Cookie,也支持 `LARKMATE_HOME`、`LARKMATE_COOKIE` 和 `--credentials-file`。先保留并检查已有登录态,可用 `larkmate status` 验证;不要读取或打印 Cookie 的值到对话、日志或命令参数中。
30
30
 
31
- 如果没有可用登录态,在直连模式下读取已安装 Skill 的 `references/auth.md`;macOS Chrome 可使用 `larkmate login` 打开飞书网页登录并在用户登录后导入凭据。其他环境可引导用户按 [快速安装](https://github.com/NWYLZW/larkmate/blob/main/INSTALL.md) 在本机安全配置。不要要求用户把 Cookie、密码或验证码发到对话中。不能自动完成登录时,如实说明,不声称已经登录。
31
+ 如果没有可用登录态,在直连模式下读取已安装 Skill 的 `references/auth.md`;优先使用 `larkmate login-qr` 展示二维码并等待用户扫码和登录结果。macOS Chrome 也可使用 `larkmate login` 打开飞书网页登录。其他情况可引导用户按 [快速安装](https://github.com/NWYLZW/larkmate/blob/main/INSTALL.md) 在本机安全配置。不要要求用户把 Cookie、密码或验证码发到对话中。不能自动完成登录时,如实说明,不声称已经登录。
32
32
 
33
33
  安装后按需读取已安装 Skill 的 `SKILL.md` 和相关参考文件,依照用户的具体要求使用 CLI。当前能力包括会话与消息、会话管理和标签、群组管理、录制妙记及文字记录;以实际 CLI 帮助和 Skill 说明为准。发送消息、文件、权限申请及其他写操作应有用户指示;对于结果不确定的写入,先核查状态,避免重复提交。
34
34
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "larkmate",
3
- "version": "0.1.31",
3
+ "version": "0.1.32",
4
4
  "description": "A small, user-identity Feishu CLI with a modular gateway client",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -35,6 +35,7 @@
35
35
  "dependencies": {
36
36
  "commander": "^13.1.0",
37
37
  "protobufjs": "^8.6.0",
38
+ "qrcode": "^1.5.4",
38
39
  "re2js": "^2.10.0",
39
40
  "rrule": "^2.8.1"
40
41
  }
@@ -2,6 +2,10 @@
2
2
 
3
3
  先运行 `larkmate status`。受限代理和系统用户委托应先检查各自的授权,不读取浏览器 Cookie、不切换账号,也不把 `POLICY_DENIED` 当成登录过期。仅在当前用户的直连模式下,根据用户的登录或修复请求处理凭据;`authenticate` 返回 401 或 `AUTH_FAILED` 时可尝试恢复。单个资源无权限、网络故障或写入结果不确定不等同于登录过期。
4
4
 
5
+ 用户要求扫码登录时,优先运行 `larkmate login-qr`,让进程保持运行并读取逐行 JSON 事件:`qr` 事件的 `path` 是本机 PNG 文件,用图片方式展示给用户;提示用户通过飞书扫一扫并在手机上确认。接着等待 `waiting`、`scanned`、`ready` 等事件,直到进程结束;不要在收到 `qr` 时就当作已登录。默认二维码保存在私有临时目录,进程结束后删除;`--output <新文件>` 可另存 PNG。登录会话及 Cookie 不会出现在事件中,不要转发或输出其内容。
6
+
7
+ 若出现 `account_confirmation_required`,根据用户要求和上下文核对事件中的账号;确有必要时询问用户。确认后向进程标准输入发送一行 `{"confirmUserId":"事件中的用户ID"}`,不匹配或取消时停止。旧账号已知时可在开始前传入 `--expect-user-id`;如果飞书要求选择账号或其他验证,说明情况并使用官方网页登录。`login-qr` 需要 Unix 文件权限,受限代理和系统用户委托不可用。
8
+
5
9
  在 macOS Chrome 上,优先运行 `larkmate login`;命令会打开飞书网页登录页面,用户按页面提示打开或扫码登录后,CLI 验证账号并导入凭据。指定浏览器配置用 `--profile 'Profile 2'`;只输出链接、不打开浏览器用 `--no-open`。旧凭据已过期且无法确认原账号时,先核对命令返回的浏览器账号,再用 `--expect-user-id <用户ID>` 重试。已保存的账号 ID 与浏览器账号不一致时,命令拒绝覆盖。该流程需要当前 Chrome 配置可用及 Node.js 的 `node:sqlite` 支持。
6
10
 
7
11
  在支持 Unix 文件权限的系统上,`larkmate auth-refresh` 验证当前账号并保存服务端返回的更新 Cookie;`larkmate auth-keepalive` 可按需启动定时刷新,默认 30 分钟,用 Ctrl+C 停止。添加 `--recover-from-chrome` 时,认证过期会尝试从同一账号已登录的 macOS Chrome 恢复;浏览器也已退出或账号不匹配时仍需处理登录。它们不能保证登录永久有效;飞书或企业要求重新登录、账号失效或权限不足时应停止并重新处理,不尝试绕过。定时刷新不会自动启动或注册后台服务。
@@ -0,0 +1,98 @@
1
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { lstat, mkdir, mkdtemp, open, readFile, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import QRCode from 'qrcode';
8
+ import { Gateway } from './gateway.js';
9
+ import { FeishuError } from './errors.js';
10
+
11
+ const ORIGIN='https://accounts.feishu.cn', REDIRECT='https://www.feishu.cn/messenger/';
12
+ const fail=(code,message)=>{throw new FeishuError(code,message)};
13
+ const digest=value=>createHash('sha256').update(value).digest('hex');
14
+ const isId=id=>typeof id==='string'&&/^[1-9]\d{0,18}$/.test(id);
15
+
16
+ // A QR login has its own in-memory jar and flow key; no user-supplied network targets are accepted.
17
+ export class QrSession {
18
+ constructor({fetchImpl=fetch,timeoutMs=30000}={}){this.fetchImpl=fetchImpl;this.timeoutMs=timeoutMs;this.cookies=new Map();this.flowKey='';}
19
+ cookieHeader(host) {
20
+ return [...this.cookies.values()].filter(c=>c.hostOnly?c.domain===host:host===c.domain||host.endsWith(`.${c.domain}`)).map(c=>`${c.name}=${c.value}`).join('; ');
21
+ }
22
+ absorb(headers,host='accounts.feishu.cn') {
23
+ for(const line of headers?.getSetCookie?.()||[]){const [pair,...attributes]=line.split(';');const i=pair.indexOf('=');if(i<=0)continue;
24
+ const name=pair.slice(0,i).trim(),value=pair.slice(i+1),domainAttr=attributes.map(x=>x.trim()).find(x=>/^domain=/i.test(x));
25
+ const domain=domainAttr?domainAttr.slice(7).replace(/^\./,'').toLowerCase():host;
26
+ if(!/^[!#$%&'*+.^_`|~\w-]+$/.test(name)||/[\r\n;]/.test(value)||!(host===domain||host.endsWith(`.${domain}`))||!['feishu.cn','accounts.feishu.cn'].includes(domain))continue;
27
+ const key=`${domain}\0${name}`;if(attributes.some(x=>/^\s*max-age=0\s*$/i.test(x)))this.cookies.delete(key);else this.cookies.set(key,{name,value,domain,hostOnly:!domainAttr});
28
+ }
29
+ }
30
+ async request(path,data,{signal}={}) {
31
+ if(!['/accounts/csrf','/accounts/qrlogin/init','/accounts/qrlogin/polling','/accounts/app'].includes(path))fail('INVALID_ARGUMENT','Unsupported login operation.');
32
+ const headers={'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',accept:'application/json, text/plain, */*',origin:ORIGIN,referer:`${ORIGIN}/accounts/page/login`,'content-type':'application/json','x-app-id':'1','x-terminal-type':'2','x-api-version':'1.0.31','x-device-info':'platform=websdk','x-request-id':randomUUID()};
33
+ const cookie=this.cookieHeader('accounts.feishu.cn');if(cookie)headers.cookie=cookie;
34
+ const csrf=[...this.cookies.values()].find(x=>x.name==='swp_csrf_token');if(csrf)headers['x-csrf-token']=csrf.value;if(this.flowKey)headers['x-flow-key']=this.flowKey;
35
+ const requestController=new AbortController(),cancel=()=>requestController.abort(),timer=setTimeout(cancel,this.timeoutMs);
36
+ if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true});
37
+ let response;try{response=await this.fetchImpl(ORIGIN+path,{method:'POST',headers,body:JSON.stringify(data),redirect:'manual',signal:requestController.signal});}catch(e){if(signal?.aborted)fail('LOGIN_CANCELLED','Login was cancelled.');fail('LOGIN_REQUEST_FAILED','Could not contact Feishu login.');}finally{clearTimeout(timer);signal?.removeEventListener('abort',cancel)}
38
+ this.absorb(response.headers);this.flowKey=response.headers.get('x-flow-key')||this.flowKey;
39
+ if(!response.ok)throw new FeishuError('LOGIN_REQUEST_FAILED','Feishu login rejected the request.',{httpStatus:response.status});
40
+ let body;try{body=await response.json()}catch{fail('LOGIN_INVALID_RESPONSE','Feishu returned an invalid login response.')}
41
+ if(body?.code!==0||(body.data!=null&&typeof body.data!=='object'))fail('LOGIN_REJECTED','Feishu could not complete the login request.');
42
+ return body.data||{};
43
+ }
44
+ async start(signal){await this.request('/accounts/csrf',{}, {signal});const data=await this.request('/accounts/qrlogin/init',{redirect_uri:REDIRECT},{signal});
45
+ if(data.next_step!=='qr_login_polling'||typeof data.step_info?.token!=='string'||!/^[-\w]{8,200}$/.test(data.step_info.token)||!this.flowKey)fail('LOGIN_INVALID_RESPONSE','Feishu did not return a usable QR login.');
46
+ return JSON.stringify({qrlogin:{token:data.step_info.token}});
47
+ }
48
+ async poll(signal){return this.request('/accounts/qrlogin/polling',{}, {signal})}
49
+ async enter(info,signal){return this.request('/accounts/app',{user_id:info?.user_id,flow_type:info?.flow_type},{signal})}
50
+ }
51
+
52
+ async function readCredentials(path) {
53
+ let file;try{file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);const st=await file.stat();
54
+ if(!st.isFile()||typeof process.getuid!=='function'||st.uid!==process.getuid()||(st.mode&0o077)||st.size>1048576)throw Error();
55
+ const text=await file.readFile('utf8'),data=JSON.parse(text);if(!data||typeof data!=='object'||Array.isArray(data))throw Error();return {exists:true,text,data};
56
+ }catch(e){if(e.code==='ENOENT')return {exists:false,text:null,data:{}};fail('CREDENTIALS_UNAVAILABLE','Cannot safely read the existing credentials file.');}finally{await file?.close()}
57
+ }
58
+ async function saveCredentials(path,snapshot,cookie,user) {
59
+ const directory=dirname(path);await mkdir(directory,{recursive:true,mode:0o700});const st=await lstat(directory);
60
+ if(!st.isDirectory()||st.isSymbolicLink()||st.uid!==process.getuid()||(st.mode&0o077))fail('CREDENTIALS_UNAVAILABLE','The credentials directory must be private and owner-controlled.');
61
+ const current=await readCredentials(path);if(current.exists!==snapshot.exists||(current.exists&&digest(current.text)!==digest(snapshot.text)))fail('CREDENTIALS_CHANGED','Credentials changed during login; no update was made.');
62
+ const temporary=`${path}.${randomBytes(12).toString('hex')}.tmp`;
63
+ try{await writeFile(temporary,JSON.stringify({...snapshot.data,cookie,accountId:user.id})+'\n',{flag:'wx',mode:0o600});await rename(temporary,path)}finally{await rm(temporary,{force:true})}
64
+ }
65
+ export async function qrLogin({credentialsFile,outputPath,expectedUserId,timeoutSeconds=180,signal,emit=()=>{},confirmAccount,session=new QrSession(),gatewayFactory=cookie=>new Gateway({cookie})}={}) {
66
+ if(typeof process.getuid!=='function')fail('UNSUPPORTED_PLATFORM','QR login currently requires Unix file permissions.');
67
+ if(!credentialsFile||typeof credentialsFile!=='string')fail('INVALID_ARGUMENT','A credentials file is required.');
68
+ if(expectedUserId&&!isId(expectedUserId))fail('INVALID_ARGUMENT','Invalid expected user ID.');
69
+ if(!Number.isInteger(timeoutSeconds)||timeoutSeconds<10||timeoutSeconds>900)fail('INVALID_ARGUMENT','Timeout must be between 10 and 900 seconds.');
70
+ const snapshot=await readCredentials(credentialsFile);let prior=isId(snapshot.data.accountId)?snapshot.data.accountId:null;
71
+ if(!prior&&snapshot.exists&&typeof snapshot.data.cookie==='string')try{prior=(await gatewayFactory(snapshot.data.cookie).authenticate()).id}catch{}
72
+ if(prior&&expectedUserId&&prior!==expectedUserId)fail('ACCOUNT_MISMATCH','The expected account differs from the existing account.');
73
+ const target=expectedUserId||prior;let tempDir,qrPath;
74
+ const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),timeoutSeconds*1000),cancel=()=>controller.abort();
75
+ if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true});const combined=controller.signal;
76
+ try {
77
+ const text=await session.start(combined), image=await QRCode.toBuffer(text,{type:'png',errorCorrectionLevel:'Q',width:400,margin:4});
78
+ if(outputPath)qrPath=resolve(outputPath);else{tempDir=await mkdtemp(join(tmpdir(),'larkmate-login-qr-'));qrPath=join(tempDir,'qr.png');}
79
+ try{await writeFile(qrPath,image,{flag:'wx',mode:0o600})}catch{fail('QR_WRITE_FAILED','Cannot create the QR image; choose a new writable path.')}
80
+ emit({event:'qr',path:qrPath,mime:'image/png',timeoutSeconds});let last;
81
+ while(!combined.aborted){let result;
82
+ try{result=await session.poll(combined)}catch(error){if(combined.aborted)break;if(error.code==='LOGIN_REQUEST_FAILED'&&(!error.details?.httpStatus||error.details.httpStatus===504)){try{await delay(1000,undefined,{signal:combined})}catch{break}continue}throw error}
83
+ if(result.next_step==='qr_login_polling'){
84
+ const status=result.step_info?.status;if(status===1||status===2){if(status!==last)emit({event:status===1?'waiting':'scanned'});last=status;try{await delay(500,undefined,{signal:combined})}catch{break}continue}
85
+ if(status===3)fail('LOGIN_CANCELLED','The scan was cancelled.');if(status===5)fail('QR_EXPIRED','The QR code expired; start a new login.');fail('LOGIN_REJECTED','Feishu could not complete QR login.');
86
+ }
87
+ if(result.next_step==='login_app')result=await session.enter(result.step_info,combined);
88
+ if(result.next_step!=='enter_app')throw new FeishuError('ADDITIONAL_LOGIN_STEP','Feishu requires another login step; use the official browser login.',{step:result.next_step||'unknown'});
89
+ const cookie=session.cookieHeader('internal-api-lark-api.feishu.cn');if(!cookie)fail('LOGIN_UNCONFIRMED','Feishu did not return a usable user session.');
90
+ const gateway=gatewayFactory(cookie);const user=await gateway.authenticate();if(!isId(user?.id))fail('LOGIN_UNCONFIRMED','The scanned account could not be verified.');
91
+ if(target&&target!==user.id)fail('ACCOUNT_MISMATCH','The scanned account differs from the expected account.');
92
+ if(snapshot.exists&&!target){emit({event:'account_confirmation_required',user:{id:user.id,name:user.name||null}});if(!confirmAccount||!await confirmAccount(user,combined))fail('ACCOUNT_CONFIRMATION_REQUIRED','The scanned account was not confirmed; no credentials were changed.');}
93
+ await saveCredentials(credentialsFile,snapshot,[...gateway.jar].map(([k,v])=>`${k}=${v}`).join('; '),user);
94
+ emit({event:'ready',user:{id:user.id,name:user.name||null}});return {status:'ready',user:{id:user.id,name:user.name||null}};
95
+ }
96
+ if(signal?.aborted)fail('LOGIN_CANCELLED','Login was cancelled.');fail('LOGIN_TIMEOUT','Login was not completed before the timeout.');
97
+ } finally {clearTimeout(timer);signal?.removeEventListener('abort',cancel);if(tempDir)await rm(tempDir,{recursive:true,force:true})}
98
+ }