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/store.js
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 持久化注册表(HookStore)。
|
|
3
|
+
*
|
|
4
|
+
* 一份 JSON 文档落在 `$DSH_HOME/session-inject/hooks.json`,写入方式是同目录
|
|
5
|
+
* tmp + rename(同文件系统内原子)且权限 0600;读全在内存,所有变更串行排在一
|
|
6
|
+
* 条写链上,所以并发 HTTP 投递与管理 RPC 不会交错写。
|
|
7
|
+
*
|
|
8
|
+
* token 按原文存(能力 URL,威胁模型与 `$DSH_HOME/.credentials.yaml` 同级);
|
|
9
|
+
* 查找走 SHA-256 索引,请求路径上永远不比较明文密钥。
|
|
10
|
+
*/
|
|
11
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
12
|
+
import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
13
|
+
import { dirname } from 'node:path';
|
|
14
|
+
import { fail } from './errors.js';
|
|
15
|
+
/** 注册表文档版本;形状不匹配直接拒绝启动(fail-loud),绝不「当成空表」。 */
|
|
16
|
+
export const STORE_VERSION = 1;
|
|
17
|
+
/** 令牌随机字节数:32 字节 base64url 后 43 个字符。 */
|
|
18
|
+
export const TOKEN_BYTES = 32;
|
|
19
|
+
/** 令牌前缀,方便一眼认出这是 session-inject 的凭据。 */
|
|
20
|
+
export const TOKEN_PREFIX = 'si_';
|
|
21
|
+
/** 三种投递方式(插话 / 排队 / 静默),顺序即 UI 展示顺序。 */
|
|
22
|
+
export const MODES = Object.freeze(['steer', 'queue', 'passive']);
|
|
23
|
+
const MODE_SET = new Set(MODES);
|
|
24
|
+
const NAME_MAX = 48;
|
|
25
|
+
const TAGS_MAX = 6;
|
|
26
|
+
const TAG_MAX = 20;
|
|
27
|
+
const DELIVERY_TTL_MS = 24 * 60 * 60 * 1000;
|
|
28
|
+
const DELIVERY_MAX = 4000;
|
|
29
|
+
/** 判断一个 JSON 值是不是普通对象(数组与 null 都不算)。 */
|
|
30
|
+
function isRecord(value) {
|
|
31
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
32
|
+
}
|
|
33
|
+
/** 计算 bearer token 的索引摘要;注册表从不按明文建索引。 */
|
|
34
|
+
function digest(token) {
|
|
35
|
+
return createHash('sha256').update(token, 'utf8').digest('base64url');
|
|
36
|
+
}
|
|
37
|
+
/** 铸造一个不可猜的能力令牌。 */
|
|
38
|
+
function mintToken() {
|
|
39
|
+
return TOKEN_PREFIX + randomBytes(TOKEN_BYTES).toString('base64url');
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* 修剪并限定用户给的名称。
|
|
43
|
+
* @param value 任意 JSON 值。
|
|
44
|
+
* @returns 合法名称。
|
|
45
|
+
*/
|
|
46
|
+
export function normalizeName(value) {
|
|
47
|
+
if (typeof value !== 'string')
|
|
48
|
+
throw fail(400, 'bad-request', 'name 必须是字符串');
|
|
49
|
+
const name = value.trim();
|
|
50
|
+
if (name === '')
|
|
51
|
+
throw fail(400, 'bad-request', 'name 不能为空');
|
|
52
|
+
if ([...name].length > NAME_MAX)
|
|
53
|
+
throw fail(400, 'bad-request', `name 最多 ${NAME_MAX} 个字符`);
|
|
54
|
+
return name;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* 修剪、限定并去重标签列表;字符串按逗号切分(兼容 curl 里图省事写 `a,b`)。
|
|
58
|
+
* @param value 任意 JSON 值。
|
|
59
|
+
*/
|
|
60
|
+
export function normalizeTags(value) {
|
|
61
|
+
if (value === undefined || value === null)
|
|
62
|
+
return [];
|
|
63
|
+
const list = Array.isArray(value) ? value : String(value).split(',');
|
|
64
|
+
const tags = [];
|
|
65
|
+
for (const entry of list) {
|
|
66
|
+
if (typeof entry !== 'string')
|
|
67
|
+
throw fail(400, 'bad-request', 'tags 必须是字符串数组');
|
|
68
|
+
const tag = entry.trim();
|
|
69
|
+
if (tag === '')
|
|
70
|
+
continue;
|
|
71
|
+
if ([...tag].length > TAG_MAX)
|
|
72
|
+
throw fail(400, 'bad-request', `每个 tag 最多 ${TAG_MAX} 个字符`);
|
|
73
|
+
if (!tags.includes(tag))
|
|
74
|
+
tags.push(tag);
|
|
75
|
+
}
|
|
76
|
+
if (tags.length > TAGS_MAX)
|
|
77
|
+
throw fail(400, 'bad-request', `最多支持 ${TAGS_MAX} 个 tag`);
|
|
78
|
+
return tags;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* 校验投递方式。
|
|
82
|
+
* @param value 任意 JSON 值。
|
|
83
|
+
* @param fallback 缺省时用的方式(默认 steer)。
|
|
84
|
+
*/
|
|
85
|
+
export function normalizeMode(value, fallback = 'steer') {
|
|
86
|
+
if (value === undefined || value === null)
|
|
87
|
+
return fallback;
|
|
88
|
+
if (typeof value !== 'string' || !MODE_SET.has(value)) {
|
|
89
|
+
throw fail(400, 'bad-request', `mode 必须是 ${MODES.join('、')} 之一`);
|
|
90
|
+
}
|
|
91
|
+
return value;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* 一条端点的对外投影。
|
|
95
|
+
* @param hook 持久化记录。
|
|
96
|
+
* @returns 不含 token 的视图(maskedUrl 只留前缀与末 4 位)。
|
|
97
|
+
*/
|
|
98
|
+
export function hookView(hook) {
|
|
99
|
+
return {
|
|
100
|
+
id: hook.id,
|
|
101
|
+
sessionId: hook.sessionId,
|
|
102
|
+
name: hook.name,
|
|
103
|
+
tags: [...hook.tags],
|
|
104
|
+
defaultMode: hook.defaultMode,
|
|
105
|
+
enabled: hook.enabled,
|
|
106
|
+
createdBy: hook.createdBy ?? 'ui',
|
|
107
|
+
maskedUrl: `${TOKEN_PREFIX}${hook.token.slice(TOKEN_PREFIX.length, TOKEN_PREFIX.length + 4)}…${hook.token.slice(-4)}`,
|
|
108
|
+
createdAt: hook.createdAt,
|
|
109
|
+
lastUsedAt: hook.lastUsedAt ?? null,
|
|
110
|
+
lastStatus: hook.lastStatus ?? null,
|
|
111
|
+
lastError: hook.lastError ?? null,
|
|
112
|
+
deliveryCount: hook.deliveryCount ?? 0,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/** 一个插件激活周期内独占的注册表实例。 */
|
|
116
|
+
export class HookStore {
|
|
117
|
+
/** 注册表文档的绝对路径(README/运维与测试都用)。 */
|
|
118
|
+
file;
|
|
119
|
+
#hooks = new Map();
|
|
120
|
+
#byToken = new Map();
|
|
121
|
+
#deliveries = [];
|
|
122
|
+
/** 写链:每个变更挂在上一次写之后,保证落盘顺序与内存顺序一致。 */
|
|
123
|
+
#chain = Promise.resolve();
|
|
124
|
+
/** 幂等键 → deliveryId 的内存索引(文档里同时有持久副本)。 */
|
|
125
|
+
#pendingKeys = new Map();
|
|
126
|
+
#logger;
|
|
127
|
+
/**
|
|
128
|
+
* @param options 注册表绝对路径与可选 logger。
|
|
129
|
+
*/
|
|
130
|
+
constructor({ file, logger }) {
|
|
131
|
+
if (typeof file !== 'string' || file === '')
|
|
132
|
+
throw new TypeError('HookStore 需要文件路径');
|
|
133
|
+
this.file = file;
|
|
134
|
+
this.#logger = logger ?? null;
|
|
135
|
+
}
|
|
136
|
+
/** 载入并校验文档;文件不存在时从空表开始。 */
|
|
137
|
+
async load() {
|
|
138
|
+
let text;
|
|
139
|
+
try {
|
|
140
|
+
text = await readFile(this.file, 'utf8');
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
if (isRecord(error) && error.code === 'ENOENT')
|
|
144
|
+
return this;
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
let document;
|
|
148
|
+
try {
|
|
149
|
+
document = JSON.parse(text);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
throw new Error(`session-inject: ${this.file} 不是合法 JSON`);
|
|
153
|
+
}
|
|
154
|
+
if (!isRecord(document) || document.version !== STORE_VERSION || !Array.isArray(document.hooks)) {
|
|
155
|
+
throw new Error(`session-inject: ${this.file} 的形状不受支持`);
|
|
156
|
+
}
|
|
157
|
+
for (const entry of document.hooks) {
|
|
158
|
+
// 与原型一致:只校验 token/sessionId 两个键,其余字段按存量记录原样信任。
|
|
159
|
+
if (!isRecord(entry) || typeof entry.token !== 'string' || typeof entry.sessionId !== 'string')
|
|
160
|
+
continue;
|
|
161
|
+
const hook = entry;
|
|
162
|
+
// 存量记录没有 createdBy(任务书口径):归一成 'ui',这样下一次落盘就补齐,
|
|
163
|
+
// 撤销权限判定也不会把老端点误判成 agent 建的。
|
|
164
|
+
hook.createdBy = hook.createdBy === 'agent' ? 'agent' : 'ui';
|
|
165
|
+
this.#hooks.set(hook.id, hook);
|
|
166
|
+
this.#byToken.set(digest(hook.token), hook.id);
|
|
167
|
+
}
|
|
168
|
+
this.#deliveries = Array.isArray(document.deliveries) ? document.deliveries : [];
|
|
169
|
+
this.#pruneDeliveries();
|
|
170
|
+
return this;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* 列出端点,新的在前。
|
|
174
|
+
* @param sessionId 只列该会话的端点(省略则列全部)。
|
|
175
|
+
*/
|
|
176
|
+
list(sessionId) {
|
|
177
|
+
const hooks = [...this.#hooks.values()]
|
|
178
|
+
.filter((hook) => sessionId === undefined || hook.sessionId === sessionId)
|
|
179
|
+
.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
|
|
180
|
+
return hooks;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* 按公开 id 取一条端点。
|
|
184
|
+
* @param id 端点 id。
|
|
185
|
+
*/
|
|
186
|
+
get(id) {
|
|
187
|
+
return this.#hooks.get(id);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* 用 webhook URL 里的 bearer token 反查端点。
|
|
191
|
+
* @param token URL 路径里的原始 token。
|
|
192
|
+
* @returns 命中的记录,或 undefined。
|
|
193
|
+
*/
|
|
194
|
+
findByToken(token) {
|
|
195
|
+
if (typeof token !== 'string' || token.length === 0 || token.length > 128)
|
|
196
|
+
return undefined;
|
|
197
|
+
const id = this.#byToken.get(digest(token));
|
|
198
|
+
return id === undefined ? undefined : this.#hooks.get(id);
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* 建一个绑定到某会话的端点。
|
|
202
|
+
* @param input 会话 id、名称、可选标签与默认投递方式。
|
|
203
|
+
* @returns 新建的记录(含明文 token,只在进程内流转)。
|
|
204
|
+
*/
|
|
205
|
+
async create(input) {
|
|
206
|
+
const sessionId = input.sessionId;
|
|
207
|
+
if (typeof sessionId !== 'string' || sessionId.trim() === '') {
|
|
208
|
+
throw fail(400, 'bad-request', 'sessionId 是必填项');
|
|
209
|
+
}
|
|
210
|
+
const name = normalizeName(input.name);
|
|
211
|
+
const tags = normalizeTags(input.tags);
|
|
212
|
+
const defaultMode = normalizeMode(input.defaultMode);
|
|
213
|
+
const createdBy = input.createdBy === 'agent' ? 'agent' : 'ui';
|
|
214
|
+
const clash = this.list(sessionId).find((hook) => hook.name === name);
|
|
215
|
+
if (clash !== undefined) {
|
|
216
|
+
throw fail(409, 'name-taken', `当前会话已有名为「${name}」的端点`);
|
|
217
|
+
}
|
|
218
|
+
const token = mintToken();
|
|
219
|
+
const hook = {
|
|
220
|
+
id: `wh_${randomUUID()}`,
|
|
221
|
+
sessionId,
|
|
222
|
+
name,
|
|
223
|
+
tags,
|
|
224
|
+
token,
|
|
225
|
+
defaultMode,
|
|
226
|
+
enabled: true,
|
|
227
|
+
createdBy,
|
|
228
|
+
createdAt: new Date().toISOString(),
|
|
229
|
+
lastUsedAt: null,
|
|
230
|
+
lastStatus: null,
|
|
231
|
+
lastError: null,
|
|
232
|
+
deliveryCount: 0,
|
|
233
|
+
};
|
|
234
|
+
this.#hooks.set(hook.id, hook);
|
|
235
|
+
this.#byToken.set(digest(token), hook.id);
|
|
236
|
+
await this.#flush();
|
|
237
|
+
return hook;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* 局部更新一条端点。
|
|
241
|
+
* @param id 端点 id。
|
|
242
|
+
* @param patch 只带要改的字段。
|
|
243
|
+
* @returns 更新后的记录。
|
|
244
|
+
*/
|
|
245
|
+
async update(id, patch) {
|
|
246
|
+
const hook = this.#require(id);
|
|
247
|
+
const next = { ...hook };
|
|
248
|
+
if (patch.name !== undefined) {
|
|
249
|
+
const name = normalizeName(patch.name);
|
|
250
|
+
const clash = this.list(hook.sessionId).find((other) => other.id !== id && other.name === name);
|
|
251
|
+
if (clash !== undefined)
|
|
252
|
+
throw fail(409, 'name-taken', `当前会话已有名为「${name}」的端点`);
|
|
253
|
+
next.name = name;
|
|
254
|
+
}
|
|
255
|
+
if (patch.tags !== undefined)
|
|
256
|
+
next.tags = normalizeTags(patch.tags);
|
|
257
|
+
if (patch.defaultMode !== undefined)
|
|
258
|
+
next.defaultMode = normalizeMode(patch.defaultMode);
|
|
259
|
+
if (patch.enabled !== undefined) {
|
|
260
|
+
if (typeof patch.enabled !== 'boolean')
|
|
261
|
+
throw fail(400, 'bad-request', 'enabled 必须是布尔值');
|
|
262
|
+
next.enabled = patch.enabled;
|
|
263
|
+
}
|
|
264
|
+
this.#hooks.set(id, next);
|
|
265
|
+
await this.#flush();
|
|
266
|
+
return next;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* 永久删除一条端点;它的 URL 立刻失效。
|
|
270
|
+
* @param id 端点 id。
|
|
271
|
+
* @returns 被删掉的记录。
|
|
272
|
+
*/
|
|
273
|
+
async revoke(id) {
|
|
274
|
+
const hook = this.#require(id);
|
|
275
|
+
this.#hooks.delete(id);
|
|
276
|
+
this.#byToken.delete(digest(hook.token));
|
|
277
|
+
this.#deliveries = this.#deliveries.filter((record) => record.hookId !== id);
|
|
278
|
+
await this.#flush();
|
|
279
|
+
return hook;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* 占一次投递,并按调用方给的幂等键去重(键按端点隔离)。
|
|
283
|
+
* @param hook 目标端点。
|
|
284
|
+
* @param key 调用方幂等键(省略/空串表示不去重)。
|
|
285
|
+
* @returns 投递 id 与「是不是重复投递」。
|
|
286
|
+
*/
|
|
287
|
+
async beginDelivery(hook, key) {
|
|
288
|
+
if (key !== undefined && key !== null && key !== '') {
|
|
289
|
+
if (typeof key !== 'string' || key.length > 200) {
|
|
290
|
+
throw fail(400, 'bad-request', 'idempotencyKey 必须是最多 200 字符的字符串');
|
|
291
|
+
}
|
|
292
|
+
const memoryKey = `${hook.id}\u0000${key}`;
|
|
293
|
+
const pending = this.#pendingKeys.get(memoryKey);
|
|
294
|
+
if (pending !== undefined)
|
|
295
|
+
return { deliveryId: pending, existing: true };
|
|
296
|
+
const stored = this.#deliveries.find((record) => record.hookId === hook.id && record.key === key);
|
|
297
|
+
if (stored !== undefined) {
|
|
298
|
+
this.#pendingKeys.set(memoryKey, stored.deliveryId);
|
|
299
|
+
return { deliveryId: stored.deliveryId, existing: true };
|
|
300
|
+
}
|
|
301
|
+
const deliveryId = `dl_${randomUUID()}`;
|
|
302
|
+
this.#pendingKeys.set(memoryKey, deliveryId);
|
|
303
|
+
this.#deliveries.push({
|
|
304
|
+
hookId: hook.id,
|
|
305
|
+
key,
|
|
306
|
+
deliveryId,
|
|
307
|
+
status: 'pending',
|
|
308
|
+
createdAt: Date.now(),
|
|
309
|
+
});
|
|
310
|
+
this.#pruneDeliveries();
|
|
311
|
+
await this.#flush();
|
|
312
|
+
return { deliveryId, existing: false };
|
|
313
|
+
}
|
|
314
|
+
return { deliveryId: `dl_${randomUUID()}`, existing: false };
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* 记录一次投递的结局,并刷新端点上的最近使用列。
|
|
318
|
+
* @param hookId 端点 id。
|
|
319
|
+
* @param deliveryId 投递 id。
|
|
320
|
+
* @param status 结局(delivered / failed …)。
|
|
321
|
+
* @param error 失败 code(成功时省略)。
|
|
322
|
+
*/
|
|
323
|
+
async settleDelivery(hookId, deliveryId, status, error) {
|
|
324
|
+
const hook = this.#hooks.get(hookId);
|
|
325
|
+
if (hook !== undefined) {
|
|
326
|
+
this.#hooks.set(hookId, {
|
|
327
|
+
...hook,
|
|
328
|
+
lastUsedAt: new Date().toISOString(),
|
|
329
|
+
lastStatus: status,
|
|
330
|
+
lastError: error ?? null,
|
|
331
|
+
deliveryCount: (hook.deliveryCount ?? 0) + (status === 'delivered' ? 1 : 0),
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
const record = this.#deliveries.find((entry) => entry.deliveryId === deliveryId);
|
|
335
|
+
if (record !== undefined)
|
|
336
|
+
record.status = status;
|
|
337
|
+
await this.#flush();
|
|
338
|
+
}
|
|
339
|
+
/** 按 id 取记录,取不到即 404。 */
|
|
340
|
+
#require(id) {
|
|
341
|
+
const hook = typeof id === 'string' ? this.#hooks.get(id) : undefined;
|
|
342
|
+
if (hook === undefined)
|
|
343
|
+
throw fail(404, 'unknown-endpoint', '没有这个 id 的端点');
|
|
344
|
+
return hook;
|
|
345
|
+
}
|
|
346
|
+
/** 按 24h / 4000 条裁剪投递流水,并清掉悬浮的幂等键索引。 */
|
|
347
|
+
#pruneDeliveries() {
|
|
348
|
+
const cutoff = Date.now() - DELIVERY_TTL_MS;
|
|
349
|
+
this.#deliveries = this.#deliveries.filter((record) => record.createdAt >= cutoff);
|
|
350
|
+
if (this.#deliveries.length > DELIVERY_MAX) {
|
|
351
|
+
this.#deliveries = this.#deliveries.slice(-DELIVERY_MAX);
|
|
352
|
+
}
|
|
353
|
+
for (const [key, value] of this.#pendingKeys) {
|
|
354
|
+
if (!this.#deliveries.some((record) => record.deliveryId === value))
|
|
355
|
+
this.#pendingKeys.delete(key);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* 把当前内存快照排到写链尾部落盘。
|
|
360
|
+
* 内存快照在入队时就冻结,所以后到的变更不会影响已排队的这一份。
|
|
361
|
+
*/
|
|
362
|
+
#flush() {
|
|
363
|
+
const snapshot = JSON.stringify({
|
|
364
|
+
version: STORE_VERSION,
|
|
365
|
+
hooks: [...this.#hooks.values()],
|
|
366
|
+
deliveries: this.#deliveries,
|
|
367
|
+
}, null, 2);
|
|
368
|
+
const run = this.#chain.then(async () => {
|
|
369
|
+
const directory = dirname(this.file);
|
|
370
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
371
|
+
const temporary = `${this.file}.${String(process.pid)}.${String(Date.now())}.tmp`;
|
|
372
|
+
await writeFile(temporary, snapshot, { mode: 0o600 });
|
|
373
|
+
await chmod(temporary, 0o600);
|
|
374
|
+
await rename(temporary, this.file);
|
|
375
|
+
});
|
|
376
|
+
this.#chain = run.catch((error) => {
|
|
377
|
+
this.#logger?.warn?.(`[session-inject] store write failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
378
|
+
});
|
|
379
|
+
return run;
|
|
380
|
+
}
|
|
381
|
+
}
|