larkmate 0.1.30 → 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,12 @@ larkmate --help
28
28
 
29
29
  ### 2. 配置登录态
30
30
 
31
+ 支持 Unix 文件权限的系统可以运行 `larkmate login-qr`,用飞书扫描命令返回的二维码并在手机上确认。Agent 可直接读取二维码与登录状态,按 Skill 的登录恢复说明完成操作。
32
+
33
+ macOS Chrome 用户可以运行 `larkmate login`,在打开的飞书页面完成登录,CLI 会验证并导入当前浏览器配置的登录态。已有账号信息无法确认时,按命令提示核对账号;具体步骤见 Skill 的登录恢复说明。
34
+
35
+ 其他环境可按下面的方式手动配置:
36
+
31
37
  登录飞书网页版后,在浏览器开发者工具中查找当前登录会话的飞书网页请求,并复制完整的 `Cookie` 请求头。Cookie 可以代表你的账号操作,请仅在本机保存,不要发给其他人、粘贴到聊天或写进终端命令。
32
38
 
33
39
  ```sh
@@ -51,7 +57,7 @@ larkmate status
51
57
 
52
58
  如果已有可用的凭据文件,直接执行 `larkmate status`,不必覆盖它。Cookie 失效时更新文件后重试。也可以通过 `LARKMATE_HOME` 选择配置目录、`LARKMATE_COOKIE` 提供 Cookie,或使用全局选项 `--credentials-file` 指定同格式文件;读取优先级依次为:指定文件、环境变量、配置目录。
53
59
 
54
- macOS Chrome 已登录飞书时,也可以让安装了 LarkMate Skill 的 AI 按 Skill 的登录恢复说明验证账户并更新本机凭据。
60
+ 登录后可按需运行 `larkmate auth-refresh` 更新当前会话,或运行 `larkmate auth-keepalive --recover-from-chrome` 定时刷新并在认证过期时尝试从已登录的 Chrome 恢复。飞书仍可能要求重新登录;定时刷新不会自动在后台启动。
55
61
 
56
62
  ### 3. 安装 Agent Skill
57
63
 
package/README.md CHANGED
@@ -37,6 +37,10 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
37
37
 
38
38
  已勾选表示已实现,未勾选表示暂不支持;具体使用仍受当前用户权限限制。
39
39
 
40
+ - 登录
41
+ - [x] 直接生成飞书扫码登录二维码,输出 Agent 可读取的登录状态
42
+ - [x] 通过飞书网页登录并导入个人登录态(macOS Chrome)
43
+ - [x] 按需刷新会话及尝试从已登录的浏览器恢复
40
44
  - 会话
41
45
  - [x] 搜索用户、机器人和群聊
42
46
  - [x] 查询收件箱、已完成和收纳中的会话(分页)
package/bin/larkmate.js CHANGED
@@ -23,6 +23,11 @@ import { createRuleOutput, loadListenRules, startListenService } from '../src/li
23
23
  import { createNameResolver } from '../src/listen-names.js';
24
24
  import { createApiKey } from '../src/access-policy.js';
25
25
  import { startApiService } from '../src/api-service.js';
26
+ import { refreshCredentials, refreshWithRecovery } from '../src/auth.js';
27
+ import { browserLogin, FEISHU_LOGIN_URL } from '../src/browser-login.js';
28
+ import { setTimeout as delay } from 'node:timers/promises';
29
+ import { createInterface } from 'node:readline';
30
+ import { qrLogin } from '../src/qr-login.js';
26
31
 
27
32
  const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
28
33
  const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
@@ -172,6 +177,39 @@ program.command('broker-info').description('Show the permissions assigned to thi
172
177
  program.command('status').description('Check the current user login.')
173
178
  .action(async () => output(await (await client()).status()));
174
179
 
180
+ function requireDirectAuth() {
181
+ if(configuredBroker()||configuredBrokerToken()||configuredDelegate()||process.env.LARKMATE_COOKIE)throw new FeishuError('UNSUPPORTED_MODE','Login maintenance requires direct mode and a protected credentials file.');
182
+ }
183
+ program.command('login').description('Open Feishu login in macOS Chrome and import the verified browser session.')
184
+ .option('--profile <name>', 'Chrome profile, Default or Profile N', 'Default')
185
+ .option('--expect-user-id <id>', 'expected numeric user ID for an existing account')
186
+ .option('--timeout <seconds>', 'wait for login, 5 to 900 seconds', '180')
187
+ .option('--no-open', 'print the login link without opening Chrome')
188
+ .action(async o=>{requireDirectAuth();if(program.opts().credentialsFile)throw new FeishuError('UNSUPPORTED_MODE','Browser login updates the default credentials file only.');
189
+ process.stderr.write(`Sign in to Feishu in Chrome: ${FEISHU_LOGIN_URL}\n`);
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)}});
202
+ program.command('auth-refresh').description('Refresh cookies returned by Feishu for the current account.')
203
+ .action(async()=>{requireDirectAuth();output(await refreshCredentials(serviceAccountFile()));});
204
+ program.command('auth-keepalive').description('Periodically refresh the current session until interrupted.')
205
+ .option('--interval <seconds>', 'refresh interval in seconds, at least 300', '1800')
206
+ .option('--recover-from-chrome', 'on expired login, reuse a verified macOS Chrome session')
207
+ .option('--profile <name>', 'Chrome profile for recovery', 'Default')
208
+ .action(async o=>{requireDirectAuth();const interval=Number(o.interval);if(!Number.isSafeInteger(interval)||interval<300||interval>86400)throw new FeishuError('INVALID_ARGUMENT','Interval must be 300 to 86400 seconds.');
209
+ if(o.recoverFromChrome&&program.opts().credentialsFile)throw new FeishuError('UNSUPPORTED_MODE','Chrome recovery updates the default credentials file only.');
210
+ const controller=new AbortController(),stop=()=>controller.abort();process.once('SIGINT',stop);process.once('SIGTERM',stop);
211
+ try{while(!controller.signal.aborted){output(await refreshWithRecovery(serviceAccountFile(),{recover:!!o.recoverFromChrome,profile:o.profile}));try{await delay(interval*1000,undefined,{signal:controller.signal})}catch(error){if(error.name!=='AbortError')throw error}}}finally{process.off('SIGINT',stop);process.off('SIGTERM',stop)}});
212
+
175
213
  program.command('search').description('Search users, bots and groups.')
176
214
  .requiredOption('--query <text>', 'search text')
177
215
  .action(async options => output(await (await client()).search(options.query)));
@@ -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 已登录飞书时,可按其中的脚本验证账号并恢复本机凭据。其他环境可引导用户按 [快速安装](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.30",
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,7 +2,15 @@
2
2
 
3
3
  先运行 `larkmate status`。受限代理和系统用户委托应先检查各自的授权,不读取浏览器 Cookie、不切换账号,也不把 `POLICY_DENIED` 当成登录过期。仅在当前用户的直连模式下,根据用户的登录或修复请求处理凭据;`authenticate` 返回 401 或 `AUTH_FAILED` 时可尝试恢复。单个资源无权限、网络故障或写入结果不确定不等同于登录过期。
4
4
 
5
- macOS 上,如果用户已在 Chrome 登录飞书,可以使用本 Skill 的 `scripts/chrome-login-macos.mjs`。它只读取所选 Chrome 配置中飞书域名的 Cookie,通过系统钥匙串解密,在私有临时目录使用 `larkmate status` 验证,并只输出账户 ID 和名称。脚本需要 `node:sqlite` 支持;旧版 Node、其他浏览器或其他系统可按安装文档手动配置。
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
+
9
+ 在 macOS Chrome 上,优先运行 `larkmate login`;命令会打开飞书网页登录页面,用户按页面提示打开或扫码登录后,CLI 验证账号并导入凭据。指定浏览器配置用 `--profile 'Profile 2'`;只输出链接、不打开浏览器用 `--no-open`。旧凭据已过期且无法确认原账号时,先核对命令返回的浏览器账号,再用 `--expect-user-id <用户ID>` 重试。已保存的账号 ID 与浏览器账号不一致时,命令拒绝覆盖。该流程需要当前 Chrome 配置可用及 Node.js 的 `node:sqlite` 支持。
10
+
11
+ 在支持 Unix 文件权限的系统上,`larkmate auth-refresh` 验证当前账号并保存服务端返回的更新 Cookie;`larkmate auth-keepalive` 可按需启动定时刷新,默认 30 分钟,用 Ctrl+C 停止。添加 `--recover-from-chrome` 时,认证过期会尝试从同一账号已登录的 macOS Chrome 恢复;浏览器也已退出或账号不匹配时仍需处理登录。它们不能保证登录永久有效;飞书或企业要求重新登录、账号失效或权限不足时应停止并重新处理,不尝试绕过。定时刷新不会自动启动或注册后台服务。
12
+
13
+ 需要单独检查 Chrome 登录态时,可以使用本 Skill 的 `scripts/chrome-login-macos.mjs`。它只读取所选 Chrome 配置中飞书域名的 Cookie,通过系统钥匙串解密,在私有临时目录使用 `larkmate status` 验证,并只输出账户 ID 和名称。旧版 Node、其他浏览器或其他系统可按安装文档手动配置。
6
14
 
7
15
  1. 执行 `node <本 Skill 目录>/scripts/chrome-login-macos.mjs` 验证 Chrome 默认配置。其他 Chrome 配置可加 `--profile 'Profile 2'`,仅检查用户选定的配置。
8
16
  2. 对照用户指定的账号或已有上下文确认返回的账户;无法确定时先向用户确认。验证通过且账号匹配后,执行 `node <本 Skill 目录>/scripts/chrome-login-macos.mjs --apply --expect-user-id <返回的用户ID>`;使用其他配置时同样传入 `--profile`。脚本会再次验证账号,再原子更新当前用户的 LarkMate 凭据文件。
@@ -73,7 +73,7 @@ async function main() {
73
73
  try{const st=await lstat(path);if(!st.isFile()||st.isSymbolicLink()||st.uid!==process.getuid()||(st.mode&0o077))throw Error('unsafe');original=JSON.parse(await readFile(path,'utf8'));if(!original||typeof original!=='object'||Array.isArray(original))throw Error('unsafe')}
74
74
  catch(e){if(e.code!=='ENOENT')throw Error('Existing credentials are not a private, owned JSON file; no changes were made.');}
75
75
  const next=join(base,`.credentials-${randomBytes(12).toString('hex')}`);
76
- try{await writeFile(next,JSON.stringify({...original,cookie})+'\n',{mode:0o600,flag:'wx'});await chmod(next,0o600);await rename(next,path)}finally{await rm(next,{force:true})}
76
+ try{await writeFile(next,JSON.stringify({...original,cookie,accountId:user.id})+'\n',{mode:0o600,flag:'wx'});await chmod(next,0o600);await rename(next,path)}finally{await rm(next,{force:true})}
77
77
  }
78
78
  console.log(JSON.stringify({ok:true,status:options.apply?'updated':'verified',user:{id:user.id,name:user.name||null}}));
79
79
  } finally {await rm(dir,{recursive:true,force:true})}
package/src/auth.js ADDED
@@ -0,0 +1,38 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { lstat, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+ import { Gateway } from './gateway.js';
5
+ import { FeishuError } from './errors.js';
6
+ import { browserLogin } from './browser-login.js';
7
+
8
+ const fail=(code,message)=>{throw new FeishuError(code,message)};
9
+ const hash=value=>createHash('sha256').update(value).digest('hex');
10
+ async function privateFile(path) {
11
+ if(typeof process.getuid!=='function')fail('UNSUPPORTED_PLATFORM','Session refresh requires Unix owner and file permissions.');
12
+ const directory=await lstat(dirname(path));
13
+ if(!directory.isDirectory()||directory.isSymbolicLink()||directory.uid!==process.getuid()||(directory.mode&0o022))fail('CREDENTIALS_UNAVAILABLE','The credentials directory must be owner-controlled.');
14
+ const st=await lstat(path);
15
+ if(!st.isFile()||st.isSymbolicLink()||st.uid!==process.getuid()||(st.mode&0o077)||st.size>1048576)fail('CREDENTIALS_UNAVAILABLE','Credentials must be an owner-only regular file.');
16
+ return readFile(path,'utf8');
17
+ }
18
+ export async function refreshCredentials(path,{gatewayFactory=cookie=>new Gateway({cookie})}={}) {
19
+ let text,data;try{text=await privateFile(path);data=JSON.parse(text)}catch(e){if(e instanceof FeishuError)throw e;fail('CREDENTIALS_UNAVAILABLE','Cannot read a private credentials file.');}
20
+ if(!data||typeof data!=='object'||Array.isArray(data)||typeof data.cookie!=='string'||!data.cookie||/[\r\n]/.test(data.cookie))fail('CREDENTIALS_INVALID','The credentials file is invalid.');
21
+ const gateway=gatewayFactory(data.cookie), user=await gateway.authenticate();
22
+ if(data.accountId&&data.accountId!==user.id)fail('ACCOUNT_MISMATCH','The current login does not match the saved account.');
23
+ const cookie=[...gateway.jar].map(([key,value])=>`${key}=${value}`).join('; ');
24
+ const confirm=gatewayFactory(cookie), verified=await confirm.authenticate();
25
+ if(!verified.id||verified.id!==user.id)fail('ACCOUNT_MISMATCH','The refreshed session did not match the original account.');
26
+ const refreshed=[...confirm.jar].map(([key,value])=>`${key}=${value}`).join('; ');
27
+ if(hash(await privateFile(path))!==hash(text))fail('CREDENTIALS_CHANGED','Credentials changed during refresh; retry after inspecting the account.');
28
+ const temp=`${path}.${randomBytes(12).toString('hex')}.tmp`;
29
+ try{await writeFile(temp,JSON.stringify({...data,cookie:refreshed,accountId:user.id})+'\n',{flag:'wx',mode:0o600});await rename(temp,path)}finally{await rm(temp,{force:true})}
30
+ return {status:'refreshed',user:{id:user.id,name:user.name||null},note:'Some session cookies were refreshed; Feishu may still require login again.'};
31
+ }
32
+ export async function refreshWithRecovery(path,{recover=false,profile='Default',refresh=refreshCredentials,login=browserLogin}={}) {
33
+ try{return await refresh(path)}catch(error){
34
+ if(!recover||!(error.code==='AUTH_FAILED'||(error.code==='REQUEST_FAILED'&&error.details?.operation==='authenticate'&&error.details?.httpStatus===401)))throw error;
35
+ await login({credentialsFile:path,profile,timeoutSeconds:10,openBrowser:false});
36
+ return refresh(path);
37
+ }
38
+ }
@@ -0,0 +1,52 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { open } from 'node:fs/promises';
6
+ import { constants } from 'node:fs';
7
+ import { Gateway } from './gateway.js';
8
+ import { FeishuError } from './errors.js';
9
+
10
+ const exec=promisify(execFile);
11
+ const helper=fileURLToPath(new URL('../skills/larkmate/scripts/chrome-login-macos.mjs',import.meta.url));
12
+ export const FEISHU_LOGIN_URL='https://www.feishu.cn/messenger/';
13
+ const fail=(code,message)=>{throw new FeishuError(code,message)};
14
+ async function helperCall(args) {
15
+ try {const result=await exec(process.execPath,['--no-warnings',helper,...args],{timeout:45000,maxBuffer:16384});return JSON.parse(result.stdout)}
16
+ catch(error){let message='Chrome login could not be checked.';try{message=JSON.parse(error.stderr).error||message}catch{}throw new FeishuError('CHROME_LOGIN_UNAVAILABLE',message)}
17
+ }
18
+ export async function browserLogin({credentialsFile,profile='Default',expectedUserId,timeoutSeconds=180,openBrowser=true,inspect,apply,launch,wait=delay,now=Date.now}={}) {
19
+ if(!/^(Default|Profile [1-9][0-9]*)$/.test(profile))fail('INVALID_ARGUMENT','Use Default or a Chrome profile named Profile N.');
20
+ if(!Number.isInteger(timeoutSeconds)||timeoutSeconds<5||timeoutSeconds>900)fail('INVALID_ARGUMENT','Login timeout must be between 5 and 900 seconds.');
21
+ if(expectedUserId&&!/^[1-9][0-9]{0,18}$/.test(expectedUserId))fail('INVALID_ARGUMENT','Invalid expected user ID.');
22
+ if(!inspect&&process.platform!=='darwin')fail('UNSUPPORTED_PLATFORM','Automatic browser login currently supports macOS Chrome only.');
23
+ let existing=false, prior=null;
24
+ let handle;try{handle=await open(credentialsFile,constants.O_RDONLY|constants.O_NOFOLLOW);const st=await handle.stat();
25
+ if(!st.isFile()||st.uid!==process.getuid()||(st.mode&0o077)||st.size>1048576)throw Error('unsafe');
26
+ const data=JSON.parse(await handle.readFile('utf8'));existing=true;
27
+ if(typeof data.accountId==='string'&&/^\d+$/.test(data.accountId))prior=data.accountId;
28
+ else if(typeof data.cookie==='string')try{prior=(await new Gateway({cookie:data.cookie}).authenticate()).id}catch{}
29
+ }catch(error){if(error.code!=='ENOENT')fail('CREDENTIALS_UNAVAILABLE','Cannot inspect the existing credentials file.');}finally{await handle?.close()}
30
+ const expected=expectedUserId||prior;
31
+ if(prior&&expectedUserId&&prior!==expectedUserId)fail('ACCOUNT_MISMATCH','The expected user differs from the existing account.');
32
+ inspect ||= ()=>helperCall(['--profile',profile]);
33
+ apply ||= id=>helperCall(['--profile',profile,'--apply','--expect-user-id',id]);
34
+ launch ||= ()=>exec('open',['-a','Google Chrome','--args',`--profile-directory=${profile}`,FEISHU_LOGIN_URL],{timeout:10000});
35
+ if(openBrowser)try{await launch()}catch{fail('BROWSER_UNAVAILABLE','Cannot open Chrome; open the login URL manually or use --no-open.');}
36
+ const end=now()+timeoutSeconds*1000;
37
+ do {
38
+ try {
39
+ const result=await inspect(), user=result?.user;
40
+ if(result?.status==='verified'&&/^\d+$/.test(user?.id||'')){
41
+ if(expected&&expected!==user.id)fail('ACCOUNT_MISMATCH','The browser is signed in as a different account.');
42
+ if(existing&&!expected)throw new FeishuError('ACCOUNT_CONFIRMATION_REQUIRED','Existing account could not be verified; repeat with --expect-user-id after confirming the browser account.',{user});
43
+ const saved=await apply(user.id);if(saved?.status!=='updated'||saved?.user?.id!==user.id)fail('LOGIN_UNCONFIRMED','The browser login could not be confirmed.');
44
+ return {status:'ready',user:saved.user};
45
+ }
46
+ }catch(error){
47
+ if(error.code!=='CHROME_LOGIN_UNAVAILABLE'||!/No usable Feishu cookies|could not be validated/.test(error.message))throw error;
48
+ }
49
+ if(now()>=end)break;await wait(Math.min(3000,Math.max(1,end-now())));
50
+ } while(now()<end);
51
+ fail('LOGIN_TIMEOUT','Sign-in was not detected before the timeout; retry after signing in.');
52
+ }
package/src/gateway.js CHANGED
@@ -62,7 +62,7 @@ export class Gateway {
62
62
  }
63
63
 
64
64
  absorbCookies(headers) {
65
- for (const row of headers.getSetCookie?.() || []) {
65
+ for (const row of headers?.getSetCookie?.() || []) {
66
66
  const first = row.split(';', 1)[0];
67
67
  const separator = first.indexOf('=');
68
68
  if (separator > 0) this.jar.set(first.slice(0, separator), first.slice(separator + 1));
@@ -100,6 +100,7 @@ export class Gateway {
100
100
  'x-request-id': randomUUID(),
101
101
  },
102
102
  }, { operation: 'authenticate' });
103
+ this.absorbCookies(response.headers);
103
104
  let body;
104
105
  try { body = await response.json(); } catch { /* classified below */ }
105
106
  const user = body?.data?.user;
@@ -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
+ }