ygc-dsh-plugin-autoupdate 0.2.0 → 0.5.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/README.md +129 -1
- package/client.js +258 -0
- package/index.js +174 -18
- package/lib/api.js +59 -0
- package/lib/core.js +34 -0
- package/lib/machine.js +156 -0
- package/lib/share.js +1018 -0
- package/lib/updater.js +30 -7
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +16 -12
package/index.js
CHANGED
|
@@ -28,9 +28,11 @@ import {
|
|
|
28
28
|
updateKind,
|
|
29
29
|
} from './lib/core.js';
|
|
30
30
|
import { normalizeRegistry, queryLatest } from './lib/registry.js';
|
|
31
|
-
import { installVersion } from './lib/updater.js';
|
|
31
|
+
import { installSpec, installVersion } from './lib/updater.js';
|
|
32
32
|
import { scheduleRestart } from './lib/restart.js';
|
|
33
33
|
import { createApi } from './lib/api.js';
|
|
34
|
+
import { installSharedPlugin, libraryRoot, shareSnapshot, syncMyFeature, writeAggregate } from './lib/share.js';
|
|
35
|
+
import { resolveIdentity } from './lib/machine.js';
|
|
34
36
|
|
|
35
37
|
export const inject = ['webServer'];
|
|
36
38
|
|
|
@@ -107,6 +109,133 @@ export function apply(ctx, config = {}) {
|
|
|
107
109
|
};
|
|
108
110
|
};
|
|
109
111
|
|
|
112
|
+
/* -------------------------------------------------------------- 共享 */
|
|
113
|
+
|
|
114
|
+
/** 共享相关的设置(目录、特征名)从状态里读,面板改完立即生效。 */
|
|
115
|
+
const shareConfig = () => {
|
|
116
|
+
const state = loadState();
|
|
117
|
+
return {
|
|
118
|
+
libraryRoot: state.shareLibraryRoot || '',
|
|
119
|
+
featureName: state.shareFeatureName || '',
|
|
120
|
+
// 已固定的特征值必须原样传回:不传就会重新推导,目录会漂移
|
|
121
|
+
machineHash: state.shareMachineHash || '',
|
|
122
|
+
publishedNames: state.publishedNames || [],
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* 把本机标识固定进状态。
|
|
128
|
+
*
|
|
129
|
+
* 规则与会话同步插件一致:第一次确定后永久不变。所以只有 state 里没有特征值时
|
|
130
|
+
* 才解析一次并落盘;已有值绝不重算(哪怕主机名改了、换用户名了)。
|
|
131
|
+
*/
|
|
132
|
+
const ensureIdentityFixed = () => {
|
|
133
|
+
const state = loadState();
|
|
134
|
+
if (state.shareMachineHash) return state.shareMachineHash;
|
|
135
|
+
const identity = resolveIdentity({ name: state.shareFeatureName });
|
|
136
|
+
const next = loadState();
|
|
137
|
+
next.shareMachineHash = identity.machineHash;
|
|
138
|
+
next.shareHashFixedAt = Date.now();
|
|
139
|
+
if (!next.shareFeatureName) next.shareFeatureName = identity.machineName;
|
|
140
|
+
saveState(next);
|
|
141
|
+
log(`本机标识已固定:${identity.machineId}(特征值来源:${identity.hashSource})`);
|
|
142
|
+
return identity.machineHash;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
let sharing = false;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 同步我自己的特征文件夹 + 汇集他人清单。
|
|
149
|
+
* 巡检每轮跑一次;面板上的「立即同步」也走这里。
|
|
150
|
+
*/
|
|
151
|
+
const runShareSync = async ({ reason } = {}) => {
|
|
152
|
+
const state = loadState();
|
|
153
|
+
if (!state.shareEnabled && reason !== '手动') {
|
|
154
|
+
return { ok: true, skipped: '共享同步已关闭' };
|
|
155
|
+
}
|
|
156
|
+
if (sharing) return { ok: false, error: '正在同步中' };
|
|
157
|
+
sharing = true;
|
|
158
|
+
try {
|
|
159
|
+
// 同步前先把本机标识钉死:第一次运行时确定,之后永久不变
|
|
160
|
+
ensureIdentityFixed();
|
|
161
|
+
const config = shareConfig();
|
|
162
|
+
const mine = await syncMyFeature({
|
|
163
|
+
config,
|
|
164
|
+
publishedNames: config.publishedNames,
|
|
165
|
+
log,
|
|
166
|
+
});
|
|
167
|
+
const aggregate = writeAggregate({
|
|
168
|
+
config,
|
|
169
|
+
publishedNames: config.publishedNames,
|
|
170
|
+
log,
|
|
171
|
+
});
|
|
172
|
+
const next = loadState();
|
|
173
|
+
next.shareLastSyncAt = Date.now();
|
|
174
|
+
next.shareLastResult = {
|
|
175
|
+
feature: mine.feature,
|
|
176
|
+
root: mine.root,
|
|
177
|
+
total: mine.counts.total,
|
|
178
|
+
bundled: mine.counts.bundled,
|
|
179
|
+
skipped: mine.counts.skipped,
|
|
180
|
+
totalMb: mine.totalMb,
|
|
181
|
+
others: aggregate.doc.counts.othersTotal,
|
|
182
|
+
installable: aggregate.doc.counts.installable,
|
|
183
|
+
sources: aggregate.doc.counts.sources,
|
|
184
|
+
reason: reason || '定时',
|
|
185
|
+
};
|
|
186
|
+
next.shareLastError = '';
|
|
187
|
+
pushHistory(next, {
|
|
188
|
+
kind: 'share',
|
|
189
|
+
reason: reason || '定时',
|
|
190
|
+
text: `共享同步:本机 ${mine.counts.total} 个插件 / 副本 ${mine.counts.bundled};他人 ${aggregate.doc.counts.othersTotal} 个,可装 ${aggregate.doc.counts.installable}`,
|
|
191
|
+
});
|
|
192
|
+
saveState(next);
|
|
193
|
+
return { ok: true, mine, aggregate: { counts: aggregate.doc.counts }, root: libraryRoot(config) };
|
|
194
|
+
} catch (error) {
|
|
195
|
+
const message = String(error?.message || error);
|
|
196
|
+
const next = loadState();
|
|
197
|
+
next.shareLastError = message;
|
|
198
|
+
pushHistory(next, { kind: 'share-failed', text: `共享同步失败:${message}` });
|
|
199
|
+
saveState(next);
|
|
200
|
+
log(`共享同步失败:${message}`);
|
|
201
|
+
return { ok: false, error: message };
|
|
202
|
+
} finally {
|
|
203
|
+
sharing = false;
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const shareState = () => {
|
|
208
|
+
try {
|
|
209
|
+
ensureIdentityFixed();
|
|
210
|
+
} catch {
|
|
211
|
+
/* 标识固定失败也要能看面板(会用临时值显示) */
|
|
212
|
+
}
|
|
213
|
+
const config = shareConfig();
|
|
214
|
+
return shareSnapshot({ config, publishedNames: config.publishedNames });
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
/** 人工安装他人清单里的一个插件。 */
|
|
218
|
+
const installFromShare = async (name) => {
|
|
219
|
+
ensureIdentityFixed();
|
|
220
|
+
const config = shareConfig();
|
|
221
|
+
const result = await installSharedPlugin({
|
|
222
|
+
ctx,
|
|
223
|
+
config,
|
|
224
|
+
publishedNames: config.publishedNames,
|
|
225
|
+
name,
|
|
226
|
+
installSpec,
|
|
227
|
+
log,
|
|
228
|
+
});
|
|
229
|
+
const next = loadState();
|
|
230
|
+
pushHistory(next, {
|
|
231
|
+
kind: result.ok ? 'share-install' : 'share-install-failed',
|
|
232
|
+
name,
|
|
233
|
+
text: result.ok ? `从共享安装 ${name}:${result.message}` : `从共享安装 ${name} 失败:${result.message}`,
|
|
234
|
+
});
|
|
235
|
+
saveState(next);
|
|
236
|
+
return result;
|
|
237
|
+
};
|
|
238
|
+
|
|
110
239
|
/* -------------------------------------------------------------- 检查 */
|
|
111
240
|
|
|
112
241
|
/**
|
|
@@ -299,37 +428,61 @@ export function apply(ctx, config = {}) {
|
|
|
299
428
|
/* -------------------------------------------------------------- 调度 */
|
|
300
429
|
|
|
301
430
|
ctx.effect(() => {
|
|
302
|
-
|
|
431
|
+
// 两件事各自排期:自动更新按「启用 + 间隔」跑;共享同步只受它自己的开关约束。
|
|
432
|
+
// 共用同一个 tick,但状态独立——用户把自动更新关掉、只想要清单同步是完全合理的。
|
|
433
|
+
let updateDueAt = 0;
|
|
434
|
+
let shareDueAt = 0;
|
|
303
435
|
let booted = false;
|
|
304
436
|
let lastIntervalMs = 0;
|
|
305
437
|
|
|
438
|
+
const intervalMsOf = (state) =>
|
|
439
|
+
Math.max(MIN_INTERVAL_MINUTES, Number(state.intervalMinutes) || 360) * 60 * 1000;
|
|
440
|
+
|
|
306
441
|
const tick = () => {
|
|
307
442
|
try {
|
|
308
443
|
const state = loadState();
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
444
|
+
|
|
445
|
+
if (!booted) {
|
|
446
|
+
booted = true;
|
|
447
|
+
// 开机首跑稍晚,避开启动高峰
|
|
448
|
+
updateDueAt = state.enabled ? Date.now() + 20 * 1000 : 0;
|
|
449
|
+
shareDueAt = state.shareEnabled ? Date.now() + 40 * 1000 : 0;
|
|
450
|
+
lastIntervalMs = intervalMsOf(state);
|
|
313
451
|
return;
|
|
314
452
|
}
|
|
315
453
|
|
|
316
|
-
const intervalMs =
|
|
317
|
-
if (
|
|
454
|
+
const intervalMs = intervalMsOf(state);
|
|
455
|
+
if (intervalMs !== lastIntervalMs) {
|
|
318
456
|
// 改了间隔立即生效:从上次检查时间按新间隔重算
|
|
319
|
-
|
|
457
|
+
if (state.enabled) updateDueAt = (state.lastCheckAt || Date.now()) + intervalMs;
|
|
458
|
+
lastIntervalMs = intervalMs;
|
|
320
459
|
}
|
|
321
|
-
lastIntervalMs = intervalMs;
|
|
322
460
|
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
461
|
+
// ---- 自动更新 ----
|
|
462
|
+
if (!state.enabled) {
|
|
463
|
+
updateDueAt = 0;
|
|
464
|
+
} else {
|
|
465
|
+
if (!updateDueAt) updateDueAt = Date.now() + 1000;
|
|
466
|
+
if (Date.now() >= updateDueAt) {
|
|
467
|
+
updateDueAt = Date.now() + intervalMs;
|
|
468
|
+
runAutoUpdate({ reason: '定时' }).catch((error) =>
|
|
469
|
+
log(`自动更新失败:${error?.message || error}`),
|
|
470
|
+
);
|
|
471
|
+
}
|
|
328
472
|
}
|
|
329
473
|
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
474
|
+
// ---- 共享同步:每次巡检跑一次 ----
|
|
475
|
+
if (!state.shareEnabled) {
|
|
476
|
+
shareDueAt = 0;
|
|
477
|
+
} else {
|
|
478
|
+
if (!shareDueAt) shareDueAt = Date.now() + 1000;
|
|
479
|
+
if (Date.now() >= shareDueAt) {
|
|
480
|
+
shareDueAt = Date.now() + intervalMs;
|
|
481
|
+
runShareSync({ reason: '定时' }).catch((error) =>
|
|
482
|
+
log(`共享同步失败:${error?.message || error}`),
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
333
486
|
} catch (error) {
|
|
334
487
|
log(`调度失败:${error?.message || error}`);
|
|
335
488
|
}
|
|
@@ -367,6 +520,9 @@ export function apply(ctx, config = {}) {
|
|
|
367
520
|
requestRestart,
|
|
368
521
|
isBusy,
|
|
369
522
|
log,
|
|
523
|
+
runShareSync,
|
|
524
|
+
shareState,
|
|
525
|
+
installFromShare,
|
|
370
526
|
});
|
|
371
527
|
|
|
372
528
|
ctx.effect(() =>
|
package/lib/api.js
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
} from './core.js';
|
|
21
21
|
import { normalizeRegistry, queryLatest } from './registry.js';
|
|
22
22
|
import { restoreBackup, listBackups } from './backup.js';
|
|
23
|
+
import { libraryRoot, myFeatureName } from './share.js';
|
|
23
24
|
|
|
24
25
|
export const API_PREFIX = '/api/local/plugin-autoupdate';
|
|
25
26
|
|
|
@@ -98,6 +99,23 @@ function snapshot(deps) {
|
|
|
98
99
|
pendingRestart: needsRestart,
|
|
99
100
|
plugins,
|
|
100
101
|
history: (state.history || []).slice(0, 40),
|
|
102
|
+
share: {
|
|
103
|
+
enabled: state.shareEnabled,
|
|
104
|
+
libraryRoot: state.shareLibraryRoot || '',
|
|
105
|
+
featureName: state.shareFeatureName || '',
|
|
106
|
+
machineHash: state.shareMachineHash || '',
|
|
107
|
+
hashFixedAt: state.shareHashFixedAt || 0,
|
|
108
|
+
lastSyncAt: state.shareLastSyncAt,
|
|
109
|
+
lastError: state.shareLastError,
|
|
110
|
+
lastResult: state.shareLastResult,
|
|
111
|
+
// 展示用:面板没填时告诉用户实际会落到哪。
|
|
112
|
+
// 这就是最终目录名本身(`<名称>-<特征值>`),不要再过 safeFeatureName 二次加工。
|
|
113
|
+
effectiveRoot: libraryRoot({ libraryRoot: state.shareLibraryRoot }),
|
|
114
|
+
effectiveFeature: myFeatureName({
|
|
115
|
+
featureName: state.shareFeatureName,
|
|
116
|
+
machineHash: state.shareMachineHash,
|
|
117
|
+
}),
|
|
118
|
+
},
|
|
101
119
|
limits: {
|
|
102
120
|
minIntervalMinutes: MIN_INTERVAL_MINUTES,
|
|
103
121
|
defaultIntervalMinutes: DEFAULT_INTERVAL_MINUTES,
|
|
@@ -129,6 +147,18 @@ export function createApi(deps) {
|
|
|
129
147
|
if (body.autoRestart !== undefined) state.autoRestart = body.autoRestart === true;
|
|
130
148
|
if (body.restartOnlyWhenIdle !== undefined) state.restartOnlyWhenIdle = body.restartOnlyWhenIdle !== false;
|
|
131
149
|
if (body.restartDelaySeconds !== undefined) state.restartDelaySeconds = body.restartDelaySeconds;
|
|
150
|
+
if (body.shareEnabled !== undefined) state.shareEnabled = body.shareEnabled === true;
|
|
151
|
+
if (body.shareLibraryRoot !== undefined) {
|
|
152
|
+
state.shareLibraryRoot = typeof body.shareLibraryRoot === 'string' ? body.shareLibraryRoot.trim() : '';
|
|
153
|
+
}
|
|
154
|
+
if (body.shareFeatureName !== undefined) {
|
|
155
|
+
state.shareFeatureName = typeof body.shareFeatureName === 'string' ? body.shareFeatureName.trim() : '';
|
|
156
|
+
}
|
|
157
|
+
if (body.shareResetHash === true) {
|
|
158
|
+
// 明确要求重算才重算:清掉固定值,下次同步重新解析
|
|
159
|
+
state.shareMachineHash = '';
|
|
160
|
+
state.shareHashFixedAt = 0;
|
|
161
|
+
}
|
|
132
162
|
if (Array.isArray(body.publishedNames)) {
|
|
133
163
|
// 「已发布的自有插件」名单:file:/link: 依赖但已在 registry 有正式产物
|
|
134
164
|
state.publishedNames = body.publishedNames
|
|
@@ -261,6 +291,35 @@ export function createApi(deps) {
|
|
|
261
291
|
json(res, 200, { ok: answer.ok, message: answer.message });
|
|
262
292
|
},
|
|
263
293
|
|
|
294
|
+
/** 共享面板:我的特征文件夹 + 他人清单(detail 里是扫盘得到的最新现状)。 */
|
|
295
|
+
'GET /share': async (req, res) => {
|
|
296
|
+
const snap = snapshot(deps);
|
|
297
|
+
json(res, 200, { ...snap, share: { ...snap.share, detail: deps.shareState() } });
|
|
298
|
+
},
|
|
299
|
+
|
|
300
|
+
'POST /share/sync': async (req, res) => {
|
|
301
|
+
const result = await deps.runShareSync({ reason: '手动' });
|
|
302
|
+
const snap = snapshot(deps);
|
|
303
|
+
json(res, 200, { ...snap, share: { ...snap.share, detail: deps.shareState() }, result });
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
/** 人工安装他人清单里的某个插件(不自动装,必须逐个点)。 */
|
|
307
|
+
'POST /share/install': async (req, res) => {
|
|
308
|
+
const body = await readJson(req);
|
|
309
|
+
const name = typeof body.name === 'string' ? body.name.trim() : '';
|
|
310
|
+
if (!name) {
|
|
311
|
+
json(res, 400, { ok: false, error: '缺少 name' });
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const result = await deps.installFromShare(name);
|
|
315
|
+
const snap = snapshot(deps);
|
|
316
|
+
json(res, result.ok ? 200 : 400, {
|
|
317
|
+
...snap,
|
|
318
|
+
share: { ...snap.share, detail: deps.shareState() },
|
|
319
|
+
result,
|
|
320
|
+
});
|
|
321
|
+
},
|
|
322
|
+
|
|
264
323
|
'GET /backups': async (req, res) => {
|
|
265
324
|
json(res, 200, { ok: true, backups: listBackups() });
|
|
266
325
|
},
|
package/lib/core.js
CHANGED
|
@@ -197,6 +197,26 @@ export function defaultState() {
|
|
|
197
197
|
* 必须显式列出,不靠猜——file: 指向的目录里有没有 publishConfig 都不能证明它发过。
|
|
198
198
|
*/
|
|
199
199
|
publishedNames: [],
|
|
200
|
+
/* ---- 插件共享(特征文件夹) ---- */
|
|
201
|
+
/** 每次巡检顺带同步自己的特征文件夹。 */
|
|
202
|
+
shareEnabled: true,
|
|
203
|
+
/** 插件库根目录;空 = 用默认 `D:\Ai工作空间\插件库`。 */
|
|
204
|
+
shareLibraryRoot: '',
|
|
205
|
+
/** 我的特征本名字;空 = 用会话同步插件的本机标识(`<名称>-<特征值>`)。 */
|
|
206
|
+
shareFeatureName: '',
|
|
207
|
+
/**
|
|
208
|
+
* 本机特征值(12 位十六进制)。与会话同步插件共用同一身份,
|
|
209
|
+
* 第一次读到时固定下来,此后永久不变——绝不在没有旧值时重算。
|
|
210
|
+
* 有旧值就必须原样传回,否则特征目录会漂移、别人汇总出两个「我」。
|
|
211
|
+
*/
|
|
212
|
+
shareMachineHash: '',
|
|
213
|
+
/** 特征值第一次固定的时间,便于排查漂移。 */
|
|
214
|
+
shareHashFixedAt: 0,
|
|
215
|
+
/** 上次同步时间与结果摘要。 */
|
|
216
|
+
shareLastSyncAt: 0,
|
|
217
|
+
shareLastResult: null,
|
|
218
|
+
shareLastError: '',
|
|
219
|
+
|
|
200
220
|
/** 运行态:上次检查时间 / 上次结果 / 待生效的更新队列。 */
|
|
201
221
|
lastCheckAt: 0,
|
|
202
222
|
lastCheckError: '',
|
|
@@ -277,6 +297,20 @@ export function normalizeState(raw) {
|
|
|
277
297
|
out.lastCheck = lastCheck;
|
|
278
298
|
|
|
279
299
|
out.history = Array.isArray(value.history) ? value.history.slice(0, 100) : [];
|
|
300
|
+
|
|
301
|
+
out.shareEnabled = value.shareEnabled !== false;
|
|
302
|
+
out.shareLibraryRoot =
|
|
303
|
+
typeof value.shareLibraryRoot === 'string' ? value.shareLibraryRoot.trim().slice(0, 400) : '';
|
|
304
|
+
out.shareFeatureName =
|
|
305
|
+
typeof value.shareFeatureName === 'string' ? value.shareFeatureName.trim().slice(0, 80) : '';
|
|
306
|
+
out.shareMachineHash =
|
|
307
|
+
typeof value.shareMachineHash === 'string' ? value.shareMachineHash.trim().slice(0, 64) : '';
|
|
308
|
+
out.shareHashFixedAt = Number(value.shareHashFixedAt) || 0;
|
|
309
|
+
out.shareLastSyncAt = Number(value.shareLastSyncAt) || 0;
|
|
310
|
+
out.shareLastResult =
|
|
311
|
+
value.shareLastResult && typeof value.shareLastResult === 'object' ? value.shareLastResult : null;
|
|
312
|
+
out.shareLastError = typeof value.shareLastError === 'string' ? value.shareLastError.slice(0, 800) : '';
|
|
313
|
+
|
|
280
314
|
out.lastCheckAt = Number(value.lastCheckAt) || 0;
|
|
281
315
|
out.lastCheckError = typeof value.lastCheckError === 'string' ? value.lastCheckError : '';
|
|
282
316
|
out.updatedAt = Number(value.updatedAt) || 0;
|
package/lib/machine.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本机标识 —— 与会话同步插件(ygc-dsh-sync-backup)完全同一套规则。
|
|
3
|
+
*
|
|
4
|
+
* 为什么必须共用:
|
|
5
|
+
* 两台机器之间的「身份」只能有一个。会话同步已经把这一格写成了
|
|
6
|
+
* `~/.dsh/storages/sync-backup.json` 里的 `machineId`,插件共享如果自己再算
|
|
7
|
+
* 一份(比如用主机名-用户名),同一台机器就会在共享盘上留下两个身份,
|
|
8
|
+
* 别人汇总时看到两个「我」,而本机自己也不确定该往哪格写。
|
|
9
|
+
*
|
|
10
|
+
* 规则(照抄会话同步,一个字都不改):
|
|
11
|
+
* - 格式 `<名称>-<特征值>`,例如 `DSH-7e6b1bb7e052`
|
|
12
|
+
* - 特征值 = 6 字节随机数的十六进制前 12 位,**第一次安装时生成一次,之后永久固定,永不重算**
|
|
13
|
+
* - 名称部分可改;改名不重算特征值
|
|
14
|
+
* - 唯一的迁移来源是既有 state 里已经存在的哈希(那是既有目录名,必须原样继承)
|
|
15
|
+
*/
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import os from 'node:os';
|
|
19
|
+
import crypto from 'node:crypto';
|
|
20
|
+
|
|
21
|
+
/** 会话同步插件的状态文件;本机标识以它为准。 */
|
|
22
|
+
export function syncBackupStateFile() {
|
|
23
|
+
const override = process.env.DSH_SYNC_STATE_FILE;
|
|
24
|
+
if (override && override.trim()) return path.resolve(override.trim());
|
|
25
|
+
return path.join(os.homedir(), '.dsh', 'storages', 'sync-backup.json');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function readJson(file) {
|
|
29
|
+
try {
|
|
30
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
31
|
+
} catch {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 生成一次性特征值:6 字节随机数 → 12 位十六进制。与会话同步同一实现。 */
|
|
37
|
+
export function generateHash() {
|
|
38
|
+
return crypto.randomBytes(6).toString('hex').slice(0, 12);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 当前主机名,只作为名称默认值,不参与哈希。 */
|
|
42
|
+
export function hostName() {
|
|
43
|
+
return (os.hostname() || 'DSH').replace(/[^A-Za-z0-9_-]/g, '') || 'DSH';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 拼标识。与会话同步的 joinId 逐字一致:
|
|
48
|
+
* 名称里的路径分隔符/空白换成下划线、去掉首尾连字符;哈希为空就只用名称。
|
|
49
|
+
*/
|
|
50
|
+
export function joinMachineId(name, hash) {
|
|
51
|
+
const n = String(name || '')
|
|
52
|
+
.trim()
|
|
53
|
+
.replace(/[\\/:*?"<>|\s]+/g, '_')
|
|
54
|
+
.replace(/^-+|-+$/g, '');
|
|
55
|
+
const h = String(hash || '').trim();
|
|
56
|
+
if (!h) return n;
|
|
57
|
+
return n ? `${n}-${h}` : h;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 拆标识:`<名称>-<特征值>`。名称可含连字符,只取最后一段十六进制当特征值。 */
|
|
61
|
+
export function splitMachineId(value, fallbackHash) {
|
|
62
|
+
const raw = String(value || '').trim();
|
|
63
|
+
if (!raw) return { name: '', hash: String(fallbackHash || '').trim() };
|
|
64
|
+
const m = raw.match(/^(.*)-([0-9a-f]{6,})$/i);
|
|
65
|
+
if (m) return { name: m[1], hash: m[2].toLowerCase() };
|
|
66
|
+
return { name: raw, hash: String(fallbackHash || '').trim() };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 读会话同步插件的本机标识。
|
|
71
|
+
* 读不到(没装那插件 / 还没初始化)返回 null,由调用方退回自己固定一份。
|
|
72
|
+
*/
|
|
73
|
+
export function readSyncBackupIdentity() {
|
|
74
|
+
const doc = readJson(syncBackupStateFile());
|
|
75
|
+
if (!doc || typeof doc !== 'object') return null;
|
|
76
|
+
const machineId = typeof doc.machineId === 'string' ? doc.machineId.trim() : '';
|
|
77
|
+
const machineHash = typeof doc.machineHash === 'string' ? doc.machineHash.trim() : '';
|
|
78
|
+
const machineName = typeof doc.machineName === 'string' ? doc.machineName.trim() : '';
|
|
79
|
+
if (!machineId && !machineHash) return null;
|
|
80
|
+
const split = splitMachineId(machineId, machineHash);
|
|
81
|
+
const hash = split.hash || machineHash;
|
|
82
|
+
const name = split.name || machineName || hostName();
|
|
83
|
+
if (!hash) return null;
|
|
84
|
+
return {
|
|
85
|
+
machineId: joinMachineId(name, hash),
|
|
86
|
+
machineName: name,
|
|
87
|
+
machineHash: hash,
|
|
88
|
+
source: 'sync-backup',
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 解析本机标识。
|
|
94
|
+
*
|
|
95
|
+
* 优先级:
|
|
96
|
+
* 1. 调用方显式给的特征值(面板/state 里已固定的那份)—— 绝不重算
|
|
97
|
+
* 2. 会话同步插件的特征值 —— 同一台机器只能有一个身份
|
|
98
|
+
* 3. 都没有才新生成一个;调用方必须把它存下来,下次原样传回
|
|
99
|
+
*
|
|
100
|
+
* @param {{hash?: string, name?: string}} [input]
|
|
101
|
+
* @returns {{machineId:string, machineName:string, machineHash:string,
|
|
102
|
+
* hashSource:'given'|'sync-backup'|'generated', sharesWithSyncBackup:boolean}}
|
|
103
|
+
*/
|
|
104
|
+
export function resolveIdentity(input) {
|
|
105
|
+
const givenHash = String(input?.hash || '').trim();
|
|
106
|
+
const shared = readSyncBackupIdentity();
|
|
107
|
+
const hash = givenHash || (shared && shared.machineHash) || generateHash();
|
|
108
|
+
const name =
|
|
109
|
+
String(input?.name || '').trim() || (shared && shared.machineName) || hostName();
|
|
110
|
+
return {
|
|
111
|
+
machineId: joinMachineId(name, hash),
|
|
112
|
+
machineName: name,
|
|
113
|
+
machineHash: hash,
|
|
114
|
+
hashSource: givenHash ? 'given' : shared && shared.machineHash ? 'sync-backup' : 'generated',
|
|
115
|
+
sharesWithSyncBackup: Boolean(shared && shared.machineHash === hash),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/* ------------------------------------------------------------- 写边界 */
|
|
120
|
+
|
|
121
|
+
/** Windows 下大小写不敏感。 */
|
|
122
|
+
function pathKey(p) {
|
|
123
|
+
const n = path.resolve(String(p)).replace(/[\\/]+/g, path.sep !== '\\' ? path.sep : '\\');
|
|
124
|
+
return process.platform === 'win32' ? n.toLowerCase() : n;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function isInside(prefix, target) {
|
|
128
|
+
const a = pathKey(prefix);
|
|
129
|
+
const b = pathKey(target);
|
|
130
|
+
if (a === b) return true;
|
|
131
|
+
return b.startsWith(a.endsWith('\\') || a.endsWith('/') ? a : `${a}${path.sep}`);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export class WriteDeniedError extends Error {
|
|
135
|
+
constructor(target, reason) {
|
|
136
|
+
super(`不是本机的特征格,拒绝写入:${target}(${reason})`);
|
|
137
|
+
this.name = 'WriteDeniedError';
|
|
138
|
+
this.code = 'WRITE_DENIED';
|
|
139
|
+
this.target = target;
|
|
140
|
+
this.reason = reason;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* 唯一写入口的守卫,与会话同步的 assertWritable 同一个思路:
|
|
146
|
+
* 目标必须落在 `特征/<本机标识>/` 之内,别人的特征本只读。
|
|
147
|
+
*/
|
|
148
|
+
export function assertOwnFeaturePath(target, { featuresRoot, machineId }) {
|
|
149
|
+
if (!featuresRoot) throw new WriteDeniedError(target, '缺少特征根目录');
|
|
150
|
+
if (!machineId) throw new WriteDeniedError(target, '缺少本机标识');
|
|
151
|
+
const allowed = path.join(featuresRoot, machineId);
|
|
152
|
+
if (!isInside(allowed, target)) {
|
|
153
|
+
throw new WriteDeniedError(target, `只允许写 ${allowed}`);
|
|
154
|
+
}
|
|
155
|
+
return target;
|
|
156
|
+
}
|