larkmate 0.1.20 → 0.1.21
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/README.md +1 -1
- package/bin/larkmate.js +11 -5
- package/bin/os-delegate-helper.js +2 -2
- package/docs/api-service.md +6 -1
- package/docs/os-delegation.md +2 -0
- package/package.json +1 -1
- package/skills/larkmate/SKILL.md +2 -0
- package/src/access-policy.js +4 -3
- package/src/api-service.js +1 -1
- package/src/credentials.js +15 -0
- package/src/listen-modes.js +4 -4
- package/src/os-delegate.js +5 -3
package/README.md
CHANGED
|
@@ -90,4 +90,4 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
90
90
|
|
|
91
91
|
具体用法和能力边界见 [LarkMate Skill](skills/larkmate/SKILL.md)。
|
|
92
92
|
|
|
93
|
-
如需将部分能力交给其他 Agent,可使用 [API 服务与 API key 授权](docs/api-service.md)、[系统用户权限委托](docs/os-delegation.md)或 [本地代理](docs/agent-broker.md)。
|
|
93
|
+
如需将部分能力交给其他 Agent,可使用 [API 服务与 API key 授权](docs/api-service.md)、[系统用户权限委托](docs/os-delegation.md)或 [本地代理](docs/agent-broker.md)。API key 和系统用户可以分别绑定不同的飞书账号。
|
package/bin/larkmate.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { Command, CommanderError } from 'commander';
|
|
3
|
-
import { loadCookie } from '../src/credentials.js';
|
|
3
|
+
import { loadCookie, loadProtectedCookie } from '../src/credentials.js';
|
|
4
4
|
import { Gateway } from '../src/gateway.js';
|
|
5
5
|
import { LarkMateClient } from '../src/client.js';
|
|
6
6
|
import { SessionControls } from '../src/session-controls.js';
|
|
7
7
|
import { Minutes, formatTranscript } from '../src/minutes.js';
|
|
8
8
|
import { writeFile, readFile } from 'node:fs/promises';
|
|
9
|
+
import { resolve, join } from 'node:path';
|
|
10
|
+
import { homedir } from 'node:os';
|
|
9
11
|
import { FeishuError } from '../src/errors.js';
|
|
10
12
|
import { exportMessages } from '../src/export-messages.js';
|
|
11
13
|
import { apiCommands, brokerCall, brokerCommands, brokerProxy, createBrokerToken, loadBrokerToken, loadPolicy, startBroker } from '../src/agent-broker.js';
|
|
@@ -23,7 +25,7 @@ import { startApiService } from '../src/api-service.js';
|
|
|
23
25
|
|
|
24
26
|
const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
|
|
25
27
|
const program = new Command();
|
|
26
|
-
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.
|
|
28
|
+
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.21');
|
|
27
29
|
program.option('--credentials-file <path>', 'read LarkMate credentials.json');
|
|
28
30
|
program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
|
|
29
31
|
program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
|
|
@@ -85,7 +87,8 @@ async function feeds() { const remote = proxy('feeds'); return remote || new Fee
|
|
|
85
87
|
async function tasks() { const remote = proxy('tasks'); return remote || new Tasks(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
|
|
86
88
|
function servicesFactory() {
|
|
87
89
|
let promise;
|
|
88
|
-
|
|
90
|
+
const make=async file=>{const gateway=new Gateway({cookie:file?await loadProtectedCookie(file):await loadCookie({file:program.opts().credentialsFile})});return {client:new LarkMateClient(gateway),controls:new SessionControls(gateway),minutes:new Minutes(gateway),sidebar:new SidebarFilters(gateway),feeds:new FeedGroups(gateway),tasks:new Tasks(gateway),calendar:new Calendar(gateway),groups:new GroupManagement(gateway)};};
|
|
91
|
+
return file=>file?make(file):(promise ||= make(null).catch(error=>{promise=undefined;throw error;}));
|
|
89
92
|
}
|
|
90
93
|
async function readJson(path, fallback) {
|
|
91
94
|
if (!path) return fallback;
|
|
@@ -177,9 +180,12 @@ program.command('listen-service').description('Serve messages on a private Unix
|
|
|
177
180
|
.action(async o => {
|
|
178
181
|
if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
|
|
179
182
|
if (o.all && o.chat.length) throw new FeishuError('INVALID_ARGUMENT', 'Use --all or --chat, not both.');
|
|
180
|
-
const
|
|
183
|
+
const selected=program.opts().credentialsFile;
|
|
184
|
+
const defaultAccountFile=process.env.LARKMATE_COOKIE?null:resolve(join(process.env.LARKMATE_HOME||join(homedir(),'.larkmate'),'credentials.json'));
|
|
185
|
+
const accountFile=selected?resolve(selected):defaultAccountFile;
|
|
186
|
+
const gateway=new Gateway({cookie:accountFile&&o.policy?await loadProtectedCookie(accountFile):await loadCookie({file:selected})}), self=await gateway.authenticate();
|
|
181
187
|
if(!['0600','0660'].includes(o.socketMode))throw new FeishuError('INVALID_ARGUMENT','Socket mode must be 0600 or 0660.');
|
|
182
|
-
const service = await startListenService(o.socket,{selfId:self.id,resolveNames:createNameResolver(gateway,self.id),policyPath:o.policy,socketMode:parseInt(o.socketMode,8)}), controller = new AbortController(), stop = () => controller.abort();
|
|
188
|
+
const service = await startListenService(o.socket,{selfId:self.id,resolveNames:createNameResolver(gateway,self.id),policyPath:o.policy,socketMode:parseInt(o.socketMode,8),credentialsFile:accountFile,defaultCredentialsFile:defaultAccountFile}), controller = new AbortController(), stop = () => controller.abort();
|
|
183
189
|
process.once('SIGINT', stop); process.once('SIGTERM', stop);
|
|
184
190
|
try { process.stderr.write(`LarkMate: event socket ${service.path}\n`); await listen({ gateway,chatIds:o.chat,output:service.output,signal:controller.signal }); }
|
|
185
191
|
finally { await service.close(); process.removeListener('SIGINT',stop);process.removeListener('SIGTERM',stop); }
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// The policy location is fixed relative to this protected installation, never to caller input.
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
import { loadDelegateConfig, serveOne } from '../src/os-delegate.js';
|
|
5
|
-
import { loadCookie } from '../src/credentials.js';
|
|
5
|
+
import { loadCookie, loadProtectedCookie } from '../src/credentials.js';
|
|
6
6
|
import { Gateway } from '../src/gateway.js';
|
|
7
7
|
import { LarkMateClient } from '../src/client.js';
|
|
8
8
|
import { SessionControls } from '../src/session-controls.js';
|
|
@@ -22,7 +22,7 @@ try {
|
|
|
22
22
|
if (!profile) throw new FeishuError('POLICY_DENIED', 'This operating-system user has no delegation profile.');
|
|
23
23
|
let services;
|
|
24
24
|
const getServices = () => services ||= (async () => {
|
|
25
|
-
const gateway = new Gateway({ cookie: await loadCookie({ file: config.credentialsFile }) });
|
|
25
|
+
const gateway = new Gateway({ cookie: profile.credentialsFile ? await loadProtectedCookie(profile.credentialsFile) : await loadCookie({ file: config.credentialsFile }) });
|
|
26
26
|
return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway), groups: new GroupManagement(gateway) };
|
|
27
27
|
})();
|
|
28
28
|
await serveOne({ input: process.stdin, output: process.stdout, uid: caller, profile, getServices });
|
package/docs/api-service.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# API 服务与 API key 授权
|
|
2
2
|
|
|
3
|
-
LarkMate 提供通用的 HTTP API 服务与 Unix socket 消息服务,两者可共用同一份策略文件。每个 API key
|
|
3
|
+
LarkMate 提供通用的 HTTP API 服务与 Unix socket 消息服务,两者可共用同一份策略文件。每个 API key 均可独立配置对应的飞书账号、允许调用的操作及可接收的消息范围。服务使用配置的飞书 Cookie 访问飞书,因此仍受对应账号权限的限制。
|
|
4
4
|
|
|
5
5
|
## 创建 key 和策略
|
|
6
6
|
|
|
@@ -23,6 +23,7 @@ larkmate api-key-create --output "$HOME/.larkmate/keys/agent-a.key"
|
|
|
23
23
|
{
|
|
24
24
|
"name": "agent-a",
|
|
25
25
|
"sha256": "替换为 api-key-create 输出的 64 位摘要",
|
|
26
|
+
"credentialsFile": "/绝对路径/account-a.json",
|
|
26
27
|
"api": {
|
|
27
28
|
"version": 1,
|
|
28
29
|
"allow": ["chat-info", "history"],
|
|
@@ -38,6 +39,8 @@ larkmate api-key-create --output "$HOME/.larkmate/keys/agent-a.key"
|
|
|
38
39
|
|
|
39
40
|
策略文件须使用绝对路径,归服务用户或 root 所有,且不能允许组用户或其他用户写入;建议设置为 `chmod 600 ~/.larkmate/api-policy.json`。策略不能是符号链接。`api` 和 `events` 可分别省略:省略后该 key 就不能使用对应的服务。增加 `keys` 条目可为不同调用方设置不同权限。
|
|
40
41
|
|
|
42
|
+
`credentialsFile` 将 key 绑定到服务端的飞书账号,使用与现有 `credentials.json` 相同的 `{"cookie":"..."}` 格式。凭据文件须是服务用户或 root 拥有、仅所有者可访问的普通文件,不能是符号链接;保护好上级目录和 ACL。多个 API key 既可绑定至同一账号,也可分别绑定至不同账号。调用方仅持有 API key,无法在请求中指定其他凭据文件。若未配置账号绑定,API 服务沿用启动时指定的账号。账号绑定的文件会在每次 API 操作时读取,更新后用于后续调用;进行中的调用可能仍使用原凭据。
|
|
43
|
+
|
|
41
44
|
`api.allow` 指定允许调用的命令;`chatIds` 限定会话。运行 `larkmate api-commands` 查看可用命令、调用方法和权限范围。某些全局操作、妙记以及附件操作还需要对应的策略字段,完整含义见 [Agent 权限委托指南](agent-broker.md)中的策略说明。请按需授权,避免使用全局授权来代替具体范围。
|
|
42
45
|
|
|
43
46
|
`events` 是授权规则数组,任一规则匹配即可接收;单条规则中的 `chatIds`、`senderIds` 和 `types` 同时生效,每个数组可包含多个值。`senderIds` 和 `types` 可以省略;每条规则必须指定 `chatIds`,或明确设置 `"allChats": true` 允许所有会话。授权使用稳定的数字 ID;调用方还可以在订阅时用名称、正则和组合条件进一步过滤,但不能扩大 key 的授权范围。
|
|
@@ -89,6 +92,8 @@ larkmate listen-service --socket "$HOME/.larkmate/events.sock" \
|
|
|
89
92
|
--policy "$HOME/.larkmate/api-policy.json"
|
|
90
93
|
```
|
|
91
94
|
|
|
95
|
+
每个消息服务进程监听一个账号。监听指定账号时,在命令名前使用 `--credentials-file /绝对路径/account-a.json`,并为不同账号启动不同的 socket。绑定了账号的 key 只能连接匹配该凭据文件的消息服务;未绑定账号的 key 只能连接使用默认凭据的消息服务。替换监听账号的 Cookie 后需重启对应消息服务。如果现有监听服务使用了 `--credentials-file` 指定非默认文件,请为其 key 添加相同的 `credentialsFile`,以继续订阅。
|
|
96
|
+
|
|
92
97
|
通过 Unix socket 连接 `/events`,同样在请求头提供 key。以下示例读取服务授权范围内的事件:
|
|
93
98
|
|
|
94
99
|
```sh
|
package/docs/os-delegation.md
CHANGED
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
|
|
15
15
|
每个用户的 `policy` 与[代理策略](agent-broker.md#配置授权)使用相同字段;只允许 `allow` 和资源范围共同匹配的操作。可通过 `larkmate delegate-commands` 查看可委托的命令及范围。可选的 `approvalScript` 必须是绝对路径、由所有者或 root 拥有的可执行普通文件,且不得允许组用户或其他用户写入;不配置时未授权操作直接拒绝。`approvalTimeoutSeconds` 默认 300 秒,可设为 1 至 600 秒。
|
|
16
16
|
|
|
17
|
+
可在每个 `users` 条目内设置 `credentialsFile` 绝对路径,为该系统用户指定飞书账号。不同用户可以指向不同文件;未设置时继承顶层的 `credentialsFile`。顶层文件可省略,但每个用户都必须有自己的文件。用户条目中的凭据文件须归所有者或 root 所有,仅所有者可访问,且必须是普通文件而非符号链接;格式与现有登录凭据相同。Agent 不能自行指定或更换账号,每个账号仍受对应用户的命令和资源策略限制。
|
|
18
|
+
|
|
17
19
|
文件、图片发送及附件下载可分别授权;上传文件由 Agent 进程读取,下载文件由 Agent 进程写入。执行器不接受 Agent 提供的所有者本地路径。下载时须提供 `history` 返回的 `--position`,执行器会核验会话、消息和资源键。单个文件受 `maxFileBytes` 限制;执行器在所有者私有临时目录中处理中转数据,正常结束或失败时删除,异常退出可能留下临时文件。部署方应保护、按需清理临时目录,并根据实际需要配置系统资源限制。
|
|
18
20
|
|
|
19
21
|
## 启动器与 sudoers 示例
|
package/package.json
CHANGED
package/skills/larkmate/SKILL.md
CHANGED
|
@@ -11,6 +11,8 @@ description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、
|
|
|
11
11
|
|
|
12
12
|
若环境提供 `LARKMATE_DELEGATE_OWNER` 和 `LARKMATE_DELEGATE_LAUNCHER`,使用系统用户委托并先执行 `larkmate delegate-info`。权限未预先开放时调用可能等待所有者审批;拒绝或失败时不尝试绕过。不要同时配置委托和本地代理,部署见 [系统用户权限委托](https://github.com/NWYLZW/larkmate/blob/main/docs/os-delegation.md)。
|
|
13
13
|
|
|
14
|
+
部署者可以为系统用户或 API key 指定不同的飞书账号。受限调用方只能使用分配的账号,不要读取其他账号的 Cookie 或尝试自行切换身份;具体配置见下方的 API 服务与授权指南。
|
|
15
|
+
|
|
14
16
|
根据任务读取所需参考:
|
|
15
17
|
|
|
16
18
|
- 查找会话、搜索与导出消息、获取链接、下载资源,以及管理会话状态和标签: [会话与消息](references/chats.md)。
|
package/src/access-policy.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { constants } from 'node:fs';
|
|
3
3
|
import { open, writeFile } from 'node:fs/promises';
|
|
4
|
-
import { isAbsolute } from 'node:path';
|
|
4
|
+
import { isAbsolute, normalize } from 'node:path';
|
|
5
5
|
import { FeishuError, requireInt64Id } from './errors.js';
|
|
6
6
|
import { parsePolicy } from './agent-broker.js';
|
|
7
7
|
|
|
@@ -22,11 +22,12 @@ export function parseAccessPolicy(raw) {
|
|
|
22
22
|
if(!only(raw,['version','keys'])||raw.version!==1||!Array.isArray(raw.keys))invalid();
|
|
23
23
|
const idsSeen=new Set(),hashes=new Set(),keys=[];
|
|
24
24
|
for(const entry of raw.keys){
|
|
25
|
-
if(!only(entry,['name','sha256','api','events'])||typeof entry.name!=='string'||!entry.name.trim()||entry.name.length>100||idsSeen.has(entry.name)||typeof entry.sha256!=='string'||!/^[a-f0-9]{64}$/.test(entry.sha256)||hashes.has(entry.sha256))invalid();
|
|
25
|
+
if(!only(entry,['name','sha256','credentialsFile','api','events'])||typeof entry.name!=='string'||!entry.name.trim()||entry.name.length>100||idsSeen.has(entry.name)||typeof entry.sha256!=='string'||!/^[a-f0-9]{64}$/.test(entry.sha256)||hashes.has(entry.sha256))invalid();
|
|
26
|
+
if(entry.credentialsFile!==undefined&&(typeof entry.credentialsFile!=='string'||!isAbsolute(entry.credentialsFile)||entry.credentialsFile.includes('\0')))invalid();
|
|
26
27
|
if(entry.api===undefined&&entry.events===undefined)invalid();
|
|
27
28
|
let api=null;if(entry.api!==undefined){try{api=parsePolicy(entry.api)}catch{invalid()}}
|
|
28
29
|
let events=null;if(entry.events!==undefined){if(!Array.isArray(entry.events)||!entry.events.length)invalid();events=entry.events.map(eventGrant)}
|
|
29
|
-
idsSeen.add(entry.name);hashes.add(entry.sha256);keys.push(Object.freeze({name:entry.name,sha256:entry.sha256,api,events}));
|
|
30
|
+
idsSeen.add(entry.name);hashes.add(entry.sha256);keys.push(Object.freeze({name:entry.name,sha256:entry.sha256,credentialsFile:entry.credentialsFile===undefined?null:normalize(entry.credentialsFile),api,events}));
|
|
30
31
|
}
|
|
31
32
|
return Object.freeze({keys:Object.freeze(keys)});
|
|
32
33
|
}
|
package/src/api-service.js
CHANGED
|
@@ -34,7 +34,7 @@ export async function startApiService({host='127.0.0.1',port=0,policyPath,getSer
|
|
|
34
34
|
}
|
|
35
35
|
if(req.url==='/v1/file'&&transfers>=2)return answer(429,'API_BUSY','Too many file transfers.');
|
|
36
36
|
const file=req.url==='/v1/file';if(file)transfers++;
|
|
37
|
-
try{req.headers.authorization=`Bearer ${token}`;await createBrokerHandler({policy:key.api,token,getServices})(req,res);}
|
|
37
|
+
try{req.headers.authorization=`Bearer ${token}`;await createBrokerHandler({policy:key.api,token,getServices:()=>getServices(key.credentialsFile)})(req,res);}
|
|
38
38
|
catch{if(!res.headersSent)answer(500,'API_ERROR','The API request failed.');else res.destroy();}
|
|
39
39
|
finally{if(file)transfers--;}
|
|
40
40
|
};
|
package/src/credentials.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { open } from 'node:fs/promises';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
2
4
|
import { homedir } from 'node:os';
|
|
3
5
|
import { join } from 'node:path';
|
|
4
6
|
import { FeishuError } from './errors.js';
|
|
@@ -21,3 +23,16 @@ export async function loadCookie({ file, env = process.env, home = homedir() } =
|
|
|
21
23
|
}
|
|
22
24
|
return cookie.trim();
|
|
23
25
|
}
|
|
26
|
+
|
|
27
|
+
// Privileged account bindings must not be replaceable or readable by delegates.
|
|
28
|
+
export async function loadProtectedCookie(file) {
|
|
29
|
+
let handle;
|
|
30
|
+
try {
|
|
31
|
+
handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
32
|
+
const st = await handle.stat();
|
|
33
|
+
if (!st.isFile() || ![0, process.getuid?.()].includes(st.uid) || (st.mode & 0o077) || st.size > 1048576) throw new Error();
|
|
34
|
+
const contents = JSON.parse(await handle.readFile('utf8'));
|
|
35
|
+
return await loadCookie({env:{LARKMATE_COOKIE:contents.cookie || 'SETUP_NEEDED'}});
|
|
36
|
+
} catch { throw new FeishuError('CREDENTIALS_UNAVAILABLE', 'Cannot read the protected account credentials.'); }
|
|
37
|
+
finally { await handle?.close(); }
|
|
38
|
+
}
|
package/src/listen-modes.js
CHANGED
|
@@ -89,7 +89,7 @@ export function createRuleOutput({rules,selfId,resolveNames,log=process.stderr})
|
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
// Exposes the configured event stream, protected by the socket and parent directory permissions.
|
|
92
|
-
export async function startListenService(socketPath, {selfId,resolveNames,policyPath,socketMode=0o600}={}) {
|
|
92
|
+
export async function startListenService(socketPath, {selfId,resolveNames,policyPath,socketMode=0o600,credentialsFile=null,defaultCredentialsFile=null}={}) {
|
|
93
93
|
if(typeof socketPath!=='string'||!isAbsolute(socketPath)||socketPath.endsWith('/'))throw new FeishuError('INVALID_ARGUMENT','Use an absolute socket path.');
|
|
94
94
|
if(![0o600,0o660].includes(socketMode)||(socketMode!==0o600&&!policyPath))throw new FeishuError('INVALID_ARGUMENT','A shared socket requires an API key policy.');
|
|
95
95
|
if(policyPath)await loadAccessPolicy(policyPath);
|
|
@@ -102,7 +102,7 @@ export async function startListenService(socketPath, {selfId,resolveNames,policy
|
|
|
102
102
|
if(!['GET','POST'].includes(req.method)){res.writeHead(404);res.end();return;}
|
|
103
103
|
let keyHash=null;
|
|
104
104
|
if(policyPath){
|
|
105
|
-
try{const key=lookupAccessKey(await loadAccessPolicy(policyPath),requestKey(req));if(!key)throw new FeishuError('API_KEY_INVALID','A valid API key is required.');if(!key.events){res.writeHead(403);res.end();return;}keyHash=key.sha256;}
|
|
105
|
+
try{const key=lookupAccessKey(await loadAccessPolicy(policyPath),requestKey(req));if(!key)throw new FeishuError('API_KEY_INVALID','A valid API key is required.');if(!key.events||(key.credentialsFile??defaultCredentialsFile)!==credentialsFile){res.writeHead(403);res.end();return;}keyHash=key.sha256;}
|
|
106
106
|
catch(error){const status=error.code==='API_KEY_INVALID'?401:503;res.writeHead(status,{'content-type':'application/json','cache-control':'no-store'});res.end(JSON.stringify({ok:false,error:{code:status===401?'API_KEY_INVALID':'ACCESS_POLICY_UNAVAILABLE',message:status===401?'A valid API key is required.':'The API key access policy is unavailable.'}}));return;}
|
|
107
107
|
}
|
|
108
108
|
let filter;
|
|
@@ -130,7 +130,7 @@ export async function startListenService(socketPath, {selfId,resolveNames,policy
|
|
|
130
130
|
let policy=null;if(policyPath){try{policy=await loadAccessPolicy(policyPath)}catch{for(const client of clients.keys())client.destroy();return;}}
|
|
131
131
|
const snapshot=[];
|
|
132
132
|
for(const [client,entry] of clients){
|
|
133
|
-
if(policyPath){const key=lookupAccessKey(policy,entry.keyHash,{hashed:true});if(!key?.events){client.destroy();continue;}
|
|
133
|
+
if(policyPath){const key=lookupAccessKey(policy,entry.keyHash,{hashed:true});if(!key?.events||(key.credentialsFile??defaultCredentialsFile)!==credentialsFile){client.destroy();continue;}
|
|
134
134
|
if(event.kind==='message'&&!eventAllowed(key.events,event))continue;
|
|
135
135
|
if(event.kind==='gap'&&event.chatId&&!chatAllowed(key.events,event.chatId))continue;
|
|
136
136
|
if(!['message','gap'].includes(event.kind))continue;
|
|
@@ -154,7 +154,7 @@ export async function startListenService(socketPath, {selfId,resolveNames,policy
|
|
|
154
154
|
const needs={chat:false,sender:false};for(const [, {needs:n}] of deferred){needs.chat ||= n.chat;needs.sender ||= n.sender;}
|
|
155
155
|
if(needs.chat||needs.sender){let names={};try{names=await resolveNames?.(event,needs)||{}}catch{}event={...event,...names};}
|
|
156
156
|
if(policyPath&&deferred.length){try{policy=await loadAccessPolicy(policyPath)}catch{for(const [client] of deferred)client.destroy();return;}}
|
|
157
|
-
for(const [client,{filter,keyHash}] of deferred){if(policyPath){const key=lookupAccessKey(policy,keyHash,{hashed:true});if(!key?.events){client.destroy();continue;}if(!eventAllowed(key.events,event))continue;}deliver(client,filter,event);}
|
|
157
|
+
for(const [client,{filter,keyHash}] of deferred){if(policyPath){const key=lookupAccessKey(policy,keyHash,{hashed:true});if(!key?.events||(key.credentialsFile??defaultCredentialsFile)!==credentialsFile){client.destroy();continue;}if(!eventAllowed(key.events,event))continue;}deliver(client,filter,event);}
|
|
158
158
|
})().then(()=>callback(),callback)}});
|
|
159
159
|
return {path,output,async close(){for(const c of clients.keys())c.destroy();await new Promise(resolve=>server.close(resolve));try{const now=await lstat(path);if(now.ino===inode&&now.isSocket())await unlink(path);}catch(e){if(e.code!=='ENOENT')throw e;}}};
|
|
160
160
|
}
|
package/src/os-delegate.js
CHANGED
|
@@ -26,16 +26,18 @@ export async function loadDelegateConfig(path, ownerUid) {
|
|
|
26
26
|
if (!info.isFile() || info.size > 262144 || ![0, ownerUid].includes(info.uid) || (info.mode & 0o022)) throw new Error();
|
|
27
27
|
raw = JSON.parse(await h.readFile('utf8'));
|
|
28
28
|
} catch { return invalid(); } finally { await h?.close(); }
|
|
29
|
-
if (!only(raw, ['version', 'ownerUid', 'credentialsFile', 'users']) || raw.version !== 1 || raw.ownerUid !== ownerUid || !isAbsolute(raw.credentialsFile || '') || !obj(raw.users)) invalid();
|
|
29
|
+
if (!only(raw, ['version', 'ownerUid', 'credentialsFile', 'users']) || raw.version !== 1 || raw.ownerUid !== ownerUid || (raw.credentialsFile !== undefined && (typeof raw.credentialsFile !== 'string' || !isAbsolute(raw.credentialsFile) || raw.credentialsFile.includes('\0'))) || !obj(raw.users)) invalid();
|
|
30
30
|
const users = {};
|
|
31
31
|
for (const [uid, v] of Object.entries(raw.users)) {
|
|
32
|
-
if (!uint(uid) || Number(uid) === ownerUid || !only(v, ['policy', 'approvalScript', 'approvalTimeoutSeconds'])) invalid();
|
|
32
|
+
if (!uint(uid) || Number(uid) === ownerUid || !only(v, ['policy', 'credentialsFile', 'approvalScript', 'approvalTimeoutSeconds'])) invalid();
|
|
33
|
+
if (v.credentialsFile !== undefined && (typeof v.credentialsFile !== 'string' || !isAbsolute(v.credentialsFile) || v.credentialsFile.includes('\0'))) invalid();
|
|
34
|
+
if (!v.credentialsFile && !raw.credentialsFile) invalid();
|
|
33
35
|
const policy = parsePolicy(v.policy);
|
|
34
36
|
const approvalScript = v.approvalScript;
|
|
35
37
|
if (approvalScript !== undefined && (typeof approvalScript !== 'string' || !isAbsolute(approvalScript))) invalid();
|
|
36
38
|
const timeout = v.approvalTimeoutSeconds ?? 300;
|
|
37
39
|
if (!Number.isInteger(timeout) || timeout < 1 || timeout > 600) invalid();
|
|
38
|
-
users[uid] = { policy, approvalScript, approvalTimeoutSeconds: timeout };
|
|
40
|
+
users[uid] = { policy, credentialsFile: v.credentialsFile, approvalScript, approvalTimeoutSeconds: timeout };
|
|
39
41
|
}
|
|
40
42
|
return { credentialsFile: raw.credentialsFile, users };
|
|
41
43
|
}
|