@he0119/dsh-settings-sync 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.en.md +122 -0
- package/README.md +76 -2
- package/cordis.patch.yml +3 -0
- package/icon.svg +7 -0
- package/lib/client.js +1175 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +1346 -0
- package/lib/types/credential-sync.d.ts +55 -0
- package/lib/types/error.d.ts +2 -0
- package/lib/types/index.d.ts +37 -0
- package/lib/types/local-only.d.ts +30 -0
- package/lib/types/patch-view.d.ts +43 -0
- package/lib/types/settings-fields.d.ts +16 -0
- package/lib/types/settings-selection.d.ts +11 -0
- package/lib/types/snapshot.d.ts +23 -0
- package/lib/types/sync-scope.d.ts +15 -0
- package/lib/types/sync.d.ts +73 -0
- package/lib/types/web.d.ts +25 -0
- package/lib/types/webdav.d.ts +38 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +94 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,1346 @@
|
|
|
1
|
+
import { credentialRef, resolveCredentialRef } from "@deepseek-ai/dsh-credentials";
|
|
2
|
+
import { DOCUMENT_VERSION, LocalCredentialProvider, parseCredentialsDocument, resolveSpec } from "@deepseek-ai/dsh-credentials-local";
|
|
3
|
+
import Schema from "@deepseek-ai/schemastery";
|
|
4
|
+
import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
|
|
5
|
+
import { constants } from "node:fs";
|
|
6
|
+
import { lstat, open } from "node:fs/promises";
|
|
7
|
+
import { dirname, resolve } from "node:path";
|
|
8
|
+
import { isDeepStrictEqual } from "node:util";
|
|
9
|
+
import { parseDocument, stringify } from "yaml";
|
|
10
|
+
import { createCipheriv, createDecipheriv, createHmac, randomBytes } from "node:crypto";
|
|
11
|
+
// src/error.ts
|
|
12
|
+
/** An operation failure whose message is safe to return to the browser. */
|
|
13
|
+
var SyncError = class extends Error {};
|
|
14
|
+
// src/patch-view.ts
|
|
15
|
+
/** 内部路径分隔符:YAML 键里几乎不会出现,避免用点号时与键名里的点混淆。 */
|
|
16
|
+
const SEP = "";
|
|
17
|
+
function isPlainObject(value) {
|
|
18
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
19
|
+
}
|
|
20
|
+
function cloneValue(value) {
|
|
21
|
+
if (Array.isArray(value)) return value.map(cloneValue);
|
|
22
|
+
if (isPlainObject(value)) {
|
|
23
|
+
const result = {};
|
|
24
|
+
for (const [key, child] of Object.entries(value)) result[key] = cloneValue(child);
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
/** 是否是 `!!js` 表达式解析出来的形状(`{ __jsExpr: "..." }`)。 */
|
|
30
|
+
function isExpression(value) {
|
|
31
|
+
return isPlainObject(value) && Object.keys(value).length === 1 && typeof value.__jsExpr === "string";
|
|
32
|
+
}
|
|
33
|
+
/** 子树里是否含有 `!!js` 表达式。表达式可能引用本机路径或环境变量,默认不跨机器搬运。 */
|
|
34
|
+
function hasExpression(value) {
|
|
35
|
+
if (isExpression(value)) return true;
|
|
36
|
+
if (Array.isArray(value)) return value.some(hasExpression);
|
|
37
|
+
if (isPlainObject(value)) return Object.values(value).some(hasExpression);
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
/** 丢掉子树里含 `!!js` 表达式的键。 */
|
|
41
|
+
function stripExpressions(config) {
|
|
42
|
+
const result = {};
|
|
43
|
+
for (const [key, value] of Object.entries(config)) {
|
|
44
|
+
if (hasExpression(value)) continue;
|
|
45
|
+
result[key] = isPlainObject(value) ? stripExpressions(value) : cloneValue(value);
|
|
46
|
+
}
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
function removeAt(config, path, depth = 0) {
|
|
50
|
+
const key = path[depth];
|
|
51
|
+
if (key === void 0) return;
|
|
52
|
+
if (depth === path.length - 1) {
|
|
53
|
+
Reflect.deleteProperty(config, key);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const child = config[key];
|
|
57
|
+
if (!isPlainObject(child)) return;
|
|
58
|
+
removeAt(child, path, depth + 1);
|
|
59
|
+
if (Object.keys(child).length === 0) Reflect.deleteProperty(config, key);
|
|
60
|
+
}
|
|
61
|
+
/** 按路径移除子树(就地修改传入的副本)。 */
|
|
62
|
+
function stripPaths(config, paths) {
|
|
63
|
+
const result = cloneValue(config);
|
|
64
|
+
for (const path of paths) if (path.length) removeAt(result, path);
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
/** 路径段列表拼成内部键。 */
|
|
68
|
+
function pathKey(path) {
|
|
69
|
+
return path.join(SEP);
|
|
70
|
+
}
|
|
71
|
+
function splitKey(key) {
|
|
72
|
+
return key.split(SEP);
|
|
73
|
+
}
|
|
74
|
+
/** 把一段配置展开成「叶子路径 → 值」。数组、标量都是叶子;空对象不产生叶子。 */
|
|
75
|
+
function flattenConfig(config, prefix = [], out = /* @__PURE__ */ new Map()) {
|
|
76
|
+
if (isPlainObject(config) && Object.keys(config).length > 0) {
|
|
77
|
+
for (const [key, child] of Object.entries(config)) flattenConfig(child, [...prefix, key], out);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
if (isPlainObject(config)) return out;
|
|
81
|
+
out.set(pathKey(prefix), cloneValue(config));
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
function deepEqual(left, right) {
|
|
85
|
+
if (left === right) return true;
|
|
86
|
+
if (Array.isArray(left) && Array.isArray(right)) return left.length === right.length && left.every((item, index) => deepEqual(item, right[index]));
|
|
87
|
+
if (isPlainObject(left) && isPlainObject(right)) {
|
|
88
|
+
const keys = /* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)]);
|
|
89
|
+
for (const key of keys) {
|
|
90
|
+
if (!Object.hasOwn(left, key) || !Object.hasOwn(right, key)) return false;
|
|
91
|
+
if (!deepEqual(left[key], right[key])) return false;
|
|
92
|
+
}
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
/** 深合并:对象逐键合并,其它值(含数组)由后者整体替换。 */
|
|
98
|
+
function mergeConfig(base, overlay) {
|
|
99
|
+
if (!isPlainObject(base) || !isPlainObject(overlay)) return cloneValue(overlay);
|
|
100
|
+
const result = {};
|
|
101
|
+
for (const [key, value] of Object.entries(base)) result[key] = cloneValue(value);
|
|
102
|
+
for (const [key, value] of Object.entries(overlay)) {
|
|
103
|
+
const current = result[key];
|
|
104
|
+
result[key] = isPlainObject(current) && isPlainObject(value) ? mergeConfig(current, value) : cloneValue(value);
|
|
105
|
+
}
|
|
106
|
+
return result;
|
|
107
|
+
}
|
|
108
|
+
/** 写回一个叶子路径(`value` 为 undefined 时删除该键)。 */
|
|
109
|
+
function setPath(config, path, value) {
|
|
110
|
+
const result = cloneValue(config);
|
|
111
|
+
if (!path.length) return result;
|
|
112
|
+
let parent = result;
|
|
113
|
+
for (const key of path.slice(0, -1)) {
|
|
114
|
+
if (!isPlainObject(parent[key])) parent[key] = {};
|
|
115
|
+
parent = parent[key];
|
|
116
|
+
}
|
|
117
|
+
const leaf = path.at(-1);
|
|
118
|
+
if (value === void 0) Reflect.deleteProperty(parent, leaf);
|
|
119
|
+
else parent[leaf] = cloneValue(value);
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
/** 逐叶子比较两段配置;返回需要写入的路径。 */
|
|
123
|
+
function diffConfig(current, target) {
|
|
124
|
+
const left = flattenConfig(current);
|
|
125
|
+
const right = flattenConfig(target);
|
|
126
|
+
const changes = [];
|
|
127
|
+
for (const key of /* @__PURE__ */ new Set([...left.keys(), ...right.keys()])) {
|
|
128
|
+
const before = left.get(key);
|
|
129
|
+
const after = right.get(key);
|
|
130
|
+
if (deepEqual(before, after)) continue;
|
|
131
|
+
changes.push({
|
|
132
|
+
path: splitKey(key),
|
|
133
|
+
before,
|
|
134
|
+
after
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
return changes.sort((a, b) => pathKey(a.path) < pathKey(b.path) ? -1 : pathKey(a.path) > pathKey(b.path) ? 1 : 0);
|
|
138
|
+
}
|
|
139
|
+
/** 预览里的值描述:文本与数组不打印内容,避免把配置正文带出预览界面。 */
|
|
140
|
+
function displayValue(value) {
|
|
141
|
+
if (value === void 0) return "未设置";
|
|
142
|
+
if (Array.isArray(value)) return `列表(${value.length} 项)`;
|
|
143
|
+
if (typeof value === "string") return "文本值";
|
|
144
|
+
if (value === null) return "null";
|
|
145
|
+
if (typeof value === "object") return "对象";
|
|
146
|
+
return String(value);
|
|
147
|
+
}
|
|
148
|
+
/** 校验一段配置能不能进快照:必须是普通对象,且不能带表达式。 */
|
|
149
|
+
function assertSyncable(config) {
|
|
150
|
+
if (!isPlainObject(config)) throw new SyncError("配置内容不是可同步的对象。");
|
|
151
|
+
if (hasExpression(config)) throw new SyncError("配置里含 !!js 表达式,不能同步。");
|
|
152
|
+
}
|
|
153
|
+
/** 按路径裁剪配置树:`keep` 返回 false 的节点连同子树一起丢掉。 */
|
|
154
|
+
function stripWhere(config, keep) {
|
|
155
|
+
function walk(value, prefix) {
|
|
156
|
+
const result = {};
|
|
157
|
+
for (const [key, child] of Object.entries(value)) {
|
|
158
|
+
const path = [...prefix, key];
|
|
159
|
+
if (!keep(path)) continue;
|
|
160
|
+
result[key] = isPlainObject(child) ? walk(child, path) : cloneValue(child);
|
|
161
|
+
}
|
|
162
|
+
return result;
|
|
163
|
+
}
|
|
164
|
+
return walk(config, []);
|
|
165
|
+
}
|
|
166
|
+
function arrayPreview(value) {
|
|
167
|
+
const ids = value.map((item) => isPlainObject(item) && typeof item.id === "string" ? item.id : void 0);
|
|
168
|
+
if (value.length > 0 && ids.every((id) => id !== void 0)) return `${value.length} 项:${ids.join("、")}`;
|
|
169
|
+
if (value.every((item) => item === null || typeof item !== "object")) return `${value.length} 项:${value.map((item) => String(item)).join("、")}`;
|
|
170
|
+
return JSON.stringify(value) ?? "";
|
|
171
|
+
}
|
|
172
|
+
/** 同步范围里显示的一行值:折成单行、截断;对象用 JSON,数组取 id 或直接列元素。 */
|
|
173
|
+
function previewValue(value, limit = 300) {
|
|
174
|
+
if (value === void 0) return "";
|
|
175
|
+
const oneLine = (Array.isArray(value) ? arrayPreview(value) : typeof value === "string" ? value : JSON.stringify(value) ?? "").replace(/\s+/g, " ").trim();
|
|
176
|
+
const characters = [...oneLine];
|
|
177
|
+
return characters.length > limit ? `${characters.slice(0, limit - 1).join("")}…` : oneLine;
|
|
178
|
+
}
|
|
179
|
+
const HEADER = Buffer.from("DSH-settings-sync/1\n");
|
|
180
|
+
const IV_LENGTH = 12;
|
|
181
|
+
const TAG_LENGTH = 16;
|
|
182
|
+
const ENTRY_ID = /^[A-Za-z0-9_@][A-Za-z0-9_@/.-]{0,99}$/;
|
|
183
|
+
function encryptionKey(secret) {
|
|
184
|
+
if (secret === void 0 || !/^[0-9a-fA-F]{64}$/.test(secret)) throw new SyncError("同步密钥需要是 64 位十六进制字符。请检查两台设备的密钥配置。");
|
|
185
|
+
return Buffer.from(secret, "hex");
|
|
186
|
+
}
|
|
187
|
+
function isEntry(value) {
|
|
188
|
+
if (!Array.isArray(value) || value.length !== 2) return false;
|
|
189
|
+
const [id, config] = value;
|
|
190
|
+
if (typeof id !== "string" || !ENTRY_ID.test(id)) return false;
|
|
191
|
+
return typeof config === "object" && config !== null && !Array.isArray(config);
|
|
192
|
+
}
|
|
193
|
+
/** 凭据部分按本机凭据文件的格式校验一遍,避免把读不回来的内容写进快照。 */
|
|
194
|
+
function checkCredentials(credentials) {
|
|
195
|
+
if (typeof credentials !== "object" || credentials === null || Array.isArray(credentials)) throw new SyncError("快照里的凭据不是可读取的对象。");
|
|
196
|
+
const { refs, records } = credentials;
|
|
197
|
+
if (typeof refs !== "object" || refs === null || typeof records !== "object" || records === null) throw new SyncError("快照里的凭据不是可读取的对象。");
|
|
198
|
+
try {
|
|
199
|
+
parseCredentialsDocument(stringify({
|
|
200
|
+
version: DOCUMENT_VERSION,
|
|
201
|
+
refs,
|
|
202
|
+
records
|
|
203
|
+
}), "snapshot");
|
|
204
|
+
} catch {
|
|
205
|
+
throw new SyncError("快照里的凭据格式无效。");
|
|
206
|
+
}
|
|
207
|
+
return {
|
|
208
|
+
refs,
|
|
209
|
+
records
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function emptyCredentials() {
|
|
213
|
+
return {
|
|
214
|
+
refs: {},
|
|
215
|
+
records: {}
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function encodeSnapshot(contents, key) {
|
|
219
|
+
const { entries, credentials } = contents;
|
|
220
|
+
const pairs = [...entries].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
|
|
221
|
+
for (const [id, config] of pairs) {
|
|
222
|
+
if (!ENTRY_ID.test(id)) throw new SyncError("快照里的条目 ID 无效。");
|
|
223
|
+
assertSyncable(config);
|
|
224
|
+
}
|
|
225
|
+
if (!pairs.length && !Object.keys(credentials.refs).length && !Object.keys(credentials.records).length) throw new SyncError("没有可同步的配置或凭据。");
|
|
226
|
+
const plaintext = JSON.stringify({
|
|
227
|
+
entries: pairs,
|
|
228
|
+
credentials: checkCredentials(credentials)
|
|
229
|
+
});
|
|
230
|
+
if (HEADER.length + IV_LENGTH + TAG_LENGTH + Buffer.byteLength(plaintext) > 262144) throw new SyncError("同步快照超过 256 KiB。请把不参与同步的条目设为仅本机。");
|
|
231
|
+
const iv = randomBytes(IV_LENGTH);
|
|
232
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
233
|
+
cipher.setAAD(HEADER);
|
|
234
|
+
const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
235
|
+
return Buffer.concat([
|
|
236
|
+
HEADER,
|
|
237
|
+
iv,
|
|
238
|
+
cipher.getAuthTag(),
|
|
239
|
+
encrypted
|
|
240
|
+
]);
|
|
241
|
+
}
|
|
242
|
+
/** 解出快照里的配置条目和凭据。 */
|
|
243
|
+
function decodeSnapshot(bytes, key) {
|
|
244
|
+
try {
|
|
245
|
+
const offset = HEADER.length + IV_LENGTH + TAG_LENGTH;
|
|
246
|
+
if (bytes.length <= offset || bytes.length > 262144 || !bytes.subarray(0, HEADER.length).equals(HEADER)) throw new Error();
|
|
247
|
+
const decipher = createDecipheriv("aes-256-gcm", key, bytes.subarray(HEADER.length, HEADER.length + IV_LENGTH));
|
|
248
|
+
decipher.setAAD(HEADER);
|
|
249
|
+
decipher.setAuthTag(bytes.subarray(HEADER.length + IV_LENGTH, offset));
|
|
250
|
+
const plaintext = Buffer.concat([decipher.update(bytes.subarray(offset)), decipher.final()]);
|
|
251
|
+
const document = JSON.parse(plaintext.toString());
|
|
252
|
+
if (typeof document !== "object" || document === null) throw new Error();
|
|
253
|
+
const { entries, credentials } = document;
|
|
254
|
+
if (!Array.isArray(entries) || !entries.every(isEntry)) throw new Error();
|
|
255
|
+
return {
|
|
256
|
+
entries: new Map(entries),
|
|
257
|
+
credentials: checkCredentials(credentials ?? emptyCredentials())
|
|
258
|
+
};
|
|
259
|
+
} catch (error) {
|
|
260
|
+
if (error instanceof SyncError) throw error;
|
|
261
|
+
throw new SyncError("无法读取远端快照。请检查密钥是否相同,以及文件是否由本插件生成。");
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
// src/credential-sync.ts
|
|
265
|
+
const LOCAL_PARSE_ERROR = "无法解析本机凭据文件。请检查文件格式和版本。";
|
|
266
|
+
const SYNC_ERROR = "凭据同步未完成。请检查文件权限后重新预览。";
|
|
267
|
+
const SELECTION_ERROR = "凭据选择无效或已不可用。请重新预览。";
|
|
268
|
+
const PATH_ERROR = "凭据文件路径不能使用符号链接,且必须指向普通文件。";
|
|
269
|
+
const UTF8 = new TextDecoder("utf-8", { fatal: true });
|
|
270
|
+
/** 没有外面传入的摘要写法时,单独用的默认文案。 */
|
|
271
|
+
function defaultDescribe({ added, replaced }) {
|
|
272
|
+
return `新增 ${added} 项,覆盖同名凭据 ${replaced} 项。`;
|
|
273
|
+
}
|
|
274
|
+
async function statIfPresent(path) {
|
|
275
|
+
try {
|
|
276
|
+
return await lstat(path);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if (error.code !== "ENOENT") throw error;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
async function checkParents(filename) {
|
|
282
|
+
const parents = [];
|
|
283
|
+
for (let path = dirname(filename); dirname(path) !== path; path = dirname(path)) parents.push(path);
|
|
284
|
+
for (const path of parents.reverse()) {
|
|
285
|
+
const stat = await statIfPresent(path);
|
|
286
|
+
if (!stat) return false;
|
|
287
|
+
if (!stat.isDirectory()) throw new SyncError(PATH_ERROR);
|
|
288
|
+
}
|
|
289
|
+
return true;
|
|
290
|
+
}
|
|
291
|
+
async function readLocal(filename) {
|
|
292
|
+
try {
|
|
293
|
+
if (!await checkParents(filename)) return null;
|
|
294
|
+
const before = await statIfPresent(filename);
|
|
295
|
+
if (!before) return null;
|
|
296
|
+
if (!before.isFile()) throw new SyncError(PATH_ERROR);
|
|
297
|
+
const file = await open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
298
|
+
try {
|
|
299
|
+
const stat = await file.stat();
|
|
300
|
+
if (!stat.isFile() || stat.dev !== before.dev || stat.ino !== before.ino) throw new SyncError(PATH_ERROR);
|
|
301
|
+
if (process.platform !== "win32" && (stat.mode & 63) !== 0) throw new SyncError("本机凭据文件必须只允许所有者访问。请检查文件权限。");
|
|
302
|
+
const tooLarge = "本机凭据文件超过 256 KiB。";
|
|
303
|
+
if (stat.size > 262144) throw new SyncError(tooLarge);
|
|
304
|
+
const bytes = Buffer.alloc(262145);
|
|
305
|
+
let length = 0;
|
|
306
|
+
while (length < bytes.length) {
|
|
307
|
+
const { bytesRead } = await file.read(bytes, length, bytes.length - length, length);
|
|
308
|
+
if (!bytesRead) break;
|
|
309
|
+
length += bytesRead;
|
|
310
|
+
}
|
|
311
|
+
if (length > 262144) throw new SyncError(tooLarge);
|
|
312
|
+
return bytes.subarray(0, length);
|
|
313
|
+
} finally {
|
|
314
|
+
await file.close();
|
|
315
|
+
}
|
|
316
|
+
} catch (error) {
|
|
317
|
+
if (error instanceof SyncError) throw error;
|
|
318
|
+
throw new SyncError("无法读取本机凭据文件。请检查路径和权限后重试。");
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function parseLocal(bytes) {
|
|
322
|
+
try {
|
|
323
|
+
const text = bytes === null ? "" : UTF8.decode(bytes);
|
|
324
|
+
return {
|
|
325
|
+
text,
|
|
326
|
+
entries: parseCredentialsDocument(text, "local")
|
|
327
|
+
};
|
|
328
|
+
} catch {
|
|
329
|
+
throw new SyncError(LOCAL_PARSE_ERROR);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
function toEntries(credentials) {
|
|
333
|
+
return {
|
|
334
|
+
refs: new Map(Object.entries(credentials.refs)),
|
|
335
|
+
records: new Map(Object.entries(credentials.records))
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
function toCredentials(entries) {
|
|
339
|
+
return {
|
|
340
|
+
refs: Object.fromEntries(entries.refs),
|
|
341
|
+
records: Object.fromEntries(entries.records)
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
/** 把条目转成同步范围里用的名字:`ref:名字` / `record:记录标识`,并排好序。 */
|
|
345
|
+
function credentialNames(entries) {
|
|
346
|
+
return [...[...entries.refs.keys()].map((name) => `ref:${name}`), ...[...entries.records.keys()].map((name) => `record:${name}`)].sort();
|
|
347
|
+
}
|
|
348
|
+
function normalizeSelection(selection) {
|
|
349
|
+
if (!Array.isArray(selection) || selection.length === 0 || selection.length > 128) throw new SyncError(SELECTION_ERROR);
|
|
350
|
+
const unique = /* @__PURE__ */ new Set();
|
|
351
|
+
for (const name of selection) {
|
|
352
|
+
if (typeof name !== "string") throw new SyncError(SELECTION_ERROR);
|
|
353
|
+
unique.add(name);
|
|
354
|
+
}
|
|
355
|
+
return [...unique].sort();
|
|
356
|
+
}
|
|
357
|
+
function selectEntries(entries, selection) {
|
|
358
|
+
const names = new Set(selection);
|
|
359
|
+
const refs = new Map([...entries.refs].filter(([key]) => names.has(`ref:${key}`)));
|
|
360
|
+
const records = new Map([...entries.records].filter(([key]) => names.has(`record:${key}`)));
|
|
361
|
+
if (refs.size + records.size !== names.size) throw new SyncError(SELECTION_ERROR);
|
|
362
|
+
return {
|
|
363
|
+
refs,
|
|
364
|
+
records
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
function planMerge(source, destination) {
|
|
368
|
+
let added = 0;
|
|
369
|
+
let replaced = 0;
|
|
370
|
+
function changes(incoming, existing) {
|
|
371
|
+
const result = /* @__PURE__ */ new Map();
|
|
372
|
+
for (const [name, value] of incoming) {
|
|
373
|
+
if (!existing.has(name)) added++;
|
|
374
|
+
else if (!isDeepStrictEqual(value, existing.get(name))) replaced++;
|
|
375
|
+
else continue;
|
|
376
|
+
result.set(name, value);
|
|
377
|
+
}
|
|
378
|
+
return result;
|
|
379
|
+
}
|
|
380
|
+
const edits = {
|
|
381
|
+
refs: changes(source.refs, destination.refs),
|
|
382
|
+
records: changes(source.records, destination.records)
|
|
383
|
+
};
|
|
384
|
+
return {
|
|
385
|
+
added,
|
|
386
|
+
replaced,
|
|
387
|
+
edits
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
function mergeEntries(destination, edits) {
|
|
391
|
+
return {
|
|
392
|
+
refs: new Map([...destination.refs, ...edits.refs]),
|
|
393
|
+
records: new Map([...destination.records, ...edits.records])
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
function renderLocal(text, local, edits) {
|
|
397
|
+
try {
|
|
398
|
+
const tree = parseDocument(text, { intAsBigInt: true });
|
|
399
|
+
const foreignEntries = (value) => Object.entries(value ?? {}).filter(([key]) => ![
|
|
400
|
+
"version",
|
|
401
|
+
"refs",
|
|
402
|
+
"records"
|
|
403
|
+
].includes(key));
|
|
404
|
+
const foreign = foreignEntries(tree.toJS());
|
|
405
|
+
tree.setIn(["version"], DOCUMENT_VERSION);
|
|
406
|
+
for (const section of ["refs", "records"]) {
|
|
407
|
+
if (edits[section].size && tree.get(section) == null) tree.set(section, tree.createNode(/* @__PURE__ */ new Map()));
|
|
408
|
+
for (const [name, value] of edits[section]) tree.setIn([section, name], value);
|
|
409
|
+
}
|
|
410
|
+
const rendered = tree.toString();
|
|
411
|
+
const { refs, records } = parseCredentialsDocument(rendered, "local");
|
|
412
|
+
if (!isDeepStrictEqual({
|
|
413
|
+
refs,
|
|
414
|
+
records
|
|
415
|
+
}, mergeEntries(local, edits)) || !isDeepStrictEqual(foreign, foreignEntries(parseDocument(rendered, { intAsBigInt: true }).toJS()))) throw new Error();
|
|
416
|
+
return rendered;
|
|
417
|
+
} catch {
|
|
418
|
+
throw new SyncError("无法安全合并本机凭据文件。请检查文件格式和 YAML 别名。");
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
function checkSignal(signal) {
|
|
422
|
+
if (signal?.aborted) throw new SyncError("凭据同步已取消。请重新预览。");
|
|
423
|
+
}
|
|
424
|
+
/** 读出某个方向的来源端凭据:上传看本机文件,下载看远端快照里的那一份。 */
|
|
425
|
+
async function readCredentialSource(options) {
|
|
426
|
+
const { direction, filename, saved, signal } = options;
|
|
427
|
+
checkSignal(signal);
|
|
428
|
+
try {
|
|
429
|
+
return { entries: direction === "push" ? parseLocal(await readLocal(resolve(filename))).entries : toEntries(saved) };
|
|
430
|
+
} catch (error) {
|
|
431
|
+
if (error instanceof SyncError) throw error;
|
|
432
|
+
checkSignal(signal);
|
|
433
|
+
throw new SyncError(SYNC_ERROR);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* 跑一次凭据搬运:从本机凭据文件或远端快照里挑出选中的条目,合进另一边。
|
|
438
|
+
* 远端那一侧只是内存里的凭据,写进加密快照由调用方统一做,这里不碰网络。
|
|
439
|
+
*/
|
|
440
|
+
function createCredentialSync(shared) {
|
|
441
|
+
const busy = shared ?? { current: false };
|
|
442
|
+
return async function run(options) {
|
|
443
|
+
const { direction, filename: rawFilename, saved, signal } = options;
|
|
444
|
+
if (busy.current) throw new SyncError("上一轮同步还在运行。请等它结束后重新预览。");
|
|
445
|
+
busy.current = true;
|
|
446
|
+
try {
|
|
447
|
+
checkSignal(signal);
|
|
448
|
+
if (direction !== "push" && direction !== "pull") throw new SyncError("请选择上传或下载。");
|
|
449
|
+
const selection = normalizeSelection(options.selection);
|
|
450
|
+
const filename = resolve(rawFilename);
|
|
451
|
+
async function plan() {
|
|
452
|
+
checkSignal(signal);
|
|
453
|
+
const { text, entries: stored } = parseLocal(await readLocal(filename));
|
|
454
|
+
const remote = toEntries(saved);
|
|
455
|
+
const source = selectEntries(direction === "push" ? stored : remote, selection);
|
|
456
|
+
const target = direction === "push" ? remote : stored;
|
|
457
|
+
const { added, replaced, edits } = planMerge(source, target);
|
|
458
|
+
const summary = (options.describe ?? defaultDescribe)({
|
|
459
|
+
added,
|
|
460
|
+
replaced
|
|
461
|
+
});
|
|
462
|
+
const merged = mergeEntries(target, edits);
|
|
463
|
+
const file = direction === "push" ? void 0 : renderLocal(text, stored, edits);
|
|
464
|
+
if (file !== void 0 && Buffer.byteLength(file) > 262144) throw new SyncError("合并后的本机凭据文件超过 256 KiB。");
|
|
465
|
+
return {
|
|
466
|
+
summary,
|
|
467
|
+
edited: added + replaced > 0,
|
|
468
|
+
saved: toCredentials(merged),
|
|
469
|
+
file
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
if (direction === "pull") {
|
|
473
|
+
if (!await checkParents(filename)) throw new SyncError("本机凭据文件所在目录不存在。");
|
|
474
|
+
const lock = await statIfPresent(`${filename}.lock`);
|
|
475
|
+
if (lock && (!lock.isFile() || lock.size > 64)) throw new SyncError("本机凭据文件的写入锁无效。");
|
|
476
|
+
return await withFileLock(filename, async () => {
|
|
477
|
+
const outcome = await plan();
|
|
478
|
+
if (outcome.file !== void 0 && !options.dryRun) {
|
|
479
|
+
checkSignal(signal);
|
|
480
|
+
await writeFileAtomic(filename, outcome.file, {
|
|
481
|
+
mode: 384,
|
|
482
|
+
dirMode: 448
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
return outcome;
|
|
486
|
+
}, {
|
|
487
|
+
signal,
|
|
488
|
+
waitMs: 3e4
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
return await plan();
|
|
492
|
+
} catch (error) {
|
|
493
|
+
if (error instanceof SyncError) throw error;
|
|
494
|
+
checkSignal(signal);
|
|
495
|
+
throw new SyncError(error.code === "FILE_LOCK_TIMEOUT" ? "本机凭据文件正在写入。请等写入结束后重新预览。" : SYNC_ERROR);
|
|
496
|
+
} finally {
|
|
497
|
+
busy.current = false;
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
// src/local-only.ts
|
|
502
|
+
const ENTRY = /^[A-Za-z0-9_@][A-Za-z0-9_@/.-]*$/;
|
|
503
|
+
/** 把 `条目ID:键.路径` 拆成段;没有冒号时只有条目本身。 */
|
|
504
|
+
function idSegments(id) {
|
|
505
|
+
const separator = id.indexOf(":");
|
|
506
|
+
if (separator < 0) return [id];
|
|
507
|
+
return [id.slice(0, separator), ...id.slice(separator + 1).split(".")];
|
|
508
|
+
}
|
|
509
|
+
/** 段列表拼回节点 ID。 */
|
|
510
|
+
function nodeId(segments) {
|
|
511
|
+
const [entry, ...path] = segments;
|
|
512
|
+
return path.length ? `${entry}:${path.join(".")}` : entry;
|
|
513
|
+
}
|
|
514
|
+
function isPrefix(prefix, target) {
|
|
515
|
+
return prefix.length <= target.length && prefix.every((segment, index) => target[index] === segment);
|
|
516
|
+
}
|
|
517
|
+
function parseRule(raw) {
|
|
518
|
+
const include = raw.startsWith("+");
|
|
519
|
+
const body = include ? raw.slice(1) : raw;
|
|
520
|
+
const separator = body.indexOf(":");
|
|
521
|
+
const entry = separator < 0 ? body : body.slice(0, separator);
|
|
522
|
+
const path = separator < 0 ? [] : body.slice(separator + 1).split(".");
|
|
523
|
+
if (entry.length > 100 || !ENTRY.test(entry)) return void 0;
|
|
524
|
+
if (path.some((segment) => segment.length === 0 || /[\u0000-\u001f]/.test(segment))) return void 0;
|
|
525
|
+
return {
|
|
526
|
+
raw,
|
|
527
|
+
include,
|
|
528
|
+
segments: [entry, ...path]
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
function localOnlyState(rules) {
|
|
532
|
+
const parsed = [];
|
|
533
|
+
const invalid = [];
|
|
534
|
+
for (const raw of rules) {
|
|
535
|
+
const rule = parseRule(raw);
|
|
536
|
+
if (rule === void 0) invalid.push(raw);
|
|
537
|
+
else parsed.push(rule);
|
|
538
|
+
}
|
|
539
|
+
function nearest(id) {
|
|
540
|
+
const target = idSegments(id);
|
|
541
|
+
let best;
|
|
542
|
+
for (const rule of parsed) {
|
|
543
|
+
if (!isPrefix(rule.segments, target)) continue;
|
|
544
|
+
if (best === void 0 || rule.segments.length > best.segments.length || rule.segments.length === best.segments.length && rule.include) best = rule;
|
|
545
|
+
}
|
|
546
|
+
return best;
|
|
547
|
+
}
|
|
548
|
+
return {
|
|
549
|
+
invalid,
|
|
550
|
+
isLocalOnly: (id) => {
|
|
551
|
+
const rule = nearest(id);
|
|
552
|
+
return rule !== void 0 && !rule.include;
|
|
553
|
+
},
|
|
554
|
+
reasonFor: (id) => nearest(id)?.raw
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
/** 找出在本机配置里找不到对应节点的规则;写法不合法的也算在里面,让页面能提示并移除。 */
|
|
558
|
+
function staleRules(rules, leaves) {
|
|
559
|
+
return rules.filter((raw) => {
|
|
560
|
+
const rule = parseRule(raw);
|
|
561
|
+
return rule === void 0 || !leaves.some((leaf) => isPrefix(rule.segments, leaf));
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
// src/web.ts
|
|
565
|
+
const PATH = "/api/dsh-settings-sync/run";
|
|
566
|
+
const MAX_BODY_BYTES = 1024;
|
|
567
|
+
const MAX_CREDENTIAL_BODY_BYTES = 262144;
|
|
568
|
+
function json(res, status, body) {
|
|
569
|
+
if (res.destroyed) return;
|
|
570
|
+
res.writeHead(status, {
|
|
571
|
+
"content-type": "application/json; charset=utf-8",
|
|
572
|
+
"cache-control": "no-store"
|
|
573
|
+
});
|
|
574
|
+
res.end(JSON.stringify(body));
|
|
575
|
+
}
|
|
576
|
+
async function readJson(req) {
|
|
577
|
+
let size = 0;
|
|
578
|
+
const chunks = [];
|
|
579
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
580
|
+
size += chunk.length;
|
|
581
|
+
if (size > MAX_CREDENTIAL_BODY_BYTES) return {
|
|
582
|
+
input: void 0,
|
|
583
|
+
size
|
|
584
|
+
};
|
|
585
|
+
chunks.push(chunk);
|
|
586
|
+
}
|
|
587
|
+
try {
|
|
588
|
+
return {
|
|
589
|
+
input: JSON.parse(Buffer.concat(chunks).toString()),
|
|
590
|
+
size
|
|
591
|
+
};
|
|
592
|
+
} catch {
|
|
593
|
+
return {
|
|
594
|
+
input: void 0,
|
|
595
|
+
size
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
function registerSyncRoute(webServer, runSync, autoStatus, listCredentials, listSettings) {
|
|
600
|
+
return webServer.register({
|
|
601
|
+
kind: "exact",
|
|
602
|
+
path: PATH,
|
|
603
|
+
auth: "required",
|
|
604
|
+
async handler(req, res) {
|
|
605
|
+
const readStatus = req.method === "GET" && autoStatus !== void 0;
|
|
606
|
+
if (req.method !== "POST" && !readStatus) {
|
|
607
|
+
res.setHeader("allow", autoStatus ? "GET, POST" : "POST");
|
|
608
|
+
return json(res, 405, { error: "请求方式无效。" });
|
|
609
|
+
}
|
|
610
|
+
const site = req.headers["sec-fetch-site"];
|
|
611
|
+
if (site && site !== "same-origin" || req.headers["x-dsh-settings-sync"] !== "1") return json(res, 403, { error: "请从 DSH 插件详情页发起同步。" });
|
|
612
|
+
if (readStatus) return json(res, 200, { summary: autoStatus() });
|
|
613
|
+
if (req.headers["content-type"]?.split(";")[0].trim() !== "application/json") return json(res, 415, { error: "同步请求需要使用 JSON。" });
|
|
614
|
+
const cancellation = new AbortController();
|
|
615
|
+
res.once("close", () => cancellation.abort());
|
|
616
|
+
try {
|
|
617
|
+
const { input, size } = await readJson(req);
|
|
618
|
+
const direction = input && typeof input === "object" && "direction" in input ? input.direction : void 0;
|
|
619
|
+
const confirmation = input && typeof input === "object" && "confirmation" in input ? input.confirmation : void 0;
|
|
620
|
+
const scope = input && typeof input === "object" && "scope" in input ? input.scope : void 0;
|
|
621
|
+
const action = input && typeof input === "object" && "action" in input ? input.action : void 0;
|
|
622
|
+
const selection = input && typeof input === "object" && "selection" in input ? input.selection : void 0;
|
|
623
|
+
if (direction !== "push" && direction !== "pull" || scope !== void 0 && scope !== "settings" && scope !== "credentials" || action !== void 0 && action !== "list" || action === "list" && (confirmation !== void 0 || selection !== void 0 || (scope === "credentials" ? !listCredentials : scope !== "settings" || !listSettings || direction !== "push")) || action === void 0 && scope === "credentials" && (!Array.isArray(selection) || selection.length < 1 || selection.length > 128 || !selection.every((item) => typeof item === "string")) || scope !== "credentials" && selection !== void 0 || scope !== "credentials" && size > MAX_BODY_BYTES || confirmation !== void 0 && (typeof confirmation !== "string" || !/^[a-f0-9]{64}$/.test(confirmation))) return json(res, 400, { error: "同步请求格式无效。" });
|
|
624
|
+
if (action === "list" && scope === "settings" && listSettings) return json(res, 200, await listSettings());
|
|
625
|
+
if (action === "list" && listCredentials) return json(res, 200, await listCredentials(direction, cancellation.signal));
|
|
626
|
+
return json(res, 200, await runSync({
|
|
627
|
+
direction,
|
|
628
|
+
confirmation,
|
|
629
|
+
scope,
|
|
630
|
+
selection: Array.isArray(selection) ? selection : void 0
|
|
631
|
+
}, cancellation.signal, "web"));
|
|
632
|
+
} catch (error) {
|
|
633
|
+
if (!cancellation.signal.aborted) {
|
|
634
|
+
const message = error instanceof SyncError ? error.message : "同步请求未能完成。请检查设置后重新预览。";
|
|
635
|
+
return json(res, error instanceof SyncError ? 422 : 500, { error: message });
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
// src/webdav.ts
|
|
642
|
+
const STRONG_ETAG = /^"[\x21\x23-\x7e]*"$/;
|
|
643
|
+
function requireFileVersion(previous) {
|
|
644
|
+
if (previous !== null && !STRONG_ETAG.test(previous.etag ?? "")) throw new SyncError("服务器没有返回可用于防覆盖的文件版本标记(强 ETag)。请检查 WebDAV 服务配置。");
|
|
645
|
+
}
|
|
646
|
+
/** 远端快照固定放在这一层目录里,用户填的地址当作它的上级。 */
|
|
647
|
+
const SYNC_DIRECTORY = "dsh-settings-sync";
|
|
648
|
+
/** 快照文件名。 */
|
|
649
|
+
const SNAPSHOT_FILE = "dsh-settings.bin";
|
|
650
|
+
/** 用户填写的地点是上级目录,没写结尾斜杠也当成文件夹:`…/dav` 与 `…/dav/` 是同一个地方。 */
|
|
651
|
+
function folderUrl(value) {
|
|
652
|
+
let url;
|
|
653
|
+
try {
|
|
654
|
+
url = new URL(value);
|
|
655
|
+
} catch {
|
|
656
|
+
throw new SyncError("请在插件的「同步配置」面板填写并保存 WebDAV 地址。");
|
|
657
|
+
}
|
|
658
|
+
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) throw new SyncError("请输入 HTTPS 地址。地址中不能带用户名、密码、查询参数或片段。");
|
|
659
|
+
if (!url.pathname.endsWith("/")) url.pathname += "/";
|
|
660
|
+
return url;
|
|
661
|
+
}
|
|
662
|
+
/** 插件自己那一层目录的地址;上传前不存在就建出来。 */
|
|
663
|
+
function syncDirectoryUrl(value) {
|
|
664
|
+
const url = folderUrl(value);
|
|
665
|
+
url.pathname += `${SYNC_DIRECTORY}/`;
|
|
666
|
+
return url;
|
|
667
|
+
}
|
|
668
|
+
/** 快照文件的地址。 */
|
|
669
|
+
function snapshotUrl(value) {
|
|
670
|
+
const url = syncDirectoryUrl(value);
|
|
671
|
+
url.pathname += SNAPSHOT_FILE;
|
|
672
|
+
return url;
|
|
673
|
+
}
|
|
674
|
+
async function readBounded(response) {
|
|
675
|
+
if (!response.body) return Buffer.alloc(0);
|
|
676
|
+
const reader = response.body.getReader();
|
|
677
|
+
const chunks = [];
|
|
678
|
+
let bytes = 0;
|
|
679
|
+
try {
|
|
680
|
+
if (Number(response.headers.get("content-length")) > 262144) throw new SyncError("远端快照超过 256 KiB。");
|
|
681
|
+
for (;;) {
|
|
682
|
+
const { done, value } = await reader.read();
|
|
683
|
+
if (done) break;
|
|
684
|
+
bytes += value.byteLength;
|
|
685
|
+
if (bytes > 262144) throw new SyncError("远端快照超过 256 KiB。");
|
|
686
|
+
chunks.push(value);
|
|
687
|
+
}
|
|
688
|
+
return Buffer.concat(chunks, bytes);
|
|
689
|
+
} finally {
|
|
690
|
+
await reader.cancel().catch(() => {});
|
|
691
|
+
reader.releaseLock();
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
/** 目录建好之后重试的那一次,状态码照样要检查。 */
|
|
695
|
+
function checkedPut(status) {
|
|
696
|
+
if ([
|
|
697
|
+
200,
|
|
698
|
+
201,
|
|
699
|
+
204
|
|
700
|
+
].includes(status)) return;
|
|
701
|
+
if (status === 412) throw new SyncError("远端文件已变化。请重新预览。");
|
|
702
|
+
throw new SyncError(`写入 WebDAV 失败(HTTP ${status})。`);
|
|
703
|
+
}
|
|
704
|
+
function webdav(url, { username, password, signal, fetcher = fetch, directory }) {
|
|
705
|
+
const auth = username ? "Basic " + Buffer.from(`${username}:${password}`).toString("base64") : void 0;
|
|
706
|
+
async function request(method, headers = {}, body) {
|
|
707
|
+
try {
|
|
708
|
+
return await fetcher(url, {
|
|
709
|
+
method,
|
|
710
|
+
body,
|
|
711
|
+
signal,
|
|
712
|
+
redirect: "error",
|
|
713
|
+
cache: "no-store",
|
|
714
|
+
headers: auth ? {
|
|
715
|
+
...headers,
|
|
716
|
+
authorization: auth
|
|
717
|
+
} : headers
|
|
718
|
+
});
|
|
719
|
+
} catch {
|
|
720
|
+
throw new SyncError("无法连接 WebDAV。请检查文件地址、证书、服务器是否重定向,以及网络连接。");
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
/** 逐层建出插件自己那一层目录;已经存在(405)不算错,其它状态如实报错。 */
|
|
724
|
+
async function ensureCollection() {
|
|
725
|
+
if (directory === void 0) return false;
|
|
726
|
+
const segments = directory.pathname.split("/").filter((part) => part !== "");
|
|
727
|
+
for (let index = 1; index <= segments.length; index++) {
|
|
728
|
+
const target = new URL(directory.href);
|
|
729
|
+
target.pathname = `/${segments.slice(0, index).join("/")}/`;
|
|
730
|
+
const response = await fetcher(target, {
|
|
731
|
+
method: "MKCOL",
|
|
732
|
+
signal,
|
|
733
|
+
redirect: "error",
|
|
734
|
+
cache: "no-store",
|
|
735
|
+
headers: auth ? { authorization: auth } : {}
|
|
736
|
+
});
|
|
737
|
+
await response.body?.cancel().catch(() => {});
|
|
738
|
+
if (response.status === 201 || response.status === 405 || response.status === 200 || response.status === 204) continue;
|
|
739
|
+
if (response.status === 401 || response.status === 403) throw new SyncError("服务器不允许在这个位置建同步文件夹。请检查 WebDAV 账号权限。");
|
|
740
|
+
throw new SyncError(`建同步文件夹失败(HTTP ${response.status})。`);
|
|
741
|
+
}
|
|
742
|
+
return true;
|
|
743
|
+
}
|
|
744
|
+
return {
|
|
745
|
+
async read() {
|
|
746
|
+
const response = await request("GET");
|
|
747
|
+
if (response.status === 200) return {
|
|
748
|
+
bytes: await readBounded(response),
|
|
749
|
+
etag: response.headers.get("etag")
|
|
750
|
+
};
|
|
751
|
+
await response.body?.cancel();
|
|
752
|
+
if (response.status === 404) return null;
|
|
753
|
+
throw new SyncError(`读取 WebDAV 失败(HTTP ${response.status})。`);
|
|
754
|
+
},
|
|
755
|
+
async write(bytes, previous) {
|
|
756
|
+
requireFileVersion(previous);
|
|
757
|
+
const put = async () => {
|
|
758
|
+
const response = await request("PUT", {
|
|
759
|
+
...previous === null ? { "if-none-match": "*" } : { "if-match": previous.etag },
|
|
760
|
+
"content-type": "application/octet-stream"
|
|
761
|
+
}, bytes);
|
|
762
|
+
await response.body?.cancel().catch(() => {});
|
|
763
|
+
return response.status;
|
|
764
|
+
};
|
|
765
|
+
const status = await put();
|
|
766
|
+
if ([
|
|
767
|
+
200,
|
|
768
|
+
201,
|
|
769
|
+
204
|
|
770
|
+
].includes(status)) return;
|
|
771
|
+
if (status === 412) throw new SyncError("远端文件已变化。请重新预览。");
|
|
772
|
+
if (status === 409 && await ensureCollection()) return put().then((retried) => checkedPut(retried));
|
|
773
|
+
throw new SyncError(`写入 WebDAV 失败(HTTP ${status})。`);
|
|
774
|
+
}
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
// src/sync.ts
|
|
778
|
+
/** 预览与结果里代表「凭据」这一项的名字。 */
|
|
779
|
+
const FILE_MARKER = "凭据文件";
|
|
780
|
+
const identity = (config) => config;
|
|
781
|
+
const BASELINE_SEP = "";
|
|
782
|
+
const MAX_PREVIEW_LINES = 20;
|
|
783
|
+
function filterAll(entries, filter) {
|
|
784
|
+
const result = /* @__PURE__ */ new Map();
|
|
785
|
+
for (const [id, config] of entries) {
|
|
786
|
+
const next = filter(config, id);
|
|
787
|
+
if (Object.keys(next).length) result.set(id, next);
|
|
788
|
+
}
|
|
789
|
+
return result;
|
|
790
|
+
}
|
|
791
|
+
/** 配置与凭据各自的确认值拼成一个:任何一半变了,整体都对不上。 */
|
|
792
|
+
function combinedConfirmation(settings, credentials) {
|
|
793
|
+
return credentials ? createHmac("sha256", settings).update(credentials).digest("hex") : settings;
|
|
794
|
+
}
|
|
795
|
+
/** 凭据那一半给出的计划要不要真的动:换过内容,或者要写本机文件。 */
|
|
796
|
+
function credentialWorkOf(plan) {
|
|
797
|
+
return plan !== null && plan.edited === true;
|
|
798
|
+
}
|
|
799
|
+
/** 没传凭据那一半时不追加任何东西。 */
|
|
800
|
+
function withCredentialsPart(settings, credentials) {
|
|
801
|
+
if (credentials === null) return settings;
|
|
802
|
+
const separator = settings.summary.endsWith("\n") ? "" : "\n";
|
|
803
|
+
return {
|
|
804
|
+
summary: `${settings.summary}${separator}${credentials.summary ?? ""}`,
|
|
805
|
+
changed: [...settings.changed, ...credentials.changed ?? []],
|
|
806
|
+
applied: [...settings.applied, ...credentials.applied ?? []]
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
const withCredentials = withCredentialsPart;
|
|
810
|
+
function changeId({ id, path }) {
|
|
811
|
+
return nodeId([id, ...path]);
|
|
812
|
+
}
|
|
813
|
+
function planPush(local, remote) {
|
|
814
|
+
const changes = [];
|
|
815
|
+
for (const [id, config] of [...local].sort(([left], [right]) => left < right ? -1 : 1)) for (const change of diffConfig(remote.get(id) ?? {}, config)) changes.push({
|
|
816
|
+
id,
|
|
817
|
+
...change
|
|
818
|
+
});
|
|
819
|
+
return changes;
|
|
820
|
+
}
|
|
821
|
+
function planPull(local, remote) {
|
|
822
|
+
const changes = [];
|
|
823
|
+
for (const [id, config] of [...remote].sort(([left], [right]) => left < right ? -1 : 1)) for (const change of diffConfig(local.get(id) ?? {}, config)) changes.push({
|
|
824
|
+
id,
|
|
825
|
+
...change
|
|
826
|
+
});
|
|
827
|
+
return changes;
|
|
828
|
+
}
|
|
829
|
+
function summarize(changes) {
|
|
830
|
+
const lines = changes.slice(0, MAX_PREVIEW_LINES).map((change) => `- ${changeId(change)}(${displayValue(change.before)} → ${displayValue(change.after)})`);
|
|
831
|
+
if (changes.length > lines.length) lines.push(`- 另有 ${changes.length - lines.length} 项`);
|
|
832
|
+
return lines;
|
|
833
|
+
}
|
|
834
|
+
function overlayFor(changes) {
|
|
835
|
+
const overlay = /* @__PURE__ */ new Map();
|
|
836
|
+
for (const { id, path, after } of changes) {
|
|
837
|
+
const config = overlay.get(id) ?? {};
|
|
838
|
+
overlay.set(id, setPath(config, path, after));
|
|
839
|
+
}
|
|
840
|
+
return overlay;
|
|
841
|
+
}
|
|
842
|
+
function entryCount(changes) {
|
|
843
|
+
return new Set(changes.map((change) => change.id)).size;
|
|
844
|
+
}
|
|
845
|
+
function createSync(access, shared) {
|
|
846
|
+
const confirmationSecret = randomBytes(32);
|
|
847
|
+
const busy = shared ?? { current: false };
|
|
848
|
+
let target;
|
|
849
|
+
const baseline = /* @__PURE__ */ new Map();
|
|
850
|
+
async function applyPull(changes, rawLocal, remote, signal, checkActive) {
|
|
851
|
+
const applied = [];
|
|
852
|
+
const overlay = overlayFor(changes);
|
|
853
|
+
for (const [id, config] of [...overlay].sort(([left], [right]) => left < right ? -1 : 1)) {
|
|
854
|
+
const next = mergeConfig(rawLocal.get(id) ?? {}, config);
|
|
855
|
+
signal?.throwIfAborted();
|
|
856
|
+
checkActive?.();
|
|
857
|
+
try {
|
|
858
|
+
await access.write(id, next);
|
|
859
|
+
} catch (error) {
|
|
860
|
+
return {
|
|
861
|
+
applied,
|
|
862
|
+
failure: {
|
|
863
|
+
id,
|
|
864
|
+
reason: error instanceof SyncError ? error.message : void 0
|
|
865
|
+
}
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
applied.push(...changes.filter((change) => change.id === id).map(changeId));
|
|
869
|
+
}
|
|
870
|
+
return { applied };
|
|
871
|
+
}
|
|
872
|
+
function fullKey(id, path) {
|
|
873
|
+
return `${id}${BASELINE_SEP}${path}`;
|
|
874
|
+
}
|
|
875
|
+
async function autoSync(rawLocal, local, remote, transport, snapshot, key, signal, checkActive, credentials = emptyCredentials()) {
|
|
876
|
+
const push = [];
|
|
877
|
+
const pull = [];
|
|
878
|
+
const conflicts = [];
|
|
879
|
+
for (const id of /* @__PURE__ */ new Set([...local.keys(), ...remote.keys()])) {
|
|
880
|
+
const left = flattenConfig(local.get(id) ?? {});
|
|
881
|
+
const right = flattenConfig(remote.get(id) ?? {});
|
|
882
|
+
for (const path of /* @__PURE__ */ new Set([...left.keys(), ...right.keys()])) {
|
|
883
|
+
const localValue = left.get(path);
|
|
884
|
+
const remoteValue = right.get(path);
|
|
885
|
+
const known = baseline.get(fullKey(id, path));
|
|
886
|
+
if (deepEqual(localValue, remoteValue)) {
|
|
887
|
+
if (localValue !== void 0) baseline.set(fullKey(id, path), localValue);
|
|
888
|
+
continue;
|
|
889
|
+
}
|
|
890
|
+
const segments = path.split(BASELINE_SEP);
|
|
891
|
+
if (known === void 0) conflicts.push(nodeId([id, ...segments]));
|
|
892
|
+
else if (deepEqual(remoteValue, known)) push.push({
|
|
893
|
+
id,
|
|
894
|
+
path: segments,
|
|
895
|
+
before: remoteValue,
|
|
896
|
+
after: localValue
|
|
897
|
+
});
|
|
898
|
+
else if (deepEqual(localValue, known)) pull.push({
|
|
899
|
+
id,
|
|
900
|
+
path: segments,
|
|
901
|
+
before: localValue,
|
|
902
|
+
after: remoteValue
|
|
903
|
+
});
|
|
904
|
+
else conflicts.push(nodeId([id, ...segments]));
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
if (pull.length) {
|
|
908
|
+
const { applied, failure } = await applyPull(pull, rawLocal, remote, signal, checkActive);
|
|
909
|
+
if (failure) throw new SyncError(`自动下载在「${failure.id}」处中断。${failure.reason ?? "请检查本机配置。"}`);
|
|
910
|
+
for (const change of pull) if (change.after !== void 0) baseline.set(fullKey(change.id, change.path.join(BASELINE_SEP)), change.after);
|
|
911
|
+
}
|
|
912
|
+
if (push.length) {
|
|
913
|
+
signal?.throwIfAborted();
|
|
914
|
+
checkActive?.();
|
|
915
|
+
const merged = new Map(remote);
|
|
916
|
+
for (const [id, config] of overlayFor(push)) merged.set(id, mergeConfig(remote.get(id) ?? {}, config));
|
|
917
|
+
await transport.write(encodeSnapshot({
|
|
918
|
+
entries: merged,
|
|
919
|
+
credentials
|
|
920
|
+
}, key), snapshot);
|
|
921
|
+
for (const change of push) if (change.after !== void 0) baseline.set(fullKey(change.id, change.path.join(BASELINE_SEP)), change.after);
|
|
922
|
+
}
|
|
923
|
+
const notes = conflicts.length ? `需要手动确认:${conflicts.slice(0, MAX_PREVIEW_LINES).join("、")}${conflicts.length > MAX_PREVIEW_LINES ? " 等" : ""}。` : "";
|
|
924
|
+
return { summary: `自动同步上传 ${push.length} 项,下载 ${pull.length} 项。${notes}` };
|
|
925
|
+
}
|
|
926
|
+
async function sync(options) {
|
|
927
|
+
const { direction, confirmation, url, username, transport, key, localOnly = [], filter = identity, signal, channel = "web", checkActive, credentials, pendingCredentials } = options;
|
|
928
|
+
if (![
|
|
929
|
+
"push",
|
|
930
|
+
"pull",
|
|
931
|
+
"auto"
|
|
932
|
+
].includes(direction)) throw new SyncError("请选择上传或下载。");
|
|
933
|
+
if (busy.current) throw new SyncError("上一轮同步还在运行。请等它结束后重新预览。");
|
|
934
|
+
busy.current = true;
|
|
935
|
+
try {
|
|
936
|
+
checkActive?.();
|
|
937
|
+
const rawLocal = access.read();
|
|
938
|
+
const local = filterAll(rawLocal, filter);
|
|
939
|
+
const remote = await transport.read();
|
|
940
|
+
signal?.throwIfAborted();
|
|
941
|
+
const decoded = remote ? decodeSnapshot(remote.bytes, key) : void 0;
|
|
942
|
+
const filtered = decoded ? filterAll(decoded.entries, filter) : /* @__PURE__ */ new Map();
|
|
943
|
+
const savedCredentials = decoded?.credentials ?? emptyCredentials();
|
|
944
|
+
const saved = filtered;
|
|
945
|
+
const scope = createHmac("sha256", confirmationSecret).update(JSON.stringify([
|
|
946
|
+
url,
|
|
947
|
+
username,
|
|
948
|
+
localOnly
|
|
949
|
+
])).update(key).digest("hex");
|
|
950
|
+
if (scope !== target) {
|
|
951
|
+
target = scope;
|
|
952
|
+
baseline.clear();
|
|
953
|
+
}
|
|
954
|
+
if (direction === "auto") {
|
|
955
|
+
if (!remote) return {
|
|
956
|
+
summary: "远端还没有配置快照。请先在一台设备上传。",
|
|
957
|
+
changed: [],
|
|
958
|
+
applied: []
|
|
959
|
+
};
|
|
960
|
+
const result = await autoSync(rawLocal, local, saved, transport, remote, key, signal, checkActive, savedCredentials);
|
|
961
|
+
const pending = pendingCredentials === void 0 ? [] : await pendingCredentials();
|
|
962
|
+
const note = pending.length ? `另有 ${pending.length} 项凭据有变化,凭据只随手动同步搬运,请在同步范围里处理。` : "";
|
|
963
|
+
return {
|
|
964
|
+
summary: result.summary + note,
|
|
965
|
+
...pending.length ? { credentialsPending: pending } : {}
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
const changes = direction === "push" ? planPush(local, saved) : planPull(local, saved);
|
|
969
|
+
const names = changes.map(changeId);
|
|
970
|
+
const kept = direction === "pull" ? [...rawLocal.keys()].filter((id) => !saved.has(id)) : [];
|
|
971
|
+
const keptText = kept.length ? `本机有 ${kept.length} 个条目不在远端快照里,保持本机配置:${kept.slice(0, 5).join("、")}${kept.length > 5 ? " 等" : ""}。` : "";
|
|
972
|
+
const token = createHmac("sha256", confirmationSecret).update(JSON.stringify([
|
|
973
|
+
channel,
|
|
974
|
+
direction,
|
|
975
|
+
url,
|
|
976
|
+
username,
|
|
977
|
+
localOnly,
|
|
978
|
+
[...rawLocal].sort(),
|
|
979
|
+
[...local].sort(),
|
|
980
|
+
remote?.etag ?? null
|
|
981
|
+
])).update(remote?.bytes ?? Buffer.alloc(0)).digest("hex");
|
|
982
|
+
const credentialPlan = credentials === void 0 ? null : await credentials({
|
|
983
|
+
direction,
|
|
984
|
+
signal,
|
|
985
|
+
dryRun: true
|
|
986
|
+
});
|
|
987
|
+
const credentialMark = credentialPlan ? [FILE_MARKER] : [];
|
|
988
|
+
const credentialText = credentialWorkOf(credentialPlan) ? [credentialPlan.summary] : [];
|
|
989
|
+
const credentialWork = credentialWorkOf(credentialPlan);
|
|
990
|
+
if (!confirmation) {
|
|
991
|
+
const action = direction === "push" ? "上传到远端" : "从远端写到本机";
|
|
992
|
+
const parts = [
|
|
993
|
+
changes.length ? `将${action} ${changes.length} 项配置,涉及 ${entryCount(changes)} 个条目。` : "没有需要同步的配置。",
|
|
994
|
+
...changes.length ? summarize(changes) : [],
|
|
995
|
+
keptText,
|
|
996
|
+
...credentialWork ? credentialText : []
|
|
997
|
+
];
|
|
998
|
+
parts.push("请确认后再应用。");
|
|
999
|
+
return {
|
|
1000
|
+
summary: parts.filter(Boolean).join("\n"),
|
|
1001
|
+
changed: [...names, ...credentialWork ? credentialMark : []],
|
|
1002
|
+
applied: [],
|
|
1003
|
+
confirmation: combinedConfirmation(token, credentialWork ? credentialText.join("\n") : "")
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
if (confirmation !== combinedConfirmation(token, credentialWork ? credentialText.join("\n") : "")) throw new SyncError("本机配置、凭据或远端文件已变化。请重新预览。");
|
|
1007
|
+
checkActive?.();
|
|
1008
|
+
const appliedPlan = credentials === void 0 ? null : await credentials({
|
|
1009
|
+
direction,
|
|
1010
|
+
signal,
|
|
1011
|
+
dryRun: false
|
|
1012
|
+
});
|
|
1013
|
+
if (direction === "push") {
|
|
1014
|
+
requireFileVersion(remote);
|
|
1015
|
+
const merged = new Map(saved);
|
|
1016
|
+
for (const [id, config] of local) merged.set(id, mergeConfig(saved.get(id) ?? {}, config));
|
|
1017
|
+
if (changes.length || credentialWorkOf(appliedPlan)) {
|
|
1018
|
+
signal?.throwIfAborted();
|
|
1019
|
+
await transport.write(encodeSnapshot({
|
|
1020
|
+
entries: merged,
|
|
1021
|
+
credentials: appliedPlan?.saved ?? savedCredentials
|
|
1022
|
+
}, key), remote);
|
|
1023
|
+
}
|
|
1024
|
+
return withCredentials({
|
|
1025
|
+
summary: changes.length ? `已上传 ${names.length} 项配置。` : "没有需要同步的配置。",
|
|
1026
|
+
changed: names,
|
|
1027
|
+
applied: names
|
|
1028
|
+
}, credentialWork ? {
|
|
1029
|
+
summary: credentialText.join("\n"),
|
|
1030
|
+
changed: credentialMark,
|
|
1031
|
+
applied: credentialMark
|
|
1032
|
+
} : null);
|
|
1033
|
+
}
|
|
1034
|
+
const credentialPart = credentialWork ? {
|
|
1035
|
+
summary: credentialText.join("\n"),
|
|
1036
|
+
changed: credentialMark,
|
|
1037
|
+
applied: credentialMark
|
|
1038
|
+
} : null;
|
|
1039
|
+
if (changes.length) {
|
|
1040
|
+
const { applied, failure } = await applyPull(changes, rawLocal, saved, signal, checkActive);
|
|
1041
|
+
if (failure) {
|
|
1042
|
+
const reason = failure.reason ?? "DSH 拒绝了这个条目的写入。请检查插件版本与配置覆盖。";
|
|
1043
|
+
const done = applied.length ? `已保存:${applied.join("、")}。` : "尚未保存任何配置。";
|
|
1044
|
+
const credentialDone = credentialWork ? "凭据已经写入本机文件。" : "";
|
|
1045
|
+
return withCredentials({
|
|
1046
|
+
summary: `同步停在「${failure.id}」。${reason}${done}${credentialDone}`,
|
|
1047
|
+
changed: names,
|
|
1048
|
+
applied
|
|
1049
|
+
}, credentialPart);
|
|
1050
|
+
}
|
|
1051
|
+
return withCredentials({
|
|
1052
|
+
summary: `已应用 ${applied.length} 项配置。${keptText}`,
|
|
1053
|
+
changed: names,
|
|
1054
|
+
applied
|
|
1055
|
+
}, credentialPart);
|
|
1056
|
+
}
|
|
1057
|
+
return withCredentials({
|
|
1058
|
+
summary: "没有需要同步的配置。",
|
|
1059
|
+
changed: [],
|
|
1060
|
+
applied: []
|
|
1061
|
+
}, credentialPart);
|
|
1062
|
+
} finally {
|
|
1063
|
+
busy.current = false;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
return sync;
|
|
1067
|
+
}
|
|
1068
|
+
// src/sync-scope.ts
|
|
1069
|
+
/**
|
|
1070
|
+
* 凭据在同步范围里的前缀。凭据那一行写成 `credentials:凭据名`(就是网页上显示的节点 ID),
|
|
1071
|
+
* 配置那一行是 `条目ID:键.路径`,两者用同一套「仅本机」规则决定要不要同步。
|
|
1072
|
+
*/
|
|
1073
|
+
const CREDENTIAL_ENTRY = "credentials";
|
|
1074
|
+
/** 内部名字里去掉身份标签:`ref:名字` 与 `record:记录标识` 都还原成名字,预览和合并按名字对应。 */
|
|
1075
|
+
function stripCredentialTag(name) {
|
|
1076
|
+
if (name.startsWith("ref:") || name.startsWith("record:")) return name.slice(name.indexOf(":") + 1);
|
|
1077
|
+
return name;
|
|
1078
|
+
}
|
|
1079
|
+
/** 一个凭据名字在不在同步范围里。规则按网页上显示的节点 ID 写,所以这里也用同一种写法去查。 */
|
|
1080
|
+
function credentialInScope(state, name) {
|
|
1081
|
+
return !state.isLocalOnly(`${CREDENTIAL_ENTRY}:${stripCredentialTag(name)}`);
|
|
1082
|
+
}
|
|
1083
|
+
/** 凭据文档里的条目 → 在同步范围里的名字,排好序。搬不搬只看范围,不另设名单。 */
|
|
1084
|
+
function scopeCredentialNames(entries, state) {
|
|
1085
|
+
return [...[...entries.refs.keys()].map((name) => `ref:${name}`), ...[...entries.records.keys()].map((name) => `record:${name}`)].filter((name) => credentialInScope(state, name)).sort();
|
|
1086
|
+
}
|
|
1087
|
+
// src/index.ts
|
|
1088
|
+
const inject = ["settings", "configEditor"];
|
|
1089
|
+
const Config = Schema.object({ sync: Schema.object({
|
|
1090
|
+
url: Schema.string().default("").description("HTTPS URL of the WebDAV directory or sync file").volatile(),
|
|
1091
|
+
auto: Schema.boolean().default(false).description("Automatically sync changes while DSH is running").volatile(),
|
|
1092
|
+
username: Schema.string().default("").description("WebDAV username, if required").volatile(),
|
|
1093
|
+
passwordRef: Schema.string().default("").description("WebDAV password credential reference").volatile(),
|
|
1094
|
+
keyEnv: Schema.string().default("DSH_SETTINGS_SYNC_KEY").volatile(),
|
|
1095
|
+
localOnly: Schema.array(Schema.string()).default([]).description("Entries or key paths that stay on this machine, in entryId or entryId:key.path form").volatile()
|
|
1096
|
+
}).default({}) });
|
|
1097
|
+
/** 同步插件自己的那条配置不能同步:两台设备的地址、用户名、范围各不相同。 */
|
|
1098
|
+
const OWN_ENTRY = "settings-sync";
|
|
1099
|
+
function apply(ctx, config) {
|
|
1100
|
+
function patchAccess() {
|
|
1101
|
+
return {
|
|
1102
|
+
read() {
|
|
1103
|
+
const entries = /* @__PURE__ */ new Map();
|
|
1104
|
+
for (const { entry, override } of ctx.configEditor.configuration()) {
|
|
1105
|
+
const id = entry.options.id;
|
|
1106
|
+
if (id === OWN_ENTRY) continue;
|
|
1107
|
+
const value = override;
|
|
1108
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length === 0) continue;
|
|
1109
|
+
entries.set(id, structuredClone(value));
|
|
1110
|
+
}
|
|
1111
|
+
return entries;
|
|
1112
|
+
},
|
|
1113
|
+
async write(id, next) {
|
|
1114
|
+
const row = ctx.configEditor.entries().find((candidate) => candidate.options.id === id);
|
|
1115
|
+
if (row === void 0) throw new SyncError(`本机没有条目「${id}」,这条配置已跳过。`);
|
|
1116
|
+
await ctx.configEditor.editRow(row, () => next);
|
|
1117
|
+
}
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
function secretsByNamespace() {
|
|
1121
|
+
const secrets = /* @__PURE__ */ new Map();
|
|
1122
|
+
for (const form of ctx.settings.describe({ redactSecrets: true })) if (form.secrets?.length) secrets.set(form.ns, form.secrets.map((secret) => [...secret.path]));
|
|
1123
|
+
return secrets;
|
|
1124
|
+
}
|
|
1125
|
+
/** 清单与同步共同的裁剪:去掉 !!js 表达式和设置接口标成秘密的字段。 */
|
|
1126
|
+
function visibleConfig(value, id, secrets) {
|
|
1127
|
+
return stripPaths(stripExpressions(value), secrets.get(id) ?? []);
|
|
1128
|
+
}
|
|
1129
|
+
/** 同步时再叠上仅本机规则。 */
|
|
1130
|
+
function makeFilter() {
|
|
1131
|
+
const state = localOnlyState(config.sync.localOnly.get());
|
|
1132
|
+
const secrets = secretsByNamespace();
|
|
1133
|
+
return (value, id) => stripWhere(visibleConfig(value, id, secrets), (path) => !state.isLocalOnly(nodeId([id, ...path])));
|
|
1134
|
+
}
|
|
1135
|
+
/**
|
|
1136
|
+
* 同步范围:本机补丁里的叶子节点、当前值的一行摘要,以及匹配不到任何节点的规则。
|
|
1137
|
+
* 这里不按仅本机规则裁剪——被排除的行要留在树里、显示为未勾选,否则取消勾选之后就没法再勾回来。
|
|
1138
|
+
*/
|
|
1139
|
+
async function listEntries(credentials = []) {
|
|
1140
|
+
const secrets = secretsByNamespace();
|
|
1141
|
+
const entries = [];
|
|
1142
|
+
const values = {};
|
|
1143
|
+
const leaves = [];
|
|
1144
|
+
for (const [id, value] of patchAccess().read()) for (const [key, leaf] of flattenConfig(visibleConfig(value, id, secrets))) {
|
|
1145
|
+
const segments = [id, ...splitKey(key)];
|
|
1146
|
+
const node = nodeId(segments);
|
|
1147
|
+
entries.push(node);
|
|
1148
|
+
values[node] = previewValue(leaf);
|
|
1149
|
+
leaves.push(segments);
|
|
1150
|
+
}
|
|
1151
|
+
for (const name of credentials) {
|
|
1152
|
+
const node = `${CREDENTIAL_ENTRY}:${stripCredentialTag(name)}`;
|
|
1153
|
+
entries.push(node);
|
|
1154
|
+
values[node] = "";
|
|
1155
|
+
leaves.push([CREDENTIAL_ENTRY, stripCredentialTag(name)]);
|
|
1156
|
+
}
|
|
1157
|
+
entries.sort((left, right) => {
|
|
1158
|
+
return (left.startsWith(`credentials:`) ? 0 : 1) - (right.startsWith(`credentials:`) ? 0 : 1) || (left < right ? -1 : left > right ? 1 : 0);
|
|
1159
|
+
});
|
|
1160
|
+
return {
|
|
1161
|
+
entries,
|
|
1162
|
+
values,
|
|
1163
|
+
stale: staleRules(config.sync.localOnly.get(), leaves)
|
|
1164
|
+
};
|
|
1165
|
+
}
|
|
1166
|
+
const busy = { current: false };
|
|
1167
|
+
const sync = createSync(patchAccess(), busy);
|
|
1168
|
+
const syncCredentials = createCredentialSync(busy);
|
|
1169
|
+
const unload = new AbortController();
|
|
1170
|
+
let autoStatus;
|
|
1171
|
+
const autoTarget = () => JSON.stringify([
|
|
1172
|
+
config.sync.url.get(),
|
|
1173
|
+
config.sync.username.get(),
|
|
1174
|
+
config.sync.localOnly.get()
|
|
1175
|
+
]);
|
|
1176
|
+
let checking = false;
|
|
1177
|
+
/** 统一同步里凭据那一行的摘要,和单独同步凭据时保持同一句话。 */
|
|
1178
|
+
const countsText = ({ added, replaced }) => `凭据:新增 ${added} 项,覆盖同名凭据 ${replaced} 项。`;
|
|
1179
|
+
async function runSync(input, callerSignal, channel, listOnly = false) {
|
|
1180
|
+
const { direction, confirmation } = input;
|
|
1181
|
+
const { url: configuredUrl, username: configuredUsername, passwordRef, keyEnv, localOnly } = config.sync;
|
|
1182
|
+
const ref = passwordRef.get().trim() || "DSH_SETTINGS_SYNC_PASSWORD";
|
|
1183
|
+
const url = snapshotUrl(configuredUrl.get());
|
|
1184
|
+
const directory = syncDirectoryUrl(configuredUrl.get());
|
|
1185
|
+
const username = configuredUsername.get();
|
|
1186
|
+
const destination = configuredUrl.get();
|
|
1187
|
+
const selection = JSON.stringify([localOnly.get()]);
|
|
1188
|
+
const checkActive = () => {
|
|
1189
|
+
if (JSON.stringify([config.sync.localOnly.get()]) !== selection) throw new SyncError("同步范围已变化。请重新预览。");
|
|
1190
|
+
if (direction === "auto" && (!config.sync.auto.get() || configuredUrl.get() !== destination || configuredUsername.get() !== username || (passwordRef.get().trim() || "DSH_SETTINGS_SYNC_PASSWORD") !== ref)) throw new SyncError("同步设置已更改,本轮自动同步已停止。");
|
|
1191
|
+
};
|
|
1192
|
+
if (username && /[:\x00-\x1f\x7f]/.test(username)) throw new SyncError("WebDAV 用户名不能含冒号或控制字符。");
|
|
1193
|
+
const signal = AbortSignal.any([
|
|
1194
|
+
callerSignal,
|
|
1195
|
+
unload.signal,
|
|
1196
|
+
AbortSignal.timeout(3e4)
|
|
1197
|
+
]);
|
|
1198
|
+
const credentials = async () => {
|
|
1199
|
+
try {
|
|
1200
|
+
let password;
|
|
1201
|
+
if (username) password = await resolveCredentialRef(ctx, credentialRef(ref));
|
|
1202
|
+
const secret = await resolveCredentialRef(ctx, credentialRef(keyEnv.get()));
|
|
1203
|
+
return {
|
|
1204
|
+
password,
|
|
1205
|
+
secret
|
|
1206
|
+
};
|
|
1207
|
+
} catch {
|
|
1208
|
+
throw new SyncError("读取同步凭据失败。请检查 passwordRef、keyEnv 及 DSH 凭据设置。");
|
|
1209
|
+
}
|
|
1210
|
+
};
|
|
1211
|
+
const { password, secret } = await credentials();
|
|
1212
|
+
if (username && !password) throw new SyncError("WebDAV 密码未配置。请在插件的同步配置面板保存密码。");
|
|
1213
|
+
const key = encryptionKey(secret);
|
|
1214
|
+
signal.throwIfAborted();
|
|
1215
|
+
const provider = ctx.get("credentials");
|
|
1216
|
+
const credentialStore = provider instanceof LocalCredentialProvider ? resolveSpec(provider.config).filename : void 0;
|
|
1217
|
+
/** 这会儿在同步范围里的凭据名字;统一同步只搬这些。 */
|
|
1218
|
+
const scopedNames = (saved) => {
|
|
1219
|
+
const state = localOnlyState(localOnly.get());
|
|
1220
|
+
return scopeCredentialNames({
|
|
1221
|
+
refs: new Map(Object.entries(saved.refs)),
|
|
1222
|
+
records: new Map(Object.entries(saved.records))
|
|
1223
|
+
}, state);
|
|
1224
|
+
};
|
|
1225
|
+
const readSource = async (direction, saved, runSignal) => {
|
|
1226
|
+
if (!credentialStore) throw new SyncError("凭据同步需要 DSH 的本地凭据存储。");
|
|
1227
|
+
const { entries } = await readCredentialSource({
|
|
1228
|
+
direction,
|
|
1229
|
+
filename: credentialStore,
|
|
1230
|
+
saved,
|
|
1231
|
+
signal: runSignal ?? signal
|
|
1232
|
+
});
|
|
1233
|
+
return credentialNames(entries);
|
|
1234
|
+
};
|
|
1235
|
+
/** 读远端快照里的凭据;远端还没有快照时就是空的一本。 */
|
|
1236
|
+
const remoteCredentials = async () => {
|
|
1237
|
+
const remote = await webdav(url, {
|
|
1238
|
+
username,
|
|
1239
|
+
password,
|
|
1240
|
+
signal,
|
|
1241
|
+
directory
|
|
1242
|
+
}).read();
|
|
1243
|
+
return remote ? decodeSnapshot(remote.bytes, key).credentials : emptyCredentials();
|
|
1244
|
+
};
|
|
1245
|
+
if (listOnly) {
|
|
1246
|
+
const config = await listEntries();
|
|
1247
|
+
if (!credentialStore) return config;
|
|
1248
|
+
try {
|
|
1249
|
+
return listEntries(await readSource("push", emptyCredentials()));
|
|
1250
|
+
} catch (error) {
|
|
1251
|
+
if (!(error instanceof SyncError)) throw error;
|
|
1252
|
+
return config;
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
const manual = input.direction !== "auto";
|
|
1256
|
+
return sync({
|
|
1257
|
+
direction,
|
|
1258
|
+
confirmation,
|
|
1259
|
+
url: url.href,
|
|
1260
|
+
username,
|
|
1261
|
+
transport: webdav(url, {
|
|
1262
|
+
username,
|
|
1263
|
+
password,
|
|
1264
|
+
signal,
|
|
1265
|
+
directory
|
|
1266
|
+
}),
|
|
1267
|
+
key,
|
|
1268
|
+
access: patchAccess(),
|
|
1269
|
+
localOnly: [...localOnly.get()],
|
|
1270
|
+
filter: makeFilter(),
|
|
1271
|
+
signal,
|
|
1272
|
+
channel,
|
|
1273
|
+
checkActive,
|
|
1274
|
+
...manual && credentialStore ? { credentials: async ({ direction: runDirection, signal: runSignal, dryRun }) => {
|
|
1275
|
+
const saved = await remoteCredentials();
|
|
1276
|
+
const inScope = (await readSource(runDirection, saved)).filter((name) => scopedNames(saved).includes(name));
|
|
1277
|
+
if (!inScope.length) return null;
|
|
1278
|
+
const outcome = await syncCredentials({
|
|
1279
|
+
direction: runDirection,
|
|
1280
|
+
filename: credentialStore,
|
|
1281
|
+
saved,
|
|
1282
|
+
selection: inScope,
|
|
1283
|
+
describe: countsText,
|
|
1284
|
+
running: busy,
|
|
1285
|
+
signal: runSignal ?? signal,
|
|
1286
|
+
dryRun
|
|
1287
|
+
});
|
|
1288
|
+
return {
|
|
1289
|
+
summary: outcome.summary,
|
|
1290
|
+
edited: outcome.edited,
|
|
1291
|
+
saved: outcome.saved
|
|
1292
|
+
};
|
|
1293
|
+
} } : {},
|
|
1294
|
+
...manual || !credentialStore ? {} : { pendingCredentials: async () => {
|
|
1295
|
+
try {
|
|
1296
|
+
return scopedNames(await remoteCredentials()).filter((name) => name !== "");
|
|
1297
|
+
} catch (error) {
|
|
1298
|
+
if (!(error instanceof SyncError)) throw error;
|
|
1299
|
+
return [];
|
|
1300
|
+
}
|
|
1301
|
+
} }
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
ctx.inject(["webServer"], (webCtx) => {
|
|
1305
|
+
webCtx.effect(() => registerSyncRoute(webCtx.webServer, runSync, () => {
|
|
1306
|
+
if (!config.sync.auto.get()) return "自动同步已关闭。";
|
|
1307
|
+
return autoStatus?.target === autoTarget() ? autoStatus.summary : "等待第一次自动检查。";
|
|
1308
|
+
}, (direction, signal) => runSync({
|
|
1309
|
+
scope: "credentials",
|
|
1310
|
+
direction
|
|
1311
|
+
}, signal, "web", true), () => runSync({
|
|
1312
|
+
direction: "push",
|
|
1313
|
+
scope: "settings"
|
|
1314
|
+
}, AbortSignal.timeout(5e3), "web", true)), "settings sync web route");
|
|
1315
|
+
});
|
|
1316
|
+
ctx.effect(() => {
|
|
1317
|
+
const timer = setInterval(async () => {
|
|
1318
|
+
if (!config.sync.auto.get()) {
|
|
1319
|
+
autoStatus = void 0;
|
|
1320
|
+
return;
|
|
1321
|
+
}
|
|
1322
|
+
if (checking) return;
|
|
1323
|
+
const target = autoTarget();
|
|
1324
|
+
checking = true;
|
|
1325
|
+
try {
|
|
1326
|
+
autoStatus = {
|
|
1327
|
+
target,
|
|
1328
|
+
summary: (await runSync({ direction: "auto" }, unload.signal, "auto")).summary
|
|
1329
|
+
};
|
|
1330
|
+
} catch (error) {
|
|
1331
|
+
autoStatus = {
|
|
1332
|
+
target,
|
|
1333
|
+
summary: error instanceof SyncError ? error.message : "自动同步失败,请检查设置。"
|
|
1334
|
+
};
|
|
1335
|
+
} finally {
|
|
1336
|
+
checking = false;
|
|
1337
|
+
}
|
|
1338
|
+
}, 6e4);
|
|
1339
|
+
timer.unref();
|
|
1340
|
+
return () => {
|
|
1341
|
+
clearInterval(timer);
|
|
1342
|
+
unload.abort();
|
|
1343
|
+
};
|
|
1344
|
+
}, "settings auto sync");
|
|
1345
|
+
}
|
|
1346
|
+
export { Config, apply, inject };
|