@dsh-mobile/mobile-remote 3.2.7 → 3.3.0
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/FAQ.md +19 -12
- package/README.md +38 -39
- package/cordis.patch.yml +8 -4
- package/docs/PRIVACY-POLICY.en.md +87 -46
- package/docs/PRIVACY-POLICY.md +87 -46
- package/docs/SUPPORT.md +5 -5
- package/docs/USER-GUIDE.zh-CN.md +562 -0
- package/lib/assistant-prefs.js +147 -0
- package/lib/auto-config.js +55 -3
- package/lib/backup.js +405 -0
- package/lib/break-reminder.js +133 -0
- package/lib/client.js +56 -10
- package/lib/config.js +94 -5
- package/lib/git-read-bundled-provider.js +12 -3
- package/lib/git-read-service.js +4 -0
- package/lib/host-compat.js +25 -0
- package/lib/http-util.js +6 -2
- package/lib/index.js +949 -70
- package/lib/memory/context.js +76 -0
- package/lib/memory/decay.js +144 -0
- package/lib/memory/extract.js +146 -0
- package/lib/memory/routes.js +198 -0
- package/lib/memory/store.js +667 -0
- package/lib/notify-copy.js +245 -0
- package/lib/permission-guide.js +184 -0
- package/lib/persona-cards.js +362 -0
- package/lib/proactive-material.js +162 -0
- package/lib/proactive.js +369 -0
- package/lib/protected-paths.js +130 -0
- package/lib/protocol.js +35 -0
- package/lib/rate-limit.js +1 -1
- package/lib/relay/connector.js +97 -12
- package/lib/relay/devices.js +14 -0
- package/lib/relay/fingerprint.js +55 -0
- package/lib/relay/identity.js +69 -0
- package/lib/relay/on-demand.js +84 -0
- package/lib/relay/phone.js +87 -12
- package/lib/reminders.js +140 -0
- package/lib/rpc-adapter.js +21 -2
- package/lib/session-rotation.js +198 -0
- package/lib/timeline.js +1 -1
- package/package.json +30 -14
- package/CHANGELOG.md +0 -1383
- package/CONTRIBUTING.md +0 -61
- package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +0 -432
- package/docs/01-PRD.md +0 -148
- package/docs/02-architecture.md +0 -249
- package/docs/03-api.md +0 -882
- package/docs/04-security.md +0 -110
- package/docs/05-test-cases.md +0 -376
- package/docs/06-install-run.md +0 -335
- package/docs/07-user-manual.md +0 -92
- package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +0 -86
- package/docs/09-compatibility.md +0 -201
- package/docs/11-remote-relay-guide.md +0 -86
- package/docs/APP-ENCRYPTION-DESCRIPTION.md +0 -50
- package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
- package/docs/APP-REVIEW-NOTES.md +0 -105
- package/docs/BRAND-ASSETS.md +0 -142
- package/docs/COMPANION-PLAN.md +0 -199
- package/docs/STORE-LAUNCH.md +0 -341
- package/docs/STORE-LISTING.md +0 -190
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 助手偏好(模式 / 人格)的读写接口(T9)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要这个接口:模式与人格必须**同时**作用在两个地方——
|
|
5
|
+
* 1. 推送与通知的措辞(服务端已有);
|
|
6
|
+
* 2. agent 对话时的上下文(人格决定语气、模式决定能看到哪些记忆)。
|
|
7
|
+
* 之前 App 里切换只写进了手机本地,服务端一直是默认值,于是「切成生活模式」
|
|
8
|
+
* 只改了手机上一句提示,电脑上的助手仍然拿着工作记忆在说话。这不是没做,
|
|
9
|
+
* 是做了但没生效。
|
|
10
|
+
*
|
|
11
|
+
* 落盘策略:写进 `<状态目录>/assistant.json`,重启后保持。之所以不写回
|
|
12
|
+
* `cordis.patch.yml`:那是用户手写的部署配置,插件不该去改它。
|
|
13
|
+
*/
|
|
14
|
+
import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { parseHm } from "./notify-copy.js";
|
|
17
|
+
|
|
18
|
+
const MODES = ["work", "life"];
|
|
19
|
+
/** Persona card ids (T-31): same rule as lib/persona-cards.js validatePersonaCard. */
|
|
20
|
+
const PERSONA_CARD_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
21
|
+
const PERSONAS = ["colleague", "character"];
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 安静时段的合法性判断。返回 `true` 表示两个时间点都能解析。
|
|
25
|
+
*
|
|
26
|
+
* 故意不接受「猜一个默认值」:配置写错时宁可多吵一次,
|
|
27
|
+
* 也不要把用户的通知整段吞掉(见 config.js 里同一条注释)。
|
|
28
|
+
*/
|
|
29
|
+
function validWindow(start, end) {
|
|
30
|
+
return parseHm(start) !== null && parseHm(end) !== null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {object} options
|
|
35
|
+
* @param {string} options.dir 状态目录(与 auth-token、记忆库同层)
|
|
36
|
+
* @param {() => {mode: string, persona: string, quietHours?: {start: string, end: string}}} options.defaults 配置里的默认值
|
|
37
|
+
*/
|
|
38
|
+
export function createAssistantPrefs({ dir, defaults }) {
|
|
39
|
+
const file = join(dir, "assistant.json");
|
|
40
|
+
let cached = null;
|
|
41
|
+
|
|
42
|
+
function load() {
|
|
43
|
+
if (cached) return cached;
|
|
44
|
+
const fallback = defaults();
|
|
45
|
+
try {
|
|
46
|
+
const raw = JSON.parse(readFileSync(file, "utf8"));
|
|
47
|
+
// 安静时段单独校验:文件里可能是旧版本写的、也可能是手改坏的。
|
|
48
|
+
// 只有两个端点都合法才采用,否则整体回落到配置值——半个窗口比没有更糟。
|
|
49
|
+
const quiet = raw?.quietHours;
|
|
50
|
+
const quietOk =
|
|
51
|
+
quiet && validWindow(quiet.start, quiet.end)
|
|
52
|
+
? { start: quiet.start, end: quiet.end }
|
|
53
|
+
: fallback.quietHours;
|
|
54
|
+
cached = {
|
|
55
|
+
mode: MODES.includes(raw?.mode) ? raw.mode : fallback.mode,
|
|
56
|
+
persona: PERSONAS.includes(raw?.persona) ? raw.persona : fallback.persona,
|
|
57
|
+
quietHours: quietOk
|
|
58
|
+
? { start: quietOk.start, end: quietOk.end }
|
|
59
|
+
: { start: "23:30", end: "08:30" },
|
|
60
|
+
// T-15: the user's own off switch for the break reminder (on unless they turned it off).
|
|
61
|
+
breakReminder: typeof raw?.breakReminder === "boolean" ? raw.breakReminder : true,
|
|
62
|
+
// T-31: the active persona card (an id). Absent = the old colleague/character switch decides.
|
|
63
|
+
...(PERSONA_CARD_ID.test(raw?.personaCard ?? "") ? { personaCard: raw.personaCard } : {}),
|
|
64
|
+
};
|
|
65
|
+
} catch {
|
|
66
|
+
// 文件不存在或损坏:回到配置默认值,不因为一个坏文件让助手不可用。
|
|
67
|
+
cached = {
|
|
68
|
+
mode: fallback.mode,
|
|
69
|
+
persona: fallback.persona,
|
|
70
|
+
quietHours: fallback.quietHours ?? { start: "23:30", end: "08:30" },
|
|
71
|
+
breakReminder: true,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return cached;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function save(next) {
|
|
78
|
+
mkdirSync(dir, { recursive: true });
|
|
79
|
+
// 原子写:先写临时文件再 rename,避免断电/崩溃留下半个 JSON。
|
|
80
|
+
const tmp = `${file}.tmp`;
|
|
81
|
+
writeFileSync(tmp, JSON.stringify(next, null, 2), "utf8");
|
|
82
|
+
renameSync(tmp, file);
|
|
83
|
+
cached = next;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
file,
|
|
88
|
+
/** 当前有效的模式与人格。 */
|
|
89
|
+
get: () => ({ ...load() }),
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 改一项或两项。非法值直接拒绝,不「猜一个最近的」:
|
|
93
|
+
* 猜错会让用户以为切换成功,实际还在原来的模式里。
|
|
94
|
+
*/
|
|
95
|
+
set(patch) {
|
|
96
|
+
const cur = load();
|
|
97
|
+
const next = { ...cur };
|
|
98
|
+
if (patch?.mode !== undefined) {
|
|
99
|
+
if (!MODES.includes(patch.mode)) {
|
|
100
|
+
throw new Error(`mode 必须是 ${MODES.join(" / ")}`);
|
|
101
|
+
}
|
|
102
|
+
next.mode = patch.mode;
|
|
103
|
+
}
|
|
104
|
+
if (patch?.persona !== undefined) {
|
|
105
|
+
if (!PERSONAS.includes(patch.persona)) {
|
|
106
|
+
throw new Error(`persona 必须是 ${PERSONAS.join(" / ")}`);
|
|
107
|
+
}
|
|
108
|
+
next.persona = patch.persona;
|
|
109
|
+
}
|
|
110
|
+
if (patch?.quietHours !== undefined) {
|
|
111
|
+
const start = patch.quietHours?.start;
|
|
112
|
+
const end = patch.quietHours?.end;
|
|
113
|
+
if (!validWindow(start, end)) {
|
|
114
|
+
// 不静默保留旧值:用户会以为自己改成功了,夜里照样被吵醒。
|
|
115
|
+
throw new Error("quietHours 必须是 {start: \"HH:MM\", end: \"HH:MM\"}");
|
|
116
|
+
}
|
|
117
|
+
next.quietHours = { start, end };
|
|
118
|
+
}
|
|
119
|
+
if (patch?.personaCard !== undefined) {
|
|
120
|
+
if (typeof patch.personaCard !== "string" || !PERSONA_CARD_ID.test(patch.personaCard)) {
|
|
121
|
+
throw new Error("personaCard 必须是人格卡的 id / personaCard must be a persona card id");
|
|
122
|
+
}
|
|
123
|
+
next.personaCard = patch.personaCard;
|
|
124
|
+
}
|
|
125
|
+
if (patch?.breakReminder !== undefined) {
|
|
126
|
+
if (typeof patch.breakReminder !== "boolean") throw new Error("breakReminder 必须是 true / false");
|
|
127
|
+
next.breakReminder = patch.breakReminder;
|
|
128
|
+
}
|
|
129
|
+
save(next);
|
|
130
|
+
return { ...next };
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// personaBrief was removed with T-31 (D8): the active persona card's own text is the only
|
|
136
|
+
// persona text the model sees (lib/persona-cards.js, personaPromptText).
|
|
137
|
+
|
|
138
|
+
/** 模式 → 一段给模型看的说明。生活模式明确要求不提工作内容。 */
|
|
139
|
+
export function modeBrief(mode) {
|
|
140
|
+
if (mode === "life") {
|
|
141
|
+
return [
|
|
142
|
+
"当前是生活模式:不主动提项目、客户、报错、未发布的功能。",
|
|
143
|
+
"记忆里工作范围的内容这一轮看不到,也不要凭印象补出来。",
|
|
144
|
+
].join("\n");
|
|
145
|
+
}
|
|
146
|
+
return "当前是工作模式:可以使用项目与长期记忆,回答以可执行、可核对为准。";
|
|
147
|
+
}
|
package/lib/auto-config.js
CHANGED
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
* - `lanBridge.enabled: "auto"` 仅在需要时开桥(桌面版 webserver 只听回环)。
|
|
9
9
|
* - `formatConnectionBanner` 启动时把手机 App 需要填的两项(地址 + 口令)打印出来。
|
|
10
10
|
*
|
|
11
|
-
* 向后兼容:`authToken`
|
|
11
|
+
* 向后兼容:`authToken` 为空仅在服务只有本机可达时表示「关闭认证」,否则按 `@auto` 处理(T-03,见
|
|
12
|
+
* `effectiveAuthSetting`);`lanBridge.enabled` 仍可写 true/false;
|
|
12
13
|
* 这些「自动」值只会出现在插件自带的 `cordis.patch.yml` 里,已有手写配置的用户行为不变。
|
|
13
14
|
*/
|
|
14
15
|
import { randomBytes } from "node:crypto";
|
|
@@ -32,7 +33,7 @@ export function mobileRemoteStateDir(env = process.env, home = homedir()) {
|
|
|
32
33
|
|
|
33
34
|
/**
|
|
34
35
|
* 解析 `authToken`。
|
|
35
|
-
* - 不是 `@auto`:原样返回(空串 =
|
|
36
|
+
* - 不是 `@auto`:原样返回(空串 = 关闭认证;调用方只在服务仅本机可达时才会传空串,见 effectiveAuthSetting)。
|
|
36
37
|
* - `@auto`:读 `<stateDir>/auth-token`;没有或损坏就生成新的并原子写入(0600)。
|
|
37
38
|
* 写盘失败不阻断启动:本次进程内用内存口令,但会返回 `persistError`,调用方应提示
|
|
38
39
|
* 「重启后口令会变,手机需要重新配对」。
|
|
@@ -60,6 +61,49 @@ export function resolveAuthToken(configured, { dir = mobileRemoteStateDir(), gen
|
|
|
60
61
|
}
|
|
61
62
|
}
|
|
62
63
|
|
|
64
|
+
/**
|
|
65
|
+
* T-03 (finding E6): whether nothing but this computer can reach the mobile API.
|
|
66
|
+
*
|
|
67
|
+
* True only when the DSH webserver listens on a loopback address and none of the ways out
|
|
68
|
+
* is on: no LAN bridge, no `trustedHosts` (a tunnel or reverse proxy), no relay (it replays
|
|
69
|
+
* phone requests into this server). An unknown webserver host counts as reachable, so the
|
|
70
|
+
* answer fails closed.
|
|
71
|
+
*/
|
|
72
|
+
export function isLoopbackOnly({ webHost, lanBridgeEnabled = false, trustedHosts = [], relayEnabled = false } = {}) {
|
|
73
|
+
if (typeof webHost !== "string" || !LOOPBACK_HOSTS.has(webHost.trim().toLowerCase())) return false;
|
|
74
|
+
if (lanBridgeEnabled || relayEnabled) return false;
|
|
75
|
+
return !(Array.isArray(trustedHosts) && trustedHosts.length > 0);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* T-03 (finding E6): the `authToken` setting to resolve.
|
|
80
|
+
*
|
|
81
|
+
* An empty token used to switch authentication off wherever the server was reachable, so a
|
|
82
|
+
* user config that replaced the shipped `"@auto"` and left the token out opened an agent with
|
|
83
|
+
* shell access to the whole LAN. Now an empty (or missing) token means "off" only when the
|
|
84
|
+
* server is loopback-only (`isLoopbackOnly`); everywhere else it is treated as `"@auto"`.
|
|
85
|
+
* A non-empty value is returned unchanged.
|
|
86
|
+
*/
|
|
87
|
+
export function effectiveAuthSetting(configured, reach = {}) {
|
|
88
|
+
if (typeof configured === "string" && configured !== "") return configured;
|
|
89
|
+
return isLoopbackOnly(reach) ? "" : AUTO;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Replace an auto-managed token with a fresh one (T-62: after a device is revoked). Written
|
|
94
|
+
* atomically over `<dir>/auth-token` (0600). Only for `@auto` tokens: a token the owner wrote
|
|
95
|
+
* into their config is theirs to change. Throws when the file cannot be written.
|
|
96
|
+
*/
|
|
97
|
+
export function rotateAuthToken({ dir = mobileRemoteStateDir(), generate = () => randomBytes(24).toString("base64url") } = {}) {
|
|
98
|
+
const file = join(dir, "auth-token");
|
|
99
|
+
const token = generate();
|
|
100
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
101
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
102
|
+
writeFileSync(tmp, `${token}\n`, { mode: 0o600 });
|
|
103
|
+
renameSync(tmp, file);
|
|
104
|
+
return { token, file };
|
|
105
|
+
}
|
|
106
|
+
|
|
63
107
|
/**
|
|
64
108
|
* 解析 `lanBridge.enabled`:true/false 原样;`"auto"` = 需要才开。
|
|
65
109
|
* 「需要」= webserver 只听回环(桌面版强制如此,手机直连不了)。web 版 webserver 已经听 0.0.0.0,
|
|
@@ -85,13 +129,21 @@ export function resolveLanBridgePort(setting, port, webPort) {
|
|
|
85
129
|
* 启动时打印给人看的「手机 App 要填的两项」。
|
|
86
130
|
* 口令只在**自动生成**时打印——那是用户唯一能第一时间拿到它的地方;用户自己写进配置的口令不进日志。
|
|
87
131
|
*/
|
|
88
|
-
|
|
132
|
+
/**
|
|
133
|
+
* T-62 (E11): an auto token is printed only on the start that generated it (`tokenNew`). Later
|
|
134
|
+
* starts say where it is saved instead: stderr often ends up in log files.
|
|
135
|
+
*/
|
|
136
|
+
export function formatConnectionBanner({ addresses, token, tokenIsAuto, tokenNew = true, tokenFile, persistError, authEnabled = true }) {
|
|
89
137
|
const [first, ...rest] = addresses;
|
|
90
138
|
const lines = ["mobile-remote ▶ 手机 App 连接信息 / Phone app connection"];
|
|
91
139
|
lines.push(` 电脑地址 Address : ${first}`);
|
|
92
140
|
for (const extra of rest) lines.push(` ${extra} (备用 alternative)`);
|
|
93
141
|
if (!authEnabled) {
|
|
94
142
|
lines.push(" 访问口令 Token : (未启用认证 / authentication is OFF)");
|
|
143
|
+
} else if (tokenIsAuto && !tokenNew) {
|
|
144
|
+
lines.push(
|
|
145
|
+
` 访问口令 Token : (已保存在 ${tokenFile ?? "状态目录"};也可在 DSH 设置页「连接移动端设备」查看 / saved in ${tokenFile ?? "the state folder"}; also shown in DSH settings)`,
|
|
146
|
+
);
|
|
95
147
|
} else if (tokenIsAuto) {
|
|
96
148
|
lines.push(` 访问口令 Token : ${token}`);
|
|
97
149
|
if (persistError) {
|
package/lib/backup.js
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 备份、恢复与「预演恢复」(P1-16)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要预演:恢复是一次**不可撤销的写入**,而用户手里的备份文件可能来自
|
|
5
|
+
* 另一台电脑、另一个版本、甚至是手改过的。让他在真写之前先看清「会写进去多少条、
|
|
6
|
+
* 跳过多少条、为什么跳过」,比事后提供一个「撤销」便宜得多。
|
|
7
|
+
*
|
|
8
|
+
* 为什么预演和真恢复必须是同一份计划:如果预演走一套判断、真恢复走另一套,
|
|
9
|
+
* 预演就变成了一句安慰话——它会说「将恢复 42 条」,而实际写进去 40 条。
|
|
10
|
+
* 所以两者都调 `planRestore()`,真恢复只是把计划执行一遍。
|
|
11
|
+
*
|
|
12
|
+
* **备份里没有凭据,这是刻意的**:
|
|
13
|
+
* - `auth-token`(连接口令)与 `relay/`(中继身份私钥)能让别人冒充这台电脑
|
|
14
|
+
* 或这个账号。备份文件通常被放进网盘、聊天记录、U 盘,一旦带上它们,
|
|
15
|
+
* 泄露面就从"一台机器"变成"所有存过备份的地方"。
|
|
16
|
+
* - `held-queue`(暂存待发消息)与 `send-receipts`(幂等回执)具有强时效性,
|
|
17
|
+
* 恢复到另一台设备只会产生重复投递与陈旧状态。
|
|
18
|
+
* 所以恢复之后需要在**新设备上重新扫码配对**——这是设计,不是缺陷,要说出来。
|
|
19
|
+
*
|
|
20
|
+
* 恢复是**只增不删**的:已有条目按 (scope, text) 判重后跳过,绝不因为备份里
|
|
21
|
+
* 没有某条就删掉本机现有的。这样即使用户拿错了备份文件,也不会丢东西。
|
|
22
|
+
*/
|
|
23
|
+
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
|
|
24
|
+
import { SCOPES } from "./memory/store.js";
|
|
25
|
+
import { parseHm } from "./notify-copy.js";
|
|
26
|
+
|
|
27
|
+
/** 文件里的格式标记。读到别的值说明这不是我们的备份,不要试着"尽力解析"。 */
|
|
28
|
+
export const BACKUP_FORMAT = "dsh-mobile-backup";
|
|
29
|
+
|
|
30
|
+
/** 版本号。将来改结构时递增,旧版本仍需可读。 */
|
|
31
|
+
export const BACKUP_VERSION = 1;
|
|
32
|
+
|
|
33
|
+
/** 单条记忆的长度上限,与 `/api/memory` 的写入校验保持一致。 */
|
|
34
|
+
const MAX_TEXT = 4000;
|
|
35
|
+
|
|
36
|
+
/** 一次恢复的条数上限:防止一个巨型/畸形文件把库灌满。 */
|
|
37
|
+
export const MAX_RESTORE_ITEMS = 5000;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Largest restore request body, in bytes (T-55, finding E5). The generic 64 KiB body limit made
|
|
41
|
+
* every real backup fail as "not valid JSON". 32 MiB holds MAX_RESTORE_ITEMS full-length items of
|
|
42
|
+
* ASCII text with room to spare; anything larger is refused with a 413 that says so.
|
|
43
|
+
*/
|
|
44
|
+
export const MAX_RESTORE_BODY_BYTES = 32 * 1024 * 1024;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 备份内容里**明确不包含**的东西。写进文件本身,让拿到备份的人一眼看到
|
|
48
|
+
* "这里面没有口令",而不是去猜。
|
|
49
|
+
*/
|
|
50
|
+
export const BACKUP_EXCLUDES = [
|
|
51
|
+
"auth-token(连接口令)",
|
|
52
|
+
"relay/(中继身份私钥与设备名单)",
|
|
53
|
+
"held-queue(暂存待发消息)",
|
|
54
|
+
"send-receipts(幂等回执)",
|
|
55
|
+
"session-titles / session-activity / session-message-time(与本机会话 id 绑定)",
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 生成备份对象。
|
|
60
|
+
*
|
|
61
|
+
* @param {object} e
|
|
62
|
+
* @param {object|null} e.store 记忆库(null = 记忆功能没开,仍可备份人格)
|
|
63
|
+
* @param {{get: () => object}} e.prefs 助手偏好
|
|
64
|
+
* @param {() => number} [e.now]
|
|
65
|
+
*/
|
|
66
|
+
export function buildBackup({ store, prefs, now = () => Date.now() }) {
|
|
67
|
+
const memories = store ? store.exportAll() : [];
|
|
68
|
+
return {
|
|
69
|
+
format: BACKUP_FORMAT,
|
|
70
|
+
version: BACKUP_VERSION,
|
|
71
|
+
createdAt: new Date(now()).toISOString(),
|
|
72
|
+
// 只备份"关于这个人"的数据:记忆 + 模式/人格/安静时段。
|
|
73
|
+
// 会话、任务、审批都是电脑上那一刻的状态,不属于可搬运的用户数据。
|
|
74
|
+
excludes: BACKUP_EXCLUDES,
|
|
75
|
+
assistant: prefs?.get?.() ?? null,
|
|
76
|
+
memories: memories.map((m) => ({
|
|
77
|
+
scope: m.scope,
|
|
78
|
+
text: m.text,
|
|
79
|
+
source: m.source === "manual" ? "manual" : "conversation",
|
|
80
|
+
origin: m.origin ?? null,
|
|
81
|
+
pinned: Boolean(m.pinned),
|
|
82
|
+
// 衰减参数一并带走:否则恢复后所有旧记忆都会被当成"刚记住",
|
|
83
|
+
// 到第 60 天集体消失一次——那不是恢复,是重置。
|
|
84
|
+
stability: typeof m.stability === "number" ? m.stability : undefined,
|
|
85
|
+
difficulty: typeof m.difficulty === "number" ? m.difficulty : undefined,
|
|
86
|
+
lastRecalledAt:
|
|
87
|
+
typeof m.lastRecalledAt === "number" ? m.lastRecalledAt : undefined,
|
|
88
|
+
// T-63:删掉的记忆不进备份(exportAll 只给现存的)。旧备份里带 `deleted: true`
|
|
89
|
+
// 的条目在恢复时仍会被跳过(见 validateMemory)。
|
|
90
|
+
})),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ── 备份口令(T-63,可选)────────────────────────────────────────────────
|
|
95
|
+
//
|
|
96
|
+
// 不设口令时备份是明文 JSON(原样可读,便于用户自己检查)。设了口令时整份备份用
|
|
97
|
+
// scrypt 派生的密钥做 AES-256-GCM 加密,文件里只剩格式标记与密文:拿到文件但不知道
|
|
98
|
+
// 口令的人读不到任何一条记忆。口令只在请求里出现一次,插件不保存它。
|
|
99
|
+
|
|
100
|
+
/** 口令最短长度。太短的口令配上离线暴力破解等于没设。 */
|
|
101
|
+
export const MIN_BACKUP_PASSPHRASE = 8;
|
|
102
|
+
|
|
103
|
+
const KDF = { name: "scrypt", N: 1 << 15, r: 8, p: 1, keyLen: 32 };
|
|
104
|
+
const deriveKey = (passphrase, salt, kdf = KDF) =>
|
|
105
|
+
scryptSync(String(passphrase).normalize("NFC"), salt, kdf.keyLen ?? 32, {
|
|
106
|
+
N: kdf.N,
|
|
107
|
+
r: kdf.r,
|
|
108
|
+
p: kdf.p,
|
|
109
|
+
maxmem: 256 * kdf.N * kdf.r + 1024 * 1024,
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
/** 备份文件是不是加了口令的。 */
|
|
113
|
+
export function isEncryptedBackup(payload) {
|
|
114
|
+
return Boolean(payload && typeof payload === "object" && payload.encrypted && typeof payload.encrypted === "object");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 给备份加口令。返回 `{ format, version, encrypted: {...} }`,可直接存成文件。
|
|
119
|
+
* @param {object} backup buildBackup 的结果
|
|
120
|
+
* @param {string} passphrase 至少 MIN_BACKUP_PASSPHRASE 个字符
|
|
121
|
+
*/
|
|
122
|
+
export function encryptBackup(backup, passphrase) {
|
|
123
|
+
if (typeof passphrase !== "string" || passphrase.length < MIN_BACKUP_PASSPHRASE) {
|
|
124
|
+
throw Object.assign(new Error(`口令至少 ${MIN_BACKUP_PASSPHRASE} 个字符 / the passphrase needs at least ${MIN_BACKUP_PASSPHRASE} characters`), { code: "weak-passphrase" });
|
|
125
|
+
}
|
|
126
|
+
const salt = randomBytes(16);
|
|
127
|
+
const iv = randomBytes(12);
|
|
128
|
+
const key = deriveKey(passphrase, salt);
|
|
129
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
130
|
+
// 格式标记作为附加认证数据:密文被挪到别的格式里会解不开。
|
|
131
|
+
cipher.setAAD(Buffer.from(`${BACKUP_FORMAT}/${BACKUP_VERSION}`));
|
|
132
|
+
const data = Buffer.concat([cipher.update(JSON.stringify(backup), "utf8"), cipher.final()]);
|
|
133
|
+
return {
|
|
134
|
+
format: BACKUP_FORMAT,
|
|
135
|
+
version: BACKUP_VERSION,
|
|
136
|
+
encrypted: {
|
|
137
|
+
kdf: { name: KDF.name, N: KDF.N, r: KDF.r, p: KDF.p, salt: salt.toString("base64") },
|
|
138
|
+
cipher: "aes-256-gcm",
|
|
139
|
+
iv: iv.toString("base64"),
|
|
140
|
+
tag: cipher.getAuthTag().toString("base64"),
|
|
141
|
+
data: data.toString("base64"),
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 解开加了口令的备份。口令不对、文件被改过、参数不认识都抛错(`code` 区分)。
|
|
148
|
+
* @returns {object} 原始备份对象(再交给 planRestore / applyRestore)
|
|
149
|
+
*/
|
|
150
|
+
export function decryptBackup(envelope, passphrase) {
|
|
151
|
+
const e = envelope?.encrypted;
|
|
152
|
+
if (!e || e.cipher !== "aes-256-gcm" || e.kdf?.name !== "scrypt") {
|
|
153
|
+
throw Object.assign(new Error("不认识的加密格式 / unknown encryption format"), { code: "bad-backup" });
|
|
154
|
+
}
|
|
155
|
+
if (typeof passphrase !== "string" || passphrase === "") {
|
|
156
|
+
throw Object.assign(new Error("这份备份设了口令 / this backup needs its passphrase"), { code: "passphrase-required" });
|
|
157
|
+
}
|
|
158
|
+
// 参数来自文件:只接受我们自己写的那一组。scryptSync 在事件循环上跑,放宽就等于让一个
|
|
159
|
+
// 恶意文件把插件卡住或吃光内存(T-63 fix)。
|
|
160
|
+
const N = Number(e.kdf.N);
|
|
161
|
+
const r = Number(e.kdf.r);
|
|
162
|
+
const p = Number(e.kdf.p);
|
|
163
|
+
if (N !== KDF.N || r !== KDF.r || p !== KDF.p) {
|
|
164
|
+
throw Object.assign(new Error("加密参数不是本插件写的 / encryption parameters not written by this plugin"), { code: "bad-backup" });
|
|
165
|
+
}
|
|
166
|
+
const tag = Buffer.from(String(e.tag), "base64");
|
|
167
|
+
if (tag.length !== 16) {
|
|
168
|
+
throw Object.assign(new Error("口令不对,或文件已损坏 / wrong passphrase, or the file is damaged"), { code: "bad-passphrase" });
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
const key = deriveKey(passphrase, Buffer.from(String(e.kdf.salt), "base64"), { N, r, p, keyLen: 32 });
|
|
172
|
+
// authTagLength: a truncated tag is refused instead of checked on fewer bits (DEP0182).
|
|
173
|
+
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(String(e.iv), "base64"), { authTagLength: 16 });
|
|
174
|
+
decipher.setAAD(Buffer.from(`${envelope.format}/${envelope.version}`));
|
|
175
|
+
decipher.setAuthTag(tag);
|
|
176
|
+
const plain = Buffer.concat([decipher.update(Buffer.from(String(e.data), "base64")), decipher.final()]);
|
|
177
|
+
return JSON.parse(plain.toString("utf8"));
|
|
178
|
+
} catch {
|
|
179
|
+
throw Object.assign(new Error("口令不对,或文件已损坏 / wrong passphrase, or the file is damaged"), { code: "bad-passphrase" });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 校验一条待恢复的记忆。返回 `{ ok: true, item }` 或 `{ ok: false, reason }`。
|
|
185
|
+
*
|
|
186
|
+
* 备份文件是外部输入,一律当作不可信:不信任任何字段的类型,也不信任长度。
|
|
187
|
+
*/
|
|
188
|
+
function validateMemory(raw, index) {
|
|
189
|
+
if (!raw || typeof raw !== "object") {
|
|
190
|
+
return { ok: false, reason: "不是对象", index };
|
|
191
|
+
}
|
|
192
|
+
const scope = raw.scope;
|
|
193
|
+
if (!SCOPES.includes(scope)) {
|
|
194
|
+
return { ok: false, reason: `scope 非法(${String(scope)})`, index };
|
|
195
|
+
}
|
|
196
|
+
if (typeof raw.text !== "string") {
|
|
197
|
+
return { ok: false, reason: "text 不是字符串", index };
|
|
198
|
+
}
|
|
199
|
+
const text = raw.text.trim();
|
|
200
|
+
if (text === "") return { ok: false, reason: "text 为空", index };
|
|
201
|
+
if (text.length > MAX_TEXT) {
|
|
202
|
+
return { ok: false, reason: `text 超过 ${MAX_TEXT} 字符`, index };
|
|
203
|
+
}
|
|
204
|
+
if (raw.deleted === true) {
|
|
205
|
+
// 旧版本的备份会带上软删除的条目:删掉的就是删掉了,不恢复。
|
|
206
|
+
return { ok: false, reason: "备份里这条已删除", index };
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
ok: true,
|
|
210
|
+
index,
|
|
211
|
+
item: {
|
|
212
|
+
scope,
|
|
213
|
+
text,
|
|
214
|
+
source: raw.source === "manual" ? "manual" : "conversation",
|
|
215
|
+
origin: typeof raw.origin === "string" ? raw.origin : null,
|
|
216
|
+
pinned: raw.pinned === true,
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* 算出「这次恢复会做什么」。纯函数:不写库、不改任何状态。
|
|
223
|
+
*
|
|
224
|
+
* @param {unknown} payload 备份文件解析后的对象
|
|
225
|
+
* @param {object} e
|
|
226
|
+
* @param {object|null} e.store
|
|
227
|
+
* @param {{get: () => object}} e.prefs
|
|
228
|
+
* @returns {{ok: boolean, error?: string, counts: object, items: object[], skipped: object[], assistant: object|null}}
|
|
229
|
+
*/
|
|
230
|
+
export function planRestore(payload, { store, prefs }) {
|
|
231
|
+
const empty = {
|
|
232
|
+
ok: false,
|
|
233
|
+
counts: { total: 0, willAdd: 0, willSkip: 0, invalid: 0 },
|
|
234
|
+
items: [],
|
|
235
|
+
skipped: [],
|
|
236
|
+
assistant: null,
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
if (!payload || typeof payload !== "object") {
|
|
240
|
+
return { ...empty, error: "备份内容不是对象" };
|
|
241
|
+
}
|
|
242
|
+
if (payload.format !== BACKUP_FORMAT) {
|
|
243
|
+
return {
|
|
244
|
+
...empty,
|
|
245
|
+
error: `不是 DSH Mobile 的备份(format=${String(payload.format)})`,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
if (!Number.isInteger(payload.version) || payload.version < 1) {
|
|
249
|
+
return { ...empty, error: "备份版本号缺失或非法" };
|
|
250
|
+
}
|
|
251
|
+
if (payload.version > BACKUP_VERSION) {
|
|
252
|
+
// 新版本备份可能带旧代码看不懂的字段。与其"尽力恢复"出一个半截状态,
|
|
253
|
+
// 不如明确拒绝并告诉用户升级插件。
|
|
254
|
+
return {
|
|
255
|
+
...empty,
|
|
256
|
+
error: `备份来自更新的版本(v${payload.version}),请先升级插件`,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
const rawList = payload.memories;
|
|
260
|
+
if (rawList !== undefined && !Array.isArray(rawList)) {
|
|
261
|
+
return { ...empty, error: "memories 不是数组" };
|
|
262
|
+
}
|
|
263
|
+
const list = Array.isArray(rawList) ? rawList : [];
|
|
264
|
+
if (list.length > MAX_RESTORE_ITEMS) {
|
|
265
|
+
return {
|
|
266
|
+
...empty,
|
|
267
|
+
error: `一次最多恢复 ${MAX_RESTORE_ITEMS} 条,这份备份有 ${list.length} 条`,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// 本机已有条目:按 (scope, text) 判重。用归一化后的文本比较——
|
|
272
|
+
// 否则「末尾多一个空格」会让同一条记忆被恢复成两条。
|
|
273
|
+
const existing = new Set();
|
|
274
|
+
if (store) {
|
|
275
|
+
for (const mode of ["work", "life"]) {
|
|
276
|
+
for (const m of store.listVisible(mode)) {
|
|
277
|
+
existing.add(`${m.scope}\u0000${m.text.trim()}`);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const items = [];
|
|
283
|
+
const skipped = [];
|
|
284
|
+
let invalid = 0;
|
|
285
|
+
const seenInFile = new Set();
|
|
286
|
+
|
|
287
|
+
list.forEach((raw, index) => {
|
|
288
|
+
const v = validateMemory(raw, index);
|
|
289
|
+
if (!v.ok) {
|
|
290
|
+
invalid += 1;
|
|
291
|
+
skipped.push({ index, reason: v.reason });
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const key = `${v.item.scope}\u0000${v.item.text}`;
|
|
295
|
+
if (seenInFile.has(key)) {
|
|
296
|
+
invalid += 1;
|
|
297
|
+
skipped.push({ index, reason: "备份文件内重复" });
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
seenInFile.add(key);
|
|
301
|
+
if (existing.has(key)) {
|
|
302
|
+
skipped.push({ index, reason: "本机已有同一条" });
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
items.push(v.item);
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
// 人格/模式:只在字段合法时恢复。非法就整块跳过,不"猜一个最近的"——
|
|
309
|
+
// 猜错会让用户以为恢复成功,实际还在原来的模式里。
|
|
310
|
+
let assistant = null;
|
|
311
|
+
const a = payload.assistant;
|
|
312
|
+
if (a && typeof a === "object") {
|
|
313
|
+
const next = {};
|
|
314
|
+
if (a.mode === "work" || a.mode === "life") next.mode = a.mode;
|
|
315
|
+
if (a.persona === "colleague" || a.persona === "character") {
|
|
316
|
+
next.persona = a.persona;
|
|
317
|
+
}
|
|
318
|
+
const q = a.quietHours;
|
|
319
|
+
// 用 `parseHm` 而不是手写正则:`/^\d{1,2}:\d{2}$/` 会放过 `25:00`,
|
|
320
|
+
// 而一个非法窗口恢复进去之后,安静时段会整段失效(或整段生效)——
|
|
321
|
+
// 用户会发现夜里突然被吵醒,却不知道是恢复带进来的。
|
|
322
|
+
if (
|
|
323
|
+
q &&
|
|
324
|
+
typeof q === "object" &&
|
|
325
|
+
parseHm(String(q.start)) !== null &&
|
|
326
|
+
parseHm(String(q.end)) !== null
|
|
327
|
+
) {
|
|
328
|
+
next.quietHours = { start: String(q.start), end: String(q.end) };
|
|
329
|
+
}
|
|
330
|
+
if (typeof a.breakReminder === "boolean") next.breakReminder = a.breakReminder;
|
|
331
|
+
if (typeof a.personaCard === "string" && /^[a-z0-9][a-z0-9-]{0,63}$/.test(a.personaCard)) next.personaCard = a.personaCard;
|
|
332
|
+
if (Object.keys(next).length > 0) assistant = next;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return {
|
|
336
|
+
ok: true,
|
|
337
|
+
backupVersion: payload.version,
|
|
338
|
+
createdAt: payload.createdAt ?? null,
|
|
339
|
+
counts: {
|
|
340
|
+
total: list.length,
|
|
341
|
+
willAdd: items.length,
|
|
342
|
+
willSkip: skipped.length,
|
|
343
|
+
invalid,
|
|
344
|
+
},
|
|
345
|
+
items,
|
|
346
|
+
skipped,
|
|
347
|
+
assistant,
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* 执行恢复:跑同一份计划,然后按计划写入。
|
|
353
|
+
*
|
|
354
|
+
* 只增不删——本机现有条目一条都不会因为这次恢复而消失。
|
|
355
|
+
*
|
|
356
|
+
* @returns {{ok: boolean, error?: string, added: number, skipped: number, invalid: number, assistant: boolean}}
|
|
357
|
+
*/
|
|
358
|
+
export function applyRestore(payload, { store, prefs }) {
|
|
359
|
+
const plan = planRestore(payload, { store, prefs });
|
|
360
|
+
if (!plan.ok) {
|
|
361
|
+
return {
|
|
362
|
+
ok: false,
|
|
363
|
+
error: plan.error,
|
|
364
|
+
added: 0,
|
|
365
|
+
skipped: 0,
|
|
366
|
+
invalid: 0,
|
|
367
|
+
assistant: false,
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
let added = 0;
|
|
371
|
+
if (store) {
|
|
372
|
+
for (const item of plan.items) {
|
|
373
|
+
try {
|
|
374
|
+
store.add({
|
|
375
|
+
scope: item.scope,
|
|
376
|
+
text: item.text,
|
|
377
|
+
source: item.source,
|
|
378
|
+
origin: item.origin,
|
|
379
|
+
pinned: item.pinned,
|
|
380
|
+
});
|
|
381
|
+
added += 1;
|
|
382
|
+
} catch (err) {
|
|
383
|
+
// 单条失败不该中断整次恢复:脱敏后为空、库写满都会走到这里。
|
|
384
|
+
plan.skipped.push({ index: -1, reason: err?.message ?? "写入失败" });
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
let assistant = false;
|
|
389
|
+
if (plan.assistant && prefs?.set) {
|
|
390
|
+
try {
|
|
391
|
+
prefs.set(plan.assistant);
|
|
392
|
+
assistant = true;
|
|
393
|
+
} catch {
|
|
394
|
+
// 人格恢复失败不影响记忆:两块分别报告,不混成一个"失败"。
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return {
|
|
398
|
+
ok: true,
|
|
399
|
+
added,
|
|
400
|
+
// 计划里的跳过 + 写入时失败的
|
|
401
|
+
skipped: plan.skipped.length,
|
|
402
|
+
invalid: plan.counts.invalid,
|
|
403
|
+
assistant,
|
|
404
|
+
};
|
|
405
|
+
}
|