engine7 7.1.142 → 7.1.144
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/dist/bg-worker.mjs +90 -15
- package/dist/cc-desktop.mjs +9 -0
- package/dist/cli.mjs +2045 -825
- package/dist/engine-startup.mjs +1049 -578
- package/dist/main.mjs +1049 -578
- package/dist/recall-worker.mjs +89 -15
- package/dist/topics-worker.mjs +166 -48
- package/dist/travel-gateway.mjs +186 -65
- package/dist/travel-host.mjs +600 -460
- package/dist/travel-node.mjs +29 -0
- package/dist/travel-oss-pull.mjs +389 -0
- package/dist/travel-oss-return.mjs +563 -0
- package/dist/travel-pairing.mjs +206 -85
- package/dist/web-console.mjs +448 -265
- package/package.json +1 -1
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
// src/travel/oss-return.ts
|
|
2
|
+
import { join as join4, isAbsolute } from "node:path";
|
|
3
|
+
import { gzipSync as gzipSync2 } from "node:zlib";
|
|
4
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
5
|
+
|
|
6
|
+
// src/travel/chunk-store.ts
|
|
7
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
8
|
+
import {
|
|
9
|
+
closeSync,
|
|
10
|
+
existsSync,
|
|
11
|
+
fstatSync,
|
|
12
|
+
fsyncSync,
|
|
13
|
+
lstatSync,
|
|
14
|
+
mkdirSync,
|
|
15
|
+
openSync,
|
|
16
|
+
readFileSync,
|
|
17
|
+
readSync,
|
|
18
|
+
renameSync,
|
|
19
|
+
unlinkSync,
|
|
20
|
+
writeFileSync,
|
|
21
|
+
writeSync,
|
|
22
|
+
constants
|
|
23
|
+
} from "node:fs";
|
|
24
|
+
import { gunzipSync, gzipSync } from "node:zlib";
|
|
25
|
+
import { dirname, join } from "node:path";
|
|
26
|
+
var CHUNK_BYTES = 1024 * 1024;
|
|
27
|
+
var SHA = /^[a-f0-9]{64}$/;
|
|
28
|
+
var sha256 = (body) => createHash("sha256").update(body).digest("hex");
|
|
29
|
+
function validateChunkRef(ref) {
|
|
30
|
+
if (!ref || !SHA.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > CHUNK_BYTES)
|
|
31
|
+
throw new Error("TRAVEL_INVALID_CHUNK");
|
|
32
|
+
}
|
|
33
|
+
function validateFileManifest(file) {
|
|
34
|
+
if (!file || !SHA.test(file.sha256) || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || !Array.isArray(file.chunks))
|
|
35
|
+
throw new Error("TRAVEL_INVALID_FILE");
|
|
36
|
+
let total = 0;
|
|
37
|
+
for (const ref of file.chunks) {
|
|
38
|
+
validateChunkRef(ref);
|
|
39
|
+
total += ref.bytes;
|
|
40
|
+
}
|
|
41
|
+
if (total !== file.bytes) throw new Error("TRAVEL_INVALID_FILE");
|
|
42
|
+
}
|
|
43
|
+
var ChunkStore = class {
|
|
44
|
+
dir;
|
|
45
|
+
constructor(dir) {
|
|
46
|
+
this.dir = dir;
|
|
47
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
48
|
+
}
|
|
49
|
+
chunkPath(sha) {
|
|
50
|
+
return join(this.dir, sha + ".gz");
|
|
51
|
+
}
|
|
52
|
+
/** 幂等:同 sha 已存在直接返回;写盘走 tmp+rename,读者永远看不到半个块。 */
|
|
53
|
+
async put(body) {
|
|
54
|
+
if (!(body instanceof Buffer) || body.length < 1 || body.length > CHUNK_BYTES) throw new Error("TRAVEL_INVALID_CHUNK");
|
|
55
|
+
const ref = { sha256: sha256(body), bytes: body.length };
|
|
56
|
+
const path = this.chunkPath(ref.sha256);
|
|
57
|
+
if (!existsSync(path)) {
|
|
58
|
+
const temp = path + "." + randomUUID() + ".tmp";
|
|
59
|
+
try {
|
|
60
|
+
writeFileSync(temp, gzipSync(body), { flag: "wx", mode: 384 });
|
|
61
|
+
renameSync(temp, path);
|
|
62
|
+
} finally {
|
|
63
|
+
try {
|
|
64
|
+
if (existsSync(temp)) unlinkSync(temp);
|
|
65
|
+
} catch {
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return ref;
|
|
70
|
+
}
|
|
71
|
+
async has(sha) {
|
|
72
|
+
if (!SHA.test(sha)) throw new Error("TRAVEL_INVALID_CHUNK");
|
|
73
|
+
if (!existsSync(this.chunkPath(sha))) return false;
|
|
74
|
+
try {
|
|
75
|
+
await this.read(sha);
|
|
76
|
+
return true;
|
|
77
|
+
} catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async read(sha, bytes = -1) {
|
|
82
|
+
if (!SHA.test(sha) || !Number.isSafeInteger(bytes) || bytes < -1 || bytes > CHUNK_BYTES) throw new Error("TRAVEL_INVALID_CHUNK");
|
|
83
|
+
let plain;
|
|
84
|
+
try {
|
|
85
|
+
plain = gunzipSync(readFileSync(this.chunkPath(sha)));
|
|
86
|
+
} catch {
|
|
87
|
+
throw new Error("TRAVEL_CHUNK_CORRUPT");
|
|
88
|
+
}
|
|
89
|
+
if (sha256(plain) !== sha || bytes >= 0 && plain.length !== bytes) throw new Error("TRAVEL_CHUNK_CORRUPT");
|
|
90
|
+
return plain;
|
|
91
|
+
}
|
|
92
|
+
/** 读磁盘上的原始 gzip 体(OSS 直传用:线上/磁盘同为 gz,省一次解压重压)。 */
|
|
93
|
+
readGzipRaw(sha) {
|
|
94
|
+
if (!SHA.test(sha)) throw new Error("TRAVEL_INVALID_CHUNK");
|
|
95
|
+
return readFileSync(this.chunkPath(sha));
|
|
96
|
+
}
|
|
97
|
+
/** 捕获 = 边读边入仓。1122 晚(VACUUM 拆除后 raw 直捕实弹):活引擎的库/wal/
|
|
98
|
+
* jsonl 读到一半被写是常态,一律拒绝会把整个准备打死(晓雯 19:31 实弹
|
|
99
|
+
* TRAVEL_SOURCE_CHANGED)。策略=重读两轮仍变=活写入者,接受最后一次自洽读
|
|
100
|
+
* (sha 与实际读到的字节严格对应;语义撕裂由对端 integrity_check 出声,
|
|
101
|
+
* 搬移的权威静止同步随后覆盖)。静止路径(引擎已停)守卫天然不触发。 */
|
|
102
|
+
async captureFile(source) {
|
|
103
|
+
let lastError = null;
|
|
104
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
105
|
+
try {
|
|
106
|
+
return await this.captureFileOnce(source, attempt === 2);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (!(error instanceof Error) || error.message !== "TRAVEL_SOURCE_CHANGED") throw error;
|
|
109
|
+
lastError = error;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
throw lastError;
|
|
113
|
+
}
|
|
114
|
+
async captureFileOnce(source, acceptLiveWrite) {
|
|
115
|
+
const fd = openSync(source, constants.O_RDONLY);
|
|
116
|
+
try {
|
|
117
|
+
const before = fstatSync(fd, { bigint: true });
|
|
118
|
+
if (!before.isFile()) throw new Error("TRAVEL_NOT_REGULAR_FILE");
|
|
119
|
+
const digest = createHash("sha256");
|
|
120
|
+
const buffer = Buffer.alloc(Math.min(CHUNK_BYTES, Number(before.size) || 1));
|
|
121
|
+
const chunks = [];
|
|
122
|
+
let bytes = 0;
|
|
123
|
+
for (; ; ) {
|
|
124
|
+
const count = readSync(fd, buffer, 0, buffer.length, null);
|
|
125
|
+
if (!count) break;
|
|
126
|
+
const piece = Buffer.from(buffer.subarray(0, count));
|
|
127
|
+
digest.update(piece);
|
|
128
|
+
bytes += count;
|
|
129
|
+
chunks.push(await this.put(piece));
|
|
130
|
+
}
|
|
131
|
+
const after = fstatSync(fd, { bigint: true });
|
|
132
|
+
const pathInfo = lstatSync(source, { bigint: true });
|
|
133
|
+
const changed = ["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((key) => after[key] !== before[key] || pathInfo[key] !== before[key]) || BigInt(bytes) !== before.size;
|
|
134
|
+
if (changed && !acceptLiveWrite) throw new Error("TRAVEL_SOURCE_CHANGED");
|
|
135
|
+
if (changed) console.warn(`[travel] ${source} \u6355\u83B7\u671F\u95F4\u6301\u7EED\u88AB\u5199\uFF08\u6D3B\u5F15\u64CE\uFF09\u2014\u2014\u63A5\u53D7\u77AC\u65F6\u5FEB\u7167\uFF0C\u9759\u6B62\u540C\u6B65\u5C06\u8986\u76D6`);
|
|
136
|
+
return { sha256: digest.digest("hex"), bytes, chunks };
|
|
137
|
+
} finally {
|
|
138
|
+
closeSync(fd);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async restoreFile(file, destination, mode = 384) {
|
|
142
|
+
validateFileManifest(file);
|
|
143
|
+
if (existsSync(destination)) throw new Error("TRAVEL_DESTINATION_EXISTS");
|
|
144
|
+
mkdirSync(dirname(destination), { recursive: true, mode: 448 });
|
|
145
|
+
const temp = destination + "." + randomUUID() + ".incoming";
|
|
146
|
+
const digest = createHash("sha256");
|
|
147
|
+
const fd = openSync(temp, "wx", mode);
|
|
148
|
+
try {
|
|
149
|
+
for (const ref of file.chunks) {
|
|
150
|
+
const body = await this.read(ref.sha256, ref.bytes);
|
|
151
|
+
digest.update(body);
|
|
152
|
+
let offset = 0;
|
|
153
|
+
while (offset < body.length) offset += writeSync(fd, body, offset, body.length - offset);
|
|
154
|
+
}
|
|
155
|
+
if (digest.digest("hex") !== file.sha256) throw new Error("TRAVEL_FILE_CORRUPT");
|
|
156
|
+
fsyncSync(fd);
|
|
157
|
+
renameSync(temp, destination);
|
|
158
|
+
} finally {
|
|
159
|
+
closeSync(fd);
|
|
160
|
+
try {
|
|
161
|
+
if (existsSync(temp)) unlinkSync(temp);
|
|
162
|
+
} catch {
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** 盘上文件是否与 manifest 一致(apply 的跳过判断)。 */
|
|
167
|
+
static fileMatches(destination, manifest) {
|
|
168
|
+
try {
|
|
169
|
+
const info = lstatSync(destination);
|
|
170
|
+
if (!info.isFile() || info.size !== manifest.bytes) return false;
|
|
171
|
+
const digest = createHash("sha256");
|
|
172
|
+
const fd = openSync(destination, constants.O_RDONLY);
|
|
173
|
+
try {
|
|
174
|
+
const buffer = Buffer.alloc(Math.min(CHUNK_BYTES, manifest.bytes || 1));
|
|
175
|
+
for (; ; ) {
|
|
176
|
+
const count = readSync(fd, buffer, 0, buffer.length, null);
|
|
177
|
+
if (!count) break;
|
|
178
|
+
digest.update(buffer.subarray(0, count));
|
|
179
|
+
}
|
|
180
|
+
} finally {
|
|
181
|
+
closeSync(fd);
|
|
182
|
+
}
|
|
183
|
+
return digest.digest("hex") === manifest.sha256;
|
|
184
|
+
} catch {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
function openChunkStore(dir) {
|
|
190
|
+
return new ChunkStore(dir);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// src/travel/tree-manifest.ts
|
|
194
|
+
import { lstatSync as lstatSync3, readdirSync } from "node:fs";
|
|
195
|
+
import { join as join3 } from "node:path";
|
|
196
|
+
|
|
197
|
+
// src/travel/exclusions.ts
|
|
198
|
+
var EXCLUDED_NAMES = /* @__PURE__ */ new Set(["node_modules", ".venv", ".venvs", "venv", ".git", "__pycache__", ".cache", "cache", "caches", "tmp", "temp", ".playwright-mcp", ".DS_Store"]);
|
|
199
|
+
var EXCLUDED_TOP = /* @__PURE__ */ new Set(["logs", "diagnostics", "node_modules", "CogniFold", "everos-venv", "ollama-models", ".log-baseline.txt"]);
|
|
200
|
+
function excludeReason(relPath, isDir) {
|
|
201
|
+
const parts = relPath.split("/");
|
|
202
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
203
|
+
const part = parts[i];
|
|
204
|
+
if (part === "media" && parts[i + 1] === "inbound") {
|
|
205
|
+
i++;
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (EXCLUDED_NAMES.has(part)) return `installed dependency, cache or temporary directory: ${part}`;
|
|
209
|
+
}
|
|
210
|
+
const name = parts[parts.length - 1];
|
|
211
|
+
if (isDir && EXCLUDED_NAMES.has(name)) return `installed dependency, cache or temporary directory: ${name}`;
|
|
212
|
+
if (parts.length === 1 && EXCLUDED_TOP.has(name)) return `diagnostics, installed or rebuildable material: ${name}`;
|
|
213
|
+
if (/\.lock$/.test(name) || /\.pid$/.test(name) || name === "package-lock.json" || name === "nohup.out") return "lock/pid/junk file";
|
|
214
|
+
if (parts.length === 1 && EXCLUDED_NAMES.has(name)) return `installed dependency, cache or temporary file: ${name}`;
|
|
215
|
+
if (/\.log$/.test(name) && parts[0] !== "workspace") return "diagnostics log";
|
|
216
|
+
const mediaIndex = parts.indexOf("media");
|
|
217
|
+
if (mediaIndex >= 0 && parts[mediaIndex + 1] === "generated") return "self-generated media";
|
|
218
|
+
return void 0;
|
|
219
|
+
}
|
|
220
|
+
var WORKSPACE_MEMORY_DIRS = /* @__PURE__ */ new Set(["topics", "memory", "inner-voice", ".calendar", ".proactive", ".system", "docs", "skills"]);
|
|
221
|
+
function workspaceTopFileReason(name, size) {
|
|
222
|
+
if (!(/\.md$/i.test(name) || name === ".gitignore")) return `workspace \u9876\u5C42\u975E md \u6587\u4EF6\u4E0D\u968F\u884C\uFF08${name}\uFF09`;
|
|
223
|
+
if (typeof size === "number" && size > WORKSPACE_BIG_FILE_BYTES) return `workspace \u9876\u5C42 md \u8D85 32MB \u4E0D\u968F\u884C\uFF08${name}\uFF09`;
|
|
224
|
+
return void 0;
|
|
225
|
+
}
|
|
226
|
+
var WORKSPACE_MEDIA_EXT = /\.(mp4|mov|mkv|webm|avi|m4v|flv|wmv|mpg|mpeg|mp3|wav|flac|aac|ogg|opus|m4a|zip|rar|7z|dmg|iso)$/i;
|
|
227
|
+
var WORKSPACE_BIG_FILE_BYTES = 32 * 1024 * 1024;
|
|
228
|
+
var RETURN_MEDIA_KEEP_MS = 14 * 24 * 3600 * 1e3;
|
|
229
|
+
function syncExcludeWith(mediaPolicy) {
|
|
230
|
+
return (relPath, isDir, size, mtimeMs) => {
|
|
231
|
+
const parts = relPath.split("/");
|
|
232
|
+
const name = parts[parts.length - 1];
|
|
233
|
+
if (!relPath.includes("/") && (relPath === "config.json" || relPath === "secrets.env")) {
|
|
234
|
+
return "\u5BF9\u7AEF\u5B89\u88C5\u4EA7\u7269\u4FDD\u62A4\uFF08config \u8D70 config-remap\uFF0Csecrets \u8D70 travel-setup\uFF09";
|
|
235
|
+
}
|
|
236
|
+
const isUserMedia = parts[0] === "media" && parts[1] === "inbound" || parts[0] === "chan7-files";
|
|
237
|
+
if (isUserMedia) {
|
|
238
|
+
if (mediaPolicy === "none") return "\u7528\u6237\u5A92\u4F53\u6863\u6848\u4E0D\u968F\u884C\uFF081122\uFF1A\u4E91\u7AEF\u7FFB\u65E7\u56FE\u8D70\u964D\u7EA7\u5360\u4F4D\uFF09";
|
|
239
|
+
if (typeof size === "number" && size > WORKSPACE_BIG_FILE_BYTES) return `\u7528\u6237\u5A92\u4F53\u5927\u6587\u4EF6\u4E0D\u968F\u884C\uFF08${(size / 1048576).toFixed(0)}MB > 32MB\uFF09`;
|
|
240
|
+
if (typeof mtimeMs === "number" && Date.now() - mtimeMs > mediaPolicy.windowMs) return `\u7528\u6237\u5A92\u4F53\u4EC5\u8FD1 ${Math.round(mediaPolicy.windowMs / 864e5)} \u5929\u968F\u884C\uFF08\u56DE\u7A0B\u7A97\u53E3\uFF09`;
|
|
241
|
+
return void 0;
|
|
242
|
+
}
|
|
243
|
+
if (parts[0] === "workspace") {
|
|
244
|
+
if (parts.length === 1) return isDir ? void 0 : workspaceTopFileReason(name, size);
|
|
245
|
+
const second = parts[1];
|
|
246
|
+
if (!WORKSPACE_MEMORY_DIRS.has(second)) {
|
|
247
|
+
if (parts.length === 2 && !isDir) return workspaceTopFileReason(second, size);
|
|
248
|
+
return `workspace \u5DE5\u4F5C\u4EA7\u7269\u4E0D\u968F\u884C\uFF08${second}/\uFF09\u2014\u2014\u53EA\u5E26\u6838\u5FC3\u8BB0\u5FC6\uFF081122 \u7ACB\u6CD5\uFF09`;
|
|
249
|
+
}
|
|
250
|
+
if (!isDir) {
|
|
251
|
+
if (WORKSPACE_MEDIA_EXT.test(name)) return `workspace \u5185\u97F3\u89C6\u9891/\u538B\u7F29\u5305\u4E0D\u968F\u884C\uFF08${name}\uFF09`;
|
|
252
|
+
if (second !== ".proactive" && typeof size === "number" && size > WORKSPACE_BIG_FILE_BYTES) return `workspace \u5927\u6587\u4EF6\u4E0D\u968F\u884C\uFF08${(size / 1048576).toFixed(0)}MB > 32MB\uFF09`;
|
|
253
|
+
}
|
|
254
|
+
return void 0;
|
|
255
|
+
}
|
|
256
|
+
if (parts[0] === "media" && parts.length >= 2) return `media \u4EC5 inbound\uFF08\u56DE\u7A0B\u8FD1\u7A97\uFF09\u968F\u884C\uFF1A${parts[1]}`;
|
|
257
|
+
if (parts[0] === "content") return "\u5185\u5BB9\u4EA7\u7269\u76EE\u5F55\u4E0D\u968F\u884C";
|
|
258
|
+
return excludeReason(relPath, isDir);
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
var syncExcludeReason = syncExcludeWith("none");
|
|
262
|
+
var syncExcludeToCloud = syncExcludeWith("none");
|
|
263
|
+
var syncExcludeToLocal = syncExcludeWith({ windowMs: RETURN_MEDIA_KEEP_MS });
|
|
264
|
+
function syncExcludeWithDays(days) {
|
|
265
|
+
return days > 0 ? syncExcludeWith({ windowMs: days * 864e5 }) : syncExcludeWith("none");
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// src/travel/capture-cache.ts
|
|
269
|
+
import { existsSync as existsSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, realpathSync, renameSync as renameSync2, writeFileSync as writeFileSync2, unlinkSync as unlinkSync2 } from "node:fs";
|
|
270
|
+
import { join as join2 } from "node:path";
|
|
271
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
272
|
+
function fileFingerprint(file) {
|
|
273
|
+
const s = lstatSync2(file, { bigint: true });
|
|
274
|
+
if (!s.isFile()) throw Error("TRAVEL_NOT_REGULAR_FILE");
|
|
275
|
+
return [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(":");
|
|
276
|
+
}
|
|
277
|
+
function readCaptureCache(root) {
|
|
278
|
+
try {
|
|
279
|
+
const value = JSON.parse(readFileSync2(join2(root, ".travel/capture-cache.json"), "utf8"));
|
|
280
|
+
if (value.version !== 1 || value.root !== realpathSync(root) || !value.entries || typeof value.entries !== "object") return /* @__PURE__ */ new Map();
|
|
281
|
+
return new Map(Object.entries(value.entries));
|
|
282
|
+
} catch {
|
|
283
|
+
return /* @__PURE__ */ new Map();
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function cachedContent(cache2, rel, fingerprint) {
|
|
287
|
+
const entry = cache2.get(rel);
|
|
288
|
+
if (!entry || entry.fingerprint !== fingerprint) return;
|
|
289
|
+
try {
|
|
290
|
+
validateFileManifest(entry.content);
|
|
291
|
+
return entry.content;
|
|
292
|
+
} catch {
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
function writeCaptureCache(root, cache2) {
|
|
297
|
+
const directory = join2(root, ".travel"), temp = join2(directory, "capture-cache." + randomUUID2() + ".tmp");
|
|
298
|
+
try {
|
|
299
|
+
mkdirSync2(directory, { recursive: true, mode: 448 });
|
|
300
|
+
writeFileSync2(temp, JSON.stringify({ version: 1, root: realpathSync(root), entries: Object.fromEntries(cache2) }), { mode: 384 });
|
|
301
|
+
renameSync2(temp, join2(directory, "capture-cache.json"));
|
|
302
|
+
} catch {
|
|
303
|
+
try {
|
|
304
|
+
unlinkSync2(temp);
|
|
305
|
+
} catch {
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
function cachedChunksExist(directory, content) {
|
|
310
|
+
return content.chunks.every((ref) => existsSync2(join2(directory, ref.sha256 + ".gz")));
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// src/travel/tree-manifest.ts
|
|
314
|
+
var TREE_MANIFEST_VERSION = 2;
|
|
315
|
+
var SELF_EXCLUDED_TOP = /* @__PURE__ */ new Set([".travel", ".travel-sync-staging"]);
|
|
316
|
+
async function buildTreeManifest(root, store, opts = {}) {
|
|
317
|
+
const exclude = opts.exclude ?? syncExcludeReason;
|
|
318
|
+
const files = [];
|
|
319
|
+
const excluded = [];
|
|
320
|
+
const previous = readCaptureCache(root), next = /* @__PURE__ */ new Map();
|
|
321
|
+
const walk = async (dir, rel) => {
|
|
322
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
323
|
+
const childRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
324
|
+
const childPath = join3(dir, entry.name);
|
|
325
|
+
if (entry.isSymbolicLink()) {
|
|
326
|
+
excluded.push(`${childRel} \u2014 symlink refused`);
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (rel === "" && SELF_EXCLUDED_TOP.has(entry.name)) {
|
|
330
|
+
excluded.push(`${childRel} \u2014 travel internal state`);
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
let size, mtimeMs;
|
|
334
|
+
if (entry.isFile()) {
|
|
335
|
+
try {
|
|
336
|
+
const info2 = lstatSync3(childPath);
|
|
337
|
+
size = info2.size;
|
|
338
|
+
mtimeMs = info2.mtimeMs;
|
|
339
|
+
} catch {
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
const reason = exclude(childRel, entry.isDirectory(), size, mtimeMs);
|
|
343
|
+
if (reason) {
|
|
344
|
+
excluded.push(`${childRel} \u2014 ${reason}`);
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
if (entry.isDirectory()) {
|
|
348
|
+
await walk(childPath, childRel);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
if (!entry.isFile()) {
|
|
352
|
+
excluded.push(`${childRel} \u2014 not a regular file`);
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
const info = lstatSync3(childPath);
|
|
356
|
+
const before = fileFingerprint(childPath);
|
|
357
|
+
let content = cachedContent(previous, childRel, before);
|
|
358
|
+
if (!content || !cachedChunksExist(store.dir, content) || fileFingerprint(childPath) !== before) content = await store.captureFile(childPath);
|
|
359
|
+
const after = fileFingerprint(childPath);
|
|
360
|
+
if (before === after && content.bytes === info.size) next.set(childRel, { fingerprint: after, content });
|
|
361
|
+
files.push({ rel: childRel, mode: info.mode & 511, content });
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
await walk(root, "");
|
|
365
|
+
files.sort((a, b) => a.rel < b.rel ? -1 : 1);
|
|
366
|
+
writeCaptureCache(root, next);
|
|
367
|
+
return { version: TREE_MANIFEST_VERSION, generatedAt: Date.now(), files, excluded };
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// src/travel/oss-transport.ts
|
|
371
|
+
import { createHmac, createHash as createHash2 } from "node:crypto";
|
|
372
|
+
|
|
373
|
+
// src/travel/oss-broker.ts
|
|
374
|
+
var cache = /* @__PURE__ */ new WeakMap();
|
|
375
|
+
var cacheKey = (o) => JSON.stringify([o.method, o.key, o.contentMD5 ?? "", o.contentType ?? ""]);
|
|
376
|
+
function validateAuthorization(config, value, operations) {
|
|
377
|
+
if (!value || !Number.isSafeInteger(value.expiresAt) || value.expiresAt > Date.now() / 1e3 + 960 || !Array.isArray(value.objects) || value.objects.length !== operations.length) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
|
|
378
|
+
if (!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(value.bucket) || !/^oss-[a-z0-9-]+(?:-internal)?\.aliyuncs\.com$/.test(value.endpoint) && !/^http:\/\/127\.0\.0\.1:\d+$/.test(value.endpoint)) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
|
|
379
|
+
if (config.bucket && config.bucket !== value.bucket || config.endpoint && config.endpoint !== value.endpoint) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
|
|
380
|
+
let tokenId = config.broker.tokenId;
|
|
381
|
+
for (let i = 0; i < operations.length; i++) {
|
|
382
|
+
const expected = operations[i], actual = value.objects[i], url = new URL(actual.url);
|
|
383
|
+
const local = value.endpoint.startsWith("http://127.0.0.1:");
|
|
384
|
+
const host = local ? new URL(value.endpoint).host : `${value.bucket}.${value.endpoint}`;
|
|
385
|
+
const root = (local ? "/" + value.bucket : "") + "/chunks/7yi/";
|
|
386
|
+
const [owner, transferId, ...key] = url.pathname.slice(root.length).split("/");
|
|
387
|
+
if (!url.pathname.startsWith(root) || !owner || !/^[1-9][0-9]{0,18}$/.test(owner) || transferId !== config.broker.transferId || key.join("/") !== expected.key || tokenId && owner !== tokenId) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
|
|
388
|
+
tokenId = owner;
|
|
389
|
+
if (actual.method !== expected.method || actual.key !== expected.key || url.host !== host || url.protocol !== (local ? "http:" : "https:") || url.username || url.password || url.hash || !actual.headers || Object.keys(actual.headers).some((k) => !["Content-MD5", "Content-Type"].includes(k))) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
|
|
390
|
+
if (expected.method === "PUT" && (actual.headers["Content-MD5"] !== expected.contentMD5 || actual.headers["Content-Type"] !== expected.contentType)) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
|
|
391
|
+
}
|
|
392
|
+
config.broker.tokenId = tokenId;
|
|
393
|
+
}
|
|
394
|
+
async function authorize(config, operations) {
|
|
395
|
+
const broker = config.broker;
|
|
396
|
+
let result;
|
|
397
|
+
try {
|
|
398
|
+
const response = await fetch(broker.url, { method: "POST", redirect: "error", headers: { Authorization: "Bearer " + broker.apiKey, "Content-Type": "application/json" }, body: JSON.stringify({ transferId: broker.transferId, internal: config.endpoint.includes("-internal."), objects: operations }), signal: AbortSignal.timeout(2e4) });
|
|
399
|
+
if (!response.ok) {
|
|
400
|
+
await response.body?.cancel();
|
|
401
|
+
throw Error(`TRAVEL_OSS_AUTHORIZATION_HTTP_${response.status}`);
|
|
402
|
+
}
|
|
403
|
+
result = await response.json();
|
|
404
|
+
validateAuthorization(config, result, operations);
|
|
405
|
+
} catch (error) {
|
|
406
|
+
if (error instanceof Error && /^TRAVEL_OSS_AUTHORIZATION_HTTP_[0-9]{3}$/.test(error.message)) throw error;
|
|
407
|
+
throw Error("TRAVEL_OSS_AUTHORIZATION_FAILED");
|
|
408
|
+
}
|
|
409
|
+
return result;
|
|
410
|
+
}
|
|
411
|
+
async function prepareOssRequests(config, operations) {
|
|
412
|
+
if (!config.broker) return;
|
|
413
|
+
let entries = cache.get(config);
|
|
414
|
+
if (!entries) {
|
|
415
|
+
entries = /* @__PURE__ */ new Map();
|
|
416
|
+
cache.set(config, entries);
|
|
417
|
+
}
|
|
418
|
+
const missing = operations.filter((o) => (entries.get(cacheKey(o))?.expiresAt ?? 0) <= Date.now() / 1e3 + 30);
|
|
419
|
+
for (let i = 0; i < missing.length; i += 128) {
|
|
420
|
+
const batch = missing.slice(i, i + 128), result = await authorize(config, batch);
|
|
421
|
+
for (const [index, object] of result.objects.entries()) entries.set(cacheKey(batch[index]), { object, expiresAt: result.expiresAt });
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
async function signedOssRequest(config, operation, refresh = false) {
|
|
425
|
+
if (refresh) cache.get(config)?.delete(cacheKey(operation));
|
|
426
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
427
|
+
await prepareOssRequests(config, [operation]);
|
|
428
|
+
const entry = cache.get(config)?.get(cacheKey(operation));
|
|
429
|
+
if (entry && entry.expiresAt > Date.now() / 1e3 + 30) return entry.object;
|
|
430
|
+
}
|
|
431
|
+
throw Error("TRAVEL_OSS_AUTHORIZATION_EXPIRED");
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// src/travel/oss-transport.ts
|
|
435
|
+
function internalEndpointOf(endpoint) {
|
|
436
|
+
if (endpoint.includes("-internal.")) return endpoint;
|
|
437
|
+
const at = endpoint.indexOf(".aliyuncs.com");
|
|
438
|
+
if (at < 0) return endpoint;
|
|
439
|
+
return endpoint.slice(0, at) + "-internal" + endpoint.slice(at);
|
|
440
|
+
}
|
|
441
|
+
function signedHeaders(config, method, resourcePath, headers) {
|
|
442
|
+
const date = (/* @__PURE__ */ new Date()).toUTCString();
|
|
443
|
+
const all = { ...headers, Date: date };
|
|
444
|
+
const ossHeaders = Object.keys(all).filter((key) => key.toLowerCase().startsWith("x-oss-")).sort((a, b) => a < b ? -1 : a > b ? 1 : 0).map((key) => `${key.toLowerCase()}:${all[key]}
|
|
445
|
+
`).join("");
|
|
446
|
+
const pick = (name) => {
|
|
447
|
+
const key = Object.keys(all).find((k) => k.toLowerCase() === name);
|
|
448
|
+
return key ? String(all[key]) : "";
|
|
449
|
+
};
|
|
450
|
+
const stringToSign = `${method}
|
|
451
|
+
${pick("content-md5")}
|
|
452
|
+
${pick("content-type")}
|
|
453
|
+
${date}
|
|
454
|
+
${ossHeaders}/${config.bucket}${resourcePath}`;
|
|
455
|
+
if (!config.accessKeyId || !config.accessKeySecret) throw Error("TRAVEL_OSS_NOT_CONFIGURED");
|
|
456
|
+
const signature = createHmac("sha1", config.accessKeySecret).update(stringToSign).digest("base64");
|
|
457
|
+
return { ...all, Authorization: `OSS ${config.accessKeyId}:${signature}` };
|
|
458
|
+
}
|
|
459
|
+
async function ossFetch(config, method, resourcePath, body, headers = {}, okCodes = [200]) {
|
|
460
|
+
if (config.broker) {
|
|
461
|
+
const operation = { method, key: resourcePath.slice(1), ...method === "PUT" ? { contentMD5: md5Base64(body ?? Buffer.alloc(0)), contentType: "application/octet-stream" } : {} };
|
|
462
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
463
|
+
const signed2 = await signedOssRequest(config, operation, attempt > 0);
|
|
464
|
+
let response2;
|
|
465
|
+
try {
|
|
466
|
+
response2 = await fetch(signed2.url, { method, headers: signed2.headers, body, redirect: "error", signal: AbortSignal.timeout(Math.max(12e4, Math.round((body?.length ?? 0) / 1048576) * 12e3)) });
|
|
467
|
+
} catch {
|
|
468
|
+
throw Error("TRAVEL_OSS_TRANSFER_FAILED");
|
|
469
|
+
}
|
|
470
|
+
if (response2.status === 403 && attempt === 0) {
|
|
471
|
+
await response2.body?.cancel();
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
if (!okCodes.includes(response2.status)) {
|
|
475
|
+
await response2.body?.cancel();
|
|
476
|
+
throw Error(`TRAVEL_OSS_ERROR (${method} \u2192 ${response2.status})`);
|
|
477
|
+
}
|
|
478
|
+
return response2;
|
|
479
|
+
}
|
|
480
|
+
throw Error("TRAVEL_OSS_TRANSFER_FAILED");
|
|
481
|
+
}
|
|
482
|
+
const signed = signedHeaders(config, method, resourcePath, headers);
|
|
483
|
+
const scheme = config.endpoint.startsWith("http://") ? "http://" : "https://";
|
|
484
|
+
const host = config.endpoint.replace(/^https?:\/\//, "");
|
|
485
|
+
const pathStyle = /^[\d.]+$/.test(host) || host.startsWith("localhost") || host.startsWith("127.");
|
|
486
|
+
const url = pathStyle ? `${scheme}${host}/${config.bucket}${resourcePath}` : `${scheme}${config.bucket}.${host}${resourcePath}`;
|
|
487
|
+
const response = await fetch(url, {
|
|
488
|
+
method,
|
|
489
|
+
headers: signed,
|
|
490
|
+
body,
|
|
491
|
+
// 1123 妹妹 review:固定 120s 对慢上行的大块太贴边(10MB@1Mbps≈80s)——
|
|
492
|
+
// 按 body 长度放宽(≥120s,每 1MB 加 12s 余量)。
|
|
493
|
+
signal: AbortSignal.timeout(Math.max(12e4, Math.round((body?.length ?? 0) / 1024 / 1024) * 12e3))
|
|
494
|
+
});
|
|
495
|
+
if (!okCodes.includes(response.status)) {
|
|
496
|
+
const detail = await response.text().catch(() => "");
|
|
497
|
+
throw new Error(`TRAVEL_OSS_ERROR\uFF08${method} ${resourcePath} \u2192 ${response.status}\uFF09\uFF1A${detail.slice(0, 300)}`);
|
|
498
|
+
}
|
|
499
|
+
return response;
|
|
500
|
+
}
|
|
501
|
+
function md5Base64(body) {
|
|
502
|
+
return createHash2("md5").update(body).digest("base64");
|
|
503
|
+
}
|
|
504
|
+
function objectPath(key) {
|
|
505
|
+
if (!/^[A-Za-z0-9/_.-]+$/.test(key) || key.startsWith("/") || key.includes("..")) throw Error("TRAVEL_OSS_INVALID_OBJECT_KEY");
|
|
506
|
+
return "/" + key;
|
|
507
|
+
}
|
|
508
|
+
async function ossPutObject(config, key, body) {
|
|
509
|
+
await ossFetch(config, "PUT", objectPath(key), body, { "Content-Type": "application/octet-stream", "Content-MD5": md5Base64(body) });
|
|
510
|
+
}
|
|
511
|
+
async function ossDeleteObject(config, key) {
|
|
512
|
+
await ossFetch(config, "DELETE", objectPath(key), void 0, {}, [204]);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// src/travel/oss-return.ts
|
|
516
|
+
async function pool(items, fn) {
|
|
517
|
+
let cursor = 0;
|
|
518
|
+
const results = await Promise.allSettled(Array.from({ length: 12 }, async () => {
|
|
519
|
+
for (; ; ) {
|
|
520
|
+
const i = cursor++;
|
|
521
|
+
if (i >= items.length) return;
|
|
522
|
+
try {
|
|
523
|
+
await fn(items[i]);
|
|
524
|
+
} catch {
|
|
525
|
+
await fn(items[i]);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}));
|
|
529
|
+
const failed = results.find((r) => r.status === "rejected");
|
|
530
|
+
if (failed?.status === "rejected") throw failed.reason;
|
|
531
|
+
}
|
|
532
|
+
async function runOssReturn(request, progress) {
|
|
533
|
+
if (!request || !isAbsolute(request.stateDir) || !/^chunks\/return\/[a-f0-9]{64}$/.test(request.prefix) || !request.config?.accessKeySecret && !request.config?.broker) throw Error("TRAVEL_OSS_RETURN_INVALID_REQUEST");
|
|
534
|
+
const config = { ...request.config, endpoint: internalEndpointOf(request.config.endpoint) };
|
|
535
|
+
if (request.op === "cleanup") {
|
|
536
|
+
const keys = request.keys ?? [];
|
|
537
|
+
if (keys.some((key) => !key.startsWith(request.prefix + "/"))) throw Error("TRAVEL_OSS_RETURN_INVALID_KEY");
|
|
538
|
+
await prepareOssRequests(config, keys.map((key) => ({ method: "DELETE", key })));
|
|
539
|
+
await pool(keys, (key) => ossDeleteObject(config, key));
|
|
540
|
+
return { deleted: keys.length };
|
|
541
|
+
}
|
|
542
|
+
const store = openChunkStore(join4(request.stateDir, ".travel/chunks"));
|
|
543
|
+
if (request.op === "capture") {
|
|
544
|
+
const manifest = await buildTreeManifest(request.stateDir, store, { exclude: syncExcludeWithDays(14) }), body = Buffer.from(JSON.stringify(manifest)), objectKey = request.prefix + "/manifest.gz";
|
|
545
|
+
await ossPutObject(config, objectKey, gzipSync2(body));
|
|
546
|
+
return { objectKey, sha256: createHash3("sha256").update(body).digest("hex"), files: manifest.files.length };
|
|
547
|
+
}
|
|
548
|
+
if (request.op !== "upload" || !Array.isArray(request.refs)) throw Error("TRAVEL_OSS_RETURN_INVALID_REQUEST");
|
|
549
|
+
for (const ref of request.refs) validateChunkRef(ref);
|
|
550
|
+
await prepareOssRequests(config, request.refs.map((ref) => ({ method: "PUT", key: request.prefix + "/chunks/" + ref.sha256 + ".gz", contentMD5: md5Base64(store.readGzipRaw(ref.sha256)), contentType: "application/octet-stream" })));
|
|
551
|
+
let done = 0, bytes = 0;
|
|
552
|
+
await pool(request.refs, async (ref) => {
|
|
553
|
+
await store.read(ref.sha256, ref.bytes);
|
|
554
|
+
await ossPutObject(config, request.prefix + "/chunks/" + ref.sha256 + ".gz", store.readGzipRaw(ref.sha256));
|
|
555
|
+
done++;
|
|
556
|
+
bytes += ref.bytes;
|
|
557
|
+
if (done % 50 === 0 || done === request.refs.length) progress?.({ done, total: request.refs.length, bytes });
|
|
558
|
+
});
|
|
559
|
+
return { uploaded: done, bytes };
|
|
560
|
+
}
|
|
561
|
+
export {
|
|
562
|
+
runOssReturn
|
|
563
|
+
};
|