agent-loft 0.2.44 → 0.2.45
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 +2 -1
- package/package.json +1 -1
- package/src/channels/web/api.ts +42 -5
- package/src/channels/web/http.ts +12 -0
- package/src/channels/web/push.ts +130 -6
- package/src/channels/web/server.ts +4 -3
- package/src/core/config.ts +36 -0
- package/src/core/servers.ts +134 -0
- package/web/css/servers.css +265 -0
- package/web/index.html +1 -0
- package/web/lib/api.js +1 -0
- package/web/lib/overlay.js +1 -1
- package/web/lib/push.js +8 -1
- package/web/lib/shell.js +691 -0
- package/web/lib/ws.js +7 -1
- package/web/settings/common.js +3 -0
- package/web/settings/index.js +2 -0
- package/web/settings/notify.js +7 -2
- package/web/settings/security.js +8 -3
- package/web/settings/servers.js +207 -0
- package/web/state.js +2 -0
- package/web/views/auth.js +3 -1
- package/web/views/composer.js +1 -1
- package/web/views/layout.js +43 -5
- package/web/views/messages.js +2 -2
- package/web/views/remote.js +2 -2
- package/web/views/sidebar.js +6 -4
- package/web/views/tasks.js +1 -1
package/README.md
CHANGED
|
@@ -57,10 +57,11 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
57
57
|
- 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。在桌面端里,这个菜单并进桌面端顶栏的「更多」,排在最上面。
|
|
58
58
|
- 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。金额都是按 API 价格算的参考值:Claude 用它自己报的费用,Codex 不报费用,按模型单价(LiteLLM 公开价格表,内置一份快照、联网时每天更新)× token 估算。从 0.2.34 开始记录,之前的用量没有日期,不计入。
|
|
59
59
|
- 「添加到主屏幕」后当 App 用;切到后台再回来会自动重连,补上错过的内容。
|
|
60
|
+
- **网页多服务器切换**:在 设置 → 服务器 添加其他 agent-loft,再点「授权」到对方页面确认,侧栏左上角就能切换;各台分别登录,切走后保持连接,列表显示待处理数和运行状态,刷新后保留选择。几台需使用同一主域名下的 HTTPS 地址(例如 `mac.example.com`、`nas.example.com`)。在外层页面开启系统通知后,各台的提醒都能推到同一个主屏幕 App,点通知自动切到对应服务器和对话。见[使用指南](docs/产品介绍.md#在网页和手机上切换多台服务器)。
|
|
60
61
|
- **系统通知**:Web 会话回复完成、出错、需要授权或提问时推送到手机 / 电脑(设置 → 通知 → 「在此设备开启通知」,可以发测试通知)。飞书会话由飞书提醒,正在前台看着的会话不推。需要 HTTPS 访问,iPhone 需 iOS 16.4+ 且从主屏幕图标打开。
|
|
61
62
|
- **跨渠道同步**:飞书里的会话在 Web 上也能打开接着聊。同一个授权请求同时出现在飞书卡片和网页上,哪边先点算哪边,另一边自动变成「已处理」。
|
|
62
63
|
- **授权**:允许一次 / 本会话全部允许 / 总是允许(按钮上写明放行范围)/ 拒绝。`/autoedit on` 让 Claude Code 在这条会话里改工作目录内的文件不再询问(Bash 仍询问)。超时一律按拒绝处理。
|
|
63
|
-
- **设置都在网页上**,按用途分组:**我的**(账号和密码、飞书绑定、登录设备、通知、记忆、技能、用量,每个人都有);**Agent**(运行环境、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude
|
|
64
|
+
- **设置都在网页上**,按用途分组:**我的**(账号和密码、飞书绑定、登录设备、通知、记忆、技能、用量,每个人都有);**Agent**(运行环境、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude 的「总是允许」名单;「/」命令);**连接**(飞书机器人、配对批准、指令面板同步;远程控制;服务器);**管理**(用户、所有人的登录设备;服务端版本和升级、重启、局域网访问和端口)。改了没保存就切页或关掉设置会先提醒。
|
|
64
65
|
- **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知,设置只有管理员能改,见下面「安全」。
|
|
65
66
|
- **聊天模式 / 工作模式**:右上角「更多」里的「聊天模式」,或者发 `/chat`、`/work`,同一条对话随时切换、上下文接着。聊天模式换成精简的系统提示,只留联网搜索,不加载技能、MCP、插件,不执行命令、不读写本机文件(文本附件的内容直接放进消息),每轮的固定开销小得多:实测一句话 Claude 约 1.6 万 → 2 千 token,Codex 约 2 万 → 1.2 万(Codex 的基础指令改不了)。适合日常聊天、查资料;要动手干活时切回工作模式。切换后第一轮要重建提示缓存,会贵一些;在工作模式里读过的大段内容还留在历史里。
|
|
66
67
|
- **记忆**:像 ChatGPT 的记忆,设置 → 记忆。「关于我」加上一条条记住的事,每次对话都带上;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),记错了用 `forget` 删。**自动整理**:把上次整理之后新说的话交给模型(不留会话记录的一次性调用),补充、更新或删掉过时的记忆,用户自己加的条目它不动。什么时候整理每个人自己定:每天一次(默认凌晨 4 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理聊天模式的/只整理工作模式的;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,只有你自己的、没被删掉的对话;第一次用时会把已有对话收录进来)。两项都能在设置里单独关。每个用户一份,Claude 和 Codex、Web 和飞书共用。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
|
package/package.json
CHANGED
package/src/channels/web/api.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { addScheduled, clearScheduled, removeScheduled } from "../../core/schedu
|
|
|
13
13
|
import { resolveUploadFile, saveBuffer, sniff, uploadKeyOf } from "../../core/uploads.js";
|
|
14
14
|
import { mentions, replyFileType, resolveReplyFile } from "../../core/reply-files.js";
|
|
15
15
|
import { HTML_CSP, HTML_MAX, htmlDocument } from "../../core/visualize.js";
|
|
16
|
+
import { cleanServers, ownFrameAncestors, shellInfo } from "../../core/servers.js";
|
|
16
17
|
import {
|
|
17
18
|
createUser,
|
|
18
19
|
getUser,
|
|
@@ -72,7 +73,16 @@ import { handleTasksApi } from "./tasks-api.js";
|
|
|
72
73
|
import { handleSkillsApi } from "./skills-api.js";
|
|
73
74
|
import { handleTerminalApi } from "./terminal.js";
|
|
74
75
|
import { handleDesktopApi, remoteStatus } from "./desktop.js";
|
|
75
|
-
import {
|
|
76
|
+
import {
|
|
77
|
+
addRelaySubscription,
|
|
78
|
+
addSubscription,
|
|
79
|
+
listSubscriptions,
|
|
80
|
+
pushToAll,
|
|
81
|
+
removeSubscription,
|
|
82
|
+
removeSubscriptionsOf,
|
|
83
|
+
vapidKeyPair,
|
|
84
|
+
vapidPublicKey,
|
|
85
|
+
} from "./push.js";
|
|
76
86
|
|
|
77
87
|
export const COOKIE = "aim_session";
|
|
78
88
|
const startedAt = Date.now();
|
|
@@ -188,7 +198,7 @@ function serveReplyFile(req: IncomingMessage, res: ServerResponse, file: string,
|
|
|
188
198
|
// (所有接口的响应事先都带上了 SECURITY_HEADERS,见 server.ts,这里得把那个也去掉)
|
|
189
199
|
delete headers["X-Frame-Options"];
|
|
190
200
|
res.removeHeader("X-Frame-Options");
|
|
191
|
-
headers["Content-Security-Policy"] =
|
|
201
|
+
headers["Content-Security-Policy"] = `default-src 'none'; frame-ancestors ${ownFrameAncestors(config().servers)}`;
|
|
192
202
|
} else {
|
|
193
203
|
headers["Content-Security-Policy"] = "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox";
|
|
194
204
|
}
|
|
@@ -280,9 +290,17 @@ function publicConfig(): unknown {
|
|
|
280
290
|
};
|
|
281
291
|
}
|
|
282
292
|
|
|
283
|
-
|
|
293
|
+
/** selfOrigin:发起保存的页面的地址(多服务器列表里不能加自己) */
|
|
294
|
+
function applyConfig(input: Partial<AppConfig>, selfOrigin?: string): void {
|
|
284
295
|
const current = config();
|
|
285
296
|
const next = structuredClone(current);
|
|
297
|
+
if (input.servers !== undefined) {
|
|
298
|
+
try {
|
|
299
|
+
next.servers = cleanServers(input.servers, current.servers, selfOrigin);
|
|
300
|
+
} catch (err) {
|
|
301
|
+
throw new HttpError(400, err instanceof Error ? err.message : String(err));
|
|
302
|
+
}
|
|
303
|
+
}
|
|
286
304
|
if (typeof input.workspaceRoot === "string" && input.workspaceRoot.trim()) next.workspaceRoot = input.workspaceRoot.trim();
|
|
287
305
|
if (typeof input.approvalTimeoutMs === "number") next.approvalTimeoutMs = Math.max(60_000, input.approvalTimeoutMs);
|
|
288
306
|
if (typeof input.sessionTtlMs === "number") next.sessionTtlMs = Math.max(0, input.sessionTtlMs);
|
|
@@ -643,6 +661,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
643
661
|
pending,
|
|
644
662
|
user: publicMe(user),
|
|
645
663
|
remote: remoteStatus(user),
|
|
664
|
+
// 左上角切换服务器:没加别的服务器是 null
|
|
665
|
+
servers: shellInfo(config().servers),
|
|
646
666
|
serverTime: Date.now(),
|
|
647
667
|
});
|
|
648
668
|
return;
|
|
@@ -671,6 +691,23 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
671
691
|
}
|
|
672
692
|
return;
|
|
673
693
|
}
|
|
694
|
+
// 多服务器(core/servers.ts):外壳把这个浏览器的订阅连同签名密钥转给嵌着的各台(web/lib/shell.js),
|
|
695
|
+
// 各台直接推到手机上,不经过外壳。密钥只在加了别的服务器时给
|
|
696
|
+
if (p === "/api/push/relay-key" && method === "GET") {
|
|
697
|
+
if (!config().servers.list.length) throw new HttpError(404, "没有加别的服务器");
|
|
698
|
+
sendJson(res, 200, vapidKeyPair());
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
if (p === "/api/push/relay" && method === "POST") {
|
|
702
|
+
const body = await readJsonBody<{ subscription?: unknown; vapid?: unknown; via?: unknown }>(req);
|
|
703
|
+
try {
|
|
704
|
+
const record = addRelaySubscription(body, String(req.headers["user-agent"] ?? ""), user.id, config().servers.embedders);
|
|
705
|
+
sendJson(res, 200, { ok: true, label: record.label });
|
|
706
|
+
} catch (err) {
|
|
707
|
+
throw new HttpError(400, err instanceof Error ? err.message : String(err));
|
|
708
|
+
}
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
674
711
|
if (p === "/api/push/unsubscribe" && method === "POST") {
|
|
675
712
|
const body = await readJsonBody<{ endpoint?: string }>(req);
|
|
676
713
|
sendJson(res, 200, { ok: removeSubscription(String(body.endpoint ?? ""), pushOwnedBy(user.id)) });
|
|
@@ -859,7 +896,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
859
896
|
res.writeHead(200, {
|
|
860
897
|
"X-Content-Type-Options": "nosniff",
|
|
861
898
|
"Referrer-Policy": "no-referrer",
|
|
862
|
-
"Content-Security-Policy": HTML_CSP,
|
|
899
|
+
"Content-Security-Policy": HTML_CSP.replace("frame-ancestors 'self'", `frame-ancestors ${ownFrameAncestors(config().servers)}`),
|
|
863
900
|
"Content-Type": "text/html; charset=utf-8",
|
|
864
901
|
"Content-Length": doc.length,
|
|
865
902
|
"Cache-Control": "private, no-cache",
|
|
@@ -974,7 +1011,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
974
1011
|
if (p === "/api/config" && method === "PUT") {
|
|
975
1012
|
const input = await readJsonBody<Partial<AppConfig>>(req);
|
|
976
1013
|
await applyListen(req, input.web);
|
|
977
|
-
applyConfig(input);
|
|
1014
|
+
applyConfig(input, typeof req.headers.origin === "string" ? req.headers.origin : undefined);
|
|
978
1015
|
sendJson(res, 200, { ...(publicConfig() as object), network: networkInfo(req) });
|
|
979
1016
|
return;
|
|
980
1017
|
}
|
package/src/channels/web/http.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// HTTP 小工具:不引框架,几十行就够用。
|
|
2
2
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
3
3
|
import { config } from "../../core/config.js";
|
|
4
|
+
import { pageCsp } from "../../core/servers.js";
|
|
4
5
|
|
|
5
6
|
export class HttpError extends Error {
|
|
6
7
|
constructor(
|
|
@@ -116,3 +117,14 @@ export const SECURITY_HEADERS: Record<string, string> = {
|
|
|
116
117
|
"Content-Security-Policy":
|
|
117
118
|
"default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' ws: wss:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'",
|
|
118
119
|
};
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 页面(静态文件)的安全头:CSP 的 frame-src / frame-ancestors 跟着多服务器的设置走(core/servers.ts)。
|
|
123
|
+
* 允许被别的地址嵌时去掉 X-Frame-Options:它只有 DENY / SAMEORIGIN,说不了「这几个地址可以」
|
|
124
|
+
*/
|
|
125
|
+
export function pageHeaders(): Record<string, string> {
|
|
126
|
+
const servers = config().servers;
|
|
127
|
+
const headers: Record<string, string> = { ...SECURITY_HEADERS, "Content-Security-Policy": pageCsp(servers) };
|
|
128
|
+
if (servers.embedders.length) delete headers["X-Frame-Options"];
|
|
129
|
+
return headers;
|
|
130
|
+
}
|
package/src/channels/web/push.ts
CHANGED
|
@@ -9,6 +9,8 @@ import crypto from "node:crypto";
|
|
|
9
9
|
import path from "node:path";
|
|
10
10
|
import { dataDir, readJson, writeJsonAtomic } from "../../home.js";
|
|
11
11
|
import { legacyOwnerId } from "../../core/users.js";
|
|
12
|
+
import { config, onConfigChange } from "../../core/config.js";
|
|
13
|
+
import { selfName, validServerId } from "../../core/servers.js";
|
|
12
14
|
|
|
13
15
|
export type PushSubscriptionRecord = {
|
|
14
16
|
endpoint: string;
|
|
@@ -19,6 +21,25 @@ export type PushSubscriptionRecord = {
|
|
|
19
21
|
lastOkAt?: number;
|
|
20
22
|
/** 哪个用户开的(core/users.ts)。升级前的没有:第一次读到时认给迁移出来的那个管理员并记下 */
|
|
21
23
|
userId?: string;
|
|
24
|
+
/** 多服务器的外壳转来的订阅,见下面的 addRelaySubscription */
|
|
25
|
+
relay?: RelayInfo;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
type VapidKey = { publicKey: string; privateJwk: crypto.JsonWebKey };
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 外壳转来的订阅:手机上只有添加到主屏幕的那个地址(外壳)能订阅推送,订阅是对着外壳那台的
|
|
32
|
+
* VAPID 公钥开的,这台推的时候也得用那把密钥签名,推送服务才认。点开通知回到外壳的页面,
|
|
33
|
+
* 地址里带上 srv=这台在外壳里的 id,由外壳切过来。
|
|
34
|
+
*/
|
|
35
|
+
export type RelayInfo = {
|
|
36
|
+
vapid: VapidKey;
|
|
37
|
+
/** 外壳的地址 */
|
|
38
|
+
origin: string;
|
|
39
|
+
/** 这台在外壳列表里的 id */
|
|
40
|
+
server: string;
|
|
41
|
+
/** 外壳列表里这台的图标和名字,加在通知标题前面 */
|
|
42
|
+
label: string;
|
|
22
43
|
};
|
|
23
44
|
|
|
24
45
|
/** 按订阅的主人筛选:拿到的是订阅里记的 userId(可能没有) */
|
|
@@ -34,7 +55,7 @@ export type PushPayload = {
|
|
|
34
55
|
};
|
|
35
56
|
|
|
36
57
|
type Store = {
|
|
37
|
-
vapid?:
|
|
58
|
+
vapid?: VapidKey;
|
|
38
59
|
subscriptions: PushSubscriptionRecord[];
|
|
39
60
|
};
|
|
40
61
|
|
|
@@ -44,6 +65,17 @@ const VAPID_SUBJECT = "https://github.com/qijieinnet/agent-loft";
|
|
|
44
65
|
|
|
45
66
|
let store: Store | null = null;
|
|
46
67
|
|
|
68
|
+
/** 取消嵌入授权后,该外壳也不能再通过旧订阅收到通知。 */
|
|
69
|
+
function dropRevokedRelays(s: Store, embedders: string[]): boolean {
|
|
70
|
+
const before = s.subscriptions.length;
|
|
71
|
+
s.subscriptions = s.subscriptions.filter((x) => !x.relay || embedders.includes(x.relay.origin));
|
|
72
|
+
return s.subscriptions.length !== before;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
onConfigChange((next) => {
|
|
76
|
+
if (store && dropRevokedRelays(store, next.servers.embedders)) persist();
|
|
77
|
+
});
|
|
78
|
+
|
|
47
79
|
function load(): Store {
|
|
48
80
|
if (!store) {
|
|
49
81
|
store = readJson<Store>(FILE(), { subscriptions: [] });
|
|
@@ -53,7 +85,8 @@ function load(): Store {
|
|
|
53
85
|
const owner = legacyOwnerId();
|
|
54
86
|
const legacy = owner ? store.subscriptions.filter((x) => !x.userId) : [];
|
|
55
87
|
for (const x of legacy) x.userId = owner;
|
|
56
|
-
|
|
88
|
+
const revoked = dropRevokedRelays(store, config().servers.embedders);
|
|
89
|
+
if (legacy.length > 0 || revoked) writeJsonAtomic(FILE(), store);
|
|
57
90
|
}
|
|
58
91
|
return store;
|
|
59
92
|
}
|
|
@@ -91,8 +124,22 @@ export function vapidPublicKey(): string {
|
|
|
91
124
|
return vapid().publicKey;
|
|
92
125
|
}
|
|
93
126
|
|
|
94
|
-
|
|
95
|
-
|
|
127
|
+
/**
|
|
128
|
+
* 这台的 VAPID 密钥对,给多服务器的外壳转给嵌着的各台(GET /api/push/relay-key)。
|
|
129
|
+
* 拿到它也只能推给已经知道订阅地址的设备:订阅地址和加密用的 p256dh / auth 只在开通知的那台浏览器
|
|
130
|
+
* 和收到订阅的服务端手里,别人的设备推不到
|
|
131
|
+
*/
|
|
132
|
+
export function vapidKeyPair(): VapidKey {
|
|
133
|
+
vapid();
|
|
134
|
+
const { publicKey, privateJwk } = load().vapid!;
|
|
135
|
+
return { publicKey, privateJwk };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** key:用别的密钥签(外壳转来的订阅),不给就用这台自己的 */
|
|
139
|
+
export function vapidHeader(endpoint: string, key?: VapidKey): string {
|
|
140
|
+
const { publicKey, privateKey } = key
|
|
141
|
+
? { publicKey: key.publicKey, privateKey: crypto.createPrivateKey({ key: key.privateJwk, format: "jwk" }) }
|
|
142
|
+
: vapid();
|
|
96
143
|
const header = b64url(Buffer.from(JSON.stringify({ typ: "JWT", alg: "ES256" })));
|
|
97
144
|
const claims = b64url(
|
|
98
145
|
Buffer.from(
|
|
@@ -162,6 +209,59 @@ export function addSubscription(sub: unknown, userAgent: string, userId?: string
|
|
|
162
209
|
return record;
|
|
163
210
|
}
|
|
164
211
|
|
|
212
|
+
function validVapid(v: unknown): v is VapidKey {
|
|
213
|
+
const key = v as { publicKey?: unknown; privateJwk?: crypto.JsonWebKey };
|
|
214
|
+
const jwk = key?.privateJwk;
|
|
215
|
+
if (typeof key?.publicKey !== "string" || !jwk || typeof jwk !== "object") return false;
|
|
216
|
+
if (jwk.kty !== "EC" || jwk.crv !== "P-256" || typeof jwk.d !== "string" || typeof jwk.x !== "string" || typeof jwk.y !== "string") return false;
|
|
217
|
+
try {
|
|
218
|
+
crypto.createPrivateKey({ key: { kty: "EC", crv: "P-256", d: jwk.d, x: jwk.x, y: jwk.y }, format: "jwk" });
|
|
219
|
+
} catch {
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
return b64url(rawPublicKey(jwk)) === key.publicKey;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const clip = (v: unknown, max: number) => [...String(v ?? "").trim()].slice(0, max).join("");
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* 外壳转来的订阅(多服务器)。embedders:这台允许谁嵌,外壳得在里面 —— 订阅只能是嵌着这台的
|
|
229
|
+
* 外壳转来的,别的地址的不收。同一个订阅地址再转一次就换掉旧的(换了账号登录也是这样归新账号)
|
|
230
|
+
*/
|
|
231
|
+
export function addRelaySubscription(
|
|
232
|
+
input: { subscription?: unknown; vapid?: unknown; via?: unknown },
|
|
233
|
+
userAgent: string,
|
|
234
|
+
userId: string,
|
|
235
|
+
embedders: string[],
|
|
236
|
+
): PushSubscriptionRecord {
|
|
237
|
+
const sub = input.subscription;
|
|
238
|
+
if (!validSubscription(sub)) throw new Error("订阅信息不完整");
|
|
239
|
+
if (!validVapid(input.vapid)) throw new Error("推送密钥不对");
|
|
240
|
+
const via = (input.via ?? {}) as { origin?: unknown; server?: unknown; label?: unknown };
|
|
241
|
+
const origin = String(via.origin ?? "");
|
|
242
|
+
if (!embedders.includes(origin)) throw new Error(`这台没有允许 ${origin || "这个地址"} 嵌入,收不了它转来的通知订阅`);
|
|
243
|
+
const server = String(via.server ?? "");
|
|
244
|
+
if (!validServerId(server)) throw new Error("订阅信息不完整");
|
|
245
|
+
const { publicKey, privateJwk } = input.vapid;
|
|
246
|
+
const s = load();
|
|
247
|
+
const record: PushSubscriptionRecord = {
|
|
248
|
+
endpoint: sub.endpoint,
|
|
249
|
+
keys: { p256dh: sub.keys.p256dh, auth: sub.keys.auth },
|
|
250
|
+
label: `${describeUa(userAgent)} · 经 ${new URL(origin).host}`,
|
|
251
|
+
createdAt: Date.now(),
|
|
252
|
+
userId,
|
|
253
|
+
relay: {
|
|
254
|
+
vapid: { publicKey, privateJwk: { kty: "EC", crv: "P-256", d: privateJwk.d, x: privateJwk.x, y: privateJwk.y } },
|
|
255
|
+
origin,
|
|
256
|
+
server,
|
|
257
|
+
label: clip(via.label, 60),
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
s.subscriptions = [...s.subscriptions.filter((x) => x.endpoint !== sub.endpoint), record];
|
|
261
|
+
persist();
|
|
262
|
+
return record;
|
|
263
|
+
}
|
|
264
|
+
|
|
165
265
|
export function removeSubscription(endpoint: string, mine?: OwnerFilter): boolean {
|
|
166
266
|
const s = load();
|
|
167
267
|
const before = s.subscriptions.length;
|
|
@@ -187,12 +287,36 @@ export function hasSubscriptions(): boolean {
|
|
|
187
287
|
|
|
188
288
|
// ---------- 发送 ----------
|
|
189
289
|
|
|
290
|
+
const prefixed = (label: string, title: string) => (label ? `${label} · ${title}` : title);
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* 真正推出去的内容。加了别的服务器(这台是外壳)时标题前面带上这台的名字,好分清是哪台的;
|
|
294
|
+
* 外壳转来的订阅带上外壳列表里这台的名字,tag 加上这台的 id(各台的会话 key 可能撞上),
|
|
295
|
+
* 点开的地址带上 srv=这台的 id
|
|
296
|
+
*/
|
|
297
|
+
export function payloadFor(sub: PushSubscriptionRecord, payload: PushPayload): PushPayload {
|
|
298
|
+
const relay = sub.relay;
|
|
299
|
+
if (!relay) {
|
|
300
|
+
const servers = config().servers;
|
|
301
|
+
if (!servers.list.length) return payload;
|
|
302
|
+
return { ...payload, title: prefixed(`${servers.selfIcon} ${selfName(servers)}`.trim(), payload.title) };
|
|
303
|
+
}
|
|
304
|
+
const url = new URL(payload.url ?? "/", "http://relay");
|
|
305
|
+
url.searchParams.set("srv", relay.server);
|
|
306
|
+
return {
|
|
307
|
+
...payload,
|
|
308
|
+
title: prefixed(relay.label, payload.title),
|
|
309
|
+
...(payload.tag ? { tag: `srv:${relay.server}:${payload.tag}` } : {}),
|
|
310
|
+
url: `${url.pathname}${url.search}${url.hash}`,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
190
314
|
async function sendOne(sub: PushSubscriptionRecord, payload: PushPayload): Promise<boolean> {
|
|
191
|
-
const body = encryptPayload(Buffer.from(JSON.stringify(payload)), sub.keys.p256dh, sub.keys.auth);
|
|
315
|
+
const body = encryptPayload(Buffer.from(JSON.stringify(payloadFor(sub, payload))), sub.keys.p256dh, sub.keys.auth);
|
|
192
316
|
const res = await fetch(sub.endpoint, {
|
|
193
317
|
method: "POST",
|
|
194
318
|
headers: {
|
|
195
|
-
Authorization: vapidHeader(sub.endpoint),
|
|
319
|
+
Authorization: vapidHeader(sub.endpoint, sub.relay?.vapid),
|
|
196
320
|
"Content-Encoding": "aes128gcm",
|
|
197
321
|
"Content-Type": "application/octet-stream",
|
|
198
322
|
TTL: String(24 * 3600),
|
|
@@ -24,7 +24,7 @@ import { authEvents, ensureSetupToken, sessionUser } from "./auth.js";
|
|
|
24
24
|
import { canSeeKey, sessionVisibleTo } from "./access.js";
|
|
25
25
|
import { cookies } from "./http.js";
|
|
26
26
|
import { COOKIE } from "./api.js";
|
|
27
|
-
import { HttpError, sameOrigin, SECURITY_HEADERS, sendJson } from "./http.js";
|
|
27
|
+
import { HttpError, pageHeaders, sameOrigin, SECURITY_HEADERS, sendJson } from "./http.js";
|
|
28
28
|
import { hasSubscriptions, pushToAll } from "./push.js";
|
|
29
29
|
import { closeListener, listen, listening, rebind } from "./listen.js";
|
|
30
30
|
import { closeTerminalClients, pingTerminalClients, recheckTerminalClients, upgradeTerminal } from "./terminal.js";
|
|
@@ -86,11 +86,12 @@ function serveFile(req: http.IncomingMessage, res: http.ServerResponse, file: st
|
|
|
86
86
|
const lastModified = new Date(Math.floor(stat.mtimeMs / 1000) * 1000);
|
|
87
87
|
const since = Date.parse(req.headers["if-modified-since"] ?? "");
|
|
88
88
|
const headers = {
|
|
89
|
-
...
|
|
89
|
+
...pageHeaders(),
|
|
90
90
|
"Cache-Control": "no-cache",
|
|
91
91
|
"Last-Modified": lastModified.toUTCString(),
|
|
92
92
|
};
|
|
93
|
-
|
|
93
|
+
// 页面本身不回 304:它的 CSP(允许谁嵌、能嵌谁)跟着设置变,304 带回的新头浏览器不一定换上
|
|
94
|
+
if (!Number.isNaN(since) && lastModified.getTime() <= since && path.extname(file) !== ".html") {
|
|
94
95
|
res.writeHead(304, headers);
|
|
95
96
|
res.end();
|
|
96
97
|
return;
|
package/src/core/config.ts
CHANGED
|
@@ -7,6 +7,7 @@ import path from "node:path";
|
|
|
7
7
|
import crypto from "node:crypto";
|
|
8
8
|
import { configPath, ensureDirs, readJson, writeJsonAtomic } from "../home.js";
|
|
9
9
|
import { cleanCustomCommands, type CommandPrefs } from "./command-catalog.js";
|
|
10
|
+
import { normalizeOrigin, validServerId } from "./servers.js";
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
|
|
@@ -96,6 +97,16 @@ export type AppConfig = {
|
|
|
96
97
|
watchdogMs: number;
|
|
97
98
|
bots: FeishuBotConfig[];
|
|
98
99
|
};
|
|
100
|
+
/** 多服务器:网页左上角切换到别的 agent-loft(见 core/servers.ts) */
|
|
101
|
+
servers: {
|
|
102
|
+
/** 切换列表里这台叫什么(空着用主机名)、用什么图标(emoji) */
|
|
103
|
+
selfName: string;
|
|
104
|
+
selfIcon: string;
|
|
105
|
+
/** 左上角能切到的其他服务器,按这个顺序。url 是 origin */
|
|
106
|
+
list: { id: string; name: string; icon: string; url: string }[];
|
|
107
|
+
/** 允许把这台的页面嵌进去的地址(origin):别的 agent-loft 要切到这台,得先在这里 */
|
|
108
|
+
embedders: string[];
|
|
109
|
+
};
|
|
99
110
|
};
|
|
100
111
|
|
|
101
112
|
export const AGENT_IDS = ["claude", "codex"] as const;
|
|
@@ -131,6 +142,7 @@ export function defaultConfig(): AppConfig {
|
|
|
131
142
|
vncPassword: "",
|
|
132
143
|
},
|
|
133
144
|
feishu: { watchdogMs: 10 * 60 * 1000, bots: [] },
|
|
145
|
+
servers: { selfName: "", selfIcon: "", list: [], embedders: [] },
|
|
134
146
|
};
|
|
135
147
|
}
|
|
136
148
|
|
|
@@ -164,6 +176,27 @@ function normalizeBot(raw: Partial<FeishuBotConfig>): FeishuBotConfig {
|
|
|
164
176
|
};
|
|
165
177
|
}
|
|
166
178
|
|
|
179
|
+
/** 多服务器的地址可能是手改的:规范成 origin,坏的、重复的丢掉 */
|
|
180
|
+
function normalizeServers(cfg: AppConfig): void {
|
|
181
|
+
const origin = (v: unknown) => {
|
|
182
|
+
try {
|
|
183
|
+
return normalizeOrigin(v);
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
const seen = new Set<string>();
|
|
189
|
+
const ids = new Set<string>();
|
|
190
|
+
cfg.servers.list = cfg.servers.list.flatMap((s) => {
|
|
191
|
+
const url = origin(s?.url);
|
|
192
|
+
if (!url || seen.has(url) || !validServerId(s.id) || ids.has(s.id)) return [];
|
|
193
|
+
seen.add(url);
|
|
194
|
+
ids.add(s.id);
|
|
195
|
+
return [{ id: s.id, name: String(s.name ?? ""), icon: String(s.icon ?? ""), url }];
|
|
196
|
+
});
|
|
197
|
+
cfg.servers.embedders = [...new Set(cfg.servers.embedders.map(origin).filter((o): o is string => !!o))];
|
|
198
|
+
}
|
|
199
|
+
|
|
167
200
|
/** 自定义命令可能是手改进配置文件的:不合规的丢掉,别让一条坏数据把命令列表搞崩 */
|
|
168
201
|
function normalizeCommands(cfg: AppConfig): void {
|
|
169
202
|
for (const id of AGENT_IDS) cfg.commands[id].custom = cleanCustomCommands(cfg.commands[id].custom);
|
|
@@ -180,6 +213,7 @@ export function loadConfig(): AppConfig {
|
|
|
180
213
|
merged.workspaceRoot = path.resolve(merged.workspaceRoot);
|
|
181
214
|
merged.feishu.bots = merged.feishu.bots.map(normalizeBot);
|
|
182
215
|
normalizeCommands(merged);
|
|
216
|
+
normalizeServers(merged);
|
|
183
217
|
current = merged;
|
|
184
218
|
if (!raw) writeJsonAtomic(configPath, merged);
|
|
185
219
|
watchExternalEdits();
|
|
@@ -206,6 +240,7 @@ function watchExternalEdits(): void {
|
|
|
206
240
|
next.workspaceRoot = path.resolve(next.workspaceRoot);
|
|
207
241
|
next.feishu.bots = next.feishu.bots.map(normalizeBot);
|
|
208
242
|
normalizeCommands(next);
|
|
243
|
+
normalizeServers(next);
|
|
209
244
|
if (JSON.stringify(next) === JSON.stringify(current)) return;
|
|
210
245
|
const prev = current;
|
|
211
246
|
current = next;
|
|
@@ -234,6 +269,7 @@ export function saveConfig(next: AppConfig): AppConfig {
|
|
|
234
269
|
const normalized = mergeDefaults(defaultConfig(), next);
|
|
235
270
|
normalized.workspaceRoot = path.resolve(normalized.workspaceRoot);
|
|
236
271
|
normalized.feishu.bots = normalized.feishu.bots.map(normalizeBot);
|
|
272
|
+
normalizeServers(normalized);
|
|
237
273
|
writeJsonAtomic(configPath, normalized);
|
|
238
274
|
current = normalized;
|
|
239
275
|
for (const listener of listeners) {
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// 多服务器:网页左上角切换到别的 agent-loft。
|
|
2
|
+
//
|
|
3
|
+
// 别的服务器的页面原样嵌在这台页面的 iframe 里,各自登录、各自直连自己的服务端,这台不中转。
|
|
4
|
+
// 几台要在同一个主域名下(a.example.com、b.example.com):同站的 iframe 才带得上登录 cookie,
|
|
5
|
+
// iPhone 的 Safari 跨站一律不带。
|
|
6
|
+
//
|
|
7
|
+
// 两头各有一份配置(config.json 的 servers):
|
|
8
|
+
// - list:这台左上角能切到哪几台(这台是「外壳」);
|
|
9
|
+
// - embedders:允许哪些地址把这台的页面嵌进去(这台被别人嵌)。页面的 frame-ancestors 就按它出,
|
|
10
|
+
// 不在里面的一律嵌不进来。
|
|
11
|
+
import crypto from "node:crypto";
|
|
12
|
+
import os from "node:os";
|
|
13
|
+
import type { AppConfig } from "./config.js";
|
|
14
|
+
|
|
15
|
+
export type ServerEntry = AppConfig["servers"]["list"][number];
|
|
16
|
+
|
|
17
|
+
/** 切换列表里最多几台:每台都是一整个常驻的页面 */
|
|
18
|
+
export const MAX_SERVERS = 12;
|
|
19
|
+
const MAX_EMBEDDERS = 20;
|
|
20
|
+
const MAX_NAME = 40;
|
|
21
|
+
/** 图标是 emoji:一个字形可能由好几个码位拼成(肤色、ZWJ 组合),按码位数放宽一点 */
|
|
22
|
+
const MAX_ICON = 16;
|
|
23
|
+
|
|
24
|
+
/** 外壳自己在列表里的 id(别的服务器的 id 是随机生成的,不会撞上) */
|
|
25
|
+
export const SELF_ID = "home";
|
|
26
|
+
|
|
27
|
+
/** 页面切换和通知链接共用的 id;home 只代表外壳自己。 */
|
|
28
|
+
export function validServerId(id: unknown): id is string {
|
|
29
|
+
return typeof id === "string" && id !== SELF_ID && /^[\w-]{1,40}$/.test(id);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 地址规范成 origin(https://a.example.com、http://localhost:8800)。
|
|
34
|
+
* 只认 http / https,不带路径、查询、账号密码:agent-loft 只能挂在根路径上。
|
|
35
|
+
*/
|
|
36
|
+
export function normalizeOrigin(raw: unknown): string {
|
|
37
|
+
const text = String(raw ?? "").trim();
|
|
38
|
+
if (!text) throw new Error("地址不能为空");
|
|
39
|
+
let url: URL;
|
|
40
|
+
try {
|
|
41
|
+
url = new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(text) ? text : `https://${text}`);
|
|
42
|
+
} catch {
|
|
43
|
+
throw new Error(`地址不对:${text}`);
|
|
44
|
+
}
|
|
45
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`只支持 http / https 地址:${text}`);
|
|
46
|
+
if (url.username || url.password) throw new Error(`地址里不能带账号密码:${text}`);
|
|
47
|
+
if ((url.pathname !== "/" && url.pathname !== "") || url.search || url.hash) {
|
|
48
|
+
throw new Error(`只填到域名(和端口)就行,agent-loft 不支持挂在子路径下:${text}`);
|
|
49
|
+
}
|
|
50
|
+
return url.origin;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const clip = (v: unknown, max: number) => [...String(v ?? "").trim()].slice(0, max).join("");
|
|
54
|
+
|
|
55
|
+
function newId(taken: Set<string>): string {
|
|
56
|
+
for (;;) {
|
|
57
|
+
const id = crypto.randomBytes(4).toString("hex");
|
|
58
|
+
if (!taken.has(id) && id !== SELF_ID) return id;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 设置页传来的 servers(只改了其中几项也行),校验后和现有的合并。
|
|
64
|
+
* selfOrigin:这台页面自己的地址,不能把自己加进列表。出错抛 Error(说明给用户看)
|
|
65
|
+
*/
|
|
66
|
+
export function cleanServers(input: unknown, current: AppConfig["servers"], selfOrigin?: string): AppConfig["servers"] {
|
|
67
|
+
const patch = (input ?? {}) as Partial<Record<keyof AppConfig["servers"], unknown>>;
|
|
68
|
+
const next = structuredClone(current);
|
|
69
|
+
if (patch.selfName !== undefined) next.selfName = clip(patch.selfName, MAX_NAME);
|
|
70
|
+
if (patch.selfIcon !== undefined) next.selfIcon = clip(patch.selfIcon, MAX_ICON);
|
|
71
|
+
|
|
72
|
+
if (patch.list !== undefined) {
|
|
73
|
+
if (!Array.isArray(patch.list)) throw new Error("服务器列表格式不对");
|
|
74
|
+
if (patch.list.length > MAX_SERVERS) throw new Error(`最多加 ${MAX_SERVERS} 台服务器`);
|
|
75
|
+
const known = new Set(current.list.map((s) => s.id));
|
|
76
|
+
const taken = new Set<string>();
|
|
77
|
+
const origins = new Set<string>();
|
|
78
|
+
const list: ServerEntry[] = [];
|
|
79
|
+
for (const raw of patch.list as Partial<ServerEntry>[]) {
|
|
80
|
+
const url = normalizeOrigin(raw?.url);
|
|
81
|
+
if (selfOrigin && url === selfOrigin) throw new Error(`${url} 就是这台自己,不用加`);
|
|
82
|
+
if (origins.has(url)) throw new Error(`${url} 加了两次`);
|
|
83
|
+
origins.add(url);
|
|
84
|
+
// 老的 id 留着(页面记着上次切到哪台、推送里带的也是它);新加的现生成
|
|
85
|
+
const id = typeof raw?.id === "string" && known.has(raw.id) && !taken.has(raw.id) ? raw.id : newId(new Set([...known, ...taken]));
|
|
86
|
+
taken.add(id);
|
|
87
|
+
const name = clip(raw?.name, MAX_NAME) || new URL(url).hostname.split(".")[0] || url;
|
|
88
|
+
list.push({ id, name, icon: clip(raw?.icon, MAX_ICON), url });
|
|
89
|
+
}
|
|
90
|
+
next.list = list;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (patch.embedders !== undefined) {
|
|
94
|
+
if (!Array.isArray(patch.embedders)) throw new Error("允许嵌入的地址格式不对");
|
|
95
|
+
const set = new Set<string>();
|
|
96
|
+
for (const raw of patch.embedders) set.add(normalizeOrigin(raw));
|
|
97
|
+
if (set.size > MAX_EMBEDDERS) throw new Error(`允许嵌入的地址最多 ${MAX_EMBEDDERS} 个`);
|
|
98
|
+
next.embedders = [...set];
|
|
99
|
+
}
|
|
100
|
+
return next;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 切换列表里这台的名字:没设就用主机名 */
|
|
104
|
+
export function selfName(cfg: AppConfig["servers"]): string {
|
|
105
|
+
return cfg.selfName || os.hostname().split(".")[0] || "这台";
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 页面要的:左上角的切换列表。没加别的服务器就是 null(不显示切换) */
|
|
109
|
+
export function shellInfo(cfg: AppConfig["servers"]) {
|
|
110
|
+
if (cfg.list.length === 0) return null;
|
|
111
|
+
return {
|
|
112
|
+
self: { id: SELF_ID, name: selfName(cfg), icon: cfg.selfIcon },
|
|
113
|
+
list: cfg.list.map(({ id, name, icon, url }) => ({ id, name, icon, url })),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 页面(HTML 等静态文件)的 CSP:
|
|
119
|
+
* - frame-src:外壳要能嵌列表里的服务器;
|
|
120
|
+
* - frame-ancestors:只让 embedders 里的地址嵌这台,没有就谁都不行。
|
|
121
|
+
*/
|
|
122
|
+
export function pageCsp(cfg: AppConfig["servers"]): string {
|
|
123
|
+
const frames = ["'self'", ...cfg.list.map((s) => s.url)].join(" ");
|
|
124
|
+
const ancestors = cfg.embedders.length ? cfg.embedders.join(" ") : "'none'";
|
|
125
|
+
return `default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' ws: wss:; frame-src ${frames}; frame-ancestors ${ancestors}; base-uri 'self'; form-action 'self'`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 这台自己嵌的东西(PDF 预览、回复里的图表)的 frame-ancestors。frame-ancestors 要求每一层祖先
|
|
130
|
+
* 都对得上:这台被外壳嵌着时,只写 'self' 的话外壳那层通不过,预览就是一片空白
|
|
131
|
+
*/
|
|
132
|
+
export function ownFrameAncestors(cfg: AppConfig["servers"]): string {
|
|
133
|
+
return ["'self'", ...cfg.embedders].join(" ");
|
|
134
|
+
}
|