@twinsearth/dsh-fang 3.1.21 → 3.1.22
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/LICENSES/LICENSES/cordis-MIT.txt +39 -0
- package/client.js +197 -3
- package/defaults/defaults/umbrella-rules.yaml +113 -0
- package/package.json +2 -2
- package/sdk/sdk/README.md +65 -0
- package/sdk/sdk/examples/status-badge/README.md +16 -0
- package/sdk/sdk/examples/status-badge/client.js +60 -0
- package/sdk/sdk/examples/status-badge/cordis.patch.yml +7 -0
- package/sdk/sdk/examples/status-badge/index.js +12 -0
- package/sdk/sdk/examples/status-badge/package.json +24 -0
- package/sdk/sdk/templates/plugin/README.md +36 -0
- package/sdk/sdk/templates/plugin/client.js +35 -0
- package/sdk/sdk/templates/plugin/cordis.patch.yml +8 -0
- package/sdk/sdk/templates/plugin/icon.svg +5 -0
- package/sdk/sdk/templates/plugin/index.js +23 -0
- package/sdk/sdk/templates/plugin/locale/en.json +6 -0
- package/sdk/sdk/templates/plugin/package.json +36 -0
- package/src/kernel/types.mjs +1 -1
- package/src/src/compose.mjs +67 -0
- package/src/src/contract/client.js +86 -0
- package/src/src/contract/constants.js +79 -0
- package/src/src/contract/envelope.js +83 -0
- package/src/src/contract/index.js +19 -0
- package/src/src/contract/negotiate.js +106 -0
- package/src/src/contract/server.js +77 -0
- package/src/src/contract/transports.js +301 -0
- package/src/src/index.mjs +11 -0
- package/src/src/kernel/core.mjs +100 -0
- package/src/src/kernel/extensions.mjs +61 -0
- package/src/src/kernel/fsx.mjs +349 -0
- package/src/src/kernel/index.mjs +21 -0
- package/src/src/kernel/ledger.mjs +94 -0
- package/src/src/kernel/paths.mjs +182 -0
- package/src/src/kernel/role.mjs +68 -0
- package/src/src/kernel/rounds.mjs +172 -0
- package/src/src/kernel/schema.mjs +5 -0
- package/src/src/kernel/types.mjs +264 -0
- package/src/src/kernel/vendor/cosmokit.mjs +421 -0
- package/src/src/kernel/vendor/schemastery.mjs +638 -0
- package/src/src/lib/adapter-client.mjs +383 -0
- package/src/src/lib/adapter-protocol.mjs +243 -0
- package/src/src/lib/ai-secret-store.mjs +202 -0
- package/src/src/lib/boot-guard.mjs +182 -0
- package/src/src/lib/branch-store.mjs +84 -0
- package/src/src/lib/branch.mjs +74 -0
- package/src/src/lib/bridge-client.mjs +133 -0
- package/src/src/lib/broker-adapter.mjs +67 -0
- package/src/src/lib/broker.mjs +45 -0
- package/src/src/lib/business-producers.mjs +109 -0
- package/src/src/lib/command-cache.mjs +209 -0
- package/src/src/lib/compat.mjs +170 -0
- package/src/src/lib/composer-journal.mjs +128 -0
- package/src/src/lib/container/index.mjs +806 -0
- package/src/src/lib/decision-events.mjs +129 -0
- package/src/src/lib/decision-ingest-client.mjs +41 -0
- package/src/src/lib/decision-outbox.mjs +129 -0
- package/src/src/lib/default-essence.mjs +61 -0
- package/src/src/lib/desktop-launch.mjs +138 -0
- package/src/src/lib/essence.mjs +1211 -0
- package/src/src/lib/fork-client.mjs +410 -0
- package/src/src/lib/fork-config-lock.mjs +153 -0
- package/src/src/lib/fork-seed.mjs +304 -0
- package/src/src/lib/fork-supervision-settings.mjs +58 -0
- package/src/src/lib/fork-supervisor.mjs +122 -0
- package/src/src/lib/fs-guard.mjs +28 -0
- package/src/src/lib/http-auth.mjs +162 -0
- package/src/src/lib/idle-audit.mjs +178 -0
- package/src/src/lib/interaction-poke.mjs +61 -0
- package/src/src/lib/mirror-etag.mjs +92 -0
- package/src/src/lib/mirror-official-source.mjs +93 -0
- package/src/src/lib/mirror.mjs +478 -0
- package/src/src/lib/mother-link.mjs +156 -0
- package/src/src/lib/mutex.mjs +31 -0
- package/src/src/lib/permissions.mjs +115 -0
- package/src/src/lib/pnpm-store.mjs +189 -0
- package/src/src/lib/preferences.mjs +212 -0
- package/src/src/lib/producer-contract.mjs +162 -0
- package/src/src/lib/reflow.mjs +41 -0
- package/src/src/lib/remote.mjs +408 -0
- package/src/src/lib/restart-contract.mjs +650 -0
- package/src/src/lib/roots.mjs +30 -0
- package/src/src/lib/rule-registry.mjs +1101 -0
- package/src/src/lib/runtime-capture.mjs +307 -0
- package/src/src/lib/semaphore.mjs +34 -0
- package/src/src/lib/session-bundle.mjs +138 -0
- package/src/src/lib/session-format.mjs +658 -0
- package/src/src/lib/sse-parser.mjs +102 -0
- package/src/src/lib/ssrf-guard.mjs +170 -0
- package/src/src/lib/status-store.mjs +257 -0
- package/src/src/lib/task-handle.mjs +622 -0
- package/src/src/lib/ui-actions.mjs +55 -0
- package/src/src/lib/umbrella.mjs +1661 -0
- package/src/src/lib/upgrade-coordinator.mjs +107 -0
- package/src/src/lib/upgrade-status.mjs +43 -0
- package/src/src/plugins/adapter.mjs +1468 -0
- package/src/src/plugins/approver.mjs +1210 -0
- package/src/src/plugins/auditor.mjs +330 -0
- package/src/src/plugins/buffer-keeper.mjs +522 -0
- package/src/src/plugins/decision-center.mjs +2265 -0
- package/src/src/plugins/forker.mjs +1594 -0
- package/src/src/plugins/healer.mjs +664 -0
- package/src/src/plugins/hot-reloader.mjs +274 -0
- package/src/src/plugins/imports.mjs +247 -0
- package/src/src/plugins/orchestrator.mjs +3806 -0
- package/src/src/plugins/restart-guard.mjs +948 -0
- package/src/src/plugins/router.mjs +714 -0
- package/src/src/plugins/scorer.mjs +624 -0
- package/src/src/plugins/session-bridge.mjs +166 -0
- package/src/src/plugins/session-catalog.mjs +771 -0
- package/src/src/plugins/session-router.mjs +125 -0
- package/src/src/plugins/session-sync.mjs +171 -0
- package/src/src/plugins/umbrella.mjs +419 -0
- package/tools/recover-queue.mjs +133 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// dsh-Fang v3.0.8 — 空闲降级审计聚合。
|
|
3
|
+
//
|
|
4
|
+
// MirrorStatusStore 在“活跃消费者 30s 无交互 → 降级”时发 ActiveIdleEvent;
|
|
5
|
+
// 本模块把事件写入 Auditor(单条 + 周期 summary),并从统计里生成 UI 优化建议:
|
|
6
|
+
// * idleAfterMs = 降级时刻 - 最后一次交互(真实的“走开时长”)
|
|
7
|
+
// * totalActiveMs = 降级时刻 - 首次 acquireActive(用户停留总时长)
|
|
8
|
+
// 样本不足(默认 <10)不给建议,避免小样本误导。
|
|
9
|
+
|
|
10
|
+
export const IDLE_AUDIT_KIND = 'mirror-idle-downgrade'
|
|
11
|
+
export const IDLE_AUDIT_SUMMARY_KIND = 'mirror-idle-downgrade-summary'
|
|
12
|
+
|
|
13
|
+
export class IdleAuditAggregator {
|
|
14
|
+
/**
|
|
15
|
+
* @param {{record: (payload: Record<string, unknown>) => (void|Promise<void>),
|
|
16
|
+
* minSamplesForRecommendation?: number, snapshotIntervalMs?: number,
|
|
17
|
+
* timers?: {setInterval: Function, clearInterval: Function}, now?: () => number}} options
|
|
18
|
+
*/
|
|
19
|
+
constructor(options) {
|
|
20
|
+
if (options === null || typeof options !== 'object' || typeof options.record !== 'function') {
|
|
21
|
+
throw new Error('IdleAuditAggregator: record required')
|
|
22
|
+
}
|
|
23
|
+
this.record = options.record
|
|
24
|
+
this.minSamples = Math.max(1, Math.floor(Number(options.minSamplesForRecommendation) || 10))
|
|
25
|
+
this.snapshotIntervalMs = Math.max(1, Math.floor(Number(options.snapshotIntervalMs) || 300_000))
|
|
26
|
+
this.timers = options.timers ?? { setInterval, clearInterval }
|
|
27
|
+
this.now = typeof options.now === 'function' ? options.now : () => Date.now()
|
|
28
|
+
this.events = []
|
|
29
|
+
this.rollingEvents = []
|
|
30
|
+
this.rollingCapacity = Math.max(1, Math.floor(Number(options.rollingCapacity) || 500))
|
|
31
|
+
this.snapshotTimer = null
|
|
32
|
+
this.sink = (event) => { this.handle(event) }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 传给 MirrorStatusStore.onIdleDowngraded(sink)。 */
|
|
36
|
+
asSink() {
|
|
37
|
+
return this.sink
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
start() {
|
|
41
|
+
this.stop()
|
|
42
|
+
this.snapshotTimer = this.timers.setInterval(() => { void this.publishSnapshot() }, this.snapshotIntervalMs)
|
|
43
|
+
this.snapshotTimer?.unref?.()
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
stop() {
|
|
47
|
+
if (this.snapshotTimer !== null) {
|
|
48
|
+
this.timers.clearInterval(this.snapshotTimer)
|
|
49
|
+
this.snapshotTimer = null
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 基于滚动窗口(长期,最近 N 条)生成结构化建议;样本不足返回空数组。 */
|
|
54
|
+
getRecommendations() {
|
|
55
|
+
if (this.rollingEvents.length < this.minSamples) return []
|
|
56
|
+
return this.buildRecommendations(this.rollingEvents)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 由事件数组生成结构化建议(fieldKey/suggestedValue/text/sampleCount/confidence)。 */
|
|
60
|
+
buildRecommendations(events) {
|
|
61
|
+
const total = events.length
|
|
62
|
+
if (total === 0) return []
|
|
63
|
+
let rapid = 0
|
|
64
|
+
let full = 0
|
|
65
|
+
for (const event of events) {
|
|
66
|
+
if (event.idleAfterMs < event.timeoutMs * 0.3) rapid += 1
|
|
67
|
+
if (event.idleAfterMs >= event.timeoutMs * 0.9) full += 1
|
|
68
|
+
}
|
|
69
|
+
const rapidRatio = rapid / total
|
|
70
|
+
const fullRatio = full / total
|
|
71
|
+
const recommendations = []
|
|
72
|
+
if (rapidRatio > 0.5) {
|
|
73
|
+
recommendations.push({
|
|
74
|
+
fieldKey: 'activeIdleTimeoutMs',
|
|
75
|
+
suggestedValue: 15_000,
|
|
76
|
+
text: `超过一半(${(rapidRatio * 100).toFixed(0)}%)的对话框打开后很快走开,可考虑把交互超时降到 15 秒,减少无意义的高频轮询。`,
|
|
77
|
+
sampleCount: total,
|
|
78
|
+
confidence: rapidRatio,
|
|
79
|
+
})
|
|
80
|
+
}
|
|
81
|
+
if (fullRatio > 0.8) {
|
|
82
|
+
recommendations.push({
|
|
83
|
+
fieldKey: 'activeIdleTimeoutMs',
|
|
84
|
+
suggestedValue: 60_000,
|
|
85
|
+
text: `${(fullRatio * 100).toFixed(0)}% 的用户活跃到超时窗口末尾,建议把交互超时提高到 60 秒,让状态刷新更实时。`,
|
|
86
|
+
sampleCount: total,
|
|
87
|
+
confidence: fullRatio,
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
return recommendations
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 发布聚合快照(无事件则不发);发布后清空窗口。 */
|
|
94
|
+
async publishSnapshot() {
|
|
95
|
+
if (this.events.length === 0) return null
|
|
96
|
+
const windowStart = this.events[0].at
|
|
97
|
+
const windowEnd = this.events[this.events.length - 1].at
|
|
98
|
+
const summary = this.computeSummary()
|
|
99
|
+
this.events = []
|
|
100
|
+
const payload = {
|
|
101
|
+
kind: IDLE_AUDIT_SUMMARY_KIND,
|
|
102
|
+
at: this.now(),
|
|
103
|
+
windowStart,
|
|
104
|
+
windowEnd,
|
|
105
|
+
summary,
|
|
106
|
+
}
|
|
107
|
+
await this.record(payload)
|
|
108
|
+
return summary
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
computeSummary() {
|
|
112
|
+
const byTimeout = {}
|
|
113
|
+
let rapidAway = 0
|
|
114
|
+
let fullTimeout = 0
|
|
115
|
+
for (const event of this.events) {
|
|
116
|
+
const bucket = byTimeout[event.timeoutMs] ?? { count: 0, totalIdleAfterMs: 0, totalActiveMs: 0 }
|
|
117
|
+
bucket.count += 1
|
|
118
|
+
bucket.totalIdleAfterMs += event.idleAfterMs
|
|
119
|
+
bucket.totalActiveMs += event.totalActiveMs
|
|
120
|
+
byTimeout[event.timeoutMs] = bucket
|
|
121
|
+
if (event.idleAfterMs < event.timeoutMs * 0.3) rapidAway += 1
|
|
122
|
+
if (event.idleAfterMs >= event.timeoutMs * 0.9) fullTimeout += 1
|
|
123
|
+
}
|
|
124
|
+
for (const key of Object.keys(byTimeout)) {
|
|
125
|
+
const bucket = byTimeout[key]
|
|
126
|
+
bucket.avgIdleAfterMs = Math.round(bucket.totalIdleAfterMs / bucket.count)
|
|
127
|
+
bucket.avgTotalActiveMs = Math.round(bucket.totalActiveMs / bucket.count)
|
|
128
|
+
delete bucket.totalIdleAfterMs
|
|
129
|
+
delete bucket.totalActiveMs
|
|
130
|
+
}
|
|
131
|
+
const recommendations = this.events.length >= this.minSamples ? this.buildRecommendations(this.events) : []
|
|
132
|
+
return {
|
|
133
|
+
totalEvents: this.events.length,
|
|
134
|
+
byTimeout,
|
|
135
|
+
rapidAwayCount: rapidAway,
|
|
136
|
+
fullTimeoutCount: fullTimeout,
|
|
137
|
+
recommendation: recommendations[0]?.text ?? null,
|
|
138
|
+
recommendations,
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
buildRecommendation(rapidAway, fullTimeout) {
|
|
143
|
+
const total = this.events.length
|
|
144
|
+
if (total < this.minSamples) return null
|
|
145
|
+
const rapidRatio = rapidAway / total
|
|
146
|
+
const fullRatio = fullTimeout / total
|
|
147
|
+
if (rapidRatio > 0.5) {
|
|
148
|
+
return `超过一半(${(rapidRatio * 100).toFixed(0)}%)的对话框打开后很快走开,建议把默认交互超时降到 15s 以减少无意义轮询。`
|
|
149
|
+
}
|
|
150
|
+
if (fullRatio > 0.8) {
|
|
151
|
+
return `${(fullRatio * 100).toFixed(0)}% 的用户活跃到超时窗口末尾,建议把默认交互超时提高到 60s。`
|
|
152
|
+
}
|
|
153
|
+
return null
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
handle(event) {
|
|
157
|
+
this.events.push(event)
|
|
158
|
+
this.rollingEvents.push(event)
|
|
159
|
+
if (this.rollingEvents.length > this.rollingCapacity) {
|
|
160
|
+
this.rollingEvents.splice(0, this.rollingEvents.length - this.rollingCapacity)
|
|
161
|
+
}
|
|
162
|
+
const payload = {
|
|
163
|
+
kind: IDLE_AUDIT_KIND,
|
|
164
|
+
at: event.at,
|
|
165
|
+
timeoutMs: event.timeoutMs,
|
|
166
|
+
idleAfterMs: event.idleAfterMs,
|
|
167
|
+
totalActiveMs: event.totalActiveMs,
|
|
168
|
+
lastPokeAt: event.lastPokeAt,
|
|
169
|
+
activeConsumers: event.activeConsumers,
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
const result = this.record(payload)
|
|
173
|
+
if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
|
|
174
|
+
result.catch(() => { /* 审计失败不影响 UI */ })
|
|
175
|
+
}
|
|
176
|
+
} catch { /* 审计失败不影响 UI */ }
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// dsh-Fang v3.1.0 — 用户交互 poke(框架无关)。
|
|
3
|
+
//
|
|
4
|
+
// 消费者(如打开的镜像设置对话框)在挂载时调用 installInteractionPoke(store, {target}),
|
|
5
|
+
// 鼠标/键盘/滚动/触摸等轻量交互会节流触发 store.pokeActive(),让 store 保持高频档;
|
|
6
|
+
// 30s 无交互后 store 自动降回 idle 间隔。
|
|
7
|
+
// 不监听 click:点击路径本身会调用 refresh/acquireActive,无需额外 poke。
|
|
8
|
+
|
|
9
|
+
export const INTERACTION_EVENTS = Object.freeze([
|
|
10
|
+
'mousemove', 'mousedown', 'wheel', 'scroll', 'keydown', 'touchstart',
|
|
11
|
+
])
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {{pokeActive: Function}} store
|
|
15
|
+
* @param {{target?: EventTarget|null, throttleMs?: number, now?: () => number,
|
|
16
|
+
* timers?: {setTimeout: Function, clearTimeout: Function}}} [options]
|
|
17
|
+
* @returns {() => void} dispose
|
|
18
|
+
*/
|
|
19
|
+
export function installInteractionPoke(store, options = {}) {
|
|
20
|
+
const target = options.target ?? (typeof window !== 'undefined' ? window : null)
|
|
21
|
+
if (target === null || target === undefined || typeof target.addEventListener !== 'function') {
|
|
22
|
+
return () => {}
|
|
23
|
+
}
|
|
24
|
+
const throttleMs = Math.max(0, Number(options.throttleMs) || 1_000)
|
|
25
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now()
|
|
26
|
+
const timers = options.timers ?? { setTimeout, clearTimeout }
|
|
27
|
+
let lastPokeAt = 0
|
|
28
|
+
let trailing = null
|
|
29
|
+
let disposed = false
|
|
30
|
+
|
|
31
|
+
const fire = () => {
|
|
32
|
+
if (disposed) return
|
|
33
|
+
lastPokeAt = now()
|
|
34
|
+
store.pokeActive()
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const onEvent = () => {
|
|
38
|
+
if (disposed) return
|
|
39
|
+
const elapsed = now() - lastPokeAt
|
|
40
|
+
if (elapsed >= throttleMs) { fire(); return }
|
|
41
|
+
if (trailing !== null) return
|
|
42
|
+
trailing = timers.setTimeout(() => {
|
|
43
|
+
trailing = null
|
|
44
|
+
fire()
|
|
45
|
+
}, throttleMs - elapsed)
|
|
46
|
+
trailing?.unref?.()
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
for (const eventName of INTERACTION_EVENTS) target.addEventListener(eventName, onEvent, { passive: true })
|
|
50
|
+
|
|
51
|
+
return () => {
|
|
52
|
+
disposed = true
|
|
53
|
+
for (const eventName of INTERACTION_EVENTS) {
|
|
54
|
+
try { target.removeEventListener(eventName, onEvent) } catch { /* 已移除 */ }
|
|
55
|
+
}
|
|
56
|
+
if (trailing !== null) {
|
|
57
|
+
timers.clearTimeout(trailing)
|
|
58
|
+
trailing = null
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// dsh-Fang v3.0.1 — 母体镜像状态的条件 GET(ETag / If-None-Match,零依赖)。
|
|
3
|
+
//
|
|
4
|
+
// 目的:60 秒轮询在状态未变化时不传输完整体。
|
|
5
|
+
// ETag 只由“稳定字段”计算:diskUsageBytes 每次请求都在漂移(日志/临时文件),
|
|
6
|
+
// 必须排除,否则永远拿不到 304;客户端在 304 时沿用上一份状态(磁盘占用可能是几十秒前的值),
|
|
7
|
+
// 用户点「刷新」走 force 路径拿最新值。
|
|
8
|
+
|
|
9
|
+
import { sha256 } from '../kernel/index.mjs'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 计算状态 ETag(强校验器,带引号)。
|
|
13
|
+
* @param {Record<string, any>} status
|
|
14
|
+
* @returns {string}
|
|
15
|
+
*/
|
|
16
|
+
export function computeMirrorStatusEtag(status) {
|
|
17
|
+
const source = status !== null && typeof status === 'object' ? status : {}
|
|
18
|
+
const meta = source.meta !== null && typeof source.meta === 'object' ? source.meta : {}
|
|
19
|
+
const backups = Array.isArray(source.backups) ? source.backups : []
|
|
20
|
+
const stable = {
|
|
21
|
+
ok: source.ok !== false,
|
|
22
|
+
currentVersion: source.currentVersion ?? null,
|
|
23
|
+
officialLatest: source.officialLatest ?? null,
|
|
24
|
+
updateAvailable: source.updateAvailable === true,
|
|
25
|
+
meta: {
|
|
26
|
+
version: meta.version ?? null,
|
|
27
|
+
backupIntervalHours: meta.backupIntervalHours ?? null,
|
|
28
|
+
lastBackupAt: meta.lastBackupAt ?? null,
|
|
29
|
+
nextBackupAt: meta.nextBackupAt ?? null,
|
|
30
|
+
},
|
|
31
|
+
backups: backups.map(entry => ({
|
|
32
|
+
id: entry?.id ?? null,
|
|
33
|
+
version: entry?.version ?? null,
|
|
34
|
+
kind: entry?.kind ?? null,
|
|
35
|
+
bucket: entry?.bucket ?? null,
|
|
36
|
+
createdAt: entry?.createdAt ?? null,
|
|
37
|
+
sizeBytes: entry?.sizeBytes ?? null,
|
|
38
|
+
})),
|
|
39
|
+
activeEssenceCount: source.activeEssenceCount ?? 0,
|
|
40
|
+
activeSessionCount: source.activeSessionCount ?? 0,
|
|
41
|
+
// diskUsageBytes 刻意排除:持续漂移字段
|
|
42
|
+
}
|
|
43
|
+
return `"${sha256(JSON.stringify(stable)).slice(0, 24)}"`
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* If-None-Match 匹配判断:支持逗号多值、`*`、弱校验前缀 `W/`(强比较语义下也接受弱值)。
|
|
48
|
+
* @param {string|string[]|undefined} header
|
|
49
|
+
* @param {string} etag 服务端计算的 ETag(带引号)
|
|
50
|
+
* @returns {boolean}
|
|
51
|
+
*/
|
|
52
|
+
export function ifNoneMatchMatches(header, etag) {
|
|
53
|
+
if (typeof header !== 'string') return false
|
|
54
|
+
const candidates = header.split(',')
|
|
55
|
+
const target = String(etag).trim()
|
|
56
|
+
const normalizedTarget = target.startsWith('W/') ? target.slice(2) : target
|
|
57
|
+
for (const raw of candidates) {
|
|
58
|
+
const candidate = raw.trim()
|
|
59
|
+
if (candidate.length === 0) continue
|
|
60
|
+
if (candidate === '*') return true
|
|
61
|
+
const normalized = candidate.startsWith('W/') ? candidate.slice(2) : candidate
|
|
62
|
+
if (normalized === normalizedTarget) return true
|
|
63
|
+
}
|
|
64
|
+
return false
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 构造镜像状态响应(200 / 304)。
|
|
69
|
+
* @param {Record<string, any>} status
|
|
70
|
+
* @param {string|string[]|undefined} ifNoneMatch
|
|
71
|
+
* @returns {{statusCode:number, headers:Record<string,string|number>, body:string|null, etag:string, notModified:boolean}}
|
|
72
|
+
*/
|
|
73
|
+
export function buildMirrorStatusResponse(status, ifNoneMatch) {
|
|
74
|
+
const etag = computeMirrorStatusEtag(status)
|
|
75
|
+
const notModified = ifNoneMatchMatches(ifNoneMatch, etag)
|
|
76
|
+
const headers = {
|
|
77
|
+
ETag: etag,
|
|
78
|
+
'Cache-Control': 'no-cache, must-revalidate',
|
|
79
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
80
|
+
}
|
|
81
|
+
if (notModified) return { statusCode: 304, headers, body: null, etag, notModified: true }
|
|
82
|
+
const body = JSON.stringify(status)
|
|
83
|
+
return {
|
|
84
|
+
statusCode: 200,
|
|
85
|
+
headers: { ...headers, 'Content-Length': Buffer.byteLength(body) },
|
|
86
|
+
body,
|
|
87
|
+
etag,
|
|
88
|
+
notModified: false,
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export const _internals = Object.freeze({ stableFields: (status) => { const m = status?.meta ?? {}; return [status?.currentVersion, m.version, m.lastBackupAt, Array.isArray(status?.backups) ? status.backups.length : 0] } })
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// mirror-official-source — 最小可用的「官方源 adapter」(manifest 协议 v1)。
|
|
5
|
+
//
|
|
6
|
+
// 协议:
|
|
7
|
+
// GET <baseUrl>/manifest.json
|
|
8
|
+
// {
|
|
9
|
+
// "version": "3.2.0",
|
|
10
|
+
// "files": {
|
|
11
|
+
// "package.json": "{\"name\":\"dsh-profile\"}",
|
|
12
|
+
// "cordis.patch.yml": "insert: []\n"
|
|
13
|
+
// }
|
|
14
|
+
// }
|
|
15
|
+
// download(version, staging):校验 version 后把 files 写到 staging(防路径逃逸)。
|
|
16
|
+
//
|
|
17
|
+
// 远程必须 HTTPS(loopback 允许 http)。MirrorManager 现在会 await
|
|
18
|
+
// getLatestVersion()/download(),因此 adapter 可以是 async。
|
|
19
|
+
|
|
20
|
+
function isLoopbackHost(hostname) {
|
|
21
|
+
return /^(localhost|127\.0\.0\.1|\[::1\]|::1)$/i.test(String(hostname))
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function validateOfficialSourceUrl(baseUrl) {
|
|
25
|
+
let endpoint = null
|
|
26
|
+
try { endpoint = new URL(String(baseUrl ?? '').trim()) } catch { return { ok: false, reason: 'base-url-required' } }
|
|
27
|
+
if (!/^https?:$/.test(endpoint.protocol)) return { ok: false, reason: 'base-url-required' }
|
|
28
|
+
if (endpoint.username || endpoint.password) return { ok: false, reason: 'base-url-userinfo-forbidden' }
|
|
29
|
+
if (!isLoopbackHost(endpoint.hostname) && endpoint.protocol !== 'https:') return { ok: false, reason: 'https-required-for-remote-endpoint' }
|
|
30
|
+
return { ok: true, url: endpoint.toString().replace(/\/+$/, '') }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 只允许 staging 内的相对路径;拒绝绝对路径、`..`、NUL。 */
|
|
34
|
+
export function safeRelativePath(relative) {
|
|
35
|
+
const raw = String(relative ?? '')
|
|
36
|
+
if (!raw || raw.includes('\0')) return null
|
|
37
|
+
if (/^[A-Za-z]:/.test(raw) || raw.startsWith('\\\\') || raw.startsWith('//')) return null
|
|
38
|
+
const parts = raw.replace(/\\/g, '/').split('/')
|
|
39
|
+
if (parts.some((part) => part === '..')) return null
|
|
40
|
+
if (parts.some((part) => part === '')) return null
|
|
41
|
+
return parts.join('/')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createManifestOfficialSource({ baseUrl, fetchImpl = globalThis.fetch, headers = {}, token = '' } = {}) {
|
|
45
|
+
const checked = validateOfficialSourceUrl(baseUrl)
|
|
46
|
+
if (!checked.ok) throw new Error(`official source: ${checked.reason}`)
|
|
47
|
+
if (typeof fetchImpl !== 'function') throw new TypeError('official source: fetchImpl required')
|
|
48
|
+
const manifestUrl = `${checked.url}/manifest.json`
|
|
49
|
+
|
|
50
|
+
async function fetchManifest() {
|
|
51
|
+
const auth = token ? { authorization: `Bearer ${token}` } : {}
|
|
52
|
+
const response = await fetchImpl(manifestUrl, { headers: { accept: 'application/json', ...auth, ...headers }, redirect: 'error' })
|
|
53
|
+
if (!response.ok) throw new Error(`official source manifest: http-${response.status}`)
|
|
54
|
+
const text = await response.text()
|
|
55
|
+
let manifest = null
|
|
56
|
+
try { manifest = JSON.parse(text) } catch { throw new Error('official source manifest: bad-json') }
|
|
57
|
+
const version = String(manifest?.version ?? '').trim()
|
|
58
|
+
if (!version) throw new Error('official source manifest: version-required')
|
|
59
|
+
const files = manifest?.files && typeof manifest.files === 'object' && !Array.isArray(manifest.files) ? manifest.files : null
|
|
60
|
+
if (!files) throw new Error('official source manifest: files-required')
|
|
61
|
+
return { version, files }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
baseUrl: checked.url,
|
|
66
|
+
async getLatestVersion() {
|
|
67
|
+
return (await fetchManifest()).version
|
|
68
|
+
},
|
|
69
|
+
async download(version, stagingDir) {
|
|
70
|
+
const manifest = await fetchManifest()
|
|
71
|
+
if (manifest.version !== String(version)) {
|
|
72
|
+
throw new Error(`official source version mismatch: manifest=${manifest.version} requested=${version}`)
|
|
73
|
+
}
|
|
74
|
+
const root = String(stagingDir ?? '')
|
|
75
|
+
if (!root) throw new Error('official source download: staging required')
|
|
76
|
+
const fs = await import('node:fs')
|
|
77
|
+
const path = await import('node:path')
|
|
78
|
+
fs.mkdirSync(root, { recursive: true })
|
|
79
|
+
const rootResolved = path.resolve(root)
|
|
80
|
+
for (const [relative, content] of Object.entries(manifest.files)) {
|
|
81
|
+
const safe = safeRelativePath(relative)
|
|
82
|
+
if (!safe) throw new Error(`official source download: unsafe path ${relative}`)
|
|
83
|
+
const target = path.resolve(rootResolved, safe)
|
|
84
|
+
if (target !== rootResolved && !target.startsWith(rootResolved + path.sep)) {
|
|
85
|
+
throw new Error(`official source download: path escape ${relative}`)
|
|
86
|
+
}
|
|
87
|
+
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
88
|
+
fs.writeFileSync(target, String(content ?? ''), 'utf8')
|
|
89
|
+
}
|
|
90
|
+
return { version: manifest.version, files: Object.keys(manifest.files).length }
|
|
91
|
+
},
|
|
92
|
+
}
|
|
93
|
+
}
|