engine7 7.1.133 → 7.1.137
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 +1 -0
- package/dist/auth-server.mjs +632 -0
- package/dist/bg-worker.mjs +31663 -28486
- package/dist/cc-desktop.mjs +951 -0
- package/dist/cli.mjs +41495 -30171
- package/dist/engine-startup.mjs +54213 -40973
- package/dist/main.mjs +50129 -36887
- package/dist/recall-worker.mjs +20446 -0
- package/dist/sqlite-maintenance-worker.mjs +1166 -124
- package/dist/stop-history-worker.mjs +180 -0
- package/dist/topics-worker.mjs +3353 -1078
- package/dist/travel-authority.mjs +1068 -0
- package/dist/travel-console.mjs +2206 -0
- package/dist/travel-controller.mjs +1883 -0
- package/dist/travel-data.mjs +7253 -0
- package/dist/travel-gateway.mjs +3259 -0
- package/dist/travel-key-service.mjs +483 -0
- package/dist/travel-node-data.mjs +4936 -0
- package/dist/travel-node.mjs +21258 -0
- package/dist/travel-retire.mjs +1095 -0
- package/dist/web-console.mjs +3355 -0
- package/package.json +32 -17
- package/templates/config.template.json +45 -0
- package/templates/skills/auth-connect/SKILL.md +22 -0
- package/templates/skills/email/SKILL.md +119 -115
- package/templates/skills/email/scripts/email-config-path.test.js +52 -0
- package/templates/skills/email/scripts/email-config.d.ts +4 -0
- package/templates/skills/email/scripts/email-config.js +6 -3
- package/templates/skills/pptx/SKILL.md +5 -0
- package/templates/skills/pptx/assets/engine7-aurora/field.png +0 -0
- package/templates/skills/pptx/assets/engine7-aurora/hero.png +0 -0
- package/templates/skills/pptx/assets/engine7-aurora/wordmark.png +0 -0
- package/templates/skills/pptx/examples/engine7-aurora.cjs +190 -0
- package/templates/skills/pptx/package-lock.json +171 -0
- package/templates/skills/pptx/package.json +12 -0
- package/templates/skills/pptx/scripts/engine7-aurora.cjs +132 -0
- package/templates/skills/pptx/styles/engine7-aurora.md +136 -0
- package/templates/skills/pptx/tests/engine7-aurora.test.cjs +116 -0
- package/templates/workspace/AGENTS.md +2 -9
- package/templates/workspace/RULES.md +22 -0
- package/templates/workspace/hooks/loop-detector.mjs +37 -0
- package/templates/workspace/souls/unnamed.md +10 -0
|
@@ -0,0 +1,3259 @@
|
|
|
1
|
+
const require=(await import('node:module')).createRequire(import.meta.url)
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __esm = (fn, res) => function __init() {
|
|
4
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
// src/continuity/runtime-authority.ts
|
|
8
|
+
var init_runtime_authority = __esm({
|
|
9
|
+
"src/continuity/runtime-authority.ts"() {
|
|
10
|
+
"use strict";
|
|
11
|
+
}
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
// src/continuity/runtime-lock.ts
|
|
15
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
16
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
17
|
+
var bootId, recoveryWriterLocks, initialBaselineAdmission;
|
|
18
|
+
var init_runtime_lock = __esm({
|
|
19
|
+
"src/continuity/runtime-lock.ts"() {
|
|
20
|
+
"use strict";
|
|
21
|
+
init_runtime_authority();
|
|
22
|
+
bootId = randomUUID3();
|
|
23
|
+
recoveryWriterLocks = new AsyncLocalStorage();
|
|
24
|
+
initialBaselineAdmission = new AsyncLocalStorage();
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
// src/memory/schema-migrations.ts
|
|
29
|
+
var init_schema_migrations = __esm({
|
|
30
|
+
"src/memory/schema-migrations.ts"() {
|
|
31
|
+
"use strict";
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
// src/continuity/legacy-sqlite-indexes.ts
|
|
36
|
+
var init_legacy_sqlite_indexes = __esm({
|
|
37
|
+
"src/continuity/legacy-sqlite-indexes.ts"() {
|
|
38
|
+
"use strict";
|
|
39
|
+
init_schema_migrations();
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// src/continuity/sqlite-replication.ts
|
|
44
|
+
var init_sqlite_replication = __esm({
|
|
45
|
+
"src/continuity/sqlite-replication.ts"() {
|
|
46
|
+
"use strict";
|
|
47
|
+
init_legacy_sqlite_indexes();
|
|
48
|
+
init_runtime_authority();
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
// src/continuity/sqlite-autocommit.ts
|
|
53
|
+
var init_sqlite_autocommit = __esm({
|
|
54
|
+
"src/continuity/sqlite-autocommit.ts"() {
|
|
55
|
+
"use strict";
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// src/mem7/core/tokenizer.ts
|
|
60
|
+
import { Jieba } from "@node-rs/jieba";
|
|
61
|
+
import { dict } from "@node-rs/jieba/dict.js";
|
|
62
|
+
var init_tokenizer = __esm({
|
|
63
|
+
"src/mem7/core/tokenizer.ts"() {
|
|
64
|
+
"use strict";
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
// src/config/writer.ts
|
|
69
|
+
import fs from "node:fs";
|
|
70
|
+
import path from "node:path";
|
|
71
|
+
function isNormalized(text) {
|
|
72
|
+
if (text === "") return true;
|
|
73
|
+
if (text.includes("\r")) return false;
|
|
74
|
+
let minIndent = Infinity;
|
|
75
|
+
for (const line of text.split("\n")) {
|
|
76
|
+
const m = /^( +)\S/.exec(line);
|
|
77
|
+
if (!m) continue;
|
|
78
|
+
const width = m[1].length;
|
|
79
|
+
if (width % 2 !== 0) return false;
|
|
80
|
+
if (width < minIndent) minIndent = width;
|
|
81
|
+
}
|
|
82
|
+
return minIndent === 2 || minIndent === Infinity;
|
|
83
|
+
}
|
|
84
|
+
function rotateBaks(filePath) {
|
|
85
|
+
const dir = path.dirname(filePath);
|
|
86
|
+
const base = path.basename(filePath);
|
|
87
|
+
const baks = fs.readdirSync(dir).filter((n) => n.startsWith(base + ".bak-")).sort();
|
|
88
|
+
while (baks.length >= KEEP_BAKS) {
|
|
89
|
+
const victim = baks.shift();
|
|
90
|
+
try {
|
|
91
|
+
fs.unlinkSync(path.join(dir, victim));
|
|
92
|
+
} catch {
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function sleepSync(ms) {
|
|
97
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
98
|
+
}
|
|
99
|
+
function errCode(err) {
|
|
100
|
+
return err?.code ?? "";
|
|
101
|
+
}
|
|
102
|
+
function writeFailure(filePath, primary, extra) {
|
|
103
|
+
const code = errCode(primary);
|
|
104
|
+
const reason = RETRYABLE_CODES.has(code) ? `\u76EE\u6807\u6587\u4EF6\u88AB\u5360\u7528\u6216\u4E0D\u53EF\u5199\uFF08${code}\uFF09\u2014\u2014\u8BF7\u5173\u95ED\u6B63\u5728\u4F7F\u7528\u5B83\u7684\u7A0B\u5E8F\uFF08\u7F16\u8F91\u5668\u3001\u6740\u6BD2\u3001\u540C\u6B65\u76D8\u7B49\uFF09\u540E\u91CD\u8BD5` : `\u5199\u5165\u5931\u8D25${code ? `\uFF08${code}\uFF09` : ""}\uFF1A${primary?.message ?? String(primary)}`;
|
|
105
|
+
return new ConfigWriteError(`\u65E0\u6CD5\u5199\u5165 ${filePath}\uFF1A${reason}${extra ? `\uFF1B${extra}` : ""}`, code, primary);
|
|
106
|
+
}
|
|
107
|
+
function renameWithRetry(from, to) {
|
|
108
|
+
for (let attempt = 1; ; attempt++) {
|
|
109
|
+
try {
|
|
110
|
+
fs.renameSync(from, to);
|
|
111
|
+
return;
|
|
112
|
+
} catch (err) {
|
|
113
|
+
if (attempt >= RENAME_ATTEMPTS || !RETRYABLE_CODES.has(errCode(err))) throw err;
|
|
114
|
+
sleepSync(RENAME_RETRY_MS);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function commitFile(tmp, filePath) {
|
|
119
|
+
try {
|
|
120
|
+
renameWithRetry(tmp, filePath);
|
|
121
|
+
return;
|
|
122
|
+
} catch (primaryErr) {
|
|
123
|
+
const old = `${filePath}.old`;
|
|
124
|
+
try {
|
|
125
|
+
fs.renameSync(filePath, old);
|
|
126
|
+
} catch (err) {
|
|
127
|
+
throw writeFailure(filePath, primaryErr, `\u6539\u540D .old \u5907\u4EFD\u4E5F\u5931\u8D25\uFF08${errCode(err) || "\u672A\u77E5"}\uFF09`);
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
fs.renameSync(tmp, filePath);
|
|
131
|
+
} catch (err) {
|
|
132
|
+
try {
|
|
133
|
+
fs.renameSync(old, filePath);
|
|
134
|
+
} catch {
|
|
135
|
+
throw writeFailure(filePath, primaryErr, `\u65B0\u5185\u5BB9\u843D\u76D8\u4E0E\u56DE\u6EDA\u90FD\u5931\u8D25\uFF0C\u65E7\u5185\u5BB9\u7559\u5728 ${old}`);
|
|
136
|
+
}
|
|
137
|
+
throw writeFailure(filePath, primaryErr, `\u6362\u540D\u843D\u76D8\u5931\u8D25\uFF08${errCode(err) || "\u672A\u77E5"}\uFF09`);
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
fs.unlinkSync(old);
|
|
141
|
+
} catch {
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function writeConfigAtomic(filePath, obj) {
|
|
146
|
+
const existed = fs.existsSync(filePath);
|
|
147
|
+
let prevText = "";
|
|
148
|
+
let fileMode;
|
|
149
|
+
if (existed) {
|
|
150
|
+
try {
|
|
151
|
+
prevText = fs.readFileSync(filePath, "utf-8");
|
|
152
|
+
fileMode = fs.statSync(filePath).mode & 511;
|
|
153
|
+
} catch (err) {
|
|
154
|
+
throw writeFailure(filePath, err);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const normalized = !existed || !isNormalized(prevText);
|
|
158
|
+
if (prevText) {
|
|
159
|
+
try {
|
|
160
|
+
fs.copyFileSync(filePath, `${filePath}.bak-${Date.now()}`);
|
|
161
|
+
} catch {
|
|
162
|
+
}
|
|
163
|
+
rotateBaks(filePath);
|
|
164
|
+
}
|
|
165
|
+
const content = JSON.stringify(obj, null, 2) + "\n";
|
|
166
|
+
const tmp = path.join(path.dirname(filePath), `.${path.basename(filePath)}.tmp-${process.pid}`);
|
|
167
|
+
try {
|
|
168
|
+
const fd = fs.openSync(tmp, "w", fileMode);
|
|
169
|
+
try {
|
|
170
|
+
if (fileMode !== void 0) fs.fchmodSync(fd, fileMode);
|
|
171
|
+
fs.writeFileSync(fd, content, "utf-8");
|
|
172
|
+
fs.fsyncSync(fd);
|
|
173
|
+
} finally {
|
|
174
|
+
fs.closeSync(fd);
|
|
175
|
+
}
|
|
176
|
+
commitFile(tmp, filePath);
|
|
177
|
+
} catch (err) {
|
|
178
|
+
throw err instanceof ConfigWriteError ? err : writeFailure(filePath, err);
|
|
179
|
+
} finally {
|
|
180
|
+
try {
|
|
181
|
+
fs.unlinkSync(tmp);
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return { normalized };
|
|
186
|
+
}
|
|
187
|
+
var KEEP_BAKS, RENAME_ATTEMPTS, RENAME_RETRY_MS, RETRYABLE_CODES, ConfigWriteError;
|
|
188
|
+
var init_writer = __esm({
|
|
189
|
+
"src/config/writer.ts"() {
|
|
190
|
+
"use strict";
|
|
191
|
+
KEEP_BAKS = 3;
|
|
192
|
+
RENAME_ATTEMPTS = 5;
|
|
193
|
+
RENAME_RETRY_MS = 50;
|
|
194
|
+
RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
|
|
195
|
+
ConfigWriteError = class extends Error {
|
|
196
|
+
code;
|
|
197
|
+
constructor(message, code, cause) {
|
|
198
|
+
super(message, { cause });
|
|
199
|
+
this.name = "ConfigWriteError";
|
|
200
|
+
this.code = code;
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
// src/config/live.ts
|
|
207
|
+
function markSelfWrite() {
|
|
208
|
+
selfWrite.pending = true;
|
|
209
|
+
}
|
|
210
|
+
var LiveConfigClass, liveConfig, selfWrite;
|
|
211
|
+
var init_live = __esm({
|
|
212
|
+
"src/config/live.ts"() {
|
|
213
|
+
"use strict";
|
|
214
|
+
init_writer();
|
|
215
|
+
LiveConfigClass = class {
|
|
216
|
+
current = null;
|
|
217
|
+
/** 启动时注入(替代 registry.config = config) */
|
|
218
|
+
init(config) {
|
|
219
|
+
this.current = config;
|
|
220
|
+
}
|
|
221
|
+
/** 取整个 config 对象(只读引用,不要缓存) */
|
|
222
|
+
all() {
|
|
223
|
+
if (!this.current) {
|
|
224
|
+
throw new Error("[liveConfig] not initialized \u2014 call liveConfig.init() first");
|
|
225
|
+
}
|
|
226
|
+
return this.current;
|
|
227
|
+
}
|
|
228
|
+
/** 安全取子段('services.voice-chat.start' → current.services.voice-chat.start) */
|
|
229
|
+
get(dotPath) {
|
|
230
|
+
if (!this.current) return void 0;
|
|
231
|
+
return dotPath.split(".").reduce((acc, key) => {
|
|
232
|
+
if (acc == null) return void 0;
|
|
233
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") return void 0;
|
|
234
|
+
return acc[key];
|
|
235
|
+
}, this.current);
|
|
236
|
+
}
|
|
237
|
+
/** reload 时原地更新(Object.assign 保持引用不变)
|
|
238
|
+
* ⚠️ 0908 立法(浅层 assign 陷阱,见 docs/hot-reload-architecture.md):
|
|
239
|
+
* 这是**浅层** assign——顶层 key 被整体换新引用,构造期捕获嵌套子对象
|
|
240
|
+
* (如 config.cron、deps.everosCfg、adapter 的 config 段)的模块 reload 后
|
|
241
|
+
* 拿着的是旧对象。两条出路:(a) 使用时 liveConfig.get() 现读;(b) 注册为
|
|
242
|
+
* reloadOrchestrator entry,key 变化驱动 stop→start 重建。禁止新增"构造期
|
|
243
|
+
* 固化嵌套 config 引用"的代码。(不做 deep-merge:会破坏"删 key"语义。) */
|
|
244
|
+
assign(newConfig) {
|
|
245
|
+
if (!this.current) {
|
|
246
|
+
this.current = newConfig;
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
Object.assign(this.current, newConfig);
|
|
250
|
+
}
|
|
251
|
+
/** 改活树上的值;文件承载路径同步持久化(read-modify-write 回 config 文件) */
|
|
252
|
+
/**
|
|
253
|
+
* 改活树 + 落盘。
|
|
254
|
+
*
|
|
255
|
+
* 返回值 = **落盘**是否成功(活树无论成败都已同步——它是先改的)。绝大多数调用点照旧
|
|
256
|
+
* `void liveConfig.set(...)` 不理它;但**要打成功日志的调用点必须 await 这个布尔值**。
|
|
257
|
+
*
|
|
258
|
+
* 为什么把这个信号交出去(1001 审查捞回):本方法本来是 fire-and-forget,落盘失败只在
|
|
259
|
+
* `persistToFile` 里 warn 一行;而启动早段的调用点(两个免费档 fixup)紧接着打了句
|
|
260
|
+
* "免费档补齐 xxx" 的成功日志 ⇒ 配置**没写进文件**却被读成"写好了":进程内生效、托盘
|
|
261
|
+
* 读文件还是旧值、下次启动重放同一句——正是本仓最恨的假信号。
|
|
262
|
+
*/
|
|
263
|
+
async set(dotPath, val, options) {
|
|
264
|
+
if (!this.current) throw new Error("[liveConfig] not initialized \u2014 call liveConfig.init() first");
|
|
265
|
+
const keys = dotPath.split(".");
|
|
266
|
+
const dangerous = keys.find((k) => k === "__proto__" || k === "constructor" || k === "prototype");
|
|
267
|
+
if (dangerous) throw new Error(`[liveConfig] set: \u8DEF\u5F84\u6BB5\u300C${dangerous}\u300D\u662F\u4FDD\u7559\u540D\uFF0C\u62D2\u7EDD\u5199\u5165\uFF08${dotPath}\uFF09`);
|
|
268
|
+
let obj = this.current;
|
|
269
|
+
for (let i = 0; i < keys.length - 1; i++) {
|
|
270
|
+
if (obj[keys[i]] == null) obj[keys[i]] = {};
|
|
271
|
+
obj = obj[keys[i]];
|
|
272
|
+
}
|
|
273
|
+
obj[keys[keys.length - 1]] = val;
|
|
274
|
+
return this.persistToFile(dotPath, val, options?.atomic === true);
|
|
275
|
+
}
|
|
276
|
+
/** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
|
|
277
|
+
async persistToFile(dotPath, val, atomic = false) {
|
|
278
|
+
const fs2 = await import("node:fs");
|
|
279
|
+
const cfgPath = this.current?._configFilePath;
|
|
280
|
+
if (!cfgPath || !fs2.existsSync(cfgPath)) {
|
|
281
|
+
console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
const raw = JSON.parse(fs2.readFileSync(cfgPath, "utf-8"));
|
|
286
|
+
const keys = dotPath.split(".");
|
|
287
|
+
let o = raw;
|
|
288
|
+
for (let i = 0; i < keys.length - 1; i++) {
|
|
289
|
+
if (o[keys[i]] == null) o[keys[i]] = {};
|
|
290
|
+
o = o[keys[i]];
|
|
291
|
+
}
|
|
292
|
+
o[keys[keys.length - 1]] = val;
|
|
293
|
+
if (atomic) {
|
|
294
|
+
writeConfigAtomic(cfgPath, raw);
|
|
295
|
+
} else fs2.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
|
|
296
|
+
const lastKey = keys[keys.length - 1].toLowerCase();
|
|
297
|
+
const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
|
|
298
|
+
const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
|
|
299
|
+
console.log(`[liveConfig] persisted ${dotPath} = ${shown} to ${cfgPath}`);
|
|
300
|
+
markSelfWrite();
|
|
301
|
+
return true;
|
|
302
|
+
} catch (e) {
|
|
303
|
+
console.warn(`[liveConfig] persist failed (${dotPath}): ${e.message}`);
|
|
304
|
+
return false;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/** 是否已初始化 */
|
|
308
|
+
isReady() {
|
|
309
|
+
return this.current !== null;
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
liveConfig = new LiveConfigClass();
|
|
313
|
+
selfWrite = { pending: false };
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// src/time/wall-parts.ts
|
|
318
|
+
var init_wall_parts = __esm({
|
|
319
|
+
"src/time/wall-parts.ts"() {
|
|
320
|
+
"use strict";
|
|
321
|
+
}
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
// src/time/clock.ts
|
|
325
|
+
var init_clock = __esm({
|
|
326
|
+
"src/time/clock.ts"() {
|
|
327
|
+
"use strict";
|
|
328
|
+
init_live();
|
|
329
|
+
init_wall_parts();
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
// src/mem7/core/scope.ts
|
|
334
|
+
var init_scope = __esm({
|
|
335
|
+
"src/mem7/core/scope.ts"() {
|
|
336
|
+
"use strict";
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
// src/mem7/core/read-budget.ts
|
|
341
|
+
var init_read_budget = __esm({
|
|
342
|
+
"src/mem7/core/read-budget.ts"() {
|
|
343
|
+
"use strict";
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
// src/mem7/core/read-guard.ts
|
|
348
|
+
var init_read_guard = __esm({
|
|
349
|
+
"src/mem7/core/read-guard.ts"() {
|
|
350
|
+
"use strict";
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
// src/mem7/core/search/timing.ts
|
|
355
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
356
|
+
var current;
|
|
357
|
+
var init_timing = __esm({
|
|
358
|
+
"src/mem7/core/search/timing.ts"() {
|
|
359
|
+
"use strict";
|
|
360
|
+
current = new AsyncLocalStorage2();
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
// src/memory/topics-cleaning/materials.ts
|
|
365
|
+
var init_materials = __esm({
|
|
366
|
+
"src/memory/topics-cleaning/materials.ts"() {
|
|
367
|
+
"use strict";
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
// src/memory/topics-history/dates.ts
|
|
372
|
+
var init_dates = __esm({
|
|
373
|
+
"src/memory/topics-history/dates.ts"() {
|
|
374
|
+
"use strict";
|
|
375
|
+
init_clock();
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
// src/mem7/core/historical-recall.ts
|
|
380
|
+
var init_historical_recall = __esm({
|
|
381
|
+
"src/mem7/core/historical-recall.ts"() {
|
|
382
|
+
"use strict";
|
|
383
|
+
init_scope();
|
|
384
|
+
init_read_guard();
|
|
385
|
+
init_read_budget();
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
// src/memory/topics-history/cutoff.ts
|
|
390
|
+
import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
|
|
391
|
+
var init_cutoff = __esm({
|
|
392
|
+
"src/memory/topics-history/cutoff.ts"() {
|
|
393
|
+
"use strict";
|
|
394
|
+
init_historical_recall();
|
|
395
|
+
init_scope();
|
|
396
|
+
init_clock();
|
|
397
|
+
init_materials();
|
|
398
|
+
init_dates();
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
// src/continuity/runtime-replication.ts
|
|
403
|
+
var init_runtime_replication = __esm({
|
|
404
|
+
"src/continuity/runtime-replication.ts"() {
|
|
405
|
+
"use strict";
|
|
406
|
+
init_schema_migrations();
|
|
407
|
+
init_sqlite_replication();
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
// src/memory/topics-history/index.ts
|
|
412
|
+
import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
|
|
413
|
+
var init_topics_history = __esm({
|
|
414
|
+
"src/memory/topics-history/index.ts"() {
|
|
415
|
+
"use strict";
|
|
416
|
+
init_materials();
|
|
417
|
+
init_dates();
|
|
418
|
+
init_tokenizer();
|
|
419
|
+
init_cutoff();
|
|
420
|
+
init_clock();
|
|
421
|
+
init_runtime_replication();
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
|
|
425
|
+
// src/continuity/gateway-main.ts
|
|
426
|
+
import { isAbsolute, resolve as resolve2 } from "node:path";
|
|
427
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
428
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
429
|
+
import * as lark2 from "@larksuiteoapi/node-sdk";
|
|
430
|
+
|
|
431
|
+
// src/continuity/authority.ts
|
|
432
|
+
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
433
|
+
import { createHash as createHash2, createPublicKey, generateKeyPairSync, randomBytes as randomBytes2, randomUUID as randomUUID2, sign, verify } from "node:crypto";
|
|
434
|
+
import { existsSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
435
|
+
import { join as join2 } from "node:path";
|
|
436
|
+
|
|
437
|
+
// src/continuity/publication-objects.ts
|
|
438
|
+
import { DatabaseSync } from "node:sqlite";
|
|
439
|
+
import {
|
|
440
|
+
constants,
|
|
441
|
+
openSync,
|
|
442
|
+
closeSync,
|
|
443
|
+
fstatSync,
|
|
444
|
+
fsyncSync,
|
|
445
|
+
readSync,
|
|
446
|
+
writeSync,
|
|
447
|
+
lstatSync,
|
|
448
|
+
realpathSync,
|
|
449
|
+
mkdirSync,
|
|
450
|
+
readFileSync,
|
|
451
|
+
writeFileSync,
|
|
452
|
+
linkSync,
|
|
453
|
+
unlinkSync
|
|
454
|
+
} from "node:fs";
|
|
455
|
+
import { join, dirname, resolve } from "node:path";
|
|
456
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
|
|
457
|
+
var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
|
|
458
|
+
var HASH = /^[a-f0-9]{64}$/;
|
|
459
|
+
var OVERHEAD = 32;
|
|
460
|
+
var MAGIC = Buffer.from("E7P1");
|
|
461
|
+
var sha = (body) => createHash("sha256").update(body).digest("hex");
|
|
462
|
+
var noFollow = constants.O_NOFOLLOW ?? 0;
|
|
463
|
+
function validateObjectRef(ref) {
|
|
464
|
+
if (!ref || !HASH.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > PUBLICATION_CHUNK_BYTES)
|
|
465
|
+
throw new Error("PUBLICATION_INVALID_OBJECT");
|
|
466
|
+
}
|
|
467
|
+
function validateFileContent(file) {
|
|
468
|
+
if (!file || !HASH.test(file.sha256) || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || !Array.isArray(file.chunks) || file.chunks.length > 1e6) throw new Error("PUBLICATION_INVALID_FILE");
|
|
469
|
+
let total = 0;
|
|
470
|
+
for (const ref of file.chunks) {
|
|
471
|
+
validateObjectRef(ref);
|
|
472
|
+
total += ref.bytes;
|
|
473
|
+
}
|
|
474
|
+
if (total !== file.bytes || !Number.isSafeInteger(total)) throw new Error("PUBLICATION_INVALID_FILE");
|
|
475
|
+
}
|
|
476
|
+
function assertPrivateDirectory(path3) {
|
|
477
|
+
const info = lstatSync(path3);
|
|
478
|
+
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path3) !== resolve(path3) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
479
|
+
throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
480
|
+
}
|
|
481
|
+
function syncDir(path3) {
|
|
482
|
+
if (process.platform === "win32") return;
|
|
483
|
+
const fd = openSync(path3, constants.O_RDONLY);
|
|
484
|
+
try {
|
|
485
|
+
fsyncSync(fd);
|
|
486
|
+
} finally {
|
|
487
|
+
closeSync(fd);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
function preparePrivateDirectory(path3) {
|
|
491
|
+
const missing = [];
|
|
492
|
+
let parent = resolve(path3);
|
|
493
|
+
for (; ; ) {
|
|
494
|
+
try {
|
|
495
|
+
lstatSync(parent);
|
|
496
|
+
break;
|
|
497
|
+
} catch (error) {
|
|
498
|
+
if (error.code !== "ENOENT") throw error;
|
|
499
|
+
}
|
|
500
|
+
missing.push(parent);
|
|
501
|
+
parent = dirname(parent);
|
|
502
|
+
}
|
|
503
|
+
if (realpathSync(parent) !== parent) throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
504
|
+
for (const directory of missing.reverse()) {
|
|
505
|
+
try {
|
|
506
|
+
mkdirSync(directory, { mode: 448 });
|
|
507
|
+
} catch (error) {
|
|
508
|
+
if (error.code !== "EEXIST") throw error;
|
|
509
|
+
}
|
|
510
|
+
assertPrivateDirectory(directory);
|
|
511
|
+
syncDir(dirname(directory));
|
|
512
|
+
}
|
|
513
|
+
assertPrivateDirectory(path3);
|
|
514
|
+
}
|
|
515
|
+
function preparePrivateDatabase(path3) {
|
|
516
|
+
for (const file of [path3, path3 + "-journal", path3 + "-wal", path3 + "-shm"]) {
|
|
517
|
+
try {
|
|
518
|
+
const info2 = lstatSync(file);
|
|
519
|
+
if (!info2.isFile() || info2.isSymbolicLink() || process.platform !== "win32" && (info2.mode & 63 || info2.uid !== process.getuid()))
|
|
520
|
+
throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
|
|
521
|
+
} catch (error) {
|
|
522
|
+
if (error.code !== "ENOENT") throw error;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
try {
|
|
526
|
+
const fd = openSync(path3, "wx", 384);
|
|
527
|
+
closeSync(fd);
|
|
528
|
+
} catch (error) {
|
|
529
|
+
if (error.code !== "EEXIST") throw error;
|
|
530
|
+
}
|
|
531
|
+
const info = lstatSync(path3);
|
|
532
|
+
if (!info.isFile() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
533
|
+
throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
|
|
534
|
+
syncDir(dirname(path3));
|
|
535
|
+
}
|
|
536
|
+
function exclusivePublish(path3, body) {
|
|
537
|
+
const temp = join(dirname(path3), "." + randomUUID() + ".partial");
|
|
538
|
+
try {
|
|
539
|
+
writeFileSync(temp, body, { flag: "wx", mode: 384, flush: true });
|
|
540
|
+
linkSync(temp, path3);
|
|
541
|
+
syncDir(dirname(path3));
|
|
542
|
+
} finally {
|
|
543
|
+
try {
|
|
544
|
+
unlinkSync(temp);
|
|
545
|
+
} catch (error) {
|
|
546
|
+
if (error.code !== "ENOENT") throw error;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
var PublicationObjects = class _PublicationObjects {
|
|
551
|
+
directory;
|
|
552
|
+
identity;
|
|
553
|
+
db;
|
|
554
|
+
key;
|
|
555
|
+
maximumBytes;
|
|
556
|
+
closed = false;
|
|
557
|
+
constructor(options) {
|
|
558
|
+
if (!(options.key instanceof Uint8Array) || options.key.length !== 32) throw new Error("PUBLICATION_INVALID_KEY");
|
|
559
|
+
if (!options.identity || ["tenantId", "companionId", "seatId"].some((k) => typeof options.identity[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(options.identity[k])))
|
|
560
|
+
throw new Error("PUBLICATION_INVALID_IDENTITY");
|
|
561
|
+
this.maximumBytes = options.maximumBytes ?? 10 * 1024 ** 3;
|
|
562
|
+
if (!Number.isSafeInteger(this.maximumBytes) || this.maximumBytes < 1) throw new Error("PUBLICATION_INVALID_LIMIT");
|
|
563
|
+
this.directory = resolve(options.directory);
|
|
564
|
+
this.key = Buffer.from(options.key);
|
|
565
|
+
this.identity = Object.freeze({ tenantId: options.identity.tenantId, companionId: options.identity.companionId, seatId: options.identity.seatId });
|
|
566
|
+
try {
|
|
567
|
+
preparePrivateDirectory(this.directory);
|
|
568
|
+
const chunks = join(this.directory, "chunks");
|
|
569
|
+
preparePrivateDirectory(chunks);
|
|
570
|
+
const file = join(this.directory, "catalog.sqlite");
|
|
571
|
+
preparePrivateDatabase(file);
|
|
572
|
+
this.db = new DatabaseSync(file);
|
|
573
|
+
this.db.exec(`PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
|
|
574
|
+
CREATE TABLE IF NOT EXISTS identity (id INTEGER PRIMARY KEY CHECK(id=1), verifier BLOB NOT NULL);
|
|
575
|
+
CREATE TABLE IF NOT EXISTS objects (hash TEXT PRIMARY KEY,bytes INTEGER NOT NULL CHECK(bytes>0));`);
|
|
576
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
577
|
+
try {
|
|
578
|
+
const row = this.db.prepare("SELECT verifier FROM identity WHERE id=1").get();
|
|
579
|
+
if (row) {
|
|
580
|
+
try {
|
|
581
|
+
if (this.decrypt(Buffer.from(row.verifier), "identity").toString() !== "publication-object-key") throw new Error();
|
|
582
|
+
} catch {
|
|
583
|
+
throw new Error("PUBLICATION_KEY_OR_IDENTITY_MISMATCH");
|
|
584
|
+
}
|
|
585
|
+
} else this.db.prepare("INSERT INTO identity VALUES(1,?)").run(this.encrypt(Buffer.from("publication-object-key"), "identity"));
|
|
586
|
+
this.db.exec("COMMIT");
|
|
587
|
+
syncDir(this.directory);
|
|
588
|
+
} catch (error) {
|
|
589
|
+
this.db.exec("ROLLBACK");
|
|
590
|
+
throw error;
|
|
591
|
+
}
|
|
592
|
+
} catch (error) {
|
|
593
|
+
this.db?.close();
|
|
594
|
+
this.key.fill(0);
|
|
595
|
+
throw error;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
static async open(options) {
|
|
599
|
+
return new _PublicationObjects(options);
|
|
600
|
+
}
|
|
601
|
+
active() {
|
|
602
|
+
if (this.closed) throw new Error("PUBLICATION_OBJECT_STORE_CLOSED");
|
|
603
|
+
}
|
|
604
|
+
aad(id3) {
|
|
605
|
+
return Buffer.from(JSON.stringify(["engine7-publication-object-v1", this.identity.tenantId, this.identity.companionId, this.identity.seatId, id3]));
|
|
606
|
+
}
|
|
607
|
+
encrypt(body, id3) {
|
|
608
|
+
const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", this.key, iv);
|
|
609
|
+
cipher.setAAD(this.aad(id3));
|
|
610
|
+
return Buffer.concat([MAGIC, iv, cipher.update(body), cipher.final(), cipher.getAuthTag()]);
|
|
611
|
+
}
|
|
612
|
+
decrypt(body, id3) {
|
|
613
|
+
if (body.length < OVERHEAD || !body.subarray(0, 4).equals(MAGIC)) throw new Error("PUBLICATION_OBJECT_CORRUPT");
|
|
614
|
+
const decipher = createDecipheriv("aes-256-gcm", this.key, body.subarray(4, 16));
|
|
615
|
+
decipher.setAAD(this.aad(id3));
|
|
616
|
+
decipher.setAuthTag(body.subarray(-16));
|
|
617
|
+
try {
|
|
618
|
+
return Buffer.concat([decipher.update(body.subarray(16, -16)), decipher.final()]);
|
|
619
|
+
} catch {
|
|
620
|
+
throw new Error("PUBLICATION_OBJECT_CORRUPT");
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
usage() {
|
|
624
|
+
this.active();
|
|
625
|
+
return this.db.prepare("SELECT count(*) objects,COALESCE(sum(bytes+32),0) bytes FROM objects").get();
|
|
626
|
+
}
|
|
627
|
+
async put(body) {
|
|
628
|
+
this.active();
|
|
629
|
+
assertPrivateDirectory(this.directory);
|
|
630
|
+
assertPrivateDirectory(join(this.directory, "chunks"));
|
|
631
|
+
if (!(body instanceof Uint8Array) || body.byteLength < 1 || body.byteLength > PUBLICATION_CHUNK_BYTES)
|
|
632
|
+
throw new Error("PUBLICATION_OBJECT_TOO_LARGE");
|
|
633
|
+
body = Buffer.from(body);
|
|
634
|
+
const ref = { sha256: sha(body), bytes: body.byteLength };
|
|
635
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
636
|
+
try {
|
|
637
|
+
const row = this.db.prepare("SELECT bytes FROM objects WHERE hash=?").get(ref.sha256);
|
|
638
|
+
if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
|
|
639
|
+
if (!row) {
|
|
640
|
+
if (this.usage().bytes + ref.bytes + OVERHEAD > this.maximumBytes) throw new Error("PUBLICATION_STORAGE_FULL");
|
|
641
|
+
this.db.prepare("INSERT INTO objects VALUES(?,?)").run(ref.sha256, ref.bytes);
|
|
642
|
+
}
|
|
643
|
+
this.db.exec("COMMIT");
|
|
644
|
+
} catch (error) {
|
|
645
|
+
this.db.exec("ROLLBACK");
|
|
646
|
+
throw error;
|
|
647
|
+
}
|
|
648
|
+
if (await this.has(ref)) return ref;
|
|
649
|
+
try {
|
|
650
|
+
exclusivePublish(join(this.directory, "chunks", ref.sha256), this.encrypt(Buffer.from(body), ref.sha256));
|
|
651
|
+
} catch (error) {
|
|
652
|
+
if (error.code !== "EEXIST") throw error;
|
|
653
|
+
}
|
|
654
|
+
await this.read(ref);
|
|
655
|
+
return ref;
|
|
656
|
+
}
|
|
657
|
+
async read(ref) {
|
|
658
|
+
this.active();
|
|
659
|
+
validateObjectRef(ref);
|
|
660
|
+
assertPrivateDirectory(this.directory);
|
|
661
|
+
assertPrivateDirectory(join(this.directory, "chunks"));
|
|
662
|
+
const path3 = join(this.directory, "chunks", ref.sha256);
|
|
663
|
+
const fd = openSync(path3, constants.O_RDONLY | noFollow);
|
|
664
|
+
try {
|
|
665
|
+
const info = fstatSync(fd);
|
|
666
|
+
if (!info.isFile() || info.size !== ref.bytes + OVERHEAD || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
667
|
+
throw new Error("PUBLICATION_OBJECT_CORRUPT");
|
|
668
|
+
const plain = this.decrypt(readFileSync(fd), ref.sha256);
|
|
669
|
+
if (plain.length !== ref.bytes || sha(plain) !== ref.sha256) throw new Error("PUBLICATION_OBJECT_CORRUPT");
|
|
670
|
+
return plain;
|
|
671
|
+
} finally {
|
|
672
|
+
closeSync(fd);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
async has(ref) {
|
|
676
|
+
try {
|
|
677
|
+
await this.read(ref);
|
|
678
|
+
return true;
|
|
679
|
+
} catch (error) {
|
|
680
|
+
if (error.code === "ENOENT") return false;
|
|
681
|
+
throw error;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
async putContent(body) {
|
|
685
|
+
body = Buffer.from(body);
|
|
686
|
+
const chunks = [];
|
|
687
|
+
for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) chunks.push(await this.put(body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES)));
|
|
688
|
+
return { bytes: body.length, sha256: sha(body), chunks };
|
|
689
|
+
}
|
|
690
|
+
async readContent(file, maximumBytes) {
|
|
691
|
+
validateFileContent(file);
|
|
692
|
+
if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0 || file.bytes > maximumBytes) throw new Error("PUBLICATION_CONTENT_TOO_LARGE");
|
|
693
|
+
const chunks = [];
|
|
694
|
+
for (const ref of file.chunks) chunks.push(await this.read(ref));
|
|
695
|
+
const body = Buffer.concat(chunks);
|
|
696
|
+
if (sha(body) !== file.sha256) throw new Error("PUBLICATION_FILE_CORRUPT");
|
|
697
|
+
return body;
|
|
698
|
+
}
|
|
699
|
+
async captureFile(source) {
|
|
700
|
+
this.active();
|
|
701
|
+
if (lstatSync(source).isSymbolicLink() || realpathSync(dirname(source)) !== resolve(dirname(source))) throw new Error("SYMLINK_REFUSED");
|
|
702
|
+
const fd = openSync(source, constants.O_RDONLY | noFollow);
|
|
703
|
+
try {
|
|
704
|
+
const before = fstatSync(fd, { bigint: true });
|
|
705
|
+
if (!before.isFile()) throw new Error("PUBLICATION_NOT_REGULAR_FILE");
|
|
706
|
+
const chunks = [], digest4 = createHash("sha256"), buffer = Buffer.alloc(PUBLICATION_CHUNK_BYTES);
|
|
707
|
+
let bytes = 0;
|
|
708
|
+
for (; ; ) {
|
|
709
|
+
const count = readSync(fd, buffer, 0, buffer.length, null);
|
|
710
|
+
if (!count) break;
|
|
711
|
+
const chunk = buffer.subarray(0, count);
|
|
712
|
+
digest4.update(chunk);
|
|
713
|
+
bytes += count;
|
|
714
|
+
chunks.push(await this.put(chunk));
|
|
715
|
+
}
|
|
716
|
+
const after = fstatSync(fd, { bigint: true }), path3 = lstatSync(source, { bigint: true });
|
|
717
|
+
if (path3.isSymbolicLink() || [after, path3].some((s) => ["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((k) => s[k] !== before[k])) || BigInt(bytes) !== before.size) throw new Error("PUBLICATION_SOURCE_CHANGED");
|
|
718
|
+
return { bytes, sha256: digest4.digest("hex"), chunks };
|
|
719
|
+
} finally {
|
|
720
|
+
closeSync(fd);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
async restoreFile(file, destination) {
|
|
724
|
+
this.active();
|
|
725
|
+
validateFileContent(file);
|
|
726
|
+
if (realpathSync(dirname(destination)) !== resolve(dirname(destination))) throw new Error("SYMLINK_REFUSED");
|
|
727
|
+
try {
|
|
728
|
+
lstatSync(destination);
|
|
729
|
+
throw new Error("CONTINUITY_DESTINATION_EXISTS");
|
|
730
|
+
} catch (error) {
|
|
731
|
+
if (error.code !== "ENOENT") throw error;
|
|
732
|
+
}
|
|
733
|
+
const temp = join(dirname(destination), "." + randomUUID() + ".partial"), digest4 = createHash("sha256");
|
|
734
|
+
const fd = openSync(temp, "wx", 384);
|
|
735
|
+
try {
|
|
736
|
+
for (const ref of file.chunks) {
|
|
737
|
+
const body = await this.read(ref);
|
|
738
|
+
digest4.update(body);
|
|
739
|
+
let offset = 0;
|
|
740
|
+
while (offset < body.length) offset += writeSync(fd, body, offset, body.length - offset);
|
|
741
|
+
}
|
|
742
|
+
if (digest4.digest("hex") !== file.sha256) throw new Error("PUBLICATION_FILE_CORRUPT");
|
|
743
|
+
fsyncSync(fd);
|
|
744
|
+
try {
|
|
745
|
+
linkSync(temp, destination);
|
|
746
|
+
} catch (error) {
|
|
747
|
+
if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
|
|
748
|
+
throw error;
|
|
749
|
+
}
|
|
750
|
+
syncDir(dirname(destination));
|
|
751
|
+
} finally {
|
|
752
|
+
closeSync(fd);
|
|
753
|
+
unlinkSync(temp);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
close() {
|
|
757
|
+
if (!this.closed) {
|
|
758
|
+
this.closed = true;
|
|
759
|
+
this.db.close();
|
|
760
|
+
this.key.fill(0);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
|
|
765
|
+
// src/continuity/key-service-store.ts
|
|
766
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
767
|
+
import { constants as constants2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, closeSync as closeSync2, readFileSync as readFileSync2, writeSync as writeSync2, fstatSync as fstatSync2, fsyncSync as fsyncSync2, unlinkSync as unlinkSync2 } from "node:fs";
|
|
768
|
+
function validateKeyIdentity(value) {
|
|
769
|
+
if (!value || ["tenantId", "companionId", "seatId", "keyId"].some((k) => typeof value[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value[k])) || !Number.isSafeInteger(value.generation) || value.generation < 1) throw new Error("KEY_SERVICE_INVALID_IDENTITY");
|
|
770
|
+
}
|
|
771
|
+
function assertPrivateStat(stat, directory) {
|
|
772
|
+
if ((directory ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
773
|
+
throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
|
|
774
|
+
}
|
|
775
|
+
function readPrivateFile(path3, maximumBytes = 65536) {
|
|
776
|
+
assertPrivateStat(lstatSync2(path3), false);
|
|
777
|
+
const fd = openSync2(path3, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
|
|
778
|
+
try {
|
|
779
|
+
const stat = fstatSync2(fd);
|
|
780
|
+
assertPrivateStat(stat, false);
|
|
781
|
+
if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
|
|
782
|
+
return readFileSync2(fd);
|
|
783
|
+
} finally {
|
|
784
|
+
closeSync2(fd);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// src/continuity/authority.ts
|
|
789
|
+
var ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
790
|
+
var HASH2 = /^[a-f0-9]{64}$/;
|
|
791
|
+
var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
792
|
+
var hash = (value) => createHash2("sha256").update(value).digest("hex");
|
|
793
|
+
function id(value) {
|
|
794
|
+
if (typeof value !== "string" || !ID.test(value)) throw new Error("TRAVEL_INVALID_ID");
|
|
795
|
+
}
|
|
796
|
+
function natural(value) {
|
|
797
|
+
if (!Number.isSafeInteger(value) || Number(value) < 0) throw new Error("TRAVEL_INVALID_NUMBER");
|
|
798
|
+
}
|
|
799
|
+
function identityText(identity) {
|
|
800
|
+
if (!identity) throw new Error("TRAVEL_INVALID_ID");
|
|
801
|
+
id(identity.tenantId);
|
|
802
|
+
id(identity.companionId);
|
|
803
|
+
id(identity.seatId);
|
|
804
|
+
return JSON.stringify([identity.tenantId, identity.companionId, identity.seatId]);
|
|
805
|
+
}
|
|
806
|
+
function unsignedPermit(permit) {
|
|
807
|
+
const { signature, ...body } = permit;
|
|
808
|
+
return Buffer.from(JSON.stringify(body));
|
|
809
|
+
}
|
|
810
|
+
function verifyTravelPermit(permit, publicKey) {
|
|
811
|
+
try {
|
|
812
|
+
return typeof permit.signature === "string" && verify(null, unsignedPermit(permit), publicKey, Buffer.from(permit.signature, "base64"));
|
|
813
|
+
} catch {
|
|
814
|
+
return false;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
var TravelAuthority = class {
|
|
818
|
+
authorityBootId = randomUUID2();
|
|
819
|
+
publicKey;
|
|
820
|
+
signingKey;
|
|
821
|
+
db;
|
|
822
|
+
owner;
|
|
823
|
+
monotonicNow;
|
|
824
|
+
wallNow;
|
|
825
|
+
leaseMs;
|
|
826
|
+
deadlines = /* @__PURE__ */ new Map();
|
|
827
|
+
healthy = /* @__PURE__ */ new Map();
|
|
828
|
+
leaseSequence = 0;
|
|
829
|
+
closed = false;
|
|
830
|
+
constructor(options) {
|
|
831
|
+
this.monotonicNow = options.monotonicNow ?? (() => Number(process.hrtime.bigint() / 1000000n));
|
|
832
|
+
this.wallNow = options.wallNow ?? Date.now;
|
|
833
|
+
this.leaseMs = options.leaseMs ?? 3e4;
|
|
834
|
+
if (!Number.isSafeInteger(this.leaseMs) || this.leaseMs < 100 || this.leaseMs > 3e5) throw new Error("TRAVEL_INVALID_LEASE");
|
|
835
|
+
preparePrivateDirectory(options.directory);
|
|
836
|
+
const ownerFile = join2(options.directory, "authority-owner.sqlite");
|
|
837
|
+
preparePrivateDatabase(ownerFile);
|
|
838
|
+
this.owner = new DatabaseSync3(ownerFile);
|
|
839
|
+
try {
|
|
840
|
+
this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY); BEGIN IMMEDIATE");
|
|
841
|
+
} catch (error) {
|
|
842
|
+
this.owner.close();
|
|
843
|
+
throw new Error("TRAVEL_AUTHORITY_BUSY", { cause: error });
|
|
844
|
+
}
|
|
845
|
+
const path3 = join2(options.directory, "authority.sqlite"), keyFile = join2(options.directory, "authority-signing.pem");
|
|
846
|
+
try {
|
|
847
|
+
const present = existsSync(path3), keyPresent = existsSync(keyFile);
|
|
848
|
+
if (present !== keyPresent) throw new Error("TRAVEL_AUTHORITY_RECOVERY_REQUIRED");
|
|
849
|
+
if (!keyPresent) {
|
|
850
|
+
const keys = generateKeyPairSync("ed25519");
|
|
851
|
+
writeFileSync2(keyFile, keys.privateKey.export({ format: "pem", type: "pkcs8" }), { mode: 384, flag: "wx", flush: true });
|
|
852
|
+
}
|
|
853
|
+
this.signingKey = readPrivateFile(keyFile).toString();
|
|
854
|
+
this.publicKey = createPublicKey(this.signingKey).export({ format: "pem", type: "spki" }).toString();
|
|
855
|
+
preparePrivateDatabase(path3);
|
|
856
|
+
this.db = new DatabaseSync3(path3);
|
|
857
|
+
this.db.exec(`PRAGMA busy_timeout=1000; PRAGMA synchronous=FULL;
|
|
858
|
+
CREATE TABLE IF NOT EXISTS seats(identity TEXT PRIMARY KEY,epoch INTEGER NOT NULL,active_node TEXT,active_boot TEXT,
|
|
859
|
+
floor INTEGER NOT NULL,checkpoint TEXT NOT NULL,build TEXT NOT NULL,retired TEXT,frozen INTEGER NOT NULL DEFAULT 0);
|
|
860
|
+
CREATE TABLE IF NOT EXISTS nodes(identity TEXT NOT NULL,node_id TEXT NOT NULL,role TEXT NOT NULL,credential_hash TEXT UNIQUE NOT NULL,
|
|
861
|
+
boot TEXT,sequence INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(identity,node_id));
|
|
862
|
+
CREATE TABLE IF NOT EXISTS boots(identity TEXT NOT NULL,node_id TEXT NOT NULL,boot TEXT NOT NULL,PRIMARY KEY(identity,node_id,boot));
|
|
863
|
+
CREATE TABLE IF NOT EXISTS deletions(companion TEXT NOT NULL,id TEXT NOT NULL,body TEXT NOT NULL,watermark INTEGER NOT NULL,
|
|
864
|
+
PRIMARY KEY(companion,id),UNIQUE(companion,watermark));
|
|
865
|
+
CREATE TABLE IF NOT EXISTS handoffs(identity TEXT NOT NULL,id TEXT NOT NULL,source TEXT NOT NULL,target TEXT NOT NULL,
|
|
866
|
+
source_epoch INTEGER NOT NULL,target_boot TEXT,state TEXT NOT NULL,checkpoint TEXT,result TEXT,PRIMARY KEY(identity,id));
|
|
867
|
+
CREATE TABLE IF NOT EXISTS checkpoints(identity TEXT NOT NULL,digest TEXT NOT NULL,parent TEXT,epoch INTEGER NOT NULL,
|
|
868
|
+
PRIMARY KEY(identity,digest));
|
|
869
|
+
CREATE TABLE IF NOT EXISTS recovery_branches(identity TEXT NOT NULL,common TEXT NOT NULL,local TEXT NOT NULL,
|
|
870
|
+
chain TEXT NOT NULL,PRIMARY KEY(identity,common,local));`);
|
|
871
|
+
this.db.exec("CREATE TABLE IF NOT EXISTS retirement_sources(identity TEXT PRIMARY KEY,body TEXT NOT NULL)");
|
|
872
|
+
if (this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_AUTHORITY_CORRUPT");
|
|
873
|
+
this.transaction(() => {
|
|
874
|
+
this.db.exec("UPDATE seats SET epoch=epoch+1,active_node=NULL,active_boot=NULL,frozen=0 WHERE retired IS NULL");
|
|
875
|
+
this.db.exec("UPDATE handoffs SET state='ABORTED' WHERE state NOT IN ('COMMITTED','ABORTED')");
|
|
876
|
+
});
|
|
877
|
+
} catch (error) {
|
|
878
|
+
this.db?.close();
|
|
879
|
+
this.owner.close();
|
|
880
|
+
throw error;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
transaction(operation) {
|
|
884
|
+
if (this.closed) throw new Error("TRAVEL_AUTHORITY_CLOSED");
|
|
885
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
886
|
+
try {
|
|
887
|
+
const result = operation();
|
|
888
|
+
this.db.exec("COMMIT");
|
|
889
|
+
return result;
|
|
890
|
+
} catch (error) {
|
|
891
|
+
this.db.exec("ROLLBACK");
|
|
892
|
+
throw error;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
seat(identity, allowRetired = false) {
|
|
896
|
+
const row = this.db.prepare("SELECT * FROM seats WHERE identity=?").get(identityText(identity));
|
|
897
|
+
if (!row) throw new Error("TRAVEL_AUTH_DENIED");
|
|
898
|
+
if (row.retired && !allowRetired) throw new Error("TRAVEL_SEAT_RETIRED");
|
|
899
|
+
return row;
|
|
900
|
+
}
|
|
901
|
+
principal(principal) {
|
|
902
|
+
const text = identityText(principal);
|
|
903
|
+
const node = this.db.prepare("SELECT * FROM nodes WHERE identity=? AND node_id=? AND credential_hash=?").get(text, principal.nodeId, principal.credentialHash);
|
|
904
|
+
if (!node || node.role !== principal.role) throw new Error("TRAVEL_AUTH_DENIED");
|
|
905
|
+
this.seat(principal);
|
|
906
|
+
return node;
|
|
907
|
+
}
|
|
908
|
+
provisionSeat(identity, nodes, baseline) {
|
|
909
|
+
const text = identityText(identity);
|
|
910
|
+
if (!HASH2.test(baseline.checkpointDigest)) throw new Error("TRAVEL_INVALID_CHECKPOINT");
|
|
911
|
+
id(baseline.buildManifestId);
|
|
912
|
+
const entries = Object.entries(nodes);
|
|
913
|
+
if (entries.length < 1 || entries.length > 16) throw new Error("TRAVEL_INVALID_NODES");
|
|
914
|
+
return this.transaction(() => {
|
|
915
|
+
if (this.db.prepare("SELECT 1 FROM seats WHERE identity=?").get(text)) throw new Error("TRAVEL_SEAT_EXISTS");
|
|
916
|
+
const companion = JSON.stringify([identity.tenantId, identity.companionId]);
|
|
917
|
+
const floor = Number(this.db.prepare("SELECT COALESCE(MAX(watermark),0) AS floor FROM deletions WHERE companion=?").get(companion).floor);
|
|
918
|
+
this.db.prepare("INSERT INTO seats VALUES(?,1,NULL,NULL,?,?,?,NULL,0)").run(text, floor, baseline.checkpointDigest, baseline.buildManifestId);
|
|
919
|
+
this.db.prepare("INSERT INTO checkpoints VALUES(?,?,NULL,1)").run(text, baseline.checkpointDigest);
|
|
920
|
+
const credentials = {};
|
|
921
|
+
for (const [node, role] of entries) {
|
|
922
|
+
id(node);
|
|
923
|
+
if (!["LOCAL", "CLOUD"].includes(role)) throw new Error("TRAVEL_INVALID_NODES");
|
|
924
|
+
const credential = "e7t_" + randomBytes2(32).toString("hex");
|
|
925
|
+
this.db.prepare("INSERT INTO nodes(identity,node_id,role,credential_hash) VALUES(?,?,?,?)").run(text, node, role, hash(credential));
|
|
926
|
+
credentials[node] = credential;
|
|
927
|
+
}
|
|
928
|
+
return credentials;
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
authenticate(credential) {
|
|
932
|
+
return this.authenticateNode(credential, false);
|
|
933
|
+
}
|
|
934
|
+
authenticateRetirement(credential) {
|
|
935
|
+
return this.authenticateNode(credential, true);
|
|
936
|
+
}
|
|
937
|
+
authenticateNode(credential, allowRetired) {
|
|
938
|
+
if (typeof credential !== "string" || !/^e7t_[a-f0-9]{64}$/.test(credential)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
939
|
+
const row = this.db.prepare("SELECT identity,node_id,role,credential_hash FROM nodes WHERE credential_hash=?").get(hash(credential));
|
|
940
|
+
if (!row) throw new Error("TRAVEL_AUTH_DENIED");
|
|
941
|
+
const [tenantId, companionId, seatId] = JSON.parse(String(row.identity));
|
|
942
|
+
const principal = { tenantId, companionId, seatId, nodeId: String(row.node_id), role: row.role, credentialHash: String(row.credential_hash) };
|
|
943
|
+
this.seat(principal, allowRetired);
|
|
944
|
+
return principal;
|
|
945
|
+
}
|
|
946
|
+
register(principal, bootId2) {
|
|
947
|
+
id(bootId2);
|
|
948
|
+
this.transaction(() => {
|
|
949
|
+
const node = this.principal(principal), text = identityText(principal);
|
|
950
|
+
if (node.boot === bootId2) {
|
|
951
|
+
this.healthy.set(text + principal.nodeId, this.monotonicNow() + this.leaseMs);
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
if (this.db.prepare("SELECT 1 FROM boots WHERE identity=? AND node_id=? AND boot=?").get(text, principal.nodeId, bootId2)) throw new Error("TRAVEL_BOOT_RETIRED");
|
|
955
|
+
this.db.prepare("INSERT INTO boots VALUES(?,?,?)").run(text, principal.nodeId, bootId2);
|
|
956
|
+
this.db.prepare("UPDATE nodes SET boot=?,sequence=0 WHERE identity=? AND node_id=?").run(bootId2, text, principal.nodeId);
|
|
957
|
+
const seat = this.seat(principal);
|
|
958
|
+
if (seat.active_node === principal.nodeId) {
|
|
959
|
+
this.db.prepare("UPDATE seats SET epoch=epoch+1,active_node=NULL,active_boot=NULL,frozen=0 WHERE identity=?").run(text);
|
|
960
|
+
this.deadlines.delete(text);
|
|
961
|
+
this.db.prepare("UPDATE handoffs SET state='ABORTED' WHERE identity=? AND state NOT IN ('COMMITTED','ABORTED')").run(text);
|
|
962
|
+
}
|
|
963
|
+
this.healthy.set(text + principal.nodeId, this.monotonicNow() + this.leaseMs);
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
readiness(row, ready) {
|
|
967
|
+
if (!ready || ready.volumeVerified !== true || ready.capabilitiesVerified !== true || ready.effectsLoaded !== true || ready.unresolvedCritical !== 0) throw new Error("TRAVEL_NOT_READY");
|
|
968
|
+
natural(ready.deletionWatermark);
|
|
969
|
+
if (ready.checkpointDigest !== row.checkpoint || ready.deletionWatermark !== row.floor || ready.buildManifestId !== row.build) throw new Error("TRAVEL_READINESS_BARRIER");
|
|
970
|
+
}
|
|
971
|
+
issue(identity, row) {
|
|
972
|
+
const text = identityText(identity), expiresAt = this.deadlines.get(text);
|
|
973
|
+
const body = {
|
|
974
|
+
tenantId: identity.tenantId,
|
|
975
|
+
companionId: identity.companionId,
|
|
976
|
+
seatId: identity.seatId,
|
|
977
|
+
nodeId: row.active_node,
|
|
978
|
+
bootId: row.active_boot,
|
|
979
|
+
authorityBootId: this.authorityBootId,
|
|
980
|
+
epoch: Number(row.epoch),
|
|
981
|
+
deletionWatermark: Number(row.floor),
|
|
982
|
+
leaseSequence: ++this.leaseSequence,
|
|
983
|
+
expiresAt,
|
|
984
|
+
validForMs: Math.max(0, Math.floor(expiresAt - this.monotonicNow()))
|
|
985
|
+
};
|
|
986
|
+
return { ...body, signature: sign(null, Buffer.from(JSON.stringify(body)), this.signingKey).toString("base64") };
|
|
987
|
+
}
|
|
988
|
+
acquire(principal, ready) {
|
|
989
|
+
return this.transaction(() => {
|
|
990
|
+
const node = this.principal(principal), text = identityText(principal), row = this.seat(principal);
|
|
991
|
+
if (!node.boot) throw new Error("TRAVEL_BOOT_REQUIRED");
|
|
992
|
+
this.readiness(row, ready);
|
|
993
|
+
if (row.frozen) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
994
|
+
if (row.active_node && (this.deadlines.get(text) ?? 0) > this.monotonicNow() && row.active_node !== principal.nodeId) throw new Error("TRAVEL_LEASE_HELD");
|
|
995
|
+
if (row.active_node && ((this.deadlines.get(text) ?? 0) <= this.monotonicNow() || row.active_boot !== node.boot)) row.epoch++;
|
|
996
|
+
row.active_node = principal.nodeId;
|
|
997
|
+
row.active_boot = String(node.boot);
|
|
998
|
+
this.db.prepare("UPDATE seats SET epoch=?,active_node=?,active_boot=? WHERE identity=?").run(row.epoch, row.active_node, row.active_boot, text);
|
|
999
|
+
this.deadlines.set(text, this.monotonicNow() + this.leaseMs);
|
|
1000
|
+
this.healthy.set(text + principal.nodeId, this.monotonicNow() + this.leaseMs);
|
|
1001
|
+
return this.issue(principal, row);
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
assertPermit(permit, operation) {
|
|
1005
|
+
if (!verifyTravelPermit(permit, this.publicKey)) throw new Error("TRAVEL_INVALID_PERMIT");
|
|
1006
|
+
const row = this.seat(permit), text = identityText(permit);
|
|
1007
|
+
if (permit.authorityBootId !== this.authorityBootId || permit.epoch !== Number(row.epoch) || permit.nodeId !== row.active_node || permit.bootId !== row.active_boot) throw new Error("TRAVEL_STALE_PERMIT");
|
|
1008
|
+
if (permit.expiresAt <= this.monotonicNow() || (this.deadlines.get(text) ?? 0) <= this.monotonicNow()) throw new Error("TRAVEL_LEASE_EXPIRED");
|
|
1009
|
+
if (operation !== "CONTROL" && row.frozen) throw new Error("TRAVEL_HANDOFF_FROZEN");
|
|
1010
|
+
if (operation !== "CONTROL" && permit.deletionWatermark !== Number(row.floor)) throw new Error("TRAVEL_DELETION_BARRIER");
|
|
1011
|
+
}
|
|
1012
|
+
heartbeat(principal, request3) {
|
|
1013
|
+
return this.transaction(() => {
|
|
1014
|
+
const node = this.principal(principal), text = identityText(principal), seat = this.seat(principal);
|
|
1015
|
+
natural(request3.sequence);
|
|
1016
|
+
if (request3.bootId !== node.boot) throw new Error("TRAVEL_BOOT_MISMATCH");
|
|
1017
|
+
if (request3.sequence <= Number(node.sequence)) throw new Error("TRAVEL_HEARTBEAT_REPLAY");
|
|
1018
|
+
let permit;
|
|
1019
|
+
if (request3.permit) {
|
|
1020
|
+
this.assertPermit(request3.permit, "CONTROL");
|
|
1021
|
+
if (request3.permit.nodeId !== principal.nodeId || !same(identityText(request3.permit), text)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1022
|
+
const floor = request3.deletionWatermark ?? request3.permit.deletionWatermark;
|
|
1023
|
+
if (floor !== Number(seat.floor)) throw new Error("TRAVEL_DELETION_BARRIER");
|
|
1024
|
+
this.deadlines.set(text, this.monotonicNow() + this.leaseMs);
|
|
1025
|
+
permit = this.issue(principal, seat);
|
|
1026
|
+
}
|
|
1027
|
+
this.db.prepare("UPDATE nodes SET sequence=? WHERE identity=? AND node_id=?").run(request3.sequence, text, principal.nodeId);
|
|
1028
|
+
this.healthy.set(text + principal.nodeId, this.monotonicNow() + this.leaseMs);
|
|
1029
|
+
return {
|
|
1030
|
+
authorityBootId: this.authorityBootId,
|
|
1031
|
+
epoch: Number(seat.epoch),
|
|
1032
|
+
activeNodeId: seat.active_node,
|
|
1033
|
+
deletionWatermark: Number(seat.floor),
|
|
1034
|
+
checkpointDigest: seat.checkpoint,
|
|
1035
|
+
buildManifestId: seat.build,
|
|
1036
|
+
frozen: !!seat.frozen,
|
|
1037
|
+
...permit ? { permit } : {}
|
|
1038
|
+
};
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
status(principal) {
|
|
1042
|
+
this.principal(principal);
|
|
1043
|
+
const seat = this.seat(principal), text = identityText(principal);
|
|
1044
|
+
return {
|
|
1045
|
+
authorityBootId: this.authorityBootId,
|
|
1046
|
+
epoch: Number(seat.epoch),
|
|
1047
|
+
activeNodeId: seat.active_node,
|
|
1048
|
+
activeBootId: seat.active_boot,
|
|
1049
|
+
expired: (this.deadlines.get(text) ?? 0) <= this.monotonicNow(),
|
|
1050
|
+
deletionWatermark: Number(seat.floor),
|
|
1051
|
+
checkpointDigest: seat.checkpoint,
|
|
1052
|
+
buildManifestId: seat.build,
|
|
1053
|
+
frozen: !!seat.frozen
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
publishCheckpoint(principal, permit, checkpointDigest, parentDigest) {
|
|
1057
|
+
if (!HASH2.test(checkpointDigest) || !HASH2.test(parentDigest)) throw new Error("TRAVEL_INVALID_CHECKPOINT");
|
|
1058
|
+
this.transaction(() => {
|
|
1059
|
+
this.principal(principal);
|
|
1060
|
+
this.assertPermit(permit, "PUBLISH");
|
|
1061
|
+
if (principal.nodeId !== permit.nodeId || identityText(principal) !== identityText(permit)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1062
|
+
const row = this.seat(principal), text = identityText(principal);
|
|
1063
|
+
const prior = this.db.prepare("SELECT parent,epoch FROM checkpoints WHERE identity=? AND digest=?").get(text, checkpointDigest);
|
|
1064
|
+
if (prior) {
|
|
1065
|
+
if (prior.parent !== parentDigest) throw new Error("TRAVEL_ID_COLLISION");
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
if (row.checkpoint !== parentDigest) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
1069
|
+
this.db.prepare("INSERT INTO checkpoints VALUES(?,?,?,?)").run(text, checkpointDigest, parentDigest, permit.epoch);
|
|
1070
|
+
this.db.prepare("UPDATE seats SET checkpoint=? WHERE identity=?").run(checkpointDigest, text);
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1073
|
+
verifyAncestor(principal, ancestor, descendant) {
|
|
1074
|
+
this.principal(principal);
|
|
1075
|
+
const text = identityText(principal), seen = /* @__PURE__ */ new Set();
|
|
1076
|
+
while (true) {
|
|
1077
|
+
if (seen.has(descendant)) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
1078
|
+
seen.add(descendant);
|
|
1079
|
+
const row = this.db.prepare("SELECT parent FROM checkpoints WHERE identity=? AND digest=?").get(text, descendant);
|
|
1080
|
+
if (!row) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
1081
|
+
if (descendant === ancestor) return;
|
|
1082
|
+
if (!row.parent) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
1083
|
+
descendant = String(row.parent);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
/** Trusted archive adapter calls this after authenticating each sealed link.
|
|
1087
|
+
* Evidence ancestry grants neither a published checkpoint nor an old lease. */
|
|
1088
|
+
recordRecoveryBranch(principal, permit, chain) {
|
|
1089
|
+
if (!Array.isArray(chain) || chain.length < 1 || chain.length > 4096 || chain.some((d) => !HASH2.test(d)) || new Set(chain).size !== chain.length) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
1090
|
+
this.transaction(() => {
|
|
1091
|
+
this.principal(principal);
|
|
1092
|
+
this.assertPermit(permit, "WRITE");
|
|
1093
|
+
if (principal.nodeId !== permit.nodeId || identityText(principal) !== identityText(permit)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1094
|
+
this.verifyAncestor(principal, chain[0], this.seat(principal).checkpoint);
|
|
1095
|
+
const identity = identityText(principal), local = chain[chain.length - 1], body = JSON.stringify(chain);
|
|
1096
|
+
const prior = this.db.prepare("SELECT chain FROM recovery_branches WHERE identity=? AND common=? AND local=?").get(identity, chain[0], local);
|
|
1097
|
+
if (prior && prior.chain !== body) throw new Error("TRAVEL_ID_COLLISION");
|
|
1098
|
+
this.db.prepare("INSERT OR IGNORE INTO recovery_branches VALUES(?,?,?,?)").run(identity, chain[0], local, body);
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
recoveryBranchStatus(principal, common, local) {
|
|
1102
|
+
this.principal(principal);
|
|
1103
|
+
const row = this.db.prepare("SELECT chain FROM recovery_branches WHERE identity=? AND common=? AND local=?").get(identityText(principal), common, local);
|
|
1104
|
+
if (!row) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
1105
|
+
return { chain: JSON.parse(String(row.chain)) };
|
|
1106
|
+
}
|
|
1107
|
+
beginHandoff(principal, permit, transferId, targetNodeId) {
|
|
1108
|
+
id(transferId);
|
|
1109
|
+
id(targetNodeId);
|
|
1110
|
+
return this.transaction(() => {
|
|
1111
|
+
this.principal(principal);
|
|
1112
|
+
this.assertPermit(permit, "CONTROL");
|
|
1113
|
+
const text = identityText(principal);
|
|
1114
|
+
if (permit.nodeId !== principal.nodeId || identityText(permit) !== text || targetNodeId === principal.nodeId) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1115
|
+
const previous = this.db.prepare("SELECT source,target FROM handoffs WHERE identity=? AND id=?").get(text, transferId);
|
|
1116
|
+
if (previous) {
|
|
1117
|
+
if (previous.source !== principal.nodeId || previous.target !== targetNodeId) throw new Error("TRAVEL_ID_COLLISION");
|
|
1118
|
+
return this.handoffStatus(principal, transferId);
|
|
1119
|
+
}
|
|
1120
|
+
if (!this.db.prepare("SELECT 1 FROM nodes WHERE identity=? AND node_id=?").get(text, targetNodeId)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1121
|
+
if (this.db.prepare("SELECT 1 FROM handoffs WHERE identity=? AND state NOT IN ('COMMITTED','ABORTED')").get(text)) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
1122
|
+
this.db.prepare("INSERT INTO handoffs VALUES(?,?,?,?,?,NULL,'PREPARING',NULL,NULL)").run(text, transferId, principal.nodeId, targetNodeId, permit.epoch);
|
|
1123
|
+
return this.handoffStatus(principal, transferId);
|
|
1124
|
+
});
|
|
1125
|
+
}
|
|
1126
|
+
freezeHandoff(principal, permit, transferId, boundary) {
|
|
1127
|
+
return this.transaction(() => {
|
|
1128
|
+
this.principal(principal);
|
|
1129
|
+
this.assertPermit(permit, "CONTROL");
|
|
1130
|
+
if (boundary.safeBoundary !== true || boundary.effectsSettled !== true) throw new Error("TRAVEL_HANDOFF_NOT_SAFE");
|
|
1131
|
+
if (!HASH2.test(boundary.checkpointDigest)) throw new Error("TRAVEL_INVALID_CHECKPOINT");
|
|
1132
|
+
const h = this.handoffRow(principal, transferId), text = identityText(principal);
|
|
1133
|
+
if (h.source !== principal.nodeId || permit.nodeId !== principal.nodeId || identityText(permit) !== text || Number(h.source_epoch) !== permit.epoch) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1134
|
+
if (h.state !== "PREPARING") {
|
|
1135
|
+
if (h.checkpoint !== boundary.checkpointDigest || !["FROZEN_AT_H", "TARGET_READY"].includes(String(h.state))) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
1136
|
+
return this.handoffStatus(principal, transferId);
|
|
1137
|
+
}
|
|
1138
|
+
const seat = this.seat(principal);
|
|
1139
|
+
if (seat.checkpoint !== boundary.checkpointDigest) {
|
|
1140
|
+
this.db.prepare("INSERT INTO checkpoints VALUES(?,?,?,?)").run(text, boundary.checkpointDigest, seat.checkpoint, permit.epoch);
|
|
1141
|
+
}
|
|
1142
|
+
this.db.prepare("UPDATE seats SET checkpoint=?,frozen=1 WHERE identity=?").run(boundary.checkpointDigest, text);
|
|
1143
|
+
this.db.prepare("UPDATE handoffs SET state='FROZEN_AT_H',checkpoint=? WHERE identity=? AND id=?").run(boundary.checkpointDigest, text, transferId);
|
|
1144
|
+
return this.handoffStatus(principal, transferId);
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
readyHandoff(principal, transferId, ready) {
|
|
1148
|
+
return this.transaction(() => {
|
|
1149
|
+
const node = this.principal(principal), h = this.handoffRow(principal, transferId), text = identityText(principal);
|
|
1150
|
+
if (h.target !== principal.nodeId) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1151
|
+
if (!["FROZEN_AT_H", "TARGET_READY"].includes(String(h.state))) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
1152
|
+
this.readiness(this.seat(principal), ready);
|
|
1153
|
+
this.db.prepare("UPDATE handoffs SET state='TARGET_READY',target_boot=? WHERE identity=? AND id=?").run(String(node.boot), text, transferId);
|
|
1154
|
+
this.healthy.set(text + principal.nodeId, this.monotonicNow() + this.leaseMs);
|
|
1155
|
+
return this.handoffStatus(principal, transferId);
|
|
1156
|
+
});
|
|
1157
|
+
}
|
|
1158
|
+
commitHandoff(principal, transferId) {
|
|
1159
|
+
return this.transaction(() => {
|
|
1160
|
+
const node = this.principal(principal), h = this.handoffRow(principal, transferId), text = identityText(principal);
|
|
1161
|
+
if (h.target !== principal.nodeId) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1162
|
+
if (h.state === "COMMITTED") return JSON.parse(String(h.result));
|
|
1163
|
+
if (h.state !== "TARGET_READY") throw new Error("TRAVEL_HANDOFF_STATE");
|
|
1164
|
+
if (h.target_boot !== node.boot || (this.healthy.get(text + principal.nodeId) ?? 0) <= this.monotonicNow()) throw new Error("TRAVEL_TARGET_OFFLINE");
|
|
1165
|
+
const seat = this.seat(principal);
|
|
1166
|
+
if (Number(h.source_epoch) !== Number(seat.epoch) || h.source !== seat.active_node || h.checkpoint !== seat.checkpoint || !seat.frozen) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
1167
|
+
seat.epoch++;
|
|
1168
|
+
seat.active_node = principal.nodeId;
|
|
1169
|
+
seat.active_boot = String(node.boot);
|
|
1170
|
+
seat.frozen = 0;
|
|
1171
|
+
this.db.prepare("UPDATE seats SET epoch=?,active_node=?,active_boot=?,frozen=0 WHERE identity=?").run(seat.epoch, seat.active_node, seat.active_boot, text);
|
|
1172
|
+
this.deadlines.set(text, this.monotonicNow() + this.leaseMs);
|
|
1173
|
+
const result = { transferId, state: "COMMITTED", sourceNodeId: String(h.source), targetNodeId: String(h.target), checkpointDigest: String(h.checkpoint), permit: this.issue(principal, seat) };
|
|
1174
|
+
this.db.prepare("UPDATE handoffs SET state='COMMITTED',result=? WHERE identity=? AND id=?").run(JSON.stringify(result), text, transferId);
|
|
1175
|
+
return result;
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
abortHandoff(principal, transferId) {
|
|
1179
|
+
return this.transaction(() => {
|
|
1180
|
+
this.principal(principal);
|
|
1181
|
+
const h = this.handoffRow(principal, transferId), text = identityText(principal);
|
|
1182
|
+
if (h.source !== principal.nodeId) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1183
|
+
if (h.state === "COMMITTED") throw new Error("TRAVEL_HANDOFF_COMMITTED");
|
|
1184
|
+
if (h.state === "ABORTED") return this.handoffStatus(principal, transferId);
|
|
1185
|
+
this.db.prepare("UPDATE handoffs SET state='ABORTED' WHERE identity=? AND id=?").run(text, transferId);
|
|
1186
|
+
const changed = this.db.prepare("UPDATE seats SET frozen=0,epoch=epoch+1 WHERE identity=? AND epoch=? AND active_node=?").run(text, Number(h.source_epoch), principal.nodeId);
|
|
1187
|
+
if (changed.changes) this.deadlines.delete(text);
|
|
1188
|
+
return this.handoffStatus(principal, transferId);
|
|
1189
|
+
});
|
|
1190
|
+
}
|
|
1191
|
+
handoffRow(principal, transferId) {
|
|
1192
|
+
id(transferId);
|
|
1193
|
+
const row = this.db.prepare("SELECT * FROM handoffs WHERE identity=? AND id=?").get(identityText(principal), transferId);
|
|
1194
|
+
if (!row) throw new Error("TRAVEL_HANDOFF_NOT_FOUND");
|
|
1195
|
+
return row;
|
|
1196
|
+
}
|
|
1197
|
+
handoffStatus(principal, transferId) {
|
|
1198
|
+
this.principal(principal);
|
|
1199
|
+
const h = this.handoffRow(principal, transferId);
|
|
1200
|
+
if (h.source !== principal.nodeId && h.target !== principal.nodeId) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1201
|
+
if (h.state === "COMMITTED") return JSON.parse(String(h.result));
|
|
1202
|
+
return { transferId, state: h.state, sourceNodeId: String(h.source), targetNodeId: String(h.target), checkpointDigest: h.checkpoint === null ? null : String(h.checkpoint) };
|
|
1203
|
+
}
|
|
1204
|
+
recordDeletion(principal, permit, input) {
|
|
1205
|
+
id(input.id);
|
|
1206
|
+
id(input.sourceId);
|
|
1207
|
+
id(input.scopeId);
|
|
1208
|
+
natural(input.version);
|
|
1209
|
+
if (!input.version) throw new Error("TRAVEL_INVALID_NUMBER");
|
|
1210
|
+
return this.transaction(() => {
|
|
1211
|
+
this.principal(principal);
|
|
1212
|
+
this.assertPermit(permit, "CONTROL");
|
|
1213
|
+
if (permit.nodeId !== principal.nodeId || identityText(permit) !== identityText(principal)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1214
|
+
const companion = JSON.stringify([principal.tenantId, principal.companionId]), body = JSON.stringify(input);
|
|
1215
|
+
const previous = this.db.prepare("SELECT body,watermark FROM deletions WHERE companion=? AND id=?").get(companion, input.id);
|
|
1216
|
+
if (previous) {
|
|
1217
|
+
if (previous.body !== body) throw new Error("TRAVEL_ID_COLLISION");
|
|
1218
|
+
return { ...input, watermark: Number(previous.watermark) };
|
|
1219
|
+
}
|
|
1220
|
+
const floor = Number(this.db.prepare("SELECT COALESCE(MAX(watermark),0) AS floor FROM deletions WHERE companion=?").get(companion).floor) + 1;
|
|
1221
|
+
this.db.prepare("INSERT INTO deletions VALUES(?,?,?,?)").run(companion, input.id, body, floor);
|
|
1222
|
+
for (const row of this.db.prepare("SELECT identity FROM seats").all()) {
|
|
1223
|
+
const ids = JSON.parse(String(row.identity));
|
|
1224
|
+
if (ids[0] === principal.tenantId && ids[1] === principal.companionId) this.db.prepare("UPDATE seats SET floor=? WHERE identity=?").run(floor, String(row.identity));
|
|
1225
|
+
}
|
|
1226
|
+
return { ...input, watermark: floor };
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
deletionsSince(principal, after) {
|
|
1230
|
+
this.principal(principal);
|
|
1231
|
+
natural(after);
|
|
1232
|
+
const companion = JSON.stringify([principal.tenantId, principal.companionId]);
|
|
1233
|
+
return this.db.prepare("SELECT body,watermark FROM deletions WHERE companion=? AND watermark>? ORDER BY watermark").all(companion, after).map((row) => ({ ...JSON.parse(String(row.body)), watermark: Number(row.watermark) }));
|
|
1234
|
+
}
|
|
1235
|
+
retire(identity, jobId) {
|
|
1236
|
+
id(jobId);
|
|
1237
|
+
this.transaction(() => {
|
|
1238
|
+
const row = this.seat(identity, true), text = identityText(identity);
|
|
1239
|
+
if (row.retired && row.retired !== jobId) throw new Error("TRAVEL_ID_COLLISION");
|
|
1240
|
+
if (!row.retired) {
|
|
1241
|
+
const source = {
|
|
1242
|
+
authorityBootId: this.authorityBootId,
|
|
1243
|
+
epoch: Number(row.epoch),
|
|
1244
|
+
activeNodeId: row.active_node,
|
|
1245
|
+
activeBootId: row.active_boot,
|
|
1246
|
+
checkpointDigest: row.checkpoint,
|
|
1247
|
+
buildManifestId: row.build,
|
|
1248
|
+
deletionWatermark: Number(row.floor),
|
|
1249
|
+
expired: true,
|
|
1250
|
+
frozen: true
|
|
1251
|
+
};
|
|
1252
|
+
this.db.prepare("INSERT INTO retirement_sources VALUES(?,?)").run(text, JSON.stringify(source));
|
|
1253
|
+
this.db.prepare("UPDATE seats SET epoch=epoch+1,active_node=NULL,active_boot=NULL,retired=?,frozen=1 WHERE identity=?").run(jobId, text);
|
|
1254
|
+
}
|
|
1255
|
+
this.deadlines.delete(text);
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
retirementStatus(principal) {
|
|
1259
|
+
const node = this.db.prepare("SELECT role FROM nodes WHERE identity=? AND node_id=? AND credential_hash=?").get(identityText(principal), principal.nodeId, principal.credentialHash);
|
|
1260
|
+
if (!node || node.role !== principal.role) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1261
|
+
const row = this.seat(principal, true);
|
|
1262
|
+
const saved = this.db.prepare("SELECT body FROM retirement_sources WHERE identity=?").get(identityText(principal));
|
|
1263
|
+
const source = row.retired ? saved ? JSON.parse(String(saved.body)) : null : this.status(principal);
|
|
1264
|
+
return {
|
|
1265
|
+
identity: { tenantId: principal.tenantId, companionId: principal.companionId, seatId: principal.seatId },
|
|
1266
|
+
principal,
|
|
1267
|
+
publicKey: this.publicKey,
|
|
1268
|
+
source,
|
|
1269
|
+
jobId: row.retired,
|
|
1270
|
+
retired: row.retired !== null,
|
|
1271
|
+
epoch: Number(row.epoch),
|
|
1272
|
+
checkpointDigest: row.checkpoint,
|
|
1273
|
+
deletionWatermark: Number(row.floor)
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
close() {
|
|
1277
|
+
if (!this.closed) {
|
|
1278
|
+
this.closed = true;
|
|
1279
|
+
this.db.close();
|
|
1280
|
+
this.owner.close();
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
};
|
|
1284
|
+
|
|
1285
|
+
// src/continuity/publication.ts
|
|
1286
|
+
import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
|
|
1287
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
1288
|
+
var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
|
|
1289
|
+
var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
|
|
1290
|
+
var ZERO = "0".repeat(64);
|
|
1291
|
+
var HASH3 = /^[a-f0-9]{64}$/;
|
|
1292
|
+
var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
1293
|
+
function natural2(value) {
|
|
1294
|
+
return Number.isSafeInteger(value) && value >= 0;
|
|
1295
|
+
}
|
|
1296
|
+
function id2(value) {
|
|
1297
|
+
if (typeof value !== "string" || !ID2.test(value)) throw new Error("PUBLICATION_INVALID_ID");
|
|
1298
|
+
}
|
|
1299
|
+
function exactIds(actual, required, error) {
|
|
1300
|
+
if (actual.length !== required.length || new Set(actual).size !== actual.length || actual.some((x) => !required.includes(x))) throw new Error(error);
|
|
1301
|
+
}
|
|
1302
|
+
function normalizePublicationProfile(value) {
|
|
1303
|
+
if (!value?.identity || ["tenantId", "companionId", "seatId"].some((k) => typeof value.identity[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value.identity[k]))) throw new Error("PUBLICATION_INVALID_IDENTITY");
|
|
1304
|
+
id2(value.baselineId);
|
|
1305
|
+
id2(value.buildManifestId);
|
|
1306
|
+
if (!natural2(value.epoch) || !value.epoch || !Array.isArray(value.databaseIds) || !value.databaseIds.length || value.databaseIds.length > 64 || !Array.isArray(value.trees) || !value.trees.length || value.trees.length > 64) throw new Error("PUBLICATION_INVALID_PROFILE");
|
|
1307
|
+
value.databaseIds.forEach(id2);
|
|
1308
|
+
value.trees.forEach((t) => {
|
|
1309
|
+
id2(t?.id);
|
|
1310
|
+
if (!["file", "vector", "session"].includes(t.kind)) throw new Error("PUBLICATION_INVALID_PROFILE");
|
|
1311
|
+
});
|
|
1312
|
+
if (new Set(value.databaseIds).size !== value.databaseIds.length || new Set(value.trees.map((t) => t.id)).size !== value.trees.length)
|
|
1313
|
+
throw new Error("PUBLICATION_INVALID_PROFILE");
|
|
1314
|
+
const profile = {
|
|
1315
|
+
identity: { tenantId: value.identity.tenantId, companionId: value.identity.companionId, seatId: value.identity.seatId },
|
|
1316
|
+
baselineId: value.baselineId,
|
|
1317
|
+
epoch: value.epoch,
|
|
1318
|
+
buildManifestId: value.buildManifestId,
|
|
1319
|
+
databaseIds: [...value.databaseIds].sort(),
|
|
1320
|
+
trees: value.trees.map((t) => ({ id: t.id, kind: t.kind })).sort((a, b) => a.id.localeCompare(b.id, "en"))
|
|
1321
|
+
};
|
|
1322
|
+
Object.freeze(profile.identity);
|
|
1323
|
+
Object.freeze(profile.databaseIds);
|
|
1324
|
+
profile.trees.forEach(Object.freeze);
|
|
1325
|
+
Object.freeze(profile.trees);
|
|
1326
|
+
return Object.freeze(profile);
|
|
1327
|
+
}
|
|
1328
|
+
function validatePublicationPath(path3) {
|
|
1329
|
+
if (typeof path3 !== "string" || !path3 || path3.length > 2048 || path3.normalize("NFC") !== path3 || /[\x00-\x1f<>:"|?*\\]/.test(path3) || path3.split("/").some((p) => !p || p === "." || p === ".." || /[. ]$/.test(p) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(p)))
|
|
1330
|
+
throw new Error("PUBLICATION_INVALID_PATH");
|
|
1331
|
+
}
|
|
1332
|
+
function normalizePublication(value) {
|
|
1333
|
+
if (!value || value.format !== "engine7-publication-v1" || !natural2(value.sequence) || !value.sequence || !HASH3.test(value.parentDigest) || !natural2(value.deletionWatermark) || !Array.isArray(value.databases) || !Array.isArray(value.trees)) throw new Error("PUBLICATION_INVALID_MANIFEST");
|
|
1334
|
+
const profile = normalizePublicationProfile(value.profile);
|
|
1335
|
+
exactIds(value.databases.map((d) => d?.databaseId), profile.databaseIds, "PUBLICATION_INCOMPLETE_DATABASES");
|
|
1336
|
+
exactIds(value.trees.map((t) => t?.id), profile.trees.map((t) => t.id), "PUBLICATION_INCOMPLETE_TREES");
|
|
1337
|
+
const databases = value.databases.map((d) => {
|
|
1338
|
+
if (!d.head || !natural2(d.head.sequence) || !HASH3.test(d.head.digest)) throw new Error("PUBLICATION_INVALID_DATABASE_HEAD");
|
|
1339
|
+
return { databaseId: d.databaseId, head: { sequence: d.head.sequence, digest: d.head.digest } };
|
|
1340
|
+
}).sort((a, b) => a.databaseId.localeCompare(b.databaseId, "en"));
|
|
1341
|
+
let paths = 0;
|
|
1342
|
+
const trees = value.trees.map((tree) => {
|
|
1343
|
+
if (!Array.isArray(tree.files) || !Array.isArray(tree.directories) || (paths += tree.files.length + tree.directories.length) > 1e5)
|
|
1344
|
+
throw new Error("PUBLICATION_INVALID_TREE");
|
|
1345
|
+
const occupied = /* @__PURE__ */ new Map();
|
|
1346
|
+
const claim = (path3, kind) => {
|
|
1347
|
+
validatePublicationPath(path3);
|
|
1348
|
+
const folded = path3.toLowerCase();
|
|
1349
|
+
if (occupied.has(folded)) throw new Error("PUBLICATION_PATH_COLLISION");
|
|
1350
|
+
occupied.set(folded, kind);
|
|
1351
|
+
};
|
|
1352
|
+
const directories = tree.directories.map((path3) => {
|
|
1353
|
+
claim(path3, "directory");
|
|
1354
|
+
return path3;
|
|
1355
|
+
}).sort();
|
|
1356
|
+
const files = tree.files.map((file) => {
|
|
1357
|
+
claim(file?.path, "file");
|
|
1358
|
+
validateFileContent(file.content);
|
|
1359
|
+
if (![384, 448].includes(file.mode)) throw new Error("PUBLICATION_INVALID_MODE");
|
|
1360
|
+
return { path: file.path, mode: file.mode, content: {
|
|
1361
|
+
bytes: file.content.bytes,
|
|
1362
|
+
sha256: file.content.sha256,
|
|
1363
|
+
chunks: file.content.chunks.map((r) => ({ sha256: r.sha256, bytes: r.bytes }))
|
|
1364
|
+
} };
|
|
1365
|
+
}).sort((a, b) => a.path.localeCompare(b.path, "en"));
|
|
1366
|
+
for (const path3 of occupied.keys()) {
|
|
1367
|
+
const parts = path3.split("/");
|
|
1368
|
+
for (let i = 1; i < parts.length; i++) if (occupied.get(parts.slice(0, i).join("/")) === "file") throw new Error("PUBLICATION_PATH_COLLISION");
|
|
1369
|
+
}
|
|
1370
|
+
return { id: tree.id, directories, files };
|
|
1371
|
+
}).sort((a, b) => a.id.localeCompare(b.id, "en"));
|
|
1372
|
+
const normalized = {
|
|
1373
|
+
format: "engine7-publication-v1",
|
|
1374
|
+
profile,
|
|
1375
|
+
sequence: value.sequence,
|
|
1376
|
+
parentDigest: value.parentDigest,
|
|
1377
|
+
deletionWatermark: value.deletionWatermark,
|
|
1378
|
+
databases,
|
|
1379
|
+
trees
|
|
1380
|
+
};
|
|
1381
|
+
if (Buffer.byteLength(JSON.stringify(normalized)) > PUBLICATION_MANIFEST_BYTES) throw new Error("PUBLICATION_MANIFEST_TOO_LARGE");
|
|
1382
|
+
return normalized;
|
|
1383
|
+
}
|
|
1384
|
+
function publicationDigest(manifest) {
|
|
1385
|
+
return createHash3("sha256").update(JSON.stringify(normalizePublication(manifest))).digest("hex");
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
// src/continuity/authority-server.ts
|
|
1389
|
+
import { createServer } from "node:https";
|
|
1390
|
+
var limit = 65536;
|
|
1391
|
+
var identifier = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
1392
|
+
var errors = /* @__PURE__ */ new Set([
|
|
1393
|
+
"TRAVEL_HEARTBEAT_REPLAY",
|
|
1394
|
+
"TRAVEL_BOOT_MISMATCH",
|
|
1395
|
+
"TRAVEL_BOOT_RETIRED",
|
|
1396
|
+
"TRAVEL_LEASE_EXPIRED",
|
|
1397
|
+
"TRAVEL_STALE_PERMIT",
|
|
1398
|
+
"TRAVEL_DELETION_BARRIER",
|
|
1399
|
+
"TRAVEL_SEAT_RETIRED",
|
|
1400
|
+
"TRAVEL_BOOT_REQUIRED",
|
|
1401
|
+
"TRAVEL_NOT_READY",
|
|
1402
|
+
"TRAVEL_READINESS_BARRIER",
|
|
1403
|
+
"TRAVEL_LEASE_HELD",
|
|
1404
|
+
"TRAVEL_INVALID_PERMIT",
|
|
1405
|
+
"TRAVEL_AUTH_DENIED",
|
|
1406
|
+
"TRAVEL_HANDOFF_STATE",
|
|
1407
|
+
"TRAVEL_HANDOFF_FROZEN",
|
|
1408
|
+
"TRAVEL_HANDOFF_NOT_SAFE",
|
|
1409
|
+
"TRAVEL_HANDOFF_NOT_FOUND",
|
|
1410
|
+
"TRAVEL_HANDOFF_COMMITTED",
|
|
1411
|
+
"TRAVEL_TARGET_OFFLINE",
|
|
1412
|
+
"TRAVEL_ID_COLLISION",
|
|
1413
|
+
"TRAVEL_ANCESTRY_GAP"
|
|
1414
|
+
]);
|
|
1415
|
+
var managementFields = {
|
|
1416
|
+
retire: ["jobId"],
|
|
1417
|
+
retirementStatus: [],
|
|
1418
|
+
status: [],
|
|
1419
|
+
identity: [],
|
|
1420
|
+
verifyAncestor: ["ancestor", "descendant"],
|
|
1421
|
+
deletionsSince: ["after", "maximum"],
|
|
1422
|
+
publishCheckpoint: ["permit", "digest", "parent"],
|
|
1423
|
+
recordRecoveryBranch: ["permit", "chain", "proof"],
|
|
1424
|
+
recoveryBranchStatus: ["common", "local"],
|
|
1425
|
+
assertPermit: ["permit", "operation"],
|
|
1426
|
+
acquire: ["ready"],
|
|
1427
|
+
beginHandoff: ["permit", "transferId", "targetNodeId"],
|
|
1428
|
+
freezeHandoff: ["permit", "transferId", "boundary"],
|
|
1429
|
+
readyHandoff: ["transferId", "ready"],
|
|
1430
|
+
commitHandoff: ["transferId"],
|
|
1431
|
+
handoffStatus: ["transferId"],
|
|
1432
|
+
abortHandoff: ["transferId"]
|
|
1433
|
+
};
|
|
1434
|
+
var retirementAction = (value) => value === "retire" || value === "retirementStatus";
|
|
1435
|
+
var record = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
1436
|
+
function validManagement(input) {
|
|
1437
|
+
if (input.action === "retire" && !(typeof input.jobId === "string" && identifier.test(input.jobId))) return false;
|
|
1438
|
+
if (!Object.hasOwn(managementFields, String(input.action))) return false;
|
|
1439
|
+
const fields = managementFields[String(input.action)];
|
|
1440
|
+
if (!fields || Object.keys(input).some((key) => !["version", "action", ...fields].includes(key)) || fields.some((key) => !Object.hasOwn(input, key))) return false;
|
|
1441
|
+
for (const key of ["ancestor", "descendant", "digest", "parent", "common", "local"]) if (Object.hasOwn(input, key) && (typeof input[key] !== "string" || !/^[a-f0-9]{64}$/.test(input[key]))) return false;
|
|
1442
|
+
for (const key of ["transferId", "targetNodeId"]) if (Object.hasOwn(input, key) && (typeof input[key] !== "string" || !identifier.test(input[key]))) return false;
|
|
1443
|
+
if (input.action === "deletionsSince" && (!Number.isSafeInteger(input.after) || Number(input.after) < 0 || !Number.isSafeInteger(input.maximum) || Number(input.maximum) < 1 || Number(input.maximum) > 32)) return false;
|
|
1444
|
+
if (input.action === "recordRecoveryBranch" && (!Array.isArray(input.chain) || input.chain.length < 1 || input.chain.length > 4096 || input.chain.some((value) => typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) || !Array.isArray(input.proof) || input.proof.length !== input.chain.length)) return false;
|
|
1445
|
+
if (Object.hasOwn(input, "permit") && !record(input.permit)) return false;
|
|
1446
|
+
if (Object.hasOwn(input, "operation") && !["WRITE", "SEND", "TOOL", "INPUT", "PUBLISH", "CONTROL"].includes(String(input.operation))) return false;
|
|
1447
|
+
if (Object.hasOwn(input, "ready") && (!record(input.ready) || Object.keys(input.ready).some((key) => !["checkpointDigest", "deletionWatermark", "buildManifestId", "volumeVerified", "capabilitiesVerified", "effectsLoaded", "unresolvedCritical"].includes(key)))) return false;
|
|
1448
|
+
if (Object.hasOwn(input, "boundary") && (!record(input.boundary) || Object.keys(input.boundary).some((key) => !["checkpointDigest", "safeBoundary", "effectsSettled"].includes(key)))) return false;
|
|
1449
|
+
return true;
|
|
1450
|
+
}
|
|
1451
|
+
function createTravelAuthorityServer(options) {
|
|
1452
|
+
const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls2 } = options;
|
|
1453
|
+
const proxies = /* @__PURE__ */ new Set(), peers = /* @__PURE__ */ new Map(), managers = /* @__PURE__ */ new Map();
|
|
1454
|
+
const fingerprint = (value) => {
|
|
1455
|
+
const normalized = value.replaceAll(":", "").toLowerCase();
|
|
1456
|
+
if (!/^[a-f0-9]{64}$/.test(normalized)) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
1457
|
+
return normalized;
|
|
1458
|
+
};
|
|
1459
|
+
for (const value of proxyFingerprints) {
|
|
1460
|
+
const fp = fingerprint(value);
|
|
1461
|
+
if (proxies.has(fp)) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
1462
|
+
proxies.add(fp);
|
|
1463
|
+
}
|
|
1464
|
+
for (const [value, credential] of Object.entries(allowedPeers)) {
|
|
1465
|
+
const fp = fingerprint(value);
|
|
1466
|
+
if (proxies.has(fp) || peers.has(fp)) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
1467
|
+
peers.set(fp, authority.authenticateRetirement(credential));
|
|
1468
|
+
}
|
|
1469
|
+
for (const [value, credentials] of Object.entries(managementPeers)) {
|
|
1470
|
+
const fp = fingerprint(value);
|
|
1471
|
+
if (managers.has(fp) || !Array.isArray(credentials) || !credentials.length || credentials.length > 128) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
1472
|
+
const grants = new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash));
|
|
1473
|
+
if (grants.size !== credentials.length) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
1474
|
+
managers.set(fp, grants);
|
|
1475
|
+
}
|
|
1476
|
+
if (!Number.isSafeInteger(maximumInFlight) || maximumInFlight < 1 || maximumInFlight > 64 || !proxies.size && !peers.size && !managers.size && !Object.keys(retirementPeers).length) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
1477
|
+
if (!Number.isSafeInteger(requestTimeoutMs) || requestTimeoutMs < 100 || requestTimeoutMs > 3e4) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
1478
|
+
const recoveryGrants = /* @__PURE__ */ new Map();
|
|
1479
|
+
for (const [value, credentials] of Object.entries(recoveryPeers)) {
|
|
1480
|
+
const fp = fingerprint(value);
|
|
1481
|
+
if (!Array.isArray(credentials) || !credentials.length || credentials.some((credential) => !managers.get(fp)?.has(authority.authenticateRetirement(credential).credentialHash))) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
1482
|
+
recoveryGrants.set(fp, new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash)));
|
|
1483
|
+
}
|
|
1484
|
+
const retirees = /* @__PURE__ */ new Map();
|
|
1485
|
+
for (const [value, credentials] of Object.entries(retirementPeers)) {
|
|
1486
|
+
const fp = fingerprint(value);
|
|
1487
|
+
if (!Array.isArray(credentials) || !credentials.length) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
1488
|
+
retirees.set(fp, new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash)));
|
|
1489
|
+
}
|
|
1490
|
+
const reports = /* @__PURE__ */ new Set(), management = /* @__PURE__ */ new Set();
|
|
1491
|
+
const server = createServer({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
|
|
1492
|
+
res.setHeader("Content-Type", "application/json");
|
|
1493
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1494
|
+
const reply = (status, value) => {
|
|
1495
|
+
res.statusCode = status;
|
|
1496
|
+
res.end(JSON.stringify(value));
|
|
1497
|
+
};
|
|
1498
|
+
const managing = req.url === "/travel/manage/v1", active = managing ? management : reports;
|
|
1499
|
+
if (req.method !== "POST" || !managing && req.url !== "/travel/control/v1") {
|
|
1500
|
+
reply(404, { error: "TRAVEL_CONTROL_NOT_FOUND" });
|
|
1501
|
+
req.resume();
|
|
1502
|
+
return;
|
|
1503
|
+
}
|
|
1504
|
+
let principal, credential, peerFingerprint;
|
|
1505
|
+
try {
|
|
1506
|
+
const socket = req.socket, fp = (socket.getPeerCertificate().fingerprint256 ?? "").replaceAll(":", "").toLowerCase();
|
|
1507
|
+
if (!socket.authorized || !managing && !proxies.has(fp) && !peers.has(fp) || req.rawHeaders.filter((_, i) => i % 2 === 0 && req.rawHeaders[i].toLowerCase() === "authorization").length !== 1) throw new Error();
|
|
1508
|
+
const authorization = req.headers.authorization;
|
|
1509
|
+
if (typeof authorization !== "string" || !/^Bearer e7t_[a-f0-9]{64}$/.test(authorization)) throw new Error();
|
|
1510
|
+
peerFingerprint = fp;
|
|
1511
|
+
credential = authorization.slice(7);
|
|
1512
|
+
principal = retirees.has(fp) && managing ? authority.authenticateRetirement(credential) : authority.authenticate(credential);
|
|
1513
|
+
if (managing) {
|
|
1514
|
+
if (!managers.get(fp)?.has(principal.credentialHash) && !retirees.get(fp)?.has(principal.credentialHash) || req.headers["x-engine7-travel-node"] !== principal.nodeId) throw new Error();
|
|
1515
|
+
} else if (proxies.has(fp)) {
|
|
1516
|
+
if (req.headers["x-engine7-travel-node"] !== principal.nodeId) throw new Error();
|
|
1517
|
+
} else if (peers.get(fp).credentialHash !== principal.credentialHash) throw new Error();
|
|
1518
|
+
} catch {
|
|
1519
|
+
reply(403, { error: "TRAVEL_AUTH_DENIED" });
|
|
1520
|
+
req.resume();
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
1523
|
+
if (active.size >= maximumInFlight || active.has(principal.credentialHash)) {
|
|
1524
|
+
reply(503, { error: "TRAVEL_CONTROL_BUSY" });
|
|
1525
|
+
req.resume();
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
active.add(principal.credentialHash);
|
|
1529
|
+
const deadline = setTimeout(() => req.destroy(), requestTimeoutMs);
|
|
1530
|
+
deadline.unref();
|
|
1531
|
+
try {
|
|
1532
|
+
const chunks = [];
|
|
1533
|
+
let bytes = 0;
|
|
1534
|
+
for await (const part of req) {
|
|
1535
|
+
bytes += part.length;
|
|
1536
|
+
if (bytes > (managing ? 40 * 1024 * 1024 : limit)) {
|
|
1537
|
+
res.setHeader("Connection", "close");
|
|
1538
|
+
reply(400, { error: "TRAVEL_CONTROL_INVALID_REQUEST" });
|
|
1539
|
+
req.resume();
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
chunks.push(part);
|
|
1543
|
+
}
|
|
1544
|
+
let envelope;
|
|
1545
|
+
try {
|
|
1546
|
+
envelope = JSON.parse(Buffer.concat(chunks).toString());
|
|
1547
|
+
} catch {
|
|
1548
|
+
reply(400, { error: "TRAVEL_CONTROL_INVALID_REQUEST" });
|
|
1549
|
+
return;
|
|
1550
|
+
}
|
|
1551
|
+
const input = envelope?.travel, keys = input?.action === "register" ? ["version", "action", "bootId"] : input?.action === "heartbeat" ? ["version", "action", "bootId", "sequence", "permit", "deletionWatermark"] : ["version", "action"];
|
|
1552
|
+
const validAction = managing ? record(input) && validManagement(input) : ["register", "heartbeat", "status"].includes(input?.action) && Object.keys(input).every((key) => keys.includes(key)) && (input.action === "status" || typeof input.bootId === "string" && identifier.test(input.bootId));
|
|
1553
|
+
if (!envelope || typeof envelope !== "object" || Array.isArray(envelope) || Object.keys(envelope).length !== 1 || !input || typeof input !== "object" || Array.isArray(input) || input.version !== 1 || !validAction) {
|
|
1554
|
+
reply(400, { error: "TRAVEL_CONTROL_INVALID_REQUEST" });
|
|
1555
|
+
return;
|
|
1556
|
+
}
|
|
1557
|
+
if (managing && retirementAction(input.action)) {
|
|
1558
|
+
if (!retirees.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1559
|
+
principal = authority.authenticateRetirement(credential);
|
|
1560
|
+
} else {
|
|
1561
|
+
if (managing && !managers.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1562
|
+
principal = authority.authenticate(credential);
|
|
1563
|
+
}
|
|
1564
|
+
let result;
|
|
1565
|
+
if (managing) {
|
|
1566
|
+
if (input.permit && ["tenantId", "companionId", "seatId", "nodeId"].some((key) => input.permit[key] !== principal[key])) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1567
|
+
switch (input.action) {
|
|
1568
|
+
case "retire":
|
|
1569
|
+
authority.retire(principal, input.jobId);
|
|
1570
|
+
result = {};
|
|
1571
|
+
break;
|
|
1572
|
+
case "retirementStatus":
|
|
1573
|
+
result = authority.retirementStatus(principal);
|
|
1574
|
+
break;
|
|
1575
|
+
case "status":
|
|
1576
|
+
result = authority.status(principal);
|
|
1577
|
+
break;
|
|
1578
|
+
case "identity":
|
|
1579
|
+
result = { principal, status: authority.status(principal), publicKey: authority.publicKey };
|
|
1580
|
+
break;
|
|
1581
|
+
case "verifyAncestor":
|
|
1582
|
+
authority.verifyAncestor(principal, input.ancestor, input.descendant);
|
|
1583
|
+
result = {};
|
|
1584
|
+
break;
|
|
1585
|
+
case "deletionsSince":
|
|
1586
|
+
result = { deletions: authority.deletionsSince(principal, input.after).slice(0, input.maximum) };
|
|
1587
|
+
break;
|
|
1588
|
+
case "publishCheckpoint":
|
|
1589
|
+
authority.publishCheckpoint(principal, input.permit, input.digest, input.parent);
|
|
1590
|
+
result = {};
|
|
1591
|
+
break;
|
|
1592
|
+
case "recoveryBranchStatus":
|
|
1593
|
+
result = authority.recoveryBranchStatus(principal, input.common, input.local);
|
|
1594
|
+
break;
|
|
1595
|
+
case "recordRecoveryBranch": {
|
|
1596
|
+
if (!recoveryGrants.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1597
|
+
const proof = input.proof.map((value) => normalizePublication(value));
|
|
1598
|
+
const profile = JSON.stringify(proof[0].profile);
|
|
1599
|
+
if (proof.some((manifest, index) => publicationDigest(manifest) !== input.chain[index] || JSON.stringify(manifest.profile) !== profile || index > 0 && (manifest.parentDigest !== input.chain[index - 1] || manifest.sequence !== proof[index - 1].sequence + 1)) || ["tenantId", "companionId", "seatId"].some((field) => proof[0].profile.identity[field] !== principal[field])) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
1600
|
+
authority.recordRecoveryBranch(principal, input.permit, input.chain);
|
|
1601
|
+
result = {};
|
|
1602
|
+
break;
|
|
1603
|
+
}
|
|
1604
|
+
case "assertPermit":
|
|
1605
|
+
authority.assertPermit(input.permit, input.operation);
|
|
1606
|
+
result = {};
|
|
1607
|
+
break;
|
|
1608
|
+
case "acquire":
|
|
1609
|
+
result = { permit: authority.acquire(principal, input.ready) };
|
|
1610
|
+
break;
|
|
1611
|
+
case "beginHandoff":
|
|
1612
|
+
result = authority.beginHandoff(principal, input.permit, input.transferId, input.targetNodeId);
|
|
1613
|
+
break;
|
|
1614
|
+
case "freezeHandoff":
|
|
1615
|
+
result = authority.freezeHandoff(principal, input.permit, input.transferId, input.boundary);
|
|
1616
|
+
break;
|
|
1617
|
+
case "readyHandoff":
|
|
1618
|
+
result = authority.readyHandoff(principal, input.transferId, input.ready);
|
|
1619
|
+
break;
|
|
1620
|
+
case "commitHandoff":
|
|
1621
|
+
result = authority.commitHandoff(principal, input.transferId);
|
|
1622
|
+
break;
|
|
1623
|
+
case "handoffStatus":
|
|
1624
|
+
result = authority.handoffStatus(principal, input.transferId);
|
|
1625
|
+
break;
|
|
1626
|
+
case "abortHandoff":
|
|
1627
|
+
result = authority.abortHandoff(principal, input.transferId);
|
|
1628
|
+
break;
|
|
1629
|
+
}
|
|
1630
|
+
} else if (input.action === "register") {
|
|
1631
|
+
authority.register(principal, input.bootId);
|
|
1632
|
+
result = authority.status(principal);
|
|
1633
|
+
} else if (input.action === "heartbeat") result = authority.heartbeat(principal, input);
|
|
1634
|
+
else result = authority.status(principal);
|
|
1635
|
+
reply(200, { travel: { version: 1, ...result } });
|
|
1636
|
+
} catch (error) {
|
|
1637
|
+
const code = error instanceof Error && errors.has(error.message) ? error.message : "TRAVEL_CONTROL_REFUSED";
|
|
1638
|
+
if (!res.writableEnded && !res.destroyed) reply(managing && code === "TRAVEL_AUTH_DENIED" ? 403 : 409, { error: code });
|
|
1639
|
+
} finally {
|
|
1640
|
+
clearTimeout(deadline);
|
|
1641
|
+
active.delete(principal.credentialHash);
|
|
1642
|
+
}
|
|
1643
|
+
});
|
|
1644
|
+
server.headersTimeout = 3e3;
|
|
1645
|
+
server.requestTimeout = requestTimeoutMs;
|
|
1646
|
+
server.keepAliveTimeout = 1e4;
|
|
1647
|
+
server.maxConnections = 64;
|
|
1648
|
+
server.maxRequestsPerSocket = 64;
|
|
1649
|
+
server.on("tlsClientError", () => {
|
|
1650
|
+
});
|
|
1651
|
+
return server;
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
// src/continuity/key-service-client.ts
|
|
1655
|
+
import { request } from "node:https";
|
|
1656
|
+
async function fetchTravelKey(options) {
|
|
1657
|
+
const url = new URL(options.url);
|
|
1658
|
+
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) throw new Error("KEY_SERVICE_HTTPS_REQUIRED");
|
|
1659
|
+
validateKeyIdentity(options.identity);
|
|
1660
|
+
if (!Number.isSafeInteger(options.minimumDeletionWatermark) || options.minimumDeletionWatermark < 0 || !options.ca?.length || !options.cert?.length || !options.key?.length)
|
|
1661
|
+
throw new Error("KEY_SERVICE_INVALID_CLIENT");
|
|
1662
|
+
const timeout = options.timeoutMs ?? 5e3;
|
|
1663
|
+
if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 6e4) throw new Error("KEY_SERVICE_INVALID_TIMEOUT");
|
|
1664
|
+
const body = JSON.stringify({ identity: options.identity, minimumDeletionWatermark: options.minimumDeletionWatermark });
|
|
1665
|
+
const value = await new Promise((resolve3, reject) => {
|
|
1666
|
+
let timer;
|
|
1667
|
+
const fail = (error) => {
|
|
1668
|
+
clearTimeout(timer);
|
|
1669
|
+
reject(error);
|
|
1670
|
+
};
|
|
1671
|
+
const req = request(url, {
|
|
1672
|
+
method: "POST",
|
|
1673
|
+
ca: options.ca,
|
|
1674
|
+
cert: options.cert,
|
|
1675
|
+
key: options.key,
|
|
1676
|
+
minVersion: "TLSv1.3",
|
|
1677
|
+
rejectUnauthorized: true,
|
|
1678
|
+
agent: false,
|
|
1679
|
+
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) }
|
|
1680
|
+
}, (res) => {
|
|
1681
|
+
if (res.statusCode !== 200) {
|
|
1682
|
+
res.resume();
|
|
1683
|
+
fail(new Error("KEY_SERVICE_DENIED"));
|
|
1684
|
+
return;
|
|
1685
|
+
}
|
|
1686
|
+
let size = 0;
|
|
1687
|
+
const chunks = [];
|
|
1688
|
+
res.on("data", (chunk) => {
|
|
1689
|
+
size += chunk.length;
|
|
1690
|
+
if (size > 16384) {
|
|
1691
|
+
fail(new Error("KEY_SERVICE_INVALID_RESPONSE"));
|
|
1692
|
+
req.destroy();
|
|
1693
|
+
return;
|
|
1694
|
+
}
|
|
1695
|
+
chunks.push(chunk);
|
|
1696
|
+
});
|
|
1697
|
+
res.on("error", () => fail(new Error("KEY_SERVICE_INVALID_RESPONSE")));
|
|
1698
|
+
res.on("end", () => {
|
|
1699
|
+
clearTimeout(timer);
|
|
1700
|
+
try {
|
|
1701
|
+
resolve3(JSON.parse(Buffer.concat(chunks).toString()));
|
|
1702
|
+
} catch {
|
|
1703
|
+
reject(new Error("KEY_SERVICE_INVALID_RESPONSE"));
|
|
1704
|
+
}
|
|
1705
|
+
});
|
|
1706
|
+
});
|
|
1707
|
+
req.on("error", () => fail(new Error("KEY_SERVICE_CONNECTION_FAILED")));
|
|
1708
|
+
timer = setTimeout(() => {
|
|
1709
|
+
req.destroy();
|
|
1710
|
+
fail(new Error("KEY_SERVICE_TIMEOUT"));
|
|
1711
|
+
}, timeout);
|
|
1712
|
+
req.end(body);
|
|
1713
|
+
});
|
|
1714
|
+
const wanted = options.identity;
|
|
1715
|
+
if (value?.protocolVersion !== 1 || !value.identity || ["tenantId", "companionId", "seatId", "keyId", "generation"].some((k) => value.identity[k] !== wanted[k]) || !Number.isSafeInteger(value.deletionWatermark) || value.deletionWatermark < options.minimumDeletionWatermark || typeof value.key !== "string" || !/^[A-Za-z0-9+/]{43}=$/.test(value.key))
|
|
1716
|
+
throw new Error("KEY_SERVICE_INVALID_RESPONSE");
|
|
1717
|
+
const key = Buffer.from(value.key, "base64");
|
|
1718
|
+
if (key.length !== 32 || key.toString("base64") !== value.key) {
|
|
1719
|
+
key.fill(0);
|
|
1720
|
+
throw new Error("KEY_SERVICE_INVALID_RESPONSE");
|
|
1721
|
+
}
|
|
1722
|
+
return { key, deletionWatermark: value.deletionWatermark };
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
// src/continuity/gateway-store.ts
|
|
1726
|
+
import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
|
|
1727
|
+
import { createHash as createHash7, randomUUID as randomUUID7 } from "node:crypto";
|
|
1728
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
1729
|
+
import { join as join4 } from "node:path";
|
|
1730
|
+
|
|
1731
|
+
// src/mem7/intake.ts
|
|
1732
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
1733
|
+
|
|
1734
|
+
// src/mem7/boot-recovery.ts
|
|
1735
|
+
import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
|
|
1736
|
+
|
|
1737
|
+
// src/mem7/core/store.ts
|
|
1738
|
+
init_runtime_lock();
|
|
1739
|
+
init_runtime_authority();
|
|
1740
|
+
init_sqlite_replication();
|
|
1741
|
+
import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
|
|
1742
|
+
|
|
1743
|
+
// src/continuity/mem7-replication.ts
|
|
1744
|
+
init_sqlite_replication();
|
|
1745
|
+
|
|
1746
|
+
// src/mem7/core/store.ts
|
|
1747
|
+
init_sqlite_autocommit();
|
|
1748
|
+
init_schema_migrations();
|
|
1749
|
+
|
|
1750
|
+
// src/mem7/core/vector-store.ts
|
|
1751
|
+
import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
|
|
1752
|
+
init_tokenizer();
|
|
1753
|
+
|
|
1754
|
+
// src/mem7/core/filters.ts
|
|
1755
|
+
init_clock();
|
|
1756
|
+
|
|
1757
|
+
// src/mem7/core/vector-publications.ts
|
|
1758
|
+
init_scope();
|
|
1759
|
+
|
|
1760
|
+
// src/mem7/core/state/dependencies.ts
|
|
1761
|
+
init_scope();
|
|
1762
|
+
|
|
1763
|
+
// src/mem7/core/state/context-time.ts
|
|
1764
|
+
init_clock();
|
|
1765
|
+
|
|
1766
|
+
// src/mem7/core/state/temporal.ts
|
|
1767
|
+
function canonicalJson(value) {
|
|
1768
|
+
const normalize = (input) => {
|
|
1769
|
+
if (Array.isArray(input)) return input.map(normalize);
|
|
1770
|
+
if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, normalize(entry)]));
|
|
1771
|
+
return input;
|
|
1772
|
+
};
|
|
1773
|
+
const json = JSON.stringify(normalize(value));
|
|
1774
|
+
if (json === void 0) throw new Error("INVALID_JSON_VALUE");
|
|
1775
|
+
return json;
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
// src/mem7/core/state/artifact-history.ts
|
|
1779
|
+
init_scope();
|
|
1780
|
+
|
|
1781
|
+
// src/mem7/core/state/knowledge-history.ts
|
|
1782
|
+
init_scope();
|
|
1783
|
+
|
|
1784
|
+
// src/mem7/core/state/artifact-history.ts
|
|
1785
|
+
init_read_budget();
|
|
1786
|
+
|
|
1787
|
+
// src/mem7/core/state/dependencies.ts
|
|
1788
|
+
init_read_budget();
|
|
1789
|
+
function invalidateDerivedDependencies(db, event) {
|
|
1790
|
+
const pending = [];
|
|
1791
|
+
const scopeParents = event.kind === "entity.changed" ? ["entities"] : ["fact.changed", "memory.deleted"].includes(event.kind) ? ["facts"] : [];
|
|
1792
|
+
for (const parent of scopeParents) pending.push(...db.prepare("SELECT child_kind,child_id FROM memory_dependencies WHERE scope_id=? AND parent_kind='scope' AND parent_id=?").all(event.scopeId, parent));
|
|
1793
|
+
for (const slot of event.changedSlotIds) {
|
|
1794
|
+
const version = event.kind === "fact.changed" && slot === event.aggregateId ? event.aggregateVersion : Number.MAX_SAFE_INTEGER;
|
|
1795
|
+
pending.push(...db.prepare("SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND slot_id=? AND slot_revision<?").all(event.scopeId, slot, version).map((row) => ({ ...row, deleted: event.kind === "memory.deleted" && row.role === "supports" })));
|
|
1796
|
+
}
|
|
1797
|
+
const parents = (event.changedEntityIds ?? []).map((id3) => ({ kind: "entity", id: id3 }));
|
|
1798
|
+
if (event.kind === "evidence.retracted" || event.kind === "memory.deleted") {
|
|
1799
|
+
parents.push(...event.sourceIds.map((id3) => ({ kind: "source", id: id3 })), { kind: event.targetKind ?? "source", id: event.aggregateId });
|
|
1800
|
+
}
|
|
1801
|
+
for (const parent of parents) {
|
|
1802
|
+
const version = event.kind === "entity.changed" && parent.id === event.aggregateId ? event.aggregateVersion : Number.MAX_SAFE_INTEGER;
|
|
1803
|
+
pending.push(...db.prepare("SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind=? AND parent_id=? AND parent_version<?").all(event.scopeId, parent.kind, parent.id, version).map((row) => ({ ...row, deleted: event.kind === "memory.deleted" && row.role === "supports" })));
|
|
1804
|
+
}
|
|
1805
|
+
return invalidateChildren(db, event.scopeId, pending, event.kind);
|
|
1806
|
+
}
|
|
1807
|
+
function invalidateChildren(db, scope, pending, reason) {
|
|
1808
|
+
const visited = /* @__PURE__ */ new Map();
|
|
1809
|
+
const result = [];
|
|
1810
|
+
let referencedPlan;
|
|
1811
|
+
while (pending.length) {
|
|
1812
|
+
const child = pending.shift();
|
|
1813
|
+
const key = JSON.stringify([child.child_kind, child.child_id]);
|
|
1814
|
+
if (visited.has(key) && (visited.get(key) || !child.deleted)) continue;
|
|
1815
|
+
visited.set(key, Boolean(child.deleted));
|
|
1816
|
+
if (child.child_kind === "graph_plan") {
|
|
1817
|
+
referencedPlan ??= db.prepare(`SELECT 1 WHERE EXISTS (SELECT 1 FROM memory_dependencies
|
|
1818
|
+
WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?)
|
|
1819
|
+
OR EXISTS (SELECT 1 FROM memory_artifact_publications WHERE scope_id=? AND kind='graph_plan' AND artifact_id=?)`);
|
|
1820
|
+
if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
|
|
1821
|
+
}
|
|
1822
|
+
const state = child.deleted ? "deleted" : "needs_revalidation";
|
|
1823
|
+
db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
|
|
1824
|
+
WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation','invalid') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
|
|
1825
|
+
result.push(child.child_id);
|
|
1826
|
+
pending.push(...db.prepare("SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?").all(scope, child.child_id).map((row) => ({ ...row, deleted: child.deleted && row.role === "supports" })));
|
|
1827
|
+
}
|
|
1828
|
+
return result;
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
// src/mem7/core/vector-store.ts
|
|
1832
|
+
init_read_guard();
|
|
1833
|
+
init_timing();
|
|
1834
|
+
init_runtime_authority();
|
|
1835
|
+
var isIntelMac = process.platform === "darwin" && process.arch === "x64";
|
|
1836
|
+
var bootAt = Date.now();
|
|
1837
|
+
|
|
1838
|
+
// src/mem7/core/prompt-render.ts
|
|
1839
|
+
init_clock();
|
|
1840
|
+
|
|
1841
|
+
// src/mem7/core/store.ts
|
|
1842
|
+
init_clock();
|
|
1843
|
+
|
|
1844
|
+
// src/mem7/core/migrations.ts
|
|
1845
|
+
init_schema_migrations();
|
|
1846
|
+
|
|
1847
|
+
// src/mem7/core/source-store.ts
|
|
1848
|
+
init_scope();
|
|
1849
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
1850
|
+
|
|
1851
|
+
// src/mem7/core/change-feed.ts
|
|
1852
|
+
import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
|
|
1853
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3, renameSync, unlinkSync as unlinkSync3, writeFileSync as writeFileSync3 } from "node:fs";
|
|
1854
|
+
function isBusyError(error) {
|
|
1855
|
+
if (!error || typeof error !== "object") return false;
|
|
1856
|
+
if (error.errcode === 5) return true;
|
|
1857
|
+
return /database is locked|SQLITE_BUSY/i.test(String(error.message ?? ""));
|
|
1858
|
+
}
|
|
1859
|
+
function deliveryReasonCode(error) {
|
|
1860
|
+
if (error && typeof error === "object") {
|
|
1861
|
+
if (isBusyError(error)) return "SQLITE_BUSY";
|
|
1862
|
+
const message = String(error.message ?? "");
|
|
1863
|
+
if (/^[A-Z][A-Z0-9_]{2,}$/.test(message)) return message;
|
|
1864
|
+
}
|
|
1865
|
+
return error instanceof Error && error.name ? error.name : "delivery_failed";
|
|
1866
|
+
}
|
|
1867
|
+
function appendMemoryChange(db, input, requestKey) {
|
|
1868
|
+
if (!input.scopeId || !input.aggregateId || !requestKey || !Number.isSafeInteger(input.aggregateVersion) || input.aggregateVersion < 1) {
|
|
1869
|
+
throw new Error("INVALID_MEMORY_CHANGE");
|
|
1870
|
+
}
|
|
1871
|
+
const normalized = {
|
|
1872
|
+
...input,
|
|
1873
|
+
changedSlotIds: [...new Set(input.changedSlotIds)].sort(),
|
|
1874
|
+
sourceIds: [...new Set(input.sourceIds)].sort(),
|
|
1875
|
+
...input.changedEntityIds ? { changedEntityIds: [...new Set(input.changedEntityIds)].sort() } : {}
|
|
1876
|
+
};
|
|
1877
|
+
const eventId = `evt_${createHash4("sha256").update(canonicalJson([input.scopeId, input.kind, requestKey])).digest("hex")}`;
|
|
1878
|
+
const previous = db.prepare("SELECT payload_json FROM memory_state_outbox WHERE event_id=?").get(eventId);
|
|
1879
|
+
if (previous) {
|
|
1880
|
+
const event2 = JSON.parse(previous.payload_json);
|
|
1881
|
+
if (canonicalJson(event2) !== canonicalJson({ ...normalized, eventId, eventSeq: event2.eventSeq, schemaVersion: 1 })) throw new Error("MEMORY_EVENT_IDEMPOTENCY_CONFLICT");
|
|
1882
|
+
return event2;
|
|
1883
|
+
}
|
|
1884
|
+
const eventSeq = Number(db.prepare("SELECT COALESCE(MAX(event_seq),0)+1 seq FROM memory_state_outbox WHERE scope_id=?").get(input.scopeId).seq);
|
|
1885
|
+
const event = { ...normalized, eventId, eventSeq, schemaVersion: 1 };
|
|
1886
|
+
invalidateDerivedDependencies(db, normalized);
|
|
1887
|
+
db.prepare("INSERT INTO memory_state_outbox(scope_id,event_seq,event_id,kind,fact_revision,aggregate_id,aggregate_version,payload_json,created_at) VALUES (?,?,?,?,?,?,?,?,?)").run(input.scopeId, eventSeq, eventId, input.kind, input.factRevision, input.aggregateId, input.aggregateVersion, canonicalJson(event), (/* @__PURE__ */ new Date()).toISOString());
|
|
1888
|
+
return event;
|
|
1889
|
+
}
|
|
1890
|
+
var ChangeFeed = class _ChangeFeed {
|
|
1891
|
+
constructor(db, transaction, gapHealLedgerPath) {
|
|
1892
|
+
this.db = db;
|
|
1893
|
+
this.transaction = transaction;
|
|
1894
|
+
this.gapHealLedgerPath = gapHealLedgerPath;
|
|
1895
|
+
}
|
|
1896
|
+
/** 1027 小柯事故:已治过的缺口去重(同缺口复发=消费者领先于生产端,需人工重放,不自动打转)。
|
|
1897
|
+
* 妹妹 review P2-4:进程内存 Set 不跨重启——去重账本落 sidecar 文件(不进 schema:
|
|
1898
|
+
* 热补 dist 混跑新旧二进制时,v36 迁移会让旧 main 撞写卫兵 ABORT;sidecar 零影响)。 */
|
|
1899
|
+
healedGaps = /* @__PURE__ */ new Set();
|
|
1900
|
+
static GAP_HEAL_RETENTION_MS = 7 * 864e5;
|
|
1901
|
+
append(input, requestKey) {
|
|
1902
|
+
return this.transaction(() => appendMemoryChange(this.db, input, requestKey));
|
|
1903
|
+
}
|
|
1904
|
+
get(eventId) {
|
|
1905
|
+
const row = this.db.prepare("SELECT payload_json FROM memory_state_outbox WHERE event_id=?").get(eventId);
|
|
1906
|
+
return row ? JSON.parse(row.payload_json) : null;
|
|
1907
|
+
}
|
|
1908
|
+
/** sink 首次注册的历史基线宽限窗:全新库 boot 后头几分钟的事件正常投递(1007 断路器) */
|
|
1909
|
+
static BASELINE_GRACE_MS = 10 * 6e4;
|
|
1910
|
+
/** 1020 死信闸:同一条事件连续失败达到上限即转终态(置 acked_at),不再无限重试、
|
|
1911
|
+
* 不再以队头阻塞拖死同 scope 后续事件(小柯 entity.changed 合并事件 37 次、.openclaw
|
|
1912
|
+
* 1134 次的教训)。事件本体留在 memory_state_outbox;重放需同步恢复消费者收据和序号。 */
|
|
1913
|
+
static DEAD_LETTER_ATTEMPTS = 5;
|
|
1914
|
+
/** SQLITE_BUSY 是环境性瞬态(图库被别的写者占住),不计死信预算,固定短间隔再试。 */
|
|
1915
|
+
static BUSY_RETRY_MS = 3e4;
|
|
1916
|
+
register(sinkId) {
|
|
1917
|
+
if (!/^[a-z][a-z0-9._-]{0,63}$/.test(sinkId)) throw new Error("INVALID_PROJECTION_SINK");
|
|
1918
|
+
const watermark = this.db.prepare("SELECT seq FROM memory_projection_sink_watermarks WHERE sink_id=?").get(sinkId);
|
|
1919
|
+
const max = Number(this.db.prepare("SELECT COALESCE(MAX(rowid),0) m FROM memory_state_outbox").get().m);
|
|
1920
|
+
if (watermark === void 0) {
|
|
1921
|
+
const since = new Date(Date.now() - _ChangeFeed.BASELINE_GRACE_MS).toISOString();
|
|
1922
|
+
this.db.prepare(`INSERT OR IGNORE INTO memory_projection_deliveries(sink_id,event_id,scope_id)
|
|
1923
|
+
SELECT ?,event_id,scope_id FROM memory_state_outbox WHERE created_at>=?`).run(sinkId, since);
|
|
1924
|
+
this.db.prepare("INSERT INTO memory_projection_sink_watermarks(sink_id,seq) VALUES (?,?)").run(sinkId, max);
|
|
1925
|
+
return;
|
|
1926
|
+
}
|
|
1927
|
+
if (max <= watermark.seq) return;
|
|
1928
|
+
this.db.prepare(`INSERT OR IGNORE INTO memory_projection_deliveries(sink_id,event_id,scope_id)
|
|
1929
|
+
SELECT ?,event_id,scope_id FROM memory_state_outbox WHERE rowid>? AND rowid<=?`).run(sinkId, watermark.seq, max);
|
|
1930
|
+
this.db.prepare("UPDATE memory_projection_sink_watermarks SET seq=? WHERE sink_id=?").run(max, sinkId);
|
|
1931
|
+
}
|
|
1932
|
+
pending(sinkId, limit2 = 50, now = Date.now()) {
|
|
1933
|
+
if (!Number.isSafeInteger(limit2) || limit2 < 1 || limit2 > 1e3) throw new Error("INVALID_DELIVERY_LIMIT");
|
|
1934
|
+
this.register(sinkId);
|
|
1935
|
+
const rows = this.db.prepare(`WITH heads AS (
|
|
1936
|
+
SELECT delivery.scope_id,MIN(event.event_seq) event_seq FROM memory_projection_deliveries delivery
|
|
1937
|
+
JOIN memory_state_outbox event ON event.event_id=delivery.event_id
|
|
1938
|
+
WHERE delivery.sink_id=? AND delivery.acked_at IS NULL GROUP BY delivery.scope_id
|
|
1939
|
+
) SELECT event.payload_json FROM heads
|
|
1940
|
+
JOIN memory_state_outbox event ON event.scope_id=heads.scope_id AND event.event_seq=heads.event_seq
|
|
1941
|
+
JOIN memory_projection_deliveries delivery ON delivery.event_id=event.event_id AND delivery.sink_id=?
|
|
1942
|
+
WHERE delivery.next_run_at<=?
|
|
1943
|
+
ORDER BY event.created_at,event.scope_id,event.event_seq LIMIT ?`).all(sinkId, sinkId, now, limit2);
|
|
1944
|
+
return rows.map((row) => JSON.parse(row.payload_json));
|
|
1945
|
+
}
|
|
1946
|
+
pendingWindow(sinkId, head, limit2) {
|
|
1947
|
+
return this.db.prepare(`SELECT event.payload_json,delivery.next_run_at FROM memory_projection_deliveries delivery
|
|
1948
|
+
JOIN memory_state_outbox event ON event.event_id=delivery.event_id
|
|
1949
|
+
WHERE delivery.sink_id=? AND delivery.scope_id=? AND delivery.acked_at IS NULL AND event.event_seq>=?
|
|
1950
|
+
ORDER BY event.event_seq LIMIT ?`).all(sinkId, head.scopeId, head.eventSeq, limit2).map((row) => ({ event: JSON.parse(row.payload_json), dueAt: Number(row.next_run_at) }));
|
|
1951
|
+
}
|
|
1952
|
+
/** Ack and enqueueing any expensive follow-up job share the producer's transaction. */
|
|
1953
|
+
acknowledge(sinkId, event, afterAck) {
|
|
1954
|
+
return this.transaction(() => {
|
|
1955
|
+
this.register(sinkId);
|
|
1956
|
+
const stored = this.get(event.eventId);
|
|
1957
|
+
if (!stored || canonicalJson(stored) !== canonicalJson(event)) throw new Error("MEMORY_EVENT_MISMATCH");
|
|
1958
|
+
const row = this.db.prepare("SELECT acked_at FROM memory_projection_deliveries WHERE sink_id=? AND event_id=?").get(sinkId, event.eventId);
|
|
1959
|
+
if (row.acked_at !== null) return false;
|
|
1960
|
+
const prior = this.db.prepare(`SELECT 1 FROM memory_projection_deliveries d JOIN memory_state_outbox e ON e.event_id=d.event_id
|
|
1961
|
+
WHERE d.sink_id=? AND d.scope_id=? AND d.acked_at IS NULL AND e.event_seq<?`).get(sinkId, event.scopeId, event.eventSeq);
|
|
1962
|
+
if (prior) throw new Error("PROJECTION_ACK_OUT_OF_ORDER");
|
|
1963
|
+
afterAck?.();
|
|
1964
|
+
this.db.prepare("UPDATE memory_projection_deliveries SET acked_at=?,last_error=NULL WHERE sink_id=? AND event_id=?").run((/* @__PURE__ */ new Date()).toISOString(), sinkId, event.eventId);
|
|
1965
|
+
return true;
|
|
1966
|
+
});
|
|
1967
|
+
}
|
|
1968
|
+
retry(sinkId, eventId, reason, now = Date.now()) {
|
|
1969
|
+
this.db.prepare(`UPDATE memory_projection_deliveries SET attempts=attempts+1,last_error=?,
|
|
1970
|
+
next_run_at=?+MIN(300000,1000*(1 << MIN(attempts,8))) WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(reason.slice(0, 300), now, sinkId, eventId);
|
|
1971
|
+
}
|
|
1972
|
+
/** 1027 小柯事故自愈:迁移/换新图(图 inbox 全新、position=0)撞上生产端带 ack 前缀 →
|
|
1973
|
+
* 队头永久 PROJECTION_SEQUENCE_GAP,投递与死信 skip 同检连坐、零进展直到人工介入。
|
|
1974
|
+
* 把缺口前缀(同 scope seq < 队头)重置为待投:新消费者如实重放缺失事件;旧消费者
|
|
1975
|
+
* inbox 收据仍在、按 duplicate 幂等 ack 不重放(poison-delivery-skip.test 重放语义)。
|
|
1976
|
+
* 同一 (sink,scope,head) 只治一次(跨重启,sidecar 账本)——复发说明消费者领先于
|
|
1977
|
+
* 回滚后的生产端,只能人工重放。死信行复活时保留 attempts(妹妹 review P2-5:已知毒
|
|
1978
|
+
* 事件重放失败一次即回死信+skip,不重烧 5 轮预算)。先 UPDATE 后记账:中间崩溃只会
|
|
1979
|
+
* 多治一次(幂等无害),反过来会出现"记了账但没治"的永久死锁。 */
|
|
1980
|
+
reenqueueGapPrefix(sinkId, head, now = Date.now()) {
|
|
1981
|
+
const key = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
|
|
1982
|
+
if (this.healedGaps.has(key)) return;
|
|
1983
|
+
const ledgerPath = this.gapHealLedgerPath;
|
|
1984
|
+
let ledger = {};
|
|
1985
|
+
if (ledgerPath) {
|
|
1986
|
+
try {
|
|
1987
|
+
ledger = JSON.parse(readFileSync3(ledgerPath, "utf8"))?.heals ?? {};
|
|
1988
|
+
} catch {
|
|
1989
|
+
}
|
|
1990
|
+
if (Number.isFinite(ledger[key])) {
|
|
1991
|
+
this.healedGaps.add(key);
|
|
1992
|
+
return;
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
this.transaction(() => {
|
|
1996
|
+
const result = this.db.prepare(`UPDATE memory_projection_deliveries
|
|
1997
|
+
SET acked_at=NULL,
|
|
1998
|
+
attempts=CASE WHEN last_error LIKE 'dead:%' THEN attempts ELSE 0 END,
|
|
1999
|
+
last_error=NULL,next_run_at=0
|
|
2000
|
+
WHERE sink_id=? AND scope_id=? AND acked_at IS NOT NULL AND event_id IN (
|
|
2001
|
+
SELECT event_id FROM memory_state_outbox WHERE scope_id=? AND event_seq<?)`).run(sinkId, head.scopeId, head.scopeId, head.eventSeq);
|
|
2002
|
+
const count = Number(result?.changes ?? 0);
|
|
2003
|
+
if (count > 0) console.warn(`[mem7] \u5E8F\u5217\u7F3A\u53E3\u81EA\u6108\uFF1Ahead seq=${head.eventSeq} \u524D ${count} \u6761\u5DF2 ack \u6295\u9012\u884C\u91CD\u7F6E\u5F85\u6295\uFF08\u65B0\u56FE\u5982\u5B9E\u91CD\u653E / \u65E7\u56FE\u5E42\u7B49 duplicate-ack\uFF1B\u6B7B\u4FE1\u884C\u4FDD\u7559 attempts\uFF09`);
|
|
2004
|
+
});
|
|
2005
|
+
this.healedGaps.add(key);
|
|
2006
|
+
if (!ledgerPath) return;
|
|
2007
|
+
const cutoff = now - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
|
|
2008
|
+
for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
|
|
2009
|
+
retained[key] = now;
|
|
2010
|
+
const temp = `${ledgerPath}.${randomUUID4()}.tmp`;
|
|
2011
|
+
try {
|
|
2012
|
+
writeFileSync3(temp, JSON.stringify({ version: 1, heals: retained }));
|
|
2013
|
+
renameSync(temp, ledgerPath);
|
|
2014
|
+
} catch (error) {
|
|
2015
|
+
try {
|
|
2016
|
+
if (existsSync2(temp)) unlinkSync3(temp);
|
|
2017
|
+
} catch {
|
|
2018
|
+
}
|
|
2019
|
+
console.warn(`[mem7] \u7F3A\u53E3\u81EA\u6108\u8D26\u672C\u5199\u5165\u5931\u8D25\uFF08\u672C\u8FDB\u7A0B\u5185\u4ECD\u53BB\u91CD\uFF0C\u91CD\u542F\u540E\u53EF\u80FD\u591A\u6CBB\u4E00\u6B21\uFF0C\u5E42\u7B49\u65E0\u5BB3\uFF09\uFF1A${error.message}`);
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
/** busy:只推后下次到期,attempts 不动(死信预算只留给真失败)。 */
|
|
2023
|
+
retryTransient(sinkId, eventId, now) {
|
|
2024
|
+
this.db.prepare(`UPDATE memory_projection_deliveries SET last_error='SQLITE_BUSY',next_run_at=?
|
|
2025
|
+
WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(now + _ChangeFeed.BUSY_RETRY_MS, sinkId, eventId);
|
|
2026
|
+
}
|
|
2027
|
+
/** 满次数转死信终态(置 acked_at 解除队头阻塞),返回是否已转。must be head-of-line:
|
|
2028
|
+
* pending() 只出同 scope 队头,走到这里的失败事件前面不存在未 ack 事件,直接置终态
|
|
2029
|
+
* 不会破坏 acknowledge 的有序约束。
|
|
2030
|
+
* 1020 astra review P1:生产端终态 ≠ 消费者序号已前进——onDead(消费者 skip 协议)
|
|
2031
|
+
* 必须先落库再置终态,否则同 scope 后续正常事件全部 PROJECTION_SEQUENCE_GAP 连坐。
|
|
2032
|
+
* skip 失败 = 不死信、下轮重试(此时 attempts 已超帽,每轮退避重试 skip,响亮留痕)。 */
|
|
2033
|
+
async deadLetter(sinkId, event, reason, now, onDead) {
|
|
2034
|
+
const row = this.db.prepare("SELECT attempts FROM memory_projection_deliveries WHERE sink_id=? AND event_id=?").get(sinkId, event.eventId);
|
|
2035
|
+
if (!row || Number(row.attempts) + 1 < _ChangeFeed.DEAD_LETTER_ATTEMPTS) return false;
|
|
2036
|
+
if (onDead) {
|
|
2037
|
+
try {
|
|
2038
|
+
await onDead(structuredClone(event));
|
|
2039
|
+
} catch (error) {
|
|
2040
|
+
console.warn(`[mem7] dead-letter consumer skip failed ${event.kind} ${event.eventId.slice(0, 24)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2041
|
+
return false;
|
|
2042
|
+
}
|
|
2043
|
+
} else {
|
|
2044
|
+
console.warn(`[mem7] sink '${sinkId}' \u65E0\u6B7B\u4FE1\u8DF3\u8FC7\u534F\u8BAE\uFF08consumer.skip \u672A\u63A5\uFF09\uFF0C\u4FDD\u7559 pending \u5E76\u91CD\u8BD5`);
|
|
2045
|
+
return false;
|
|
2046
|
+
}
|
|
2047
|
+
this.transaction(() => {
|
|
2048
|
+
this.db.prepare(`UPDATE memory_projection_deliveries SET attempts=attempts+1,last_error=?,acked_at=?,next_run_at=?
|
|
2049
|
+
WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(`dead:${reason.slice(0, 290)}`, new Date(now).toISOString(), now, sinkId, event.eventId);
|
|
2050
|
+
});
|
|
2051
|
+
console.warn(`[mem7] delivery dead-lettered ${event.kind} ${event.eventId.slice(0, 24)} after ${_ChangeFeed.DEAD_LETTER_ATTEMPTS} attempts: ${reason}\uFF08\u91CD\u653E\uFF1A\u6682\u505C\u6295\u9012\u5E76\u4FEE\u597D\u6839\u56E0\uFF0C\u91CD\u7F6E\u540C sink/scope \u4ECE seq=${event.eventSeq} \u8D77\u7684\u5168\u90E8\u6295\u9012\u884C\uFF0C\u5220\u540C scope \u8BE5\u6BB5 inbox \u6536\u636E\uFF0Cposition \u56DE\u9000\u81F3 ${event.eventSeq - 1}\uFF1B\u4FDD\u7559 heads \u5E76\u6309\u5E8F\u6062\u590D\uFF09`);
|
|
2052
|
+
return true;
|
|
2053
|
+
}
|
|
2054
|
+
status(sinkId) {
|
|
2055
|
+
this.register(sinkId);
|
|
2056
|
+
const row = this.db.prepare(`SELECT SUM(acked_at IS NULL) pending,
|
|
2057
|
+
SUM(acked_at IS NOT NULL AND last_error IS NULL) delivered,
|
|
2058
|
+
SUM(acked_at IS NOT NULL AND last_error IS NOT NULL) failed
|
|
2059
|
+
FROM memory_projection_deliveries WHERE sink_id=?`).get(sinkId);
|
|
2060
|
+
return { pending: Number(row.pending ?? 0), delivered: Number(row.delivered ?? 0), failed: Number(row.failed ?? 0) };
|
|
2061
|
+
}
|
|
2062
|
+
async deliver(sinkId, receive, options = {}) {
|
|
2063
|
+
const now = options.now ?? Date.now();
|
|
2064
|
+
const limit2 = options.limit ?? 100;
|
|
2065
|
+
if (!Number.isSafeInteger(limit2) || limit2 < 1 || limit2 > 1e3) throw new Error("INVALID_DELIVERY_LIMIT");
|
|
2066
|
+
let delivered = 0;
|
|
2067
|
+
let attempted = 0;
|
|
2068
|
+
const blockedScopes = /* @__PURE__ */ new Set();
|
|
2069
|
+
while (attempted < limit2) {
|
|
2070
|
+
const pending = this.pending(sinkId, limit2, now).filter((event) => !blockedScopes.has(event.scopeId));
|
|
2071
|
+
if (!pending.length) break;
|
|
2072
|
+
const perScope = Math.max(1, Math.floor((limit2 - attempted) / pending.length));
|
|
2073
|
+
const windows = pending.map((head) => this.pendingWindow(sinkId, head, perScope));
|
|
2074
|
+
const batch = Array.from({ length: perScope }, (_, index) => windows.flatMap((window) => window[index] ? [window[index]] : [])).flat();
|
|
2075
|
+
for (const { event, dueAt } of batch) {
|
|
2076
|
+
if (blockedScopes.has(event.scopeId)) continue;
|
|
2077
|
+
if (dueAt > now) {
|
|
2078
|
+
blockedScopes.add(event.scopeId);
|
|
2079
|
+
continue;
|
|
2080
|
+
}
|
|
2081
|
+
if (attempted++ >= limit2) break;
|
|
2082
|
+
try {
|
|
2083
|
+
if (!await receive(structuredClone(event))) throw new Error("consumer_unavailable");
|
|
2084
|
+
if (this.acknowledge(sinkId, event, () => options.afterAck?.(event))) delivered++;
|
|
2085
|
+
} catch (error) {
|
|
2086
|
+
const reason = deliveryReasonCode(error);
|
|
2087
|
+
if (isBusyError(error)) {
|
|
2088
|
+
this.retryTransient(sinkId, event.eventId, now);
|
|
2089
|
+
} else {
|
|
2090
|
+
console.warn(`[mem7] delivery failed ${event.kind} ${event.eventId.slice(0, 24)}: ${reason} ${(error instanceof Error ? error.message : String(error)).slice(0, 300)}`);
|
|
2091
|
+
if (reason === "PROJECTION_SEQUENCE_GAP") this.reenqueueGapPrefix(sinkId, event);
|
|
2092
|
+
if (!await this.deadLetter(sinkId, event, reason, now, options.onDead)) this.retry(sinkId, event.eventId, reason, now);
|
|
2093
|
+
}
|
|
2094
|
+
blockedScopes.add(event.scopeId);
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
return delivered;
|
|
2099
|
+
}
|
|
2100
|
+
};
|
|
2101
|
+
|
|
2102
|
+
// src/mem7/core/source-store.ts
|
|
2103
|
+
init_read_budget();
|
|
2104
|
+
var digest = (value) => createHash5("sha256").update(JSON.stringify(value)).digest("hex");
|
|
2105
|
+
function projectedSourceIdFromScopeId(id3, originKey, sourceVersion) {
|
|
2106
|
+
return "src_" + digest([id3, originKey, sourceVersion]);
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
// src/mem7/core/state/tombstones.ts
|
|
2110
|
+
init_scope();
|
|
2111
|
+
|
|
2112
|
+
// src/mem7/core/host-turns.ts
|
|
2113
|
+
init_scope();
|
|
2114
|
+
import { randomUUID as randomUUID5, createHash as createHash6 } from "node:crypto";
|
|
2115
|
+
var processOwnerId = randomUUID5();
|
|
2116
|
+
var currentSource = `EXISTS (SELECT 1 FROM memory_sources s WHERE s.scope_id=memory_host_turns.scope_id
|
|
2117
|
+
AND s.source_id=memory_host_turns.source_id AND s.role='user' AND s.origin_class='host_user' AND s.interpretation_status<>'deleted'
|
|
2118
|
+
AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id AND newer.origin_key=s.origin_key
|
|
2119
|
+
AND newer.source_version>s.source_version))`;
|
|
2120
|
+
var owned = `state='running' AND lease_token=? AND version=? AND source_version=?
|
|
2121
|
+
AND ((owner_pid=? AND owner_id=?) OR (owner_pid IS NULL AND lease_until>?)) AND ${currentSource}`;
|
|
2122
|
+
|
|
2123
|
+
// src/mem7/core/job-provenance.ts
|
|
2124
|
+
init_scope();
|
|
2125
|
+
var MEMORY_PIPELINE_JOB_KINDS = ["episode.extract", "atomic.extract", "foresight.extract", "artifact.publish", "vector.upsert"];
|
|
2126
|
+
var MEMORY_AGENT_JOB_KINDS = ["agent-case", "skill-cluster", "skill-extract", "profile-cluster", "profile-extract"];
|
|
2127
|
+
|
|
2128
|
+
// src/mem7/core/legacy-recovery.ts
|
|
2129
|
+
init_scope();
|
|
2130
|
+
|
|
2131
|
+
// src/mem7/core/state/social-sources.ts
|
|
2132
|
+
init_scope();
|
|
2133
|
+
init_read_budget();
|
|
2134
|
+
|
|
2135
|
+
// src/mem7/core/recall-sources.ts
|
|
2136
|
+
init_scope();
|
|
2137
|
+
|
|
2138
|
+
// src/mem7/core/state/relationships.ts
|
|
2139
|
+
init_scope();
|
|
2140
|
+
init_read_budget();
|
|
2141
|
+
|
|
2142
|
+
// src/mem7/core/state/social-interpretation.ts
|
|
2143
|
+
init_read_guard();
|
|
2144
|
+
init_scope();
|
|
2145
|
+
|
|
2146
|
+
// src/mem7/core/episode.ts
|
|
2147
|
+
import { readFileSync as readFileSync4 } from "node:fs";
|
|
2148
|
+
import { join as join3, dirname as dirname2 } from "node:path";
|
|
2149
|
+
import { fileURLToPath } from "node:url";
|
|
2150
|
+
var PROMPT = readFileSync4(join3(dirname2(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
|
|
2151
|
+
|
|
2152
|
+
// src/mem7/core/relationship-cognition.ts
|
|
2153
|
+
init_scope();
|
|
2154
|
+
|
|
2155
|
+
// src/memory/proactive/relationship-context.ts
|
|
2156
|
+
init_scope();
|
|
2157
|
+
|
|
2158
|
+
// src/mem7/core/relationship-context.ts
|
|
2159
|
+
init_scope();
|
|
2160
|
+
|
|
2161
|
+
// src/messages/attachments.ts
|
|
2162
|
+
init_topics_history();
|
|
2163
|
+
|
|
2164
|
+
// src/memory/proactive/recall-score.ts
|
|
2165
|
+
var DEFAULT_MIN_SCORE = Number(process.env.RECALL_MIN_SCORE ?? 1);
|
|
2166
|
+
|
|
2167
|
+
// src/mem7/core/relationship-context.ts
|
|
2168
|
+
init_read_budget();
|
|
2169
|
+
|
|
2170
|
+
// src/memory/proactive/relationship-context.ts
|
|
2171
|
+
init_read_budget();
|
|
2172
|
+
|
|
2173
|
+
// src/mem7/core/relationship-cognition.ts
|
|
2174
|
+
init_read_guard();
|
|
2175
|
+
|
|
2176
|
+
// src/mem7/core/state/relationship-notices.ts
|
|
2177
|
+
init_scope();
|
|
2178
|
+
|
|
2179
|
+
// src/mem7/core/state/entities.ts
|
|
2180
|
+
init_scope();
|
|
2181
|
+
|
|
2182
|
+
// src/mem7/core/state/facts.ts
|
|
2183
|
+
init_scope();
|
|
2184
|
+
|
|
2185
|
+
// src/mem7/core/store.ts
|
|
2186
|
+
init_scope();
|
|
2187
|
+
init_read_guard();
|
|
2188
|
+
|
|
2189
|
+
// src/mem7/core/job-retention.ts
|
|
2190
|
+
import { gzip, gunzipSync } from "node:zlib";
|
|
2191
|
+
import { promisify } from "node:util";
|
|
2192
|
+
var compress = promisify(gzip);
|
|
2193
|
+
var kinds = [
|
|
2194
|
+
"boundary",
|
|
2195
|
+
"source.interpret",
|
|
2196
|
+
"social.interpret",
|
|
2197
|
+
"relationship.cognition",
|
|
2198
|
+
"graph.reason",
|
|
2199
|
+
...MEMORY_PIPELINE_JOB_KINDS,
|
|
2200
|
+
...MEMORY_AGENT_JOB_KINDS
|
|
2201
|
+
];
|
|
2202
|
+
|
|
2203
|
+
// src/mem7/core/retire-graph-audits.ts
|
|
2204
|
+
init_schema_migrations();
|
|
2205
|
+
|
|
2206
|
+
// src/mem7/core/store.ts
|
|
2207
|
+
var STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
|
|
2208
|
+
|
|
2209
|
+
// src/mem7/intake.ts
|
|
2210
|
+
function hostMessageKey(channel, channelId, messageId) {
|
|
2211
|
+
return JSON.stringify(["host", channel, channelId, messageId || randomUUID6()]);
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
// src/continuity/gateway-store.ts
|
|
2215
|
+
var digest3 = (value) => createHash7("sha256").update(value).digest("hex");
|
|
2216
|
+
var identityKey = (identity) => JSON.stringify([identity.tenantId, identity.companionId, identity.seatId]);
|
|
2217
|
+
var validId = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
2218
|
+
var bodyLimit = 16 * 1024 * 1024;
|
|
2219
|
+
var TravelGatewayStore = class {
|
|
2220
|
+
constructor(options) {
|
|
2221
|
+
this.options = options;
|
|
2222
|
+
if (identityKey(options.identity) !== identityKey(options.objects.identity)) throw new Error("TRAVEL_GATEWAY_IDENTITY");
|
|
2223
|
+
preparePrivateDirectory(options.directory);
|
|
2224
|
+
const ownerFile = join4(options.directory, "gateway-owner.sqlite");
|
|
2225
|
+
preparePrivateDatabase(ownerFile);
|
|
2226
|
+
this.owner = new DatabaseSync10(ownerFile);
|
|
2227
|
+
try {
|
|
2228
|
+
this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY); BEGIN IMMEDIATE");
|
|
2229
|
+
} catch {
|
|
2230
|
+
this.owner.close();
|
|
2231
|
+
throw new Error("TRAVEL_GATEWAY_BUSY");
|
|
2232
|
+
}
|
|
2233
|
+
try {
|
|
2234
|
+
const path3 = join4(options.directory, "gateway.sqlite"), present = existsSync3(path3);
|
|
2235
|
+
preparePrivateDatabase(path3);
|
|
2236
|
+
this.db = new DatabaseSync10(path3);
|
|
2237
|
+
this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
|
|
2238
|
+
if (!present) this.db.exec([
|
|
2239
|
+
"CREATE TABLE binding(identity TEXT NOT NULL,format TEXT NOT NULL);",
|
|
2240
|
+
"CREATE TABLE inbox(sequence INTEGER PRIMARY KEY AUTOINCREMENT,event_id TEXT UNIQUE NOT NULL,body_hash TEXT NOT NULL,body_ref TEXT NOT NULL,session_hash TEXT NOT NULL,occurred_at INTEGER NOT NULL,state TEXT NOT NULL,node_id TEXT,boot_id TEXT,epoch INTEGER,output_sealed INTEGER NOT NULL DEFAULT 0);",
|
|
2241
|
+
"CREATE TABLE claims(request_key TEXT PRIMARY KEY,digest TEXT NOT NULL,event_ids TEXT NOT NULL);",
|
|
2242
|
+
"CREATE TABLE cancellations(event_id TEXT PRIMARY KEY,cancel_id TEXT NOT NULL,session_hash TEXT);",
|
|
2243
|
+
"CREATE TABLE effects(effect_id TEXT PRIMARY KEY,event_id TEXT NOT NULL,kind TEXT NOT NULL,ordinal INTEGER NOT NULL,version INTEGER NOT NULL,body_hash TEXT NOT NULL,body_ref TEXT NOT NULL,state TEXT NOT NULL,platform_key TEXT NOT NULL UNIQUE,dispatch_id TEXT UNIQUE,dispatch_node TEXT,dispatch_boot TEXT,dispatch_epoch INTEGER,receipt TEXT,result_hash TEXT,result_ref TEXT,UNIQUE(event_id,kind,ordinal));",
|
|
2244
|
+
"CREATE INDEX effects_event ON effects(event_id); CREATE INDEX inbox_pending ON inbox(state,sequence);"
|
|
2245
|
+
].join("\n"));
|
|
2246
|
+
if (!present) this.db.prepare("INSERT INTO binding VALUES(?,?)").run(identityKey(options.identity), "engine7-travel-gateway-v1");
|
|
2247
|
+
const binding = this.db.prepare("SELECT * FROM binding").all();
|
|
2248
|
+
if (binding.length !== 1 || binding[0].identity !== identityKey(options.identity) || binding[0].format !== "engine7-travel-gateway-v1" || this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_GATEWAY_RECOVERY_REQUIRED");
|
|
2249
|
+
if (!this.db.prepare("PRAGMA table_info(cancellations)").all().some((column) => column.name === "session_hash")) {
|
|
2250
|
+
this.transaction(() => {
|
|
2251
|
+
this.db.exec("ALTER TABLE cancellations ADD COLUMN session_hash TEXT");
|
|
2252
|
+
this.db.exec("UPDATE cancellations SET session_hash=(SELECT session_hash FROM inbox WHERE inbox.event_id=cancellations.event_id)");
|
|
2253
|
+
});
|
|
2254
|
+
}
|
|
2255
|
+
this.transaction(() => this.db.prepare("UPDATE effects SET state='UNKNOWN' WHERE state='DISPATCHING'").run());
|
|
2256
|
+
this.db.exec("CREATE TABLE IF NOT EXISTS processed_inputs(event_id TEXT PRIMARY KEY,platform_id_hash TEXT NOT NULL UNIQUE)");
|
|
2257
|
+
if (!this.db.prepare("PRAGMA table_info(inbox)").all().some((column) => column.name === "platform_id_hash")) this.db.exec("ALTER TABLE inbox ADD COLUMN platform_id_hash TEXT");
|
|
2258
|
+
} catch (error) {
|
|
2259
|
+
try {
|
|
2260
|
+
this.db?.close();
|
|
2261
|
+
} finally {
|
|
2262
|
+
this.owner.close();
|
|
2263
|
+
}
|
|
2264
|
+
;
|
|
2265
|
+
throw error;
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
db;
|
|
2269
|
+
owner;
|
|
2270
|
+
closed = false;
|
|
2271
|
+
transaction(operation) {
|
|
2272
|
+
if (this.closed) throw new Error("TRAVEL_GATEWAY_CLOSED");
|
|
2273
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
2274
|
+
try {
|
|
2275
|
+
const result = operation();
|
|
2276
|
+
this.db.exec("COMMIT");
|
|
2277
|
+
return result;
|
|
2278
|
+
} catch (error) {
|
|
2279
|
+
if (this.db.isTransaction) this.db.exec("ROLLBACK");
|
|
2280
|
+
throw error;
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
/** Trusted standby preparation reads the actual shared receipt ledger. A
|
|
2284
|
+
* recorded UNKNOWN is retained; an ongoing dispatch is never called settled. */
|
|
2285
|
+
preparationEvidence(principal) {
|
|
2286
|
+
if (this.closed) throw new Error("TRAVEL_GATEWAY_CLOSED");
|
|
2287
|
+
if (identityKey(principal) !== identityKey(this.options.identity)) throw new Error("TRAVEL_GATEWAY_AUTH_DENIED");
|
|
2288
|
+
const status = this.options.authority.status(principal);
|
|
2289
|
+
if (!existsSync3(join4(this.options.directory, "gateway.sqlite")) || this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_GATEWAY_RECOVERY_REQUIRED");
|
|
2290
|
+
const inFlight = Number(this.db.prepare("SELECT count(*) AS n FROM effects WHERE state='DISPATCHING'").get().n);
|
|
2291
|
+
const unknownEffects = Number(this.db.prepare("SELECT count(*) AS n FROM effects WHERE state='UNKNOWN'").get().n);
|
|
2292
|
+
const unresolvedInputs = Number(this.db.prepare("SELECT count(*) AS n FROM inbox WHERE state='QUARANTINED'").get().n);
|
|
2293
|
+
return { identity: this.options.identity, deletionWatermark: status.deletionWatermark, loaded: true, effectsSettled: inFlight === 0, unknownEffects, unresolvedInputs };
|
|
2294
|
+
}
|
|
2295
|
+
active(principal, permit, kind) {
|
|
2296
|
+
this.options.authority.status(principal);
|
|
2297
|
+
this.options.authority.assertPermit(permit, kind);
|
|
2298
|
+
if (identityKey(principal) !== identityKey(this.options.identity) || identityKey(permit) !== identityKey(this.options.identity) || principal.nodeId !== permit.nodeId) throw new Error("TRAVEL_GATEWAY_AUTH_DENIED");
|
|
2299
|
+
}
|
|
2300
|
+
owned(principal, permit, eventId, kind) {
|
|
2301
|
+
this.active(principal, permit, kind);
|
|
2302
|
+
if (!validId(eventId)) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2303
|
+
const event = this.db.prepare("SELECT state,node_id,boot_id,epoch FROM inbox WHERE event_id=?").get(eventId);
|
|
2304
|
+
if (!event) throw new Error("TRAVEL_GATEWAY_EVENT_NOT_FOUND");
|
|
2305
|
+
if (event.state === "CANCELLED") throw new Error("TRAVEL_GATEWAY_CANCELLED");
|
|
2306
|
+
if (event.state === "QUARANTINED") throw new Error("TRAVEL_GATEWAY_DELETION_BARRIER");
|
|
2307
|
+
if (event.node_id !== permit.nodeId || event.boot_id !== permit.bootId || Number(event.epoch) !== permit.epoch) throw new Error("TRAVEL_GATEWAY_CLAIM_REQUIRED");
|
|
2308
|
+
}
|
|
2309
|
+
inputDeletion(principal, row, body) {
|
|
2310
|
+
const floor = this.options.authority.status(principal).deletionWatermark;
|
|
2311
|
+
if (!floor) return void 0;
|
|
2312
|
+
let packet;
|
|
2313
|
+
try {
|
|
2314
|
+
packet = JSON.parse(body.toString());
|
|
2315
|
+
} catch {
|
|
2316
|
+
return "UNBOUND";
|
|
2317
|
+
}
|
|
2318
|
+
if (packet?.format !== "engine7-feishu-gateway-inbound-v1") return "UNBOUND";
|
|
2319
|
+
const message = packet.event?.message;
|
|
2320
|
+
if (typeof message?.message_id !== "string" || !message.message_id || typeof message.chat_id !== "string" || !message.chat_id || digest3(JSON.stringify([identityKey(this.options.identity), "feishu", message.message_id])) !== row.event_id || digest3(message.chat_id) !== row.session_hash) throw new Error("TRAVEL_GATEWAY_BODY_CORRUPT");
|
|
2321
|
+
const origin = hostMessageKey("feishu", message.chat_id, message.message_id), log = this.options.authority.deletionsSince(principal, 0);
|
|
2322
|
+
if (log.length !== floor || log.some((entry, index) => entry.watermark !== index + 1)) throw new Error("TRAVEL_GATEWAY_DELETION_BARRIER");
|
|
2323
|
+
return log.find((entry) => entry.sourceId === projectedSourceIdFromScopeId(entry.scopeId, origin, entry.version));
|
|
2324
|
+
}
|
|
2325
|
+
async currentInputBody(principal, permit, eventId) {
|
|
2326
|
+
this.owned(principal, permit, eventId, "INPUT");
|
|
2327
|
+
const row = this.db.prepare("SELECT * FROM inbox WHERE event_id=?").get(eventId);
|
|
2328
|
+
const body = await this.options.objects.readContent(JSON.parse(String(row.body_ref)), bodyLimit);
|
|
2329
|
+
this.owned(principal, permit, eventId, "INPUT");
|
|
2330
|
+
if (digest3(body) !== row.body_hash) throw new Error("TRAVEL_GATEWAY_BODY_CORRUPT");
|
|
2331
|
+
const deletion = this.inputDeletion(principal, row, body);
|
|
2332
|
+
if (deletion === "UNBOUND") {
|
|
2333
|
+
this.transaction(() => {
|
|
2334
|
+
this.owned(principal, permit, eventId, "INPUT");
|
|
2335
|
+
this.db.prepare("UPDATE inbox SET state='QUARANTINED' WHERE event_id=?").run(eventId);
|
|
2336
|
+
});
|
|
2337
|
+
throw new Error("TRAVEL_GATEWAY_DELETION_BARRIER");
|
|
2338
|
+
}
|
|
2339
|
+
if (deletion) {
|
|
2340
|
+
this.cancel(eventId, "memory-deletion:" + deletion.id);
|
|
2341
|
+
throw new Error("TRAVEL_GATEWAY_CANCELLED");
|
|
2342
|
+
}
|
|
2343
|
+
return body;
|
|
2344
|
+
}
|
|
2345
|
+
async assertInputCurrent(principal, permit, eventId) {
|
|
2346
|
+
if (this.options.authority.status(principal).deletionWatermark) await this.currentInputBody(principal, permit, eventId);
|
|
2347
|
+
else this.owned(principal, permit, eventId, "INPUT");
|
|
2348
|
+
}
|
|
2349
|
+
async receive(event) {
|
|
2350
|
+
if (event.channel !== "feishu" || typeof event.platformId !== "string" || !event.platformId || event.platformId.length > 512 || typeof event.sessionKey !== "string" || !event.sessionKey || event.sessionKey.length > 1024 || !Number.isSafeInteger(event.occurredAt) || event.occurredAt < 0 || !Buffer.isBuffer(event.body) || !event.body.length || event.body.length > bodyLimit) throw new Error("TRAVEL_GATEWAY_INVALID_EVENT");
|
|
2351
|
+
const id3 = digest3(JSON.stringify([identityKey(this.options.identity), event.channel, event.platformId]));
|
|
2352
|
+
if (this.db.prepare("SELECT 1 FROM processed_inputs WHERE event_id=?").get(id3)) return { id: id3, accepted: true };
|
|
2353
|
+
const body = Buffer.from(event.body), bodyHash = digest3(body), ref = await this.options.objects.putContent(body);
|
|
2354
|
+
return this.transaction(() => {
|
|
2355
|
+
const prior = this.db.prepare("SELECT body_hash,session_hash FROM inbox WHERE event_id=?").get(id3), session = digest3(event.sessionKey);
|
|
2356
|
+
if (prior) {
|
|
2357
|
+
if (prior.body_hash !== bodyHash || prior.session_hash !== session) throw new Error("TRAVEL_GATEWAY_ID_COLLISION");
|
|
2358
|
+
} else {
|
|
2359
|
+
if (event.cancelPending) {
|
|
2360
|
+
const active = this.db.prepare("SELECT event_id FROM inbox WHERE session_hash=? AND state IN ('CLAIMED','ACKED','UNKNOWN')").all(session);
|
|
2361
|
+
for (const pending of active) this.cancelInside(String(pending.event_id), event.platformId);
|
|
2362
|
+
}
|
|
2363
|
+
const cancelled = this.db.prepare("SELECT session_hash FROM cancellations WHERE event_id=?").get(id3);
|
|
2364
|
+
if (cancelled?.session_hash && cancelled.session_hash !== session) throw new Error("TRAVEL_GATEWAY_ID_COLLISION");
|
|
2365
|
+
this.db.prepare("INSERT INTO inbox(event_id,body_hash,body_ref,session_hash,occurred_at,state) VALUES(?,?,?,?,?,?)").run(id3, bodyHash, JSON.stringify(ref), session, event.occurredAt, cancelled ? "CANCELLED" : "RECEIVED");
|
|
2366
|
+
this.db.prepare("UPDATE inbox SET platform_id_hash=? WHERE event_id=?").run(digest3(event.platformId), id3);
|
|
2367
|
+
}
|
|
2368
|
+
return { id: id3, accepted: true };
|
|
2369
|
+
});
|
|
2370
|
+
}
|
|
2371
|
+
/** Host-owned import of actual previously processed platform IDs. A receipt
|
|
2372
|
+
* is negative dedupe only: it cannot create input or enqueue a task. */
|
|
2373
|
+
importProcessedInputs(platformIds) {
|
|
2374
|
+
if (!Array.isArray(platformIds) || platformIds.length > 1e5 || platformIds.some((id3) => typeof id3 !== "string" || !id3 || id3.length > 512)) throw new Error("TRAVEL_GATEWAY_INVALID_EVENT");
|
|
2375
|
+
this.transaction(() => {
|
|
2376
|
+
for (const platformId of platformIds) {
|
|
2377
|
+
const id3 = digest3(JSON.stringify([identityKey(this.options.identity), "feishu", platformId]));
|
|
2378
|
+
if (this.db.prepare("SELECT 1 FROM inbox WHERE event_id=? AND state NOT IN ('DONE','CANCELLED')").get(id3)) throw new Error("TRAVEL_GATEWAY_MIGRATION_CONFLICT");
|
|
2379
|
+
this.db.prepare("INSERT OR IGNORE INTO processed_inputs VALUES(?,?)").run(id3, digest3(platformId));
|
|
2380
|
+
}
|
|
2381
|
+
});
|
|
2382
|
+
}
|
|
2383
|
+
async migrateStoredInputs() {
|
|
2384
|
+
const rows = this.db.prepare("SELECT event_id,body_hash,body_ref,session_hash FROM inbox WHERE platform_id_hash IS NULL LIMIT 100001").all();
|
|
2385
|
+
if (rows.length > 1e5) throw new Error("TRAVEL_GATEWAY_LEGACY_RECEIPTS_PENDING");
|
|
2386
|
+
const migrated = [];
|
|
2387
|
+
for (const row of rows) {
|
|
2388
|
+
const body = await this.options.objects.readContent(JSON.parse(String(row.body_ref)), bodyLimit);
|
|
2389
|
+
if (digest3(body) !== row.body_hash) throw new Error("TRAVEL_GATEWAY_BODY_CORRUPT");
|
|
2390
|
+
let packet;
|
|
2391
|
+
try {
|
|
2392
|
+
packet = JSON.parse(body.toString());
|
|
2393
|
+
} catch {
|
|
2394
|
+
throw new Error("TRAVEL_GATEWAY_LEGACY_RECEIPTS_PENDING");
|
|
2395
|
+
}
|
|
2396
|
+
const message = packet?.event?.message;
|
|
2397
|
+
if (packet?.format !== "engine7-feishu-gateway-inbound-v1" || typeof message?.message_id !== "string" || !message.message_id || digest3(JSON.stringify([identityKey(this.options.identity), "feishu", message.message_id])) !== row.event_id || digest3(message.chat_id) !== row.session_hash) throw new Error("TRAVEL_GATEWAY_LEGACY_RECEIPTS_PENDING");
|
|
2398
|
+
migrated.push({ id: String(row.event_id), hash: digest3(message.message_id) });
|
|
2399
|
+
}
|
|
2400
|
+
this.transaction(() => {
|
|
2401
|
+
for (const row of migrated) this.db.prepare("UPDATE inbox SET platform_id_hash=? WHERE event_id=? AND platform_id_hash IS NULL").run(row.hash, row.id);
|
|
2402
|
+
});
|
|
2403
|
+
}
|
|
2404
|
+
exitDedupeReceipt(principal, permit) {
|
|
2405
|
+
this.active(principal, permit, "CONTROL");
|
|
2406
|
+
if (this.db.prepare("SELECT 1 FROM effects WHERE state='DISPATCHING' LIMIT 1").get()) throw new Error("TRAVEL_GATEWAY_EFFECTS_IN_FLIGHT");
|
|
2407
|
+
const inputs = this.db.prepare("SELECT event_id AS id,platform_id_hash AS platformIdHash,state FROM inbox ORDER BY sequence").all();
|
|
2408
|
+
if (inputs.some((row) => !validId(row.platformIdHash))) throw new Error("TRAVEL_GATEWAY_LEGACY_RECEIPTS_PENDING");
|
|
2409
|
+
const effects = this.db.prepare("SELECT effect_id AS id,event_id AS eventId,kind,ordinal,version,state,platform_key AS platformKey,receipt FROM effects ORDER BY effect_id").all();
|
|
2410
|
+
const body = {
|
|
2411
|
+
format: "engine7-travel-exit-dedupe-v1",
|
|
2412
|
+
identity: this.options.identity,
|
|
2413
|
+
checkpointDigest: this.options.authority.status(principal).checkpointDigest,
|
|
2414
|
+
deletionWatermark: this.options.authority.status(principal).deletionWatermark,
|
|
2415
|
+
inputs: [...inputs, ...this.db.prepare("SELECT event_id AS id,platform_id_hash AS platformIdHash,'DONE' AS state FROM processed_inputs ORDER BY event_id").all()],
|
|
2416
|
+
effects
|
|
2417
|
+
};
|
|
2418
|
+
return { ...body, digest: digest3(JSON.stringify(body)) };
|
|
2419
|
+
}
|
|
2420
|
+
/** Trusted platform ingress only. Nodes can read resources solely by a
|
|
2421
|
+
* claimed event and its attachment ordinal, never an arbitrary object ref. */
|
|
2422
|
+
async putResource(body) {
|
|
2423
|
+
if (!Buffer.isBuffer(body) || !body.length || body.length > bodyLimit) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
|
|
2424
|
+
return this.options.objects.putContent(body);
|
|
2425
|
+
}
|
|
2426
|
+
async resource(principal, permit, eventId, index) {
|
|
2427
|
+
this.owned(principal, permit, eventId, "INPUT");
|
|
2428
|
+
if (!Number.isSafeInteger(index) || index < 0 || index > 7) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2429
|
+
const packet = JSON.parse((await this.currentInputBody(principal, permit, eventId)).toString());
|
|
2430
|
+
const resource = packet.resources?.[index];
|
|
2431
|
+
if (!resource?.ref) throw new Error("TRAVEL_GATEWAY_RESOURCE_NOT_FOUND");
|
|
2432
|
+
const bytes = await this.options.objects.readContent(resource.ref, bodyLimit);
|
|
2433
|
+
this.owned(principal, permit, eventId, "INPUT");
|
|
2434
|
+
return bytes;
|
|
2435
|
+
}
|
|
2436
|
+
async claim(principal, permit, options = {}) {
|
|
2437
|
+
this.active(principal, permit, "INPUT");
|
|
2438
|
+
const limit2 = options.limit ?? 10, requestId = options.requestId ?? randomUUID7();
|
|
2439
|
+
if (!Number.isSafeInteger(limit2) || limit2 < 1 || limit2 > 100 || typeof requestId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(requestId)) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2440
|
+
const requestKey = digest3(JSON.stringify([permit.nodeId, permit.bootId, permit.epoch, requestId])), requestDigest = digest3(String(limit2));
|
|
2441
|
+
const prior = this.db.prepare("SELECT digest,event_ids FROM claims WHERE request_key=?").get(requestKey);
|
|
2442
|
+
if (prior && prior.digest !== requestDigest) throw new Error("TRAVEL_GATEWAY_ID_COLLISION");
|
|
2443
|
+
const ids = prior ? JSON.parse(String(prior.event_ids)) : void 0;
|
|
2444
|
+
const candidates = ids ? ids.map((id3) => this.db.prepare("SELECT * FROM inbox WHERE event_id=?").get(id3)) : this.db.prepare("SELECT * FROM inbox WHERE state IN ('RECEIVED','CLAIMED','ACKED','UNKNOWN') AND (node_id IS NULL OR node_id<>? OR boot_id<>? OR epoch<>?) ORDER BY sequence LIMIT ?").all(permit.nodeId, permit.bootId, permit.epoch, limit2);
|
|
2445
|
+
const loaded = [];
|
|
2446
|
+
let bytes = 0;
|
|
2447
|
+
for (const candidate of candidates) {
|
|
2448
|
+
if (!candidate || candidate.state === "CANCELLED" || candidate.state === "DONE") continue;
|
|
2449
|
+
const body = await this.options.objects.readContent(JSON.parse(String(candidate.body_ref)), bodyLimit);
|
|
2450
|
+
if (digest3(body) !== candidate.body_hash) throw new Error("TRAVEL_GATEWAY_BODY_CORRUPT");
|
|
2451
|
+
bytes += body.length;
|
|
2452
|
+
if (bytes > 32 * 1024 * 1024) break;
|
|
2453
|
+
loaded.push({ candidate, body });
|
|
2454
|
+
}
|
|
2455
|
+
return this.transaction(() => {
|
|
2456
|
+
this.active(principal, permit, "INPUT");
|
|
2457
|
+
const known = this.db.prepare("SELECT digest,event_ids FROM claims WHERE request_key=?").get(requestKey);
|
|
2458
|
+
if (known && known.digest !== requestDigest) throw new Error("TRAVEL_GATEWAY_ID_COLLISION");
|
|
2459
|
+
const knownIds = known ? new Set(JSON.parse(String(known.event_ids))) : void 0;
|
|
2460
|
+
const result = [];
|
|
2461
|
+
for (const { candidate, body } of loaded) {
|
|
2462
|
+
if (knownIds && !knownIds.has(String(candidate.event_id))) continue;
|
|
2463
|
+
const current2 = this.db.prepare("SELECT state,node_id,boot_id,epoch,output_sealed FROM inbox WHERE event_id=?").get(candidate.event_id);
|
|
2464
|
+
if (!current2 || current2.state === "CANCELLED" || current2.state === "DONE" || !knownIds && current2.node_id === permit.nodeId && current2.boot_id === permit.bootId && Number(current2.epoch) === permit.epoch) continue;
|
|
2465
|
+
const deletion = this.inputDeletion(principal, candidate, body);
|
|
2466
|
+
if (deletion === "UNBOUND") {
|
|
2467
|
+
this.db.prepare("UPDATE inbox SET state='QUARANTINED' WHERE event_id=?").run(candidate.event_id);
|
|
2468
|
+
continue;
|
|
2469
|
+
}
|
|
2470
|
+
if (deletion) {
|
|
2471
|
+
this.cancelInside(String(candidate.event_id), "memory-deletion:" + deletion.id);
|
|
2472
|
+
continue;
|
|
2473
|
+
}
|
|
2474
|
+
const effects = this.db.prepare("SELECT state FROM effects WHERE event_id=?").all(candidate.event_id);
|
|
2475
|
+
const mode = effects.some((e) => ["DISPATCHING", "UNKNOWN"].includes(String(e.state))) ? "RECONCILE" : effects.length ? current2.output_sealed ? "RESUME_OUTPUT" : "RECONCILE" : "EXECUTE";
|
|
2476
|
+
this.db.prepare("UPDATE inbox SET state='CLAIMED',node_id=?,boot_id=?,epoch=? WHERE event_id=?").run(permit.nodeId, permit.bootId, permit.epoch, candidate.event_id);
|
|
2477
|
+
result.push({ id: String(candidate.event_id), body, mode, nodeId: permit.nodeId, bootId: permit.bootId, epoch: permit.epoch });
|
|
2478
|
+
}
|
|
2479
|
+
this.db.prepare("INSERT OR IGNORE INTO claims VALUES(?,?,?)").run(requestKey, requestDigest, JSON.stringify(result.map((item) => item.id)));
|
|
2480
|
+
return result;
|
|
2481
|
+
});
|
|
2482
|
+
}
|
|
2483
|
+
ack(principal, permit, eventId) {
|
|
2484
|
+
this.transaction(() => {
|
|
2485
|
+
this.owned(principal, permit, eventId, "INPUT");
|
|
2486
|
+
this.db.prepare("UPDATE inbox SET state='ACKED' WHERE event_id=? AND state<>'DONE'").run(eventId);
|
|
2487
|
+
});
|
|
2488
|
+
}
|
|
2489
|
+
finish(principal, permit, eventId) {
|
|
2490
|
+
this.transaction(() => {
|
|
2491
|
+
this.owned(principal, permit, eventId, "INPUT");
|
|
2492
|
+
if (this.db.prepare("SELECT 1 FROM effects WHERE event_id=? AND state NOT IN ('SENT','CANCELLED') LIMIT 1").get(eventId)) throw new Error("TRAVEL_GATEWAY_UNFINISHED_EFFECTS");
|
|
2493
|
+
this.db.prepare("UPDATE inbox SET state='DONE' WHERE event_id=?").run(eventId);
|
|
2494
|
+
});
|
|
2495
|
+
}
|
|
2496
|
+
/** Authenticated ingress and the gateway's independent deletion projection. */
|
|
2497
|
+
cancel(eventId, cancelId) {
|
|
2498
|
+
if (!validId(eventId) || typeof cancelId !== "string" || !cancelId || cancelId.length > 512) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2499
|
+
this.transaction(() => this.cancelInside(eventId, cancelId));
|
|
2500
|
+
}
|
|
2501
|
+
/** Trusted stopped-H cleanup supplies original native source/alias bindings.
|
|
2502
|
+
* HTTP requires the separate recovery certificate grant. Negative input
|
|
2503
|
+
* receipts also cover an original alias that the platform has not sent yet. */
|
|
2504
|
+
applyRecoveryDeletedInputs(principal, bindings, floor) {
|
|
2505
|
+
if (identityKey(principal) !== identityKey(this.options.identity) || bindings.length > 1e6) throw new Error("TRAVEL_GATEWAY_DELETION_BARRIER");
|
|
2506
|
+
const check = () => {
|
|
2507
|
+
if (this.options.authority.status(principal).deletionWatermark !== floor) throw new Error("TRAVEL_GATEWAY_DELETION_BARRIER");
|
|
2508
|
+
};
|
|
2509
|
+
check();
|
|
2510
|
+
const log = this.options.authority.deletionsSince(principal, 0);
|
|
2511
|
+
if (log.length !== floor || log.some((entry, index) => entry.watermark !== index + 1)) throw new Error("TRAVEL_GATEWAY_DELETION_BARRIER");
|
|
2512
|
+
const ids = new Set(log.map((entry) => entry.id)), events = /* @__PURE__ */ new Map();
|
|
2513
|
+
let bytes = 0;
|
|
2514
|
+
for (const binding of bindings) {
|
|
2515
|
+
bytes += Buffer.byteLength(binding.originKey);
|
|
2516
|
+
if (bytes > 64 * 1024 * 1024 || !ids.has(binding.deletionId)) throw new Error("TRAVEL_GATEWAY_DELETION_BARRIER");
|
|
2517
|
+
let origin;
|
|
2518
|
+
try {
|
|
2519
|
+
origin = JSON.parse(binding.originKey);
|
|
2520
|
+
} catch {
|
|
2521
|
+
continue;
|
|
2522
|
+
}
|
|
2523
|
+
if (!Array.isArray(origin) || origin[0] !== "host") continue;
|
|
2524
|
+
if (origin[1] !== "feishu") continue;
|
|
2525
|
+
if (origin.length !== 4 || typeof origin[2] !== "string" || !origin[2] || origin[2].length > 1024 || typeof origin[3] !== "string" || !origin[3] || origin[3].length > 512 || hostMessageKey("feishu", origin[2], origin[3]) !== binding.originKey) throw new Error("TRAVEL_GATEWAY_DELETION_BARRIER");
|
|
2526
|
+
const id3 = digest3(JSON.stringify([identityKey(this.options.identity), "feishu", origin[3]])), session = digest3(origin[2]);
|
|
2527
|
+
if (events.has(id3) && events.get(id3).session !== session) throw new Error("TRAVEL_GATEWAY_ID_COLLISION");
|
|
2528
|
+
events.set(id3, { session, cancelId: "memory-deletion:" + binding.deletionId });
|
|
2529
|
+
}
|
|
2530
|
+
return this.transaction(() => {
|
|
2531
|
+
check();
|
|
2532
|
+
for (const [id3, event] of events) {
|
|
2533
|
+
const rows = this.db.prepare("SELECT session_hash FROM inbox WHERE event_id=? UNION ALL SELECT session_hash FROM cancellations WHERE event_id=?").all(id3, id3);
|
|
2534
|
+
if (rows.some((row) => row.session_hash && row.session_hash !== event.session)) throw new Error("TRAVEL_GATEWAY_ID_COLLISION");
|
|
2535
|
+
}
|
|
2536
|
+
for (const [id3, event] of events) {
|
|
2537
|
+
this.cancelInside(id3, event.cancelId, true);
|
|
2538
|
+
this.db.prepare("UPDATE cancellations SET session_hash=? WHERE event_id=? AND session_hash IS NULL").run(event.session, id3);
|
|
2539
|
+
}
|
|
2540
|
+
check();
|
|
2541
|
+
return { format: "engine7-recovery-gateway-input-deletions-v1", deletionWatermark: floor, logDigest: digest3(JSON.stringify(log)), origins: events.size };
|
|
2542
|
+
});
|
|
2543
|
+
}
|
|
2544
|
+
cancelInside(eventId, cancelId, allowMissing = false) {
|
|
2545
|
+
const prior = this.db.prepare("SELECT cancel_id FROM cancellations WHERE event_id=?").get(eventId);
|
|
2546
|
+
if (prior) return;
|
|
2547
|
+
if (!allowMissing && !this.db.prepare("SELECT 1 FROM inbox WHERE event_id=?").get(eventId)) throw new Error("TRAVEL_GATEWAY_EVENT_NOT_FOUND");
|
|
2548
|
+
this.db.prepare("INSERT INTO cancellations(event_id,cancel_id,session_hash) VALUES(?,?,(SELECT session_hash FROM inbox WHERE event_id=?))").run(eventId, cancelId, eventId);
|
|
2549
|
+
this.db.prepare("UPDATE inbox SET state='CANCELLED' WHERE event_id=?").run(eventId);
|
|
2550
|
+
this.db.prepare("UPDATE effects SET state=CASE WHEN state='DISPATCHING' THEN 'UNKNOWN' ELSE 'CANCELLED' END WHERE event_id=? AND state IN ('PRODUCED','INTENT','FAILED_NOT_SENT','DISPATCHING')").run(eventId);
|
|
2551
|
+
}
|
|
2552
|
+
async produce(principal, permit, input) {
|
|
2553
|
+
return (await this.produceBatch(principal, permit, [input]))[0];
|
|
2554
|
+
}
|
|
2555
|
+
/** A complete reply is made visible in one transaction. Failed object writes
|
|
2556
|
+
* cannot leave a durable prefix that would be mistaken for a full answer. */
|
|
2557
|
+
async produceBatch(principal, permit, inputs, options = {}) {
|
|
2558
|
+
if (!Array.isArray(inputs) || !inputs.length || inputs.length > 100) throw new Error("TRAVEL_GATEWAY_INVALID_EFFECT");
|
|
2559
|
+
const loaded = [], checked = /* @__PURE__ */ new Set();
|
|
2560
|
+
let bytes = 0;
|
|
2561
|
+
for (const value of inputs) {
|
|
2562
|
+
const input = { ...value, body: Buffer.from(value.body) }, kind = input.kind === "TOOL" ? "TOOL" : "SEND";
|
|
2563
|
+
this.owned(principal, permit, input.eventId, kind);
|
|
2564
|
+
if (!checked.has(input.eventId)) {
|
|
2565
|
+
await this.assertInputCurrent(principal, permit, input.eventId);
|
|
2566
|
+
checked.add(input.eventId);
|
|
2567
|
+
}
|
|
2568
|
+
if (!["REPLY", "TOOL", "MEDIA", "PREVIEW", "TASK"].includes(input.kind) || !Number.isSafeInteger(input.ordinal) || input.ordinal < 1 || input.ordinal > 1e5 || !Number.isSafeInteger(input.version) || input.version < 1 || !Buffer.isBuffer(value.body) || !input.body.length || input.body.length > bodyLimit) throw new Error("TRAVEL_GATEWAY_INVALID_EFFECT");
|
|
2569
|
+
bytes += input.body.length;
|
|
2570
|
+
if (bytes > 16 * 1024 * 1024) throw new Error("TRAVEL_GATEWAY_INVALID_EFFECT");
|
|
2571
|
+
const id3 = digest3(JSON.stringify([identityKey(this.options.identity), input.eventId, input.kind, input.ordinal, input.version]));
|
|
2572
|
+
loaded.push({ input, id: id3, bodyHash: digest3(input.body), ref: await this.options.objects.putContent(input.body) });
|
|
2573
|
+
}
|
|
2574
|
+
return this.transaction(() => {
|
|
2575
|
+
for (const { input, id: id3, bodyHash, ref } of loaded) {
|
|
2576
|
+
this.owned(principal, permit, input.eventId, input.kind === "TOOL" ? "TOOL" : "SEND");
|
|
2577
|
+
const prior = this.db.prepare("SELECT effect_id,body_hash,version FROM effects WHERE event_id=? AND kind=? AND ordinal=?").get(input.eventId, input.kind, input.ordinal);
|
|
2578
|
+
if (prior) {
|
|
2579
|
+
if (prior.effect_id !== id3 || prior.body_hash !== bodyHash || Number(prior.version) !== input.version) throw new Error("TRAVEL_GATEWAY_SEGMENT_VERSION_COLLISION");
|
|
2580
|
+
} else {
|
|
2581
|
+
if (this.db.prepare("SELECT state FROM inbox WHERE event_id=?").get(input.eventId)?.state === "DONE") throw new Error("TRAVEL_GATEWAY_EVENT_COMPLETED");
|
|
2582
|
+
this.db.prepare("INSERT INTO effects(effect_id,event_id,kind,ordinal,version,body_hash,body_ref,state,platform_key) VALUES(?,?,?,?,?,?,?,?,?)").run(id3, input.eventId, input.kind, input.ordinal, input.version, bodyHash, JSON.stringify(ref), "PRODUCED", id3.slice(0, 32));
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
if (options.finalOutput) {
|
|
2586
|
+
if (inputs.some((input) => input.eventId !== inputs[0].eventId || input.kind !== "REPLY")) throw new Error("TRAVEL_GATEWAY_INVALID_EFFECT");
|
|
2587
|
+
this.db.prepare("UPDATE inbox SET output_sealed=1 WHERE event_id=?").run(inputs[0].eventId);
|
|
2588
|
+
}
|
|
2589
|
+
return loaded.map(({ id: id3 }) => this.effect(id3));
|
|
2590
|
+
});
|
|
2591
|
+
}
|
|
2592
|
+
effects(principal, permit, eventId) {
|
|
2593
|
+
this.owned(principal, permit, eventId, "INPUT");
|
|
2594
|
+
return this.db.prepare("SELECT effect_id FROM effects WHERE event_id=? ORDER BY kind,ordinal").all(eventId).map((row) => this.effect(String(row.effect_id)));
|
|
2595
|
+
}
|
|
2596
|
+
effect(id3) {
|
|
2597
|
+
if (!validId(id3)) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2598
|
+
const row = this.db.prepare("SELECT * FROM effects WHERE effect_id=?").get(id3);
|
|
2599
|
+
if (!row) throw new Error("TRAVEL_GATEWAY_EFFECT_NOT_FOUND");
|
|
2600
|
+
return {
|
|
2601
|
+
id: id3,
|
|
2602
|
+
eventId: String(row.event_id),
|
|
2603
|
+
kind: row.kind,
|
|
2604
|
+
ordinal: Number(row.ordinal),
|
|
2605
|
+
version: Number(row.version),
|
|
2606
|
+
state: row.state,
|
|
2607
|
+
platformKey: String(row.platform_key),
|
|
2608
|
+
bodyHash: String(row.body_hash),
|
|
2609
|
+
...row.receipt ? { receipt: JSON.parse(String(row.receipt)) } : {}
|
|
2610
|
+
};
|
|
2611
|
+
}
|
|
2612
|
+
async effectBody(principal, permit, id3) {
|
|
2613
|
+
const effect = this.effect(id3);
|
|
2614
|
+
this.owned(principal, permit, effect.eventId, effect.kind === "TOOL" ? "TOOL" : "SEND");
|
|
2615
|
+
await this.assertInputCurrent(principal, permit, effect.eventId);
|
|
2616
|
+
const row = this.db.prepare("SELECT body_ref FROM effects WHERE effect_id=?").get(id3);
|
|
2617
|
+
const body = await this.options.objects.readContent(JSON.parse(String(row.body_ref)), bodyLimit);
|
|
2618
|
+
this.owned(principal, permit, effect.eventId, effect.kind === "TOOL" ? "TOOL" : "SEND");
|
|
2619
|
+
if (digest3(body) !== effect.bodyHash) throw new Error("TRAVEL_GATEWAY_BODY_CORRUPT");
|
|
2620
|
+
return body;
|
|
2621
|
+
}
|
|
2622
|
+
intent(principal, permit, id3) {
|
|
2623
|
+
return this.transaction(() => {
|
|
2624
|
+
const effect = this.effect(id3);
|
|
2625
|
+
this.owned(principal, permit, effect.eventId, effect.kind === "TOOL" ? "TOOL" : "SEND");
|
|
2626
|
+
if (effect.state === "CANCELLED") throw new Error("TRAVEL_GATEWAY_CANCELLED");
|
|
2627
|
+
if (effect.state === "UNKNOWN" || effect.state === "DISPATCHING") throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
|
|
2628
|
+
if (effect.state === "PRODUCED" || effect.state === "FAILED_NOT_SENT") this.db.prepare("UPDATE effects SET state='INTENT' WHERE effect_id=?").run(id3);
|
|
2629
|
+
return this.effect(id3);
|
|
2630
|
+
});
|
|
2631
|
+
}
|
|
2632
|
+
start(principal, permit, id3) {
|
|
2633
|
+
return this.transaction(() => {
|
|
2634
|
+
const effect = this.effect(id3);
|
|
2635
|
+
this.owned(principal, permit, effect.eventId, effect.kind === "TOOL" ? "TOOL" : "SEND");
|
|
2636
|
+
if (effect.state === "SENT") throw new Error("TRAVEL_GATEWAY_ALREADY_SENT");
|
|
2637
|
+
if (effect.state === "UNKNOWN" || effect.state === "DISPATCHING") throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
|
|
2638
|
+
if (effect.state === "CANCELLED") throw new Error("TRAVEL_GATEWAY_CANCELLED");
|
|
2639
|
+
if (effect.state !== "INTENT") throw new Error("TRAVEL_GATEWAY_INTENT_REQUIRED");
|
|
2640
|
+
if (effect.kind === "REPLY" && effect.ordinal > 1) {
|
|
2641
|
+
const prior = this.db.prepare("SELECT state FROM effects WHERE event_id=? AND kind=? AND ordinal=?").get(effect.eventId, "REPLY", effect.ordinal - 1);
|
|
2642
|
+
if (prior?.state !== "SENT") throw new Error("TRAVEL_GATEWAY_PREFIX_NOT_CONFIRMED");
|
|
2643
|
+
}
|
|
2644
|
+
const dispatchId = randomUUID7();
|
|
2645
|
+
this.db.prepare("UPDATE effects SET state='DISPATCHING',dispatch_id=?,dispatch_node=?,dispatch_boot=?,dispatch_epoch=? WHERE effect_id=?").run(dispatchId, permit.nodeId, permit.bootId, permit.epoch, id3);
|
|
2646
|
+
return { ...this.effect(id3), dispatchId };
|
|
2647
|
+
});
|
|
2648
|
+
}
|
|
2649
|
+
/** A gateway-owned SDK completion may arrive after lease loss or cancellation.
|
|
2650
|
+
* Its actual receipt must still be recorded; node callbacks cannot call this. */
|
|
2651
|
+
assertDispatch(principal, permit, dispatchId) {
|
|
2652
|
+
const row = this.db.prepare("SELECT * FROM effects WHERE dispatch_id=?").get(dispatchId);
|
|
2653
|
+
if (!row) throw new Error("TRAVEL_GATEWAY_DISPATCH_NOT_FOUND");
|
|
2654
|
+
this.owned(principal, permit, String(row.event_id), row.kind === "TOOL" ? "TOOL" : "SEND");
|
|
2655
|
+
if (row.dispatch_node !== permit.nodeId || row.dispatch_boot !== permit.bootId || Number(row.dispatch_epoch) !== permit.epoch) throw new Error("TRAVEL_GATEWAY_CLAIM_REQUIRED");
|
|
2656
|
+
if (row.state !== "DISPATCHING") throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
|
|
2657
|
+
}
|
|
2658
|
+
sent(dispatchId, receipt) {
|
|
2659
|
+
if (typeof dispatchId !== "string" || typeof receipt?.messageId !== "string" || !receipt.messageId || receipt.messageId.length > 512) throw new Error("TRAVEL_GATEWAY_INVALID_RECEIPT");
|
|
2660
|
+
this.transaction(() => {
|
|
2661
|
+
const row = this.db.prepare("SELECT state,receipt FROM effects WHERE dispatch_id=?").get(dispatchId);
|
|
2662
|
+
if (!row) throw new Error("TRAVEL_GATEWAY_DISPATCH_NOT_FOUND");
|
|
2663
|
+
if (row.state === "SENT") {
|
|
2664
|
+
if (row.receipt !== JSON.stringify(receipt)) throw new Error("TRAVEL_GATEWAY_RECEIPT_COLLISION");
|
|
2665
|
+
return;
|
|
2666
|
+
}
|
|
2667
|
+
if (!["DISPATCHING", "UNKNOWN"].includes(String(row.state))) throw new Error("TRAVEL_GATEWAY_DISPATCH_STATE");
|
|
2668
|
+
this.db.prepare("UPDATE effects SET state='SENT',receipt=? WHERE dispatch_id=?").run(JSON.stringify(receipt), dispatchId);
|
|
2669
|
+
});
|
|
2670
|
+
}
|
|
2671
|
+
async toolFinish(principal, permit, dispatchId, result) {
|
|
2672
|
+
if (!Buffer.isBuffer(result) || !result.length || result.length > bodyLimit) throw new Error("TRAVEL_GATEWAY_INVALID_RECEIPT");
|
|
2673
|
+
const original = Buffer.from(result), hash2 = digest3(original);
|
|
2674
|
+
const check = () => {
|
|
2675
|
+
this.active(principal, permit, "TOOL");
|
|
2676
|
+
const row = this.db.prepare("SELECT * FROM effects WHERE dispatch_id=?").get(dispatchId);
|
|
2677
|
+
if (row?.kind !== "TOOL") throw new Error("TRAVEL_GATEWAY_INVALID_RECEIPT");
|
|
2678
|
+
this.owned(principal, permit, String(row.event_id), "TOOL");
|
|
2679
|
+
if (row.dispatch_node !== permit.nodeId || row.dispatch_boot !== permit.bootId || Number(row.dispatch_epoch) !== permit.epoch) throw new Error("TRAVEL_GATEWAY_CLAIM_REQUIRED");
|
|
2680
|
+
if (row.state === "SENT") {
|
|
2681
|
+
if (row.result_hash !== hash2) throw new Error("TRAVEL_GATEWAY_RECEIPT_COLLISION");
|
|
2682
|
+
return false;
|
|
2683
|
+
}
|
|
2684
|
+
this.assertDispatch(principal, permit, dispatchId);
|
|
2685
|
+
return true;
|
|
2686
|
+
};
|
|
2687
|
+
if (!check()) return;
|
|
2688
|
+
const ref = await this.options.objects.putContent(original);
|
|
2689
|
+
this.transaction(() => {
|
|
2690
|
+
if (!check()) return;
|
|
2691
|
+
this.db.prepare("UPDATE effects SET state='SENT',result_hash=?,result_ref=?,receipt=? WHERE dispatch_id=?").run(hash2, JSON.stringify(ref), JSON.stringify({ messageId: "tool:" + hash2 }), dispatchId);
|
|
2692
|
+
});
|
|
2693
|
+
}
|
|
2694
|
+
async toolResult(principal, permit, id3) {
|
|
2695
|
+
const effect = this.effect(id3);
|
|
2696
|
+
this.owned(principal, permit, effect.eventId, "TOOL");
|
|
2697
|
+
await this.assertInputCurrent(principal, permit, effect.eventId);
|
|
2698
|
+
const row = this.db.prepare("SELECT result_hash,result_ref FROM effects WHERE effect_id=?").get(id3);
|
|
2699
|
+
if (effect.kind !== "TOOL" || effect.state !== "SENT" || !row.result_ref) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
|
|
2700
|
+
const body = await this.options.objects.readContent(JSON.parse(String(row.result_ref)), bodyLimit);
|
|
2701
|
+
this.owned(principal, permit, effect.eventId, "TOOL");
|
|
2702
|
+
if (digest3(body) !== row.result_hash) throw new Error("TRAVEL_GATEWAY_BODY_CORRUPT");
|
|
2703
|
+
return body;
|
|
2704
|
+
}
|
|
2705
|
+
fail(dispatchId, state) {
|
|
2706
|
+
if (!["FAILED_NOT_SENT", "UNKNOWN"].includes(state)) throw new Error("TRAVEL_GATEWAY_INVALID_RECEIPT");
|
|
2707
|
+
this.transaction(() => {
|
|
2708
|
+
const row = this.db.prepare("SELECT state FROM effects WHERE dispatch_id=?").get(dispatchId);
|
|
2709
|
+
if (!row) throw new Error("TRAVEL_GATEWAY_DISPATCH_NOT_FOUND");
|
|
2710
|
+
if (row.state === "SENT") return;
|
|
2711
|
+
if (!["DISPATCHING", "UNKNOWN", state].includes(String(row.state))) throw new Error("TRAVEL_GATEWAY_DISPATCH_STATE");
|
|
2712
|
+
this.db.prepare("UPDATE effects SET state=? WHERE dispatch_id=?").run(state, dispatchId);
|
|
2713
|
+
});
|
|
2714
|
+
}
|
|
2715
|
+
close() {
|
|
2716
|
+
if (this.closed) return;
|
|
2717
|
+
this.closed = true;
|
|
2718
|
+
try {
|
|
2719
|
+
this.db.close();
|
|
2720
|
+
} finally {
|
|
2721
|
+
this.owner.close();
|
|
2722
|
+
}
|
|
2723
|
+
}
|
|
2724
|
+
};
|
|
2725
|
+
|
|
2726
|
+
// src/continuity/gateway-server.ts
|
|
2727
|
+
import { Agent, createServer as createServer2, request as request2 } from "node:https";
|
|
2728
|
+
var prefix = "/travel/gateway/v1/";
|
|
2729
|
+
var requestLimit = 24 * 1024 * 1024;
|
|
2730
|
+
var responseLimit = 48 * 1024 * 1024;
|
|
2731
|
+
var publicErrors = /* @__PURE__ */ new Set([
|
|
2732
|
+
"TRAVEL_GATEWAY_UNKNOWN_EFFECT",
|
|
2733
|
+
"TRAVEL_GATEWAY_CANCELLED",
|
|
2734
|
+
"TRAVEL_GATEWAY_ALREADY_SENT",
|
|
2735
|
+
"TRAVEL_GATEWAY_PREFIX_NOT_CONFIRMED",
|
|
2736
|
+
"TRAVEL_GATEWAY_SEGMENT_VERSION_COLLISION",
|
|
2737
|
+
"TRAVEL_GATEWAY_ID_COLLISION",
|
|
2738
|
+
"TRAVEL_GATEWAY_RECEIPT_COLLISION",
|
|
2739
|
+
"TRAVEL_GATEWAY_INVALID_REQUEST",
|
|
2740
|
+
"TRAVEL_GATEWAY_INTENT_REQUIRED",
|
|
2741
|
+
"TRAVEL_GATEWAY_TOOL_ENTRY_REQUIRED",
|
|
2742
|
+
"TRAVEL_GATEWAY_UNFINISHED_EFFECTS",
|
|
2743
|
+
"TRAVEL_GATEWAY_KEY_UNAVAILABLE",
|
|
2744
|
+
"TRAVEL_GATEWAY_DELETION_BARRIER"
|
|
2745
|
+
]);
|
|
2746
|
+
function decodeBody(value, maximum = 16 * 1024 * 1024) {
|
|
2747
|
+
if (typeof value !== "string" || value.length > Math.ceil(maximum / 3) * 4) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2748
|
+
const body = Buffer.from(value, "base64");
|
|
2749
|
+
if (!body.length || body.length > maximum || body.toString("base64") !== value) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2750
|
+
return body;
|
|
2751
|
+
}
|
|
2752
|
+
function createTravelGatewayServer(options) {
|
|
2753
|
+
const { authority, store, allowedPeers, recoveryPeers = {}, platform, assertReady, ...tls2 } = options, peers = /* @__PURE__ */ new Map(), recovery = /* @__PURE__ */ new Map();
|
|
2754
|
+
for (const [fingerprint, credential] of Object.entries(allowedPeers)) {
|
|
2755
|
+
const normalized = fingerprint.replaceAll(":", "").toLowerCase();
|
|
2756
|
+
if (!/^[a-f0-9]{64}$/.test(normalized) || peers.has(normalized)) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
|
|
2757
|
+
peers.set(normalized, authority.authenticate(credential));
|
|
2758
|
+
}
|
|
2759
|
+
for (const [fingerprint, credential] of Object.entries(recoveryPeers)) {
|
|
2760
|
+
const normalized = fingerprint.replaceAll(":", "").toLowerCase();
|
|
2761
|
+
if (!/^[a-f0-9]{64}$/.test(normalized) || recovery.has(normalized)) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
|
|
2762
|
+
recovery.set(normalized, authority.authenticate(credential));
|
|
2763
|
+
}
|
|
2764
|
+
if (!peers.size || typeof platform.deliver !== "function") throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
|
|
2765
|
+
let inFlight = 0;
|
|
2766
|
+
const server = createServer2({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
|
|
2767
|
+
res.setHeader("Cache-Control", "no-store");
|
|
2768
|
+
res.setHeader("Content-Type", "application/json");
|
|
2769
|
+
const reply = (status, value) => {
|
|
2770
|
+
if (status === 200) assertReady?.();
|
|
2771
|
+
res.statusCode = status;
|
|
2772
|
+
res.end(JSON.stringify(value));
|
|
2773
|
+
};
|
|
2774
|
+
const socket = req.socket, fingerprint = (socket.getPeerCertificate().fingerprint256 ?? "").replaceAll(":", "").toLowerCase();
|
|
2775
|
+
const recovering = req.url === "/travel/gateway-recovery/v1", principal = (recovering ? recovery : peers).get(fingerprint);
|
|
2776
|
+
if (!socket.authorized || !principal) {
|
|
2777
|
+
reply(403, { error: "TRAVEL_GATEWAY_DENIED" });
|
|
2778
|
+
req.resume();
|
|
2779
|
+
return;
|
|
2780
|
+
}
|
|
2781
|
+
const action = req.url?.startsWith(prefix) ? req.url.slice(prefix.length) : "";
|
|
2782
|
+
if (req.method !== "POST" || !recovering && !["preparation", "exit-dedupe", "claim", "ack", "finish", "produce", "produce-batch", "effects", "dispatch", "tool-start", "tool-finish", "tool-result", "resource"].includes(action)) {
|
|
2783
|
+
reply(404, { error: "TRAVEL_GATEWAY_NOT_FOUND" });
|
|
2784
|
+
req.resume();
|
|
2785
|
+
return;
|
|
2786
|
+
}
|
|
2787
|
+
if (inFlight >= 4) {
|
|
2788
|
+
reply(503, { error: "TRAVEL_GATEWAY_BUSY" });
|
|
2789
|
+
req.resume();
|
|
2790
|
+
return;
|
|
2791
|
+
}
|
|
2792
|
+
inFlight++;
|
|
2793
|
+
try {
|
|
2794
|
+
assertReady?.();
|
|
2795
|
+
const chunks = [];
|
|
2796
|
+
let bytes = 0;
|
|
2797
|
+
for await (const chunk of req) {
|
|
2798
|
+
bytes += chunk.length;
|
|
2799
|
+
if (bytes > requestLimit) {
|
|
2800
|
+
res.setHeader("Connection", "close");
|
|
2801
|
+
reply(400, { error: "TRAVEL_GATEWAY_INVALID_REQUEST" });
|
|
2802
|
+
req.resume();
|
|
2803
|
+
return;
|
|
2804
|
+
}
|
|
2805
|
+
chunks.push(chunk);
|
|
2806
|
+
}
|
|
2807
|
+
let input;
|
|
2808
|
+
try {
|
|
2809
|
+
input = JSON.parse(Buffer.concat(chunks).toString());
|
|
2810
|
+
} catch {
|
|
2811
|
+
throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2812
|
+
}
|
|
2813
|
+
if (recovering) {
|
|
2814
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).sort().join(",") !== "bindings,floor" || !Array.isArray(input.bindings) || input.bindings.length > 1e5 || !Number.isSafeInteger(input.floor) || input.floor < 0 || input.bindings.some((binding) => !binding || typeof binding !== "object" || Array.isArray(binding) || Object.keys(binding).sort().join(",") !== "deletionId,originKey" || typeof binding.originKey !== "string" || binding.originKey.length > 4096 || typeof binding.deletionId !== "string")) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2815
|
+
authority.authenticate(Object.entries(recoveryPeers).find(([value]) => value.replaceAll(":", "").toLowerCase() === fingerprint)[1]);
|
|
2816
|
+
reply(200, store.applyRecoveryDeletedInputs(principal, input.bindings, input.floor));
|
|
2817
|
+
return;
|
|
2818
|
+
}
|
|
2819
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => !["permit", "options", "eventId", "input", "inputs", "effectId", "dispatchId", "resultBase64", "index", "finalOutput"].includes(key))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2820
|
+
if (action === "preparation") {
|
|
2821
|
+
if (Object.keys(input).length) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2822
|
+
reply(200, store.preparationEvidence(principal));
|
|
2823
|
+
return;
|
|
2824
|
+
}
|
|
2825
|
+
const permit = input.permit;
|
|
2826
|
+
authority.assertPermit(permit, action === "exit-dedupe" ? "CONTROL" : action.startsWith("tool-") ? "TOOL" : action === "claim" || action === "ack" || action === "finish" ? "INPUT" : "SEND");
|
|
2827
|
+
if (principal.nodeId !== permit.nodeId || principal.tenantId !== permit.tenantId || principal.companionId !== permit.companionId || principal.seatId !== permit.seatId) {
|
|
2828
|
+
reply(403, { error: "TRAVEL_GATEWAY_DENIED" });
|
|
2829
|
+
return;
|
|
2830
|
+
}
|
|
2831
|
+
if (action === "exit-dedupe") {
|
|
2832
|
+
reply(200, store.exitDedupeReceipt(principal, permit));
|
|
2833
|
+
return;
|
|
2834
|
+
}
|
|
2835
|
+
if (action === "claim") {
|
|
2836
|
+
const claims = await store.claim(principal, permit, input.options);
|
|
2837
|
+
reply(200, claims.map(({ body: body2, ...claim }) => ({ ...claim, bodyBase64: body2.toString("base64") })));
|
|
2838
|
+
return;
|
|
2839
|
+
}
|
|
2840
|
+
if (action === "ack" || action === "finish") {
|
|
2841
|
+
store[action](principal, permit, input.eventId);
|
|
2842
|
+
reply(200, { accepted: true });
|
|
2843
|
+
return;
|
|
2844
|
+
}
|
|
2845
|
+
if (action === "effects") {
|
|
2846
|
+
reply(200, store.effects(principal, permit, input.eventId));
|
|
2847
|
+
return;
|
|
2848
|
+
}
|
|
2849
|
+
if (action === "resource") {
|
|
2850
|
+
reply(200, { bodyBase64: (await store.resource(principal, permit, input.eventId, input.index)).toString("base64") });
|
|
2851
|
+
return;
|
|
2852
|
+
}
|
|
2853
|
+
if (action === "tool-result") {
|
|
2854
|
+
reply(200, { bodyBase64: (await store.toolResult(principal, permit, input.effectId)).toString("base64") });
|
|
2855
|
+
return;
|
|
2856
|
+
}
|
|
2857
|
+
if (action === "tool-finish") {
|
|
2858
|
+
await store.toolFinish(principal, permit, input.dispatchId, decodeBody(input.resultBase64));
|
|
2859
|
+
reply(200, { accepted: true });
|
|
2860
|
+
return;
|
|
2861
|
+
}
|
|
2862
|
+
if (action === "produce" || action === "produce-batch") {
|
|
2863
|
+
const values = action === "produce" ? [input.input] : input.inputs;
|
|
2864
|
+
if (!Array.isArray(values) || !values.length || values.length > 100) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2865
|
+
const decoded = values.map((value) => {
|
|
2866
|
+
if (!value || typeof value !== "object" || Object.keys(value).some((key) => !["eventId", "kind", "ordinal", "version", "bodyBase64"].includes(key))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2867
|
+
return { ...value, body: decodeBody(value.bodyBase64) };
|
|
2868
|
+
});
|
|
2869
|
+
if (input.finalOutput !== void 0 && typeof input.finalOutput !== "boolean") throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
|
|
2870
|
+
const effects = await store.produceBatch(principal, permit, decoded, { finalOutput: input.finalOutput });
|
|
2871
|
+
reply(200, action === "produce" ? effects[0] : effects);
|
|
2872
|
+
return;
|
|
2873
|
+
}
|
|
2874
|
+
const effect = store.intent(principal, permit, input.effectId);
|
|
2875
|
+
if (effect.state === "SENT") {
|
|
2876
|
+
reply(200, effect);
|
|
2877
|
+
return;
|
|
2878
|
+
}
|
|
2879
|
+
if (action === "tool-start") {
|
|
2880
|
+
if (effect.kind !== "TOOL") throw new Error("TRAVEL_GATEWAY_TOOL_ENTRY_REQUIRED");
|
|
2881
|
+
await store.assertInputCurrent(principal, permit, effect.eventId);
|
|
2882
|
+
reply(200, store.start(principal, permit, effect.id));
|
|
2883
|
+
return;
|
|
2884
|
+
}
|
|
2885
|
+
if (effect.kind === "TOOL") throw new Error("TRAVEL_GATEWAY_TOOL_ENTRY_REQUIRED");
|
|
2886
|
+
const body = await store.effectBody(principal, permit, effect.id), started = store.start(principal, permit, effect.id);
|
|
2887
|
+
try {
|
|
2888
|
+
const receipt = await platform.deliver(effect, body, () => store.assertDispatch(principal, permit, started.dispatchId));
|
|
2889
|
+
store.sent(started.dispatchId, receipt);
|
|
2890
|
+
} catch {
|
|
2891
|
+
store.fail(started.dispatchId, "UNKNOWN");
|
|
2892
|
+
throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
|
|
2893
|
+
}
|
|
2894
|
+
reply(200, store.effect(effect.id));
|
|
2895
|
+
} catch (error) {
|
|
2896
|
+
if (!res.writableEnded) {
|
|
2897
|
+
const code = error instanceof Error && publicErrors.has(error.message) ? error.message : "TRAVEL_GATEWAY_REFUSED";
|
|
2898
|
+
reply(409, { error: code });
|
|
2899
|
+
}
|
|
2900
|
+
} finally {
|
|
2901
|
+
inFlight--;
|
|
2902
|
+
}
|
|
2903
|
+
});
|
|
2904
|
+
server.requestTimeout = 15e3;
|
|
2905
|
+
server.headersTimeout = 5e3;
|
|
2906
|
+
server.keepAliveTimeout = 1e4;
|
|
2907
|
+
server.maxConnections = 32;
|
|
2908
|
+
server.maxRequestsPerSocket = 32;
|
|
2909
|
+
server.on("tlsClientError", () => {
|
|
2910
|
+
});
|
|
2911
|
+
return server;
|
|
2912
|
+
}
|
|
2913
|
+
|
|
2914
|
+
// src/continuity/gateway-feishu.ts
|
|
2915
|
+
import * as lark from "@larksuiteoapi/node-sdk";
|
|
2916
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
|
|
2917
|
+
|
|
2918
|
+
// src/continuity/gateway-media.ts
|
|
2919
|
+
var gatewayMediaLimit = 16 * 1024 * 1024 - 16384;
|
|
2920
|
+
function decodeGatewayMedia(body) {
|
|
2921
|
+
if (body.length < 5) throw new Error("TRAVEL_GATEWAY_INVALID_MEDIA");
|
|
2922
|
+
const length = body.readUInt32BE();
|
|
2923
|
+
if (length < 1 || length > 16380 || body.length < length + 5) throw new Error("TRAVEL_GATEWAY_INVALID_MEDIA");
|
|
2924
|
+
const metadata = JSON.parse(body.subarray(4, 4 + length).toString()), bytes = body.subarray(4 + length);
|
|
2925
|
+
if (metadata.format !== "engine7-gateway-media-v1" || metadata.bytes !== bytes.length || bytes.length > gatewayMediaLimit || typeof metadata.target !== "string" || !metadata.target || typeof metadata.text !== "string" || typeof metadata.filename !== "string" || !metadata.filename || /[\/\\\r\n]/.test(metadata.filename) || typeof metadata.mimeType !== "string" || metadata.mimeType.length > 128) throw new Error("TRAVEL_GATEWAY_INVALID_MEDIA");
|
|
2926
|
+
return { metadata, bytes };
|
|
2927
|
+
}
|
|
2928
|
+
|
|
2929
|
+
// src/continuity/gateway-feishu.ts
|
|
2930
|
+
import { basename } from "node:path";
|
|
2931
|
+
|
|
2932
|
+
// src/continuity/gateway-feishu-render.ts
|
|
2933
|
+
var feishuGatewayPost = (text) => ({ zh_cn: { content: [[{ tag: "md", text }]] } });
|
|
2934
|
+
|
|
2935
|
+
// src/continuity/gateway-feishu.ts
|
|
2936
|
+
var quiet = { error: () => {
|
|
2937
|
+
}, warn: () => {
|
|
2938
|
+
}, info: () => {
|
|
2939
|
+
}, debug: () => {
|
|
2940
|
+
}, trace: () => {
|
|
2941
|
+
} };
|
|
2942
|
+
var dispatchContext = new AsyncLocalStorage3();
|
|
2943
|
+
var format = "engine7-feishu-gateway-inbound-v1";
|
|
2944
|
+
function createFeishuGatewayDispatcher(options) {
|
|
2945
|
+
return new lark.EventDispatcher({ verificationToken: options.verificationToken, encryptKey: options.encryptKey, logger: quiet }).register({
|
|
2946
|
+
"im.message.receive_v1": async (data) => {
|
|
2947
|
+
options.assertIngress?.();
|
|
2948
|
+
const message = data?.message, sender = data?.sender;
|
|
2949
|
+
if (!message || !sender || typeof message.message_id !== "string" || !message.message_id || typeof message.chat_id !== "string" || !message.chat_id) throw new Error("TRAVEL_FEISHU_INVALID_EVENT");
|
|
2950
|
+
const timestamp = Number(message.create_time);
|
|
2951
|
+
if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error("TRAVEL_FEISHU_INVALID_EVENT");
|
|
2952
|
+
const content = JSON.parse(String(message.content)), descriptors = [];
|
|
2953
|
+
const add = (key, type, filename, contentType) => {
|
|
2954
|
+
if (typeof key === "string" && key) descriptors.push({ key, type, filename, contentType });
|
|
2955
|
+
};
|
|
2956
|
+
if (message.message_type === "image") add(content.image_key, "image", "image.jpg", "image/jpeg");
|
|
2957
|
+
if (["file", "audio", "media"].includes(message.message_type)) add(content.file_key, "file", basename(String(content.file_name ?? (message.message_type === "audio" ? "audio.opus" : message.message_type === "media" ? "video.mp4" : "file"))), message.message_type === "audio" ? "audio/opus" : message.message_type === "media" ? "video/mp4" : "application/octet-stream");
|
|
2958
|
+
if (message.message_type === "post") {
|
|
2959
|
+
for (const line of (content.zh_cn ?? content.en_us ?? content).content ?? []) for (const item of line ?? []) if (item.tag === "img") add(item.image_key, "image", "image-" + descriptors.length + ".jpg", "image/jpeg");
|
|
2960
|
+
}
|
|
2961
|
+
if (descriptors.length > 8) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
|
|
2962
|
+
const resources = [];
|
|
2963
|
+
let bytes = 0;
|
|
2964
|
+
for (const descriptor of descriptors) {
|
|
2965
|
+
if (!options.downloadResource) throw new Error("TRAVEL_FEISHU_RESOURCE_UNAVAILABLE");
|
|
2966
|
+
const original = await options.downloadResource(message.message_id, descriptor.key, descriptor.type);
|
|
2967
|
+
bytes += original.length;
|
|
2968
|
+
if (bytes > 32 * 1024 * 1024) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
|
|
2969
|
+
resources.push({ filename: descriptor.filename, contentType: descriptor.contentType, ref: await options.store.putResource(original) });
|
|
2970
|
+
}
|
|
2971
|
+
options.assertIngress?.();
|
|
2972
|
+
await options.store.receive({
|
|
2973
|
+
platformId: message.message_id,
|
|
2974
|
+
channel: "feishu",
|
|
2975
|
+
sessionKey: message.chat_id,
|
|
2976
|
+
occurredAt: timestamp,
|
|
2977
|
+
cancelPending: message.message_type === "text" && /^\/stop\s*$/i.test(String(content.text)) && sender.sender_type === "user" && options.authorizeStop?.(sender, message) === true,
|
|
2978
|
+
body: Buffer.from(JSON.stringify({ format, event: { sender, message }, ...resources.length ? { resources } : {} }))
|
|
2979
|
+
});
|
|
2980
|
+
options.assertIngress?.();
|
|
2981
|
+
},
|
|
2982
|
+
"im.message.reaction.created_v1": async () => {
|
|
2983
|
+
},
|
|
2984
|
+
"im.message.reaction.deleted_v1": async () => {
|
|
2985
|
+
}
|
|
2986
|
+
});
|
|
2987
|
+
}
|
|
2988
|
+
function createFeishuGatewayPlatform(options) {
|
|
2989
|
+
if (typeof options.appId !== "string" || !options.appId || typeof options.appSecret !== "string" || !options.appSecret) throw new Error("TRAVEL_FEISHU_INVALID_CONFIG");
|
|
2990
|
+
const client = new lark.Client({ ...options, logger: quiet });
|
|
2991
|
+
const interceptor = lark.defaultHttpInstance.interceptors.request.use((config) => {
|
|
2992
|
+
dispatchContext.getStore()?.();
|
|
2993
|
+
return config;
|
|
2994
|
+
});
|
|
2995
|
+
let closed = false;
|
|
2996
|
+
return {
|
|
2997
|
+
deliver: async (effect, body, assertCurrent) => {
|
|
2998
|
+
if (closed) throw new Error("TRAVEL_FEISHU_CLOSED");
|
|
2999
|
+
const media = effect.kind === "MEDIA" ? decodeGatewayMedia(body) : void 0;
|
|
3000
|
+
const packet = media?.metadata ?? JSON.parse(body.toString());
|
|
3001
|
+
if (!["REPLY", "TASK", "PREVIEW", "MEDIA"].includes(effect.kind) || typeof packet.target !== "string" || !packet.target || typeof packet.text !== "string" || Buffer.byteLength(JSON.stringify({ text: packet.text })) > 15e4) throw new Error("TRAVEL_FEISHU_INVALID_SEND");
|
|
3002
|
+
return dispatchContext.run(assertCurrent, async () => {
|
|
3003
|
+
assertCurrent();
|
|
3004
|
+
let msgType = packet.format === "post" ? "post" : "text", content = packet.format === "post" ? feishuGatewayPost(packet.text) : { text: packet.text };
|
|
3005
|
+
if (media) {
|
|
3006
|
+
if (packet.mimeType.startsWith("image/")) {
|
|
3007
|
+
if (media.bytes.length > 10 * 1024 * 1024) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
|
|
3008
|
+
const upload = await client.im.image.create({ data: { image_type: "message", image: media.bytes } });
|
|
3009
|
+
if (!upload?.image_key) throw new Error("TRAVEL_FEISHU_UPLOAD_UNKNOWN");
|
|
3010
|
+
msgType = packet.text ? "post" : "image";
|
|
3011
|
+
content = packet.text ? { zh_cn: { content: [[{ tag: "md", text: packet.text }], [{ tag: "img", image_key: upload.image_key }]] } } : { image_key: upload.image_key };
|
|
3012
|
+
} else {
|
|
3013
|
+
const opus = packet.mimeType.startsWith("audio/") && /\.(opus|ogg)$/i.test(packet.filename), video = packet.mimeType.startsWith("video/");
|
|
3014
|
+
const duration = Number.isFinite(packet.voiceDurationSec) ? Math.max(1, Math.round(packet.voiceDurationSec * 1e3)) : Math.max(1, Math.round(media.bytes.length / 3));
|
|
3015
|
+
const upload = await client.im.file.create({ data: { file_type: opus ? "opus" : video ? "mp4" : "stream", file_name: packet.filename, file: media.bytes, ...opus ? { duration } : {} } });
|
|
3016
|
+
if (!upload?.file_key) throw new Error("TRAVEL_FEISHU_UPLOAD_UNKNOWN");
|
|
3017
|
+
msgType = opus ? "audio" : video ? "media" : "file";
|
|
3018
|
+
content = { file_key: upload.file_key };
|
|
3019
|
+
}
|
|
3020
|
+
}
|
|
3021
|
+
assertCurrent();
|
|
3022
|
+
const result = await client.im.message.create({ params: { receive_id_type: packet.target.startsWith("ou_") ? "open_id" : "chat_id" }, data: { receive_id: packet.target, msg_type: msgType, content: JSON.stringify(content), uuid: effect.platformKey } });
|
|
3023
|
+
if (result.code !== 0 || typeof result.data?.message_id !== "string" || !result.data.message_id) throw new Error("TRAVEL_FEISHU_SEND_UNKNOWN");
|
|
3024
|
+
return { messageId: result.data.message_id };
|
|
3025
|
+
});
|
|
3026
|
+
},
|
|
3027
|
+
downloadResource: async (messageId, key, type) => {
|
|
3028
|
+
if (closed) throw new Error("TRAVEL_FEISHU_CLOSED");
|
|
3029
|
+
const response = await client.im.messageResource.get({ path: { message_id: messageId, file_key: key }, params: { type } });
|
|
3030
|
+
const stream = response.getReadableStream(), chunks = [];
|
|
3031
|
+
let bytes = 0;
|
|
3032
|
+
try {
|
|
3033
|
+
for await (const chunk of stream) {
|
|
3034
|
+
const buffer = Buffer.from(chunk);
|
|
3035
|
+
bytes += buffer.length;
|
|
3036
|
+
if (bytes > 16 * 1024 * 1024) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
|
|
3037
|
+
chunks.push(buffer);
|
|
3038
|
+
}
|
|
3039
|
+
} catch (error) {
|
|
3040
|
+
stream.destroy();
|
|
3041
|
+
throw error;
|
|
3042
|
+
}
|
|
3043
|
+
if (!bytes) throw new Error("TRAVEL_FEISHU_INVALID_RESOURCE");
|
|
3044
|
+
return Buffer.concat(chunks);
|
|
3045
|
+
},
|
|
3046
|
+
close: () => {
|
|
3047
|
+
if (closed) return;
|
|
3048
|
+
closed = true;
|
|
3049
|
+
lark.defaultHttpInstance.interceptors.request.eject(interceptor);
|
|
3050
|
+
}
|
|
3051
|
+
};
|
|
3052
|
+
}
|
|
3053
|
+
|
|
3054
|
+
// src/continuity/gateway-main.ts
|
|
3055
|
+
var quiet2 = { error: () => {
|
|
3056
|
+
}, warn: () => {
|
|
3057
|
+
}, info: () => {
|
|
3058
|
+
}, debug: () => {
|
|
3059
|
+
}, trace: () => {
|
|
3060
|
+
} };
|
|
3061
|
+
function path2(value) {
|
|
3062
|
+
if (typeof value !== "string" || !isAbsolute(value)) throw new Error("TRAVEL_GATEWAY_ABSOLUTE_PATH_REQUIRED");
|
|
3063
|
+
return resolve2(value);
|
|
3064
|
+
}
|
|
3065
|
+
function tls(config) {
|
|
3066
|
+
return { ca: readPrivateFile(path2(config?.caFile), 1024 * 1024), cert: readPrivateFile(path2(config?.certFile), 1024 * 1024), key: readPrivateFile(path2(config?.keyFile), 16384) };
|
|
3067
|
+
}
|
|
3068
|
+
async function startTravelGateway(config) {
|
|
3069
|
+
if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key) => config.identity[key] !== config.keyService.identity[key])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
|
|
3070
|
+
if (!Number.isSafeInteger(config.port) || config.port < 0 || config.port > 65535 || typeof config.host !== "string" || !config.host) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
|
|
3071
|
+
if (config.feishu?.ingressEnabled !== false && !/^cli_[0-9a-fA-F]{16}$/.test(config.feishu?.appId)) throw new Error("TRAVEL_FEISHU_INVALID_CONFIG");
|
|
3072
|
+
const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls(config.keyService.tls), timeoutMs: 1e4 };
|
|
3073
|
+
const material = await fetchTravelKey(keyConfig);
|
|
3074
|
+
const keyDigest = createHash8("sha256").update(material.key).digest("hex");
|
|
3075
|
+
let keyWatermark = material.deletionWatermark;
|
|
3076
|
+
const refreshInterval = config.keyRefreshIntervalMs ?? 1e4, maxKeyAge = config.keyMaxAgeMs ?? 3e4;
|
|
3077
|
+
if (!Number.isSafeInteger(refreshInterval) || refreshInterval < 100 || refreshInterval > 1e4 || !Number.isSafeInteger(maxKeyAge) || maxKeyAge < 2 * refreshInterval || maxKeyAge > 3e4) {
|
|
3078
|
+
material.key.fill(0);
|
|
3079
|
+
throw new Error("TRAVEL_GATEWAY_INVALID_KEY_TIMING");
|
|
3080
|
+
}
|
|
3081
|
+
let objects, authority, store, platform, server, controlServer, ws, closed = false, retry, refresh;
|
|
3082
|
+
let lastKeyCheck = Number(process.hrtime.bigint() / 1000000n), checking = false;
|
|
3083
|
+
const assertKey = () => {
|
|
3084
|
+
if (closed || Number(process.hrtime.bigint() / 1000000n) - lastKeyCheck >= maxKeyAge) throw new Error("TRAVEL_GATEWAY_KEY_UNAVAILABLE");
|
|
3085
|
+
if (authority) {
|
|
3086
|
+
for (const credential of Object.values(config.allowedPeers)) if (authority.status(authority.authenticate(String(credential))).deletionWatermark !== keyWatermark) throw new Error("TRAVEL_GATEWAY_DELETION_BARRIER");
|
|
3087
|
+
}
|
|
3088
|
+
};
|
|
3089
|
+
const close = async () => {
|
|
3090
|
+
if (closed) return;
|
|
3091
|
+
closed = true;
|
|
3092
|
+
if (retry) clearTimeout(retry);
|
|
3093
|
+
if (refresh) clearInterval(refresh);
|
|
3094
|
+
ws?.close({ force: true });
|
|
3095
|
+
platform?.close();
|
|
3096
|
+
if (controlServer) {
|
|
3097
|
+
controlServer.closeAllConnections();
|
|
3098
|
+
await new Promise((resolve3) => controlServer.close(() => resolve3()));
|
|
3099
|
+
}
|
|
3100
|
+
if (server) {
|
|
3101
|
+
server.closeAllConnections();
|
|
3102
|
+
await new Promise((resolve3) => server.close(() => resolve3()));
|
|
3103
|
+
}
|
|
3104
|
+
try {
|
|
3105
|
+
store?.close();
|
|
3106
|
+
} finally {
|
|
3107
|
+
objects?.close();
|
|
3108
|
+
authority?.close();
|
|
3109
|
+
keyConfig.key.fill(0);
|
|
3110
|
+
}
|
|
3111
|
+
};
|
|
3112
|
+
try {
|
|
3113
|
+
objects = await PublicationObjects.open({ directory: path2(config.objectsDir), identity: config.identity, key: material.key });
|
|
3114
|
+
authority = new TravelAuthority({ directory: path2(config.authorityDir), leaseMs: config.leaseMs });
|
|
3115
|
+
if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
|
|
3116
|
+
for (const credential of Object.values(config.allowedPeers)) {
|
|
3117
|
+
const principal = authority.authenticate(String(credential));
|
|
3118
|
+
if (["tenantId", "companionId", "seatId"].some((key) => principal[key] !== config.identity[key]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
|
|
3119
|
+
}
|
|
3120
|
+
store = new TravelGatewayStore({ directory: path2(config.gatewayDir), identity: config.identity, objects, authority });
|
|
3121
|
+
await store.migrateStoredInputs();
|
|
3122
|
+
if (config.previouslyProcessedPlatformIds) store.importProcessedInputs(config.previouslyProcessedPlatformIds);
|
|
3123
|
+
platform = createFeishuGatewayPlatform(config.feishu);
|
|
3124
|
+
server = createTravelGatewayServer({ ...tls(config.tls), store, authority, allowedPeers: config.allowedPeers, recoveryPeers: config.recoveryPeers, assertReady: assertKey, platform: { deliver: (effect, body, assertCurrent) => platform.deliver(effect, body, () => {
|
|
3125
|
+
assertKey();
|
|
3126
|
+
assertCurrent();
|
|
3127
|
+
}) } });
|
|
3128
|
+
await new Promise((resolve3, reject) => {
|
|
3129
|
+
server.once("error", reject);
|
|
3130
|
+
server.listen(config.port, config.host, resolve3);
|
|
3131
|
+
});
|
|
3132
|
+
if (config.control) {
|
|
3133
|
+
if (!Number.isSafeInteger(config.control.port) || config.control.port < 0 || config.control.port > 65535 || typeof config.control.host !== "string" || !config.control.host) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
3134
|
+
controlServer = createTravelAuthorityServer({
|
|
3135
|
+
...tls(config.control.tls ?? config.tls),
|
|
3136
|
+
authority,
|
|
3137
|
+
proxyFingerprints: config.control.proxyFingerprints,
|
|
3138
|
+
allowedPeers: config.control.allowedPeers,
|
|
3139
|
+
managementPeers: config.control.managementPeers,
|
|
3140
|
+
recoveryPeers: config.control.recoveryPeers,
|
|
3141
|
+
retirementPeers: config.control.retirementPeers,
|
|
3142
|
+
maximumInFlight: config.control.maximumInFlight,
|
|
3143
|
+
requestTimeoutMs: config.control.requestTimeoutMs
|
|
3144
|
+
});
|
|
3145
|
+
await new Promise((resolve3, reject) => {
|
|
3146
|
+
controlServer.once("error", reject);
|
|
3147
|
+
controlServer.listen(config.control.port, config.control.host, resolve3);
|
|
3148
|
+
});
|
|
3149
|
+
}
|
|
3150
|
+
const dispatcher = createFeishuGatewayDispatcher({
|
|
3151
|
+
store,
|
|
3152
|
+
verificationToken: config.feishu.verificationToken,
|
|
3153
|
+
encryptKey: config.feishu.encryptKey,
|
|
3154
|
+
assertIngress: assertKey,
|
|
3155
|
+
authorizeStop: (sender) => Array.isArray(config.feishu.stopAllowedUserIds) && config.feishu.stopAllowedUserIds.includes(sender.sender_id?.open_id),
|
|
3156
|
+
downloadResource: async (messageId, key, type) => {
|
|
3157
|
+
assertKey();
|
|
3158
|
+
return platform.downloadResource(messageId, key, type);
|
|
3159
|
+
}
|
|
3160
|
+
});
|
|
3161
|
+
if (config.feishu.ingressEnabled !== false) {
|
|
3162
|
+
let backoff = 1e3;
|
|
3163
|
+
const start = () => {
|
|
3164
|
+
if (closed) return;
|
|
3165
|
+
ws?.close({ force: true });
|
|
3166
|
+
const current2 = new lark2.WSClient({
|
|
3167
|
+
appId: config.feishu.appId,
|
|
3168
|
+
appSecret: config.feishu.appSecret,
|
|
3169
|
+
logger: quiet2,
|
|
3170
|
+
wsConfig: { pingTimeout: config.feishu.pingTimeoutSec ?? 90 },
|
|
3171
|
+
handshakeTimeoutMs: 15e3,
|
|
3172
|
+
// SDK start() returns before its initial handshake. close() during
|
|
3173
|
+
// that window has no socket yet, so close a late successful handshake.
|
|
3174
|
+
onReady: () => {
|
|
3175
|
+
if (closed || ws !== current2) {
|
|
3176
|
+
current2.close({ force: true });
|
|
3177
|
+
return;
|
|
3178
|
+
}
|
|
3179
|
+
;
|
|
3180
|
+
backoff = 1e3;
|
|
3181
|
+
},
|
|
3182
|
+
onReconnected: () => {
|
|
3183
|
+
if (closed || ws !== current2) current2.close({ force: true });
|
|
3184
|
+
},
|
|
3185
|
+
onError: () => {
|
|
3186
|
+
if (!closed && ws === current2 && !retry) {
|
|
3187
|
+
retry = setTimeout(() => {
|
|
3188
|
+
retry = void 0;
|
|
3189
|
+
start();
|
|
3190
|
+
}, backoff);
|
|
3191
|
+
retry.unref();
|
|
3192
|
+
backoff = Math.min(backoff * 2, 3e4);
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
});
|
|
3196
|
+
ws = current2;
|
|
3197
|
+
void current2.start({ eventDispatcher: dispatcher }).catch(() => {
|
|
3198
|
+
if (!closed && ws === current2 && !retry) {
|
|
3199
|
+
retry = setTimeout(() => {
|
|
3200
|
+
retry = void 0;
|
|
3201
|
+
start();
|
|
3202
|
+
}, backoff);
|
|
3203
|
+
retry.unref();
|
|
3204
|
+
backoff = Math.min(backoff * 2, 3e4);
|
|
3205
|
+
}
|
|
3206
|
+
});
|
|
3207
|
+
};
|
|
3208
|
+
start();
|
|
3209
|
+
}
|
|
3210
|
+
refresh = setInterval(() => {
|
|
3211
|
+
if (closed || checking) return;
|
|
3212
|
+
checking = true;
|
|
3213
|
+
void fetchTravelKey(keyConfig).then((current2) => {
|
|
3214
|
+
try {
|
|
3215
|
+
if (!objects || createHash8("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
|
|
3216
|
+
keyWatermark = current2.deletionWatermark;
|
|
3217
|
+
lastKeyCheck = Number(process.hrtime.bigint() / 1000000n);
|
|
3218
|
+
} finally {
|
|
3219
|
+
current2.key.fill(0);
|
|
3220
|
+
}
|
|
3221
|
+
}).catch(() => {
|
|
3222
|
+
}).finally(() => {
|
|
3223
|
+
checking = false;
|
|
3224
|
+
});
|
|
3225
|
+
}, refreshInterval);
|
|
3226
|
+
refresh.unref();
|
|
3227
|
+
return { server, controlServer, authority, store, close, assertKey, ingress: config.feishu.ingressEnabled === false ? "disabled" : "websocket" };
|
|
3228
|
+
} catch (error) {
|
|
3229
|
+
await close();
|
|
3230
|
+
throw error;
|
|
3231
|
+
} finally {
|
|
3232
|
+
material.key.fill(0);
|
|
3233
|
+
}
|
|
3234
|
+
}
|
|
3235
|
+
async function runTravelGatewayCli(args) {
|
|
3236
|
+
if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-gateway serve --config /absolute/private-config.json" };
|
|
3237
|
+
if (args.length !== 3 || args[0] !== "serve" || args[1] !== "--config") throw new Error("TRAVEL_GATEWAY_INVALID_COMMAND");
|
|
3238
|
+
const config = JSON.parse(readPrivateFile(path2(args[2]), 65536).toString());
|
|
3239
|
+
const gateway = await startTravelGateway(config);
|
|
3240
|
+
let closing = false;
|
|
3241
|
+
const stop = () => {
|
|
3242
|
+
if (closing) return;
|
|
3243
|
+
closing = true;
|
|
3244
|
+
void gateway.close().then(() => process.exit(0), () => process.exit(1));
|
|
3245
|
+
};
|
|
3246
|
+
process.once("SIGTERM", stop);
|
|
3247
|
+
process.once("SIGINT", stop);
|
|
3248
|
+
return { listening: true, port: gateway.server.address().port, ingress: gateway.ingress };
|
|
3249
|
+
}
|
|
3250
|
+
if (process.argv[1] && resolve2(process.argv[1]) === fileURLToPath2(import.meta.url)) {
|
|
3251
|
+
runTravelGatewayCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
|
|
3252
|
+
process.stderr.write("TRAVEL_GATEWAY_REFUSED\n");
|
|
3253
|
+
process.exitCode = 1;
|
|
3254
|
+
});
|
|
3255
|
+
}
|
|
3256
|
+
export {
|
|
3257
|
+
runTravelGatewayCli,
|
|
3258
|
+
startTravelGateway
|
|
3259
|
+
};
|