dsh-session-webhook 0.0.0-stage → 0.2.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.md +412 -2
- package/cordis.patch.yml +8 -0
- package/docs/ACCEPTANCE.md +158 -0
- package/docs/DESIGN.md +136 -0
- package/docs/TOOL-CONTRACT.md +315 -0
- package/icon.svg +13 -0
- package/lib/bases.js +527 -0
- package/lib/client.js +1755 -0
- package/lib/control.js +321 -0
- package/lib/deliver.js +272 -0
- package/lib/errors.js +62 -0
- package/lib/http.js +258 -0
- package/lib/index.js +220 -0
- package/lib/store.js +381 -0
- package/lib/tools.js +433 -0
- package/lib/types.js +1 -0
- package/lib/urlfile.js +290 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +72 -4
- package/scripts/cold-resume-health.mjs +268 -0
- package/scripts/verify-client.mjs +1199 -0
- package/scripts/verify-health-contract.mjs +173 -0
- package/scripts/verify-host.mjs +1322 -0
package/lib/bases.js
ADDED
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 命名入口(publicBaseUrls)与设置持久化。
|
|
3
|
+
*
|
|
4
|
+
* 概念区分(见 docs/DESIGN.md §3):**端点决定「谁收」,入口决定「怎么到达」**。
|
|
5
|
+
* 同一个令牌可以有多条可达路径,例如内网直连 `http://dsh.internal.example:3080` 与反代
|
|
6
|
+
* `https://dsh.corp.example/dsh`。入口是管理员配置,agent 不可指定。
|
|
7
|
+
*
|
|
8
|
+
* 本模块只做四件事,全部是纯逻辑或纯文件 I/O,不碰 cordis 服务:
|
|
9
|
+
* 1. 校验:名称、URL、默认入口、限额(错误码供设置页与工具复用);
|
|
10
|
+
* 2. `BaseResolver`:把「显式入口 + 隐式 direct」解析成完整的入口集合与 URL;
|
|
11
|
+
* 3. `RuntimeConfig`:插件激活时的生效快照,`config/set` 成功后可原地替换;
|
|
12
|
+
* 4. `SettingsStore`:`$DSH_HOME/session-inject/settings.json` 的原子读写。
|
|
13
|
+
*
|
|
14
|
+
* direct 入口的 origin 必须**用时现取**:`webServer.getOrigin()` 在监听端口绑定前
|
|
15
|
+
* 会抛错,原实现把它 catch 成空串缓存,会静默产出相对路径 URL——这正是本模块
|
|
16
|
+
* 要修掉的隐患。取不到时明确抛错,绝不回落。
|
|
17
|
+
*/
|
|
18
|
+
import { chmod, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
19
|
+
import { dirname } from 'node:path';
|
|
20
|
+
import { randomUUID } from 'node:crypto';
|
|
21
|
+
import { fail } from './errors.js';
|
|
22
|
+
/** 隐式入口名:恒存在,默认取 `webServer.getOrigin()`。 */
|
|
23
|
+
export const DIRECT_BASE_NAME = 'direct';
|
|
24
|
+
/** 入口名称规则:小写字母开头,只含小写字母、数字与连字符。 */
|
|
25
|
+
export const BASE_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
26
|
+
/** 入口名称长度上限(同时约束 urlFile 文件名长度)。 */
|
|
27
|
+
export const BASE_NAME_MAX = 48;
|
|
28
|
+
/** 一次配置里允许的显式入口数量上限(含 direct 覆盖)。 */
|
|
29
|
+
export const BASE_COUNT_MAX = 20;
|
|
30
|
+
/** 限额取值范围;设置页按同一组数字做本地预检,避免「界面放过、Host 才拒」。 */
|
|
31
|
+
export const LIMIT_BOUNDS = Object.freeze({
|
|
32
|
+
maxBodyBytes: Object.freeze({ min: 1024, max: 64 * 1024 * 1024 }),
|
|
33
|
+
maxTextBytes: Object.freeze({ min: 1, max: 1024 * 1024 }),
|
|
34
|
+
ratePerMinute: Object.freeze({ min: 1, max: 6000 }),
|
|
35
|
+
});
|
|
36
|
+
/** 三个限额的默认值(与 index.ts 的 Config 默认值保持一致)。 */
|
|
37
|
+
export const DEFAULT_LIMITS = Object.freeze({
|
|
38
|
+
maxBodyBytes: 1024 * 1024,
|
|
39
|
+
maxTextBytes: 64 * 1024,
|
|
40
|
+
ratePerMinute: 60,
|
|
41
|
+
});
|
|
42
|
+
/** 把任意输入规范成一个入口名称,或抛出中文校验错误。 */
|
|
43
|
+
export function normalizeBaseName(value) {
|
|
44
|
+
if (typeof value !== 'string') {
|
|
45
|
+
throw fail(400, 'invalid-name', '入口名称必须是字符串');
|
|
46
|
+
}
|
|
47
|
+
const name = value.trim();
|
|
48
|
+
if (name === '')
|
|
49
|
+
throw fail(400, 'invalid-name', '入口名称不能为空');
|
|
50
|
+
if (name.length > BASE_NAME_MAX) {
|
|
51
|
+
throw fail(400, 'invalid-name', `入口名称最多 ${BASE_NAME_MAX} 个字符`);
|
|
52
|
+
}
|
|
53
|
+
if (!BASE_NAME_PATTERN.test(name)) {
|
|
54
|
+
throw fail(400, 'invalid-name', `入口名称必须以小写字母开头,且只含小写字母、数字与连字符(实际:${JSON.stringify(value)})`);
|
|
55
|
+
}
|
|
56
|
+
return name;
|
|
57
|
+
}
|
|
58
|
+
/** 把任意输入规范成一个入口 URL,或抛出中文校验错误。 */
|
|
59
|
+
export function normalizeBaseUrl(value) {
|
|
60
|
+
if (typeof value !== 'string') {
|
|
61
|
+
throw fail(400, 'invalid-url', '入口 URL 必须是字符串');
|
|
62
|
+
}
|
|
63
|
+
const text = value.trim();
|
|
64
|
+
if (text === '')
|
|
65
|
+
throw fail(400, 'invalid-url', '入口 URL 不能为空');
|
|
66
|
+
let parsed;
|
|
67
|
+
try {
|
|
68
|
+
parsed = new URL(text);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
throw fail(400, 'invalid-url', `入口 URL 不是合法的绝对地址(实际:${JSON.stringify(value)})`);
|
|
72
|
+
}
|
|
73
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
74
|
+
throw fail(400, 'invalid-url', `入口 URL 必须以 http:// 或 https:// 开头(实际:${JSON.stringify(value)})`);
|
|
75
|
+
}
|
|
76
|
+
// 入口是「基地址」:查询串与片段无法与后面的固定路径拼接,必须显式拒绝。
|
|
77
|
+
if (parsed.search !== '' || parsed.hash !== '') {
|
|
78
|
+
throw fail(400, 'invalid-url', '入口 URL 不能带查询参数或片段(? 与 #)');
|
|
79
|
+
}
|
|
80
|
+
// 统一去掉尾斜杠:拼接时由调用方补上唯一的 `/`。
|
|
81
|
+
const trimmed = text.replace(/\/+$/, '');
|
|
82
|
+
return trimmed === '' ? text : trimmed;
|
|
83
|
+
}
|
|
84
|
+
/** 校验「名称 → URL」的入口映射;`undefined`/`null` 视为未配置。 */
|
|
85
|
+
export function normalizePublicBaseUrls(value) {
|
|
86
|
+
if (value === undefined || value === null)
|
|
87
|
+
return {};
|
|
88
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
89
|
+
throw fail(400, 'bad-request', 'publicBaseUrls 必须是「入口名称 → URL」的对象');
|
|
90
|
+
}
|
|
91
|
+
const entries = Object.entries(value);
|
|
92
|
+
if (entries.length > BASE_COUNT_MAX) {
|
|
93
|
+
throw fail(400, 'bad-request', `最多配置 ${BASE_COUNT_MAX} 个显式入口`);
|
|
94
|
+
}
|
|
95
|
+
const urls = {};
|
|
96
|
+
for (const [rawName, rawUrl] of entries) {
|
|
97
|
+
const name = normalizeBaseName(rawName);
|
|
98
|
+
urls[name] = normalizeBaseUrl(rawUrl);
|
|
99
|
+
}
|
|
100
|
+
return urls;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* 校验默认入口:必须存在于入口映射里(`direct` 恒存在),否则报错。
|
|
104
|
+
* @param value 配置值;空值表示未配置,回落到 `direct`。
|
|
105
|
+
* @param urls 有效的显式入口映射。
|
|
106
|
+
* @returns 有效的默认入口名。
|
|
107
|
+
*/
|
|
108
|
+
export function normalizeDefaultBase(value, urls) {
|
|
109
|
+
if (value === undefined || value === null || value === '')
|
|
110
|
+
return DIRECT_BASE_NAME;
|
|
111
|
+
const name = normalizeBaseName(value);
|
|
112
|
+
const available = [DIRECT_BASE_NAME, ...Object.keys(urls).filter((key) => key !== DIRECT_BASE_NAME)];
|
|
113
|
+
if (name !== DIRECT_BASE_NAME && !Object.hasOwn(urls, name)) {
|
|
114
|
+
throw fail(400, 'unknown-base', `默认入口「${name}」不在入口表中(可用:${available.join('、')})`, { defaultBase: name, available });
|
|
115
|
+
}
|
|
116
|
+
return name;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* 读取限额:字段缺省时沿用 `fallback`,并逐项校验范围与跨字段关系。
|
|
120
|
+
* @param value 配置值;必须是普通对象(`undefined` 表示整段沿用 fallback)。
|
|
121
|
+
* @param fallback 缺省字段的回退值;不传时要求三个字段齐全(设置文件的语义)。
|
|
122
|
+
* @returns 生效限额。
|
|
123
|
+
*/
|
|
124
|
+
export function normalizeLimits(value, fallback) {
|
|
125
|
+
if (value === undefined && fallback !== undefined)
|
|
126
|
+
return { ...fallback };
|
|
127
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
128
|
+
throw fail(400, 'bad-request', 'limits 必须是对象');
|
|
129
|
+
}
|
|
130
|
+
const source = value;
|
|
131
|
+
const result = {
|
|
132
|
+
maxBodyBytes: fallback?.maxBodyBytes ?? Number.NaN,
|
|
133
|
+
maxTextBytes: fallback?.maxTextBytes ?? Number.NaN,
|
|
134
|
+
ratePerMinute: fallback?.ratePerMinute ?? Number.NaN,
|
|
135
|
+
};
|
|
136
|
+
for (const field of Object.keys(LIMIT_BOUNDS)) {
|
|
137
|
+
if (!Object.hasOwn(source, field)) {
|
|
138
|
+
if (Number.isNaN(result[field])) {
|
|
139
|
+
throw fail(400, 'invalid-limit', `limits 缺少字段 ${field}`);
|
|
140
|
+
}
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
result[field] = normalizeLimitValue(field, source[field]);
|
|
144
|
+
}
|
|
145
|
+
if (result.maxTextBytes > result.maxBodyBytes) {
|
|
146
|
+
throw fail(400, 'invalid-limit', `maxTextBytes(${result.maxTextBytes})不能大于 maxBodyBytes(${result.maxBodyBytes})`, { field: 'maxTextBytes', maxBodyBytes: result.maxBodyBytes });
|
|
147
|
+
}
|
|
148
|
+
return result;
|
|
149
|
+
}
|
|
150
|
+
/** 校验单个限额字段的整数性与范围。 */
|
|
151
|
+
function normalizeLimitValue(field, value) {
|
|
152
|
+
const bounds = LIMIT_BOUNDS[field];
|
|
153
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < bounds.min || value > bounds.max) {
|
|
154
|
+
throw fail(400, 'invalid-limit', `${field} 必须是 ${bounds.min} 到 ${bounds.max} 之间的整数(实际:${JSON.stringify(value)})`, { field, min: bounds.min, max: bounds.max });
|
|
155
|
+
}
|
|
156
|
+
return value;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* 校验插件 Config 里的入口字段(YAML 层,启动时调用,失败即终止激活)。
|
|
160
|
+
* @param config 解析后的插件配置。
|
|
161
|
+
* @returns 显式入口映射与默认入口名。
|
|
162
|
+
*/
|
|
163
|
+
export function resolveBaseConfig(config) {
|
|
164
|
+
const explicit = normalizePublicBaseUrls(config.publicBaseUrls);
|
|
165
|
+
const defaultBase = normalizeDefaultBase(config.defaultBase, explicit);
|
|
166
|
+
return { explicit, defaultBase };
|
|
167
|
+
}
|
|
168
|
+
/** 一个生效入口的完整 base URL。 */
|
|
169
|
+
export function composeHookUrl(base, basePath, token) {
|
|
170
|
+
return `${base}${basePath}/hooks/${token}`;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* 入口解析器:显式入口(配置)+ 隐式 direct(现取 origin)。
|
|
174
|
+
*
|
|
175
|
+
* 不可变对象;`config/set` 保存成功后由 `RuntimeConfig` 换一个新实例,
|
|
176
|
+
* 因此每次取 URL 都读到最新配置,不需要重启插件。
|
|
177
|
+
*/
|
|
178
|
+
export class BaseResolver {
|
|
179
|
+
#explicit;
|
|
180
|
+
#defaultBase;
|
|
181
|
+
#directOrigin;
|
|
182
|
+
/**
|
|
183
|
+
* @param explicit 显式入口映射(已校验)。
|
|
184
|
+
* @param defaultBase 默认入口名(已校验存在于集合中)。
|
|
185
|
+
* @param directOrigin 现取 direct origin 的函数;取不到时应抛错。
|
|
186
|
+
*/
|
|
187
|
+
constructor(explicit, defaultBase, directOrigin) {
|
|
188
|
+
this.#explicit = { ...explicit };
|
|
189
|
+
this.#defaultBase = normalizeDefaultBase(defaultBase, this.#explicit);
|
|
190
|
+
this.#directOrigin = directOrigin;
|
|
191
|
+
}
|
|
192
|
+
/** 有效的显式入口映射(副本,不含隐式 direct)。 */
|
|
193
|
+
get explicit() {
|
|
194
|
+
return { ...this.#explicit };
|
|
195
|
+
}
|
|
196
|
+
/** 默认入口名。 */
|
|
197
|
+
get defaultBase() {
|
|
198
|
+
return this.#defaultBase;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* 全部入口名:`direct` 恒在首位,其余按名称排序(保证 urlFile 输出稳定)。
|
|
202
|
+
* @returns 入口名数组。
|
|
203
|
+
*/
|
|
204
|
+
names() {
|
|
205
|
+
const named = Object.keys(this.#explicit).filter((key) => key !== DIRECT_BASE_NAME).sort();
|
|
206
|
+
return [DIRECT_BASE_NAME, ...named];
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* 现取全部入口的 base URL。
|
|
210
|
+
*
|
|
211
|
+
* `direct` 恒存在:配置里没显式给 `direct` 时才去现取 origin(显式值覆盖默认值),
|
|
212
|
+
* 所以纯反代部署即使 `getOrigin()` 不可用也能照常拼非 direct 入口的 URL。
|
|
213
|
+
* @returns 入口名 → base URL。
|
|
214
|
+
* @throws 当 direct 需要现取而 origin 取不到时(fail-loud,不回落空串)。
|
|
215
|
+
*/
|
|
216
|
+
bases() {
|
|
217
|
+
const result = { ...this.#explicit };
|
|
218
|
+
if (!Object.hasOwn(result, DIRECT_BASE_NAME))
|
|
219
|
+
result[DIRECT_BASE_NAME] = this.directOrigin();
|
|
220
|
+
return result;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* 现取 direct origin。
|
|
224
|
+
* @returns 例如 `http://127.0.0.1:3080`。
|
|
225
|
+
* @throws `direct-origin-unavailable`:`webServer.getOrigin()` 抛错(监听未绑定等
|
|
226
|
+
* 宿主状态问题)或返回值不是合法 http(s) URL。绝不回落空串——那会产出相对路径 URL。
|
|
227
|
+
*/
|
|
228
|
+
directOrigin() {
|
|
229
|
+
let raw;
|
|
230
|
+
try {
|
|
231
|
+
raw = this.#directOrigin();
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
235
|
+
throw fail(503, 'direct-origin-unavailable', `取不到本机直连 origin(webServer.getOrigin 抛错:${reason}),无法生成完整 URL;`
|
|
236
|
+
+ '请在 publicBaseUrls 里显式配置 direct 入口。');
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
return normalizeBaseUrl(raw);
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
243
|
+
throw fail(503, 'direct-origin-unavailable', `webServer.getOrigin() 返回的不是合法 http(s) URL(${reason}),无法生成完整 URL。`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* 一个令牌在全部入口下的完整 URL。
|
|
248
|
+
* @param basePath 投递路由前缀。
|
|
249
|
+
* @param token 端点令牌。
|
|
250
|
+
* @returns 入口名 → 完整 URL。
|
|
251
|
+
*/
|
|
252
|
+
urlsFor(basePath, token) {
|
|
253
|
+
const result = {};
|
|
254
|
+
for (const [name, base] of Object.entries(this.bases())) {
|
|
255
|
+
result[name] = composeHookUrl(base, basePath, token);
|
|
256
|
+
}
|
|
257
|
+
return result;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* 默认入口下的完整 URL。
|
|
261
|
+
* @param basePath 投递路由前缀。
|
|
262
|
+
* @param token 端点令牌。
|
|
263
|
+
* @returns 完整 URL。
|
|
264
|
+
* @throws 当默认入口缺失(理论上不可能,构造时已校验)时,宁可报错也不拼相对路径。
|
|
265
|
+
*/
|
|
266
|
+
urlFor(basePath, token) {
|
|
267
|
+
const base = this.bases()[this.#defaultBase];
|
|
268
|
+
if (base === undefined) {
|
|
269
|
+
throw fail(500, 'unknown-base', `默认入口「${this.#defaultBase}」不在入口表中`);
|
|
270
|
+
}
|
|
271
|
+
return composeHookUrl(base, basePath, token);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* 插件激活时的生效配置快照。
|
|
276
|
+
*
|
|
277
|
+
* 优先级(Lead 定稿,唯一实现在本类,不要散落到调用点):
|
|
278
|
+
*
|
|
279
|
+
* 生效值 = settings.json(键存在时) > YAML 配置层 > 隐式默认
|
|
280
|
+
*
|
|
281
|
+
* 隐式默认 = `direct` 入口取 `webServer.getOrigin()`、限额取 `DEFAULT_LIMITS`。
|
|
282
|
+
*
|
|
283
|
+
* 存在的理由:`config/set` 保存后要在**同一个进程里**立刻生效(URL 文件重写、
|
|
284
|
+
* 投递限额重建),而不是等一次插件重载。设置页保存后调用 `replaceSettings()`,
|
|
285
|
+
* 所有读 URL / 读限额的代码路径都通过本对象取值。
|
|
286
|
+
*/
|
|
287
|
+
export class RuntimeConfig {
|
|
288
|
+
#basePath;
|
|
289
|
+
#yaml;
|
|
290
|
+
#directOrigin;
|
|
291
|
+
#settings;
|
|
292
|
+
#bases;
|
|
293
|
+
#limits;
|
|
294
|
+
constructor(options) {
|
|
295
|
+
this.#basePath = options.basePath;
|
|
296
|
+
this.#yaml = { ...options.yaml };
|
|
297
|
+
this.#settings = { ...(options.settings ?? {}) };
|
|
298
|
+
this.#directOrigin = options.directOrigin;
|
|
299
|
+
const resolved = this.#resolve();
|
|
300
|
+
this.#bases = resolved.bases;
|
|
301
|
+
this.#limits = resolved.limits;
|
|
302
|
+
}
|
|
303
|
+
/** 投递路由前缀。 */
|
|
304
|
+
get basePath() {
|
|
305
|
+
return this.#basePath;
|
|
306
|
+
}
|
|
307
|
+
/** 当前入口解析器。 */
|
|
308
|
+
get bases() {
|
|
309
|
+
return this.#bases;
|
|
310
|
+
}
|
|
311
|
+
/** 当前生效限额(副本)。 */
|
|
312
|
+
get limits() {
|
|
313
|
+
return { ...this.#limits };
|
|
314
|
+
}
|
|
315
|
+
/** 当前生效的显式入口映射(不含隐式 direct;`config/set` 的局部更新基线)。 */
|
|
316
|
+
get explicitBases() {
|
|
317
|
+
return this.#bases.explicit;
|
|
318
|
+
}
|
|
319
|
+
/** 当前生效的默认入口名。 */
|
|
320
|
+
get effectiveDefaultBase() {
|
|
321
|
+
return this.#bases.defaultBase;
|
|
322
|
+
}
|
|
323
|
+
/** 当前生效的界面覆盖层(副本;`config/reset` 的删除基线)。 */
|
|
324
|
+
get settingsLayer() {
|
|
325
|
+
return copyLayer(this.#settings);
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* 只校验一个候选界面层,不改生效值(`config/reset` 在落盘前用)。
|
|
329
|
+
*
|
|
330
|
+
* 删除覆盖键可能让 `defaultBase` 指向一个只存在于被删层里的入口,所以必须
|
|
331
|
+
* **先校验再落盘**:失败时 settings.json 与生效值都保持原样。
|
|
332
|
+
* @param settings 候选界面层。
|
|
333
|
+
* @throws `unknown-base` / `invalid-limit` 等校验失败。
|
|
334
|
+
*/
|
|
335
|
+
validateSettings(settings) {
|
|
336
|
+
this.#resolveWith(settings);
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* 用一次校验通过的界面层替换生效值(`config/set` / `config/reset` 持久化成功后调用)。
|
|
340
|
+
* @param settings 新的界面层。
|
|
341
|
+
*/
|
|
342
|
+
replaceSettings(settings) {
|
|
343
|
+
const resolved = this.#resolveWith(settings);
|
|
344
|
+
this.#settings = { ...settings };
|
|
345
|
+
this.#bases = resolved.bases;
|
|
346
|
+
this.#limits = resolved.limits;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* 设置页读取用的三层视图(`config/get` 与 `config/set` 共用)。
|
|
350
|
+
*
|
|
351
|
+
* 与前文的 fail-loud 不矛盾:**取 URL 的路径**(create/reveal/urlFile)取不到 origin
|
|
352
|
+
* 会明确抛 `direct-origin-unavailable`;而**查看配置**要能显示这种状态,所以这里
|
|
353
|
+
* 捕获它并回 `directOrigin: null` + `directError`,绝不静默成空串。
|
|
354
|
+
* @returns 三层视图。
|
|
355
|
+
*/
|
|
356
|
+
describe() {
|
|
357
|
+
const effective = {
|
|
358
|
+
publicBaseUrls: {},
|
|
359
|
+
defaultBase: this.#bases.defaultBase,
|
|
360
|
+
limits: this.limits,
|
|
361
|
+
};
|
|
362
|
+
let directOrigin = null;
|
|
363
|
+
let directError;
|
|
364
|
+
try {
|
|
365
|
+
directOrigin = this.#bases.directOrigin();
|
|
366
|
+
effective.publicBaseUrls = this.#bases.bases();
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
directError = error instanceof Error ? error.message : String(error);
|
|
370
|
+
// 取不到 origin 时仍把已知的显式入口回给界面(显式 direct 也在其中)。
|
|
371
|
+
effective.publicBaseUrls = this.#bases.explicit;
|
|
372
|
+
}
|
|
373
|
+
return {
|
|
374
|
+
yaml: copyLayer(this.#yaml),
|
|
375
|
+
settings: copyLayer(this.#settings),
|
|
376
|
+
effective,
|
|
377
|
+
directOrigin,
|
|
378
|
+
...(directError === undefined ? {} : { directError }),
|
|
379
|
+
basePath: this.#basePath,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
/** 按当前生效的界面层算出生效入口与限额。 */
|
|
383
|
+
#resolve() {
|
|
384
|
+
return this.#resolveWith(this.#settings);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* 按一个候选界面层算出生效入口与限额(优先级唯一实现)。
|
|
388
|
+
* @param settings 候选界面层。
|
|
389
|
+
*/
|
|
390
|
+
#resolveWith(settings) {
|
|
391
|
+
const explicit = settings.publicBaseUrls
|
|
392
|
+
?? this.#yaml.publicBaseUrls
|
|
393
|
+
?? {};
|
|
394
|
+
const defaultBase = normalizeDefaultBase(settings.defaultBase ?? this.#yaml.defaultBase, explicit);
|
|
395
|
+
const limits = normalizeLimits({
|
|
396
|
+
...DEFAULT_LIMITS,
|
|
397
|
+
...this.#yaml.limits,
|
|
398
|
+
...settings.limits,
|
|
399
|
+
});
|
|
400
|
+
return { bases: new BaseResolver(explicit, defaultBase, this.#directOrigin), limits };
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/** 复制一层视图(避免调用方改到内部状态)。 */
|
|
404
|
+
function copyLayer(layer) {
|
|
405
|
+
return {
|
|
406
|
+
...(layer.publicBaseUrls === undefined ? {} : { publicBaseUrls: { ...layer.publicBaseUrls } }),
|
|
407
|
+
...(layer.defaultBase === undefined ? {} : { defaultBase: layer.defaultBase }),
|
|
408
|
+
...(layer.limits === undefined ? {} : { limits: { ...layer.limits } }),
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
/** 设置文件版本号;形状不匹配即视为损坏并报错,不静默重置。 */
|
|
412
|
+
export const SETTINGS_VERSION = 1;
|
|
413
|
+
/**
|
|
414
|
+
* 设置页写入的持久化层:`$DSH_HOME/session-inject/settings.json`。
|
|
415
|
+
*
|
|
416
|
+
* 为什么自存文件而不是 `ctx.configEditor.edit`:后者写的是 profile patch YAML,
|
|
417
|
+
* 且入口的普通字段一变,Loader 会**重挂载插件**(volatile-only 才就地更新)。
|
|
418
|
+
* 重挂载发生在 RPC 返回之前,等于让「保存」这个调用拆掉自己正在用的管理路由;
|
|
419
|
+
* 生效时机也不由我们控制。自存文件让「保存 → 立即生效」成为确定事实,
|
|
420
|
+
* 重启后 `apply` 再读一次即可恢复。
|
|
421
|
+
*
|
|
422
|
+
* 语义:设置文件是 GUI 的全量覆盖层(`publicBaseUrls` 整表替换、`defaultBase`
|
|
423
|
+
* 覆盖、`limits` 逐字段覆盖);文件不存在表示没有 GUI 覆盖,全部沿用 YAML。
|
|
424
|
+
*/
|
|
425
|
+
export class SettingsStore {
|
|
426
|
+
#file;
|
|
427
|
+
#logger;
|
|
428
|
+
#writes = Promise.resolve();
|
|
429
|
+
constructor(options) {
|
|
430
|
+
if (typeof options.file !== 'string' || options.file === '') {
|
|
431
|
+
throw new TypeError('SettingsStore 需要文件路径');
|
|
432
|
+
}
|
|
433
|
+
this.#file = options.file;
|
|
434
|
+
this.#logger = options.logger ?? null;
|
|
435
|
+
}
|
|
436
|
+
/** 设置文件的绝对路径(供 README/运维与测试断言)。 */
|
|
437
|
+
get file() {
|
|
438
|
+
return this.#file;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* 读取并校验设置文件;不存在返回 `undefined`(表示没有界面覆盖)。
|
|
442
|
+
*
|
|
443
|
+
* 按**键**独立校验:文件里只有哪些键,就覆盖哪些键(`config/get` 的 settings 层
|
|
444
|
+
* 也用同一形状)。跨字段关系(defaultBase 是否存在于入口表)留给 `RuntimeConfig`
|
|
445
|
+
* 合并后统一校验,这样「YAML 提供入口表、settings 只覆盖 defaultBase」也能成立。
|
|
446
|
+
* @returns 校验过的覆盖层,或 undefined。
|
|
447
|
+
*/
|
|
448
|
+
async load() {
|
|
449
|
+
let text;
|
|
450
|
+
try {
|
|
451
|
+
text = await readFile(this.#file, 'utf8');
|
|
452
|
+
}
|
|
453
|
+
catch (error) {
|
|
454
|
+
if (error.code === 'ENOENT')
|
|
455
|
+
return undefined;
|
|
456
|
+
throw error;
|
|
457
|
+
}
|
|
458
|
+
let document;
|
|
459
|
+
try {
|
|
460
|
+
document = JSON.parse(text);
|
|
461
|
+
}
|
|
462
|
+
catch {
|
|
463
|
+
throw new Error(`session-inject: ${this.#file} 不是合法 JSON`);
|
|
464
|
+
}
|
|
465
|
+
if (document === null || typeof document !== 'object' || Array.isArray(document)) {
|
|
466
|
+
throw new Error(`session-inject: ${this.#file} 的形状不受支持`);
|
|
467
|
+
}
|
|
468
|
+
const record = document;
|
|
469
|
+
if (record.version !== SETTINGS_VERSION) {
|
|
470
|
+
throw new Error(`session-inject: ${this.#file} 的版本不受支持(期望 ${SETTINGS_VERSION})`);
|
|
471
|
+
}
|
|
472
|
+
const layer = {};
|
|
473
|
+
if (record.publicBaseUrls !== undefined)
|
|
474
|
+
layer.publicBaseUrls = normalizePublicBaseUrls(record.publicBaseUrls);
|
|
475
|
+
if (record.defaultBase !== undefined)
|
|
476
|
+
layer.defaultBase = normalizeBaseName(record.defaultBase);
|
|
477
|
+
if (record.limits !== undefined)
|
|
478
|
+
layer.limits = normalizeLimits(record.limits);
|
|
479
|
+
return layer;
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* 原子写入设置文件(目录 0700、文件 0600),写链串行化避免并发半写。
|
|
483
|
+
*
|
|
484
|
+
* 写的是**覆盖层**:`publicBaseUrls` / `defaultBase` / `limits` 三个键各自独立,
|
|
485
|
+
* 哪个键存在就覆盖哪个键(`config/reset` 删掉某个键后自然回落到 YAML 层)。
|
|
486
|
+
* @param layer 待持久化的覆盖层。
|
|
487
|
+
*/
|
|
488
|
+
async save(layer) {
|
|
489
|
+
const snapshot = JSON.stringify({
|
|
490
|
+
version: SETTINGS_VERSION,
|
|
491
|
+
...copyLayer(layer),
|
|
492
|
+
}, null, 2);
|
|
493
|
+
await this.#enqueue(async () => {
|
|
494
|
+
const directory = dirname(this.#file);
|
|
495
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
496
|
+
const temporary = `${this.#file}.${process.pid}.${randomUUID()}.tmp`;
|
|
497
|
+
await writeFile(temporary, `${snapshot}\n`, { mode: 0o600 });
|
|
498
|
+
await chmod(temporary, 0o600);
|
|
499
|
+
await rename(temporary, this.#file);
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* 删除设置文件(`config/reset` 把覆盖层清空时用)。
|
|
504
|
+
*
|
|
505
|
+
* 语义上等价于「没有任何界面覆盖」;文件不存在时静默成功(幂等)。
|
|
506
|
+
*/
|
|
507
|
+
async clear() {
|
|
508
|
+
await this.#enqueue(async () => {
|
|
509
|
+
try {
|
|
510
|
+
await unlink(this.#file);
|
|
511
|
+
}
|
|
512
|
+
catch (error) {
|
|
513
|
+
if (!(error instanceof Error) || error.code !== 'ENOENT')
|
|
514
|
+
throw error;
|
|
515
|
+
}
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
/** 把一次文件操作串到写链上,失败只记日志但仍让后续操作继续。 */
|
|
519
|
+
async #enqueue(operation) {
|
|
520
|
+
const run = this.#writes.then(operation);
|
|
521
|
+
this.#writes = run.catch((error) => {
|
|
522
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
523
|
+
this.#logger?.warn?.(`[session-inject] 设置文件写入失败:${message}`);
|
|
524
|
+
});
|
|
525
|
+
await run;
|
|
526
|
+
}
|
|
527
|
+
}
|