engine7 7.1.132 → 7.1.136
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 +32198 -28733
- package/dist/cc-desktop.mjs +951 -0
- package/dist/cli.mjs +41391 -29912
- package/dist/engine-startup.mjs +68176 -54684
- package/dist/main.mjs +54090 -40596
- package/dist/recall-worker.mjs +20443 -0
- package/dist/sqlite-maintenance-worker.mjs +1163 -124
- package/dist/stop-history-worker.mjs +180 -0
- package/dist/topics-worker.mjs +3350 -1078
- package/dist/travel-authority.mjs +1068 -0
- package/dist/travel-console.mjs +2205 -0
- package/dist/travel-controller.mjs +1883 -0
- package/dist/travel-data.mjs +7250 -0
- package/dist/travel-gateway.mjs +3258 -0
- package/dist/travel-key-service.mjs +483 -0
- package/dist/travel-node-data.mjs +4930 -0
- package/dist/travel-node.mjs +21233 -0
- package/dist/travel-retire.mjs +1094 -0
- package/dist/web-console.mjs +2425 -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,1094 @@
|
|
|
1
|
+
const require=(await import('node:module')).createRequire(import.meta.url)
|
|
2
|
+
|
|
3
|
+
// src/continuity/retirement-main.ts
|
|
4
|
+
import { readFileSync as readFileSync6, existsSync as existsSync3 } from "node:fs";
|
|
5
|
+
import { isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { execFile } from "node:child_process";
|
|
8
|
+
import { promisify } from "node:util";
|
|
9
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
10
|
+
|
|
11
|
+
// src/continuity/retirement.ts
|
|
12
|
+
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
13
|
+
import { createHash } from "node:crypto";
|
|
14
|
+
import { existsSync } from "node:fs";
|
|
15
|
+
import { lstatSync as lstatSync3, readdirSync, readFileSync as readFileSync3, readlinkSync, realpathSync as realpathSync2, rmSync } from "node:fs";
|
|
16
|
+
import { isAbsolute, join as join3, resolve as resolve2, relative } from "node:path";
|
|
17
|
+
|
|
18
|
+
// src/continuity/publication-objects.ts
|
|
19
|
+
import { DatabaseSync } from "node:sqlite";
|
|
20
|
+
import {
|
|
21
|
+
constants,
|
|
22
|
+
openSync,
|
|
23
|
+
closeSync,
|
|
24
|
+
fstatSync,
|
|
25
|
+
fsyncSync,
|
|
26
|
+
readSync,
|
|
27
|
+
writeSync,
|
|
28
|
+
lstatSync,
|
|
29
|
+
realpathSync,
|
|
30
|
+
mkdirSync,
|
|
31
|
+
readFileSync,
|
|
32
|
+
writeFileSync,
|
|
33
|
+
linkSync,
|
|
34
|
+
unlinkSync
|
|
35
|
+
} from "node:fs";
|
|
36
|
+
import { join, dirname, resolve } from "node:path";
|
|
37
|
+
var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
|
|
38
|
+
var MAGIC = Buffer.from("E7P1");
|
|
39
|
+
var noFollow = constants.O_NOFOLLOW ?? 0;
|
|
40
|
+
function assertPrivateDirectory(path2) {
|
|
41
|
+
const info = lstatSync(path2);
|
|
42
|
+
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path2) !== resolve(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
43
|
+
throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
44
|
+
}
|
|
45
|
+
function syncDir(path2) {
|
|
46
|
+
if (process.platform === "win32") return;
|
|
47
|
+
const fd = openSync(path2, constants.O_RDONLY);
|
|
48
|
+
try {
|
|
49
|
+
fsyncSync(fd);
|
|
50
|
+
} finally {
|
|
51
|
+
closeSync(fd);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function preparePrivateDirectory(path2) {
|
|
55
|
+
const missing = [];
|
|
56
|
+
let parent = resolve(path2);
|
|
57
|
+
for (; ; ) {
|
|
58
|
+
try {
|
|
59
|
+
lstatSync(parent);
|
|
60
|
+
break;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (error.code !== "ENOENT") throw error;
|
|
63
|
+
}
|
|
64
|
+
missing.push(parent);
|
|
65
|
+
parent = dirname(parent);
|
|
66
|
+
}
|
|
67
|
+
if (realpathSync(parent) !== parent) throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
68
|
+
for (const directory of missing.reverse()) {
|
|
69
|
+
try {
|
|
70
|
+
mkdirSync(directory, { mode: 448 });
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error.code !== "EEXIST") throw error;
|
|
73
|
+
}
|
|
74
|
+
assertPrivateDirectory(directory);
|
|
75
|
+
syncDir(dirname(directory));
|
|
76
|
+
}
|
|
77
|
+
assertPrivateDirectory(path2);
|
|
78
|
+
}
|
|
79
|
+
function preparePrivateDatabase(path2) {
|
|
80
|
+
for (const file of [path2, path2 + "-journal", path2 + "-wal", path2 + "-shm"]) {
|
|
81
|
+
try {
|
|
82
|
+
const info2 = lstatSync(file);
|
|
83
|
+
if (!info2.isFile() || info2.isSymbolicLink() || process.platform !== "win32" && (info2.mode & 63 || info2.uid !== process.getuid()))
|
|
84
|
+
throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error.code !== "ENOENT") throw error;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
const fd = openSync(path2, "wx", 384);
|
|
91
|
+
closeSync(fd);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (error.code !== "EEXIST") throw error;
|
|
94
|
+
}
|
|
95
|
+
const info = lstatSync(path2);
|
|
96
|
+
if (!info.isFile() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
97
|
+
throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
|
|
98
|
+
syncDir(dirname(path2));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/continuity/key-service-store.ts
|
|
102
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
103
|
+
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";
|
|
104
|
+
import { join as join2 } from "node:path";
|
|
105
|
+
import { randomUUID } from "node:crypto";
|
|
106
|
+
function validateKeyIdentity(value) {
|
|
107
|
+
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");
|
|
108
|
+
}
|
|
109
|
+
function identityText(value) {
|
|
110
|
+
validateKeyIdentity(value);
|
|
111
|
+
return JSON.stringify([value.tenantId, value.companionId, value.seatId, value.keyId, value.generation]);
|
|
112
|
+
}
|
|
113
|
+
function watermark(value) {
|
|
114
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error("KEY_SERVICE_INVALID_WATERMARK");
|
|
115
|
+
}
|
|
116
|
+
function fingerprint(value) {
|
|
117
|
+
if (!/^[A-F0-9]{64}$/.test(value)) throw new Error("KEY_SERVICE_INVALID_CERTIFICATE");
|
|
118
|
+
}
|
|
119
|
+
function assertPrivateStat(stat, directory) {
|
|
120
|
+
if ((directory ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
121
|
+
throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
|
|
122
|
+
}
|
|
123
|
+
function privateDirectory(path2) {
|
|
124
|
+
try {
|
|
125
|
+
mkdirSync2(path2, { mode: 448 });
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (error.code !== "EEXIST") throw error;
|
|
128
|
+
}
|
|
129
|
+
assertPrivateStat(lstatSync2(path2), true);
|
|
130
|
+
}
|
|
131
|
+
function readPrivateFile(path2, maximumBytes = 65536) {
|
|
132
|
+
assertPrivateStat(lstatSync2(path2), false);
|
|
133
|
+
const fd = openSync2(path2, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
|
|
134
|
+
try {
|
|
135
|
+
const stat = fstatSync2(fd);
|
|
136
|
+
assertPrivateStat(stat, false);
|
|
137
|
+
if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
|
|
138
|
+
return readFileSync2(fd);
|
|
139
|
+
} finally {
|
|
140
|
+
closeSync2(fd);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
var KeyServiceStore = class {
|
|
144
|
+
constructor(directory) {
|
|
145
|
+
this.directory = directory;
|
|
146
|
+
privateDirectory(directory);
|
|
147
|
+
this.secrets = join2(directory, "secrets");
|
|
148
|
+
privateDirectory(this.secrets);
|
|
149
|
+
const path2 = join2(directory, "control.sqlite");
|
|
150
|
+
try {
|
|
151
|
+
closeSync2(openSync2(path2, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384));
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (error.code !== "EEXIST") throw error;
|
|
154
|
+
}
|
|
155
|
+
assertPrivateStat(lstatSync2(path2), false);
|
|
156
|
+
for (const suffix of ["-wal", "-shm", "-journal"]) {
|
|
157
|
+
try {
|
|
158
|
+
assertPrivateStat(lstatSync2(path2 + suffix), false);
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (error.code !== "ENOENT") throw error;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
this.db = new DatabaseSync2(path2);
|
|
164
|
+
try {
|
|
165
|
+
this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
|
|
166
|
+
CREATE TABLE IF NOT EXISTS seat_keys (
|
|
167
|
+
key_id TEXT PRIMARY KEY, identity TEXT NOT NULL, secret_file TEXT NOT NULL,
|
|
168
|
+
state TEXT NOT NULL CHECK(state IN ('active','revoked')), deletion_watermark INTEGER NOT NULL DEFAULT 0);
|
|
169
|
+
CREATE TABLE IF NOT EXISTS certificates (
|
|
170
|
+
fingerprint TEXT PRIMARY KEY, identity TEXT NOT NULL, expires_at INTEGER NOT NULL,
|
|
171
|
+
state TEXT NOT NULL DEFAULT 'active' CHECK(state IN ('active','revoked')));`);
|
|
172
|
+
} catch (error) {
|
|
173
|
+
this.db.close();
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
db;
|
|
178
|
+
secrets;
|
|
179
|
+
closed = false;
|
|
180
|
+
transaction(operation) {
|
|
181
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
182
|
+
try {
|
|
183
|
+
const result = operation();
|
|
184
|
+
this.db.exec("COMMIT");
|
|
185
|
+
return result;
|
|
186
|
+
} catch (error) {
|
|
187
|
+
this.db.exec("ROLLBACK");
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
provision(identity3, key) {
|
|
192
|
+
const text = identityText(identity3);
|
|
193
|
+
if (!(key instanceof Uint8Array) || key.byteLength !== 32) throw new Error("KEY_SERVICE_INVALID_KEY");
|
|
194
|
+
this.transaction(() => {
|
|
195
|
+
if (this.db.prepare("SELECT key_id FROM seat_keys WHERE key_id=?").get(identity3.keyId))
|
|
196
|
+
throw new Error("KEY_SERVICE_KEY_EXISTS");
|
|
197
|
+
const filename = `${randomUUID()}.key`, path2 = join2(this.secrets, filename);
|
|
198
|
+
assertPrivateStat(lstatSync2(this.secrets), true);
|
|
199
|
+
const fd = openSync2(path2, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384);
|
|
200
|
+
try {
|
|
201
|
+
let written = 0;
|
|
202
|
+
while (written < key.byteLength) written += writeSync2(fd, key, written, key.byteLength - written);
|
|
203
|
+
fsyncSync2(fd);
|
|
204
|
+
} catch (error) {
|
|
205
|
+
closeSync2(fd);
|
|
206
|
+
unlinkSync2(path2);
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
closeSync2(fd);
|
|
210
|
+
if (process.platform !== "win32") {
|
|
211
|
+
const dir = openSync2(this.secrets, constants2.O_RDONLY);
|
|
212
|
+
try {
|
|
213
|
+
fsyncSync2(dir);
|
|
214
|
+
} finally {
|
|
215
|
+
closeSync2(dir);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
try {
|
|
219
|
+
this.db.prepare("INSERT INTO seat_keys(key_id,identity,secret_file,state) VALUES(?,?,?,'active')").run(identity3.keyId, text, filename);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
unlinkSync2(path2);
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
authorizeCertificate(certFingerprint, identity3, expiresAt) {
|
|
227
|
+
fingerprint(certFingerprint);
|
|
228
|
+
const text = identityText(identity3);
|
|
229
|
+
if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now()) throw new Error("KEY_SERVICE_INVALID_EXPIRY");
|
|
230
|
+
this.transaction(() => {
|
|
231
|
+
const seat = this.db.prepare("SELECT identity,state FROM seat_keys WHERE key_id=?").get(identity3.keyId);
|
|
232
|
+
const previous = this.db.prepare("SELECT identity,state FROM certificates WHERE fingerprint=?").get(certFingerprint);
|
|
233
|
+
if (!seat || seat.identity !== text || seat.state !== "active" || previous && (previous.identity !== text || previous.state !== "active"))
|
|
234
|
+
throw new Error("KEY_SERVICE_DENIED");
|
|
235
|
+
this.db.prepare(`INSERT INTO certificates(fingerprint,identity,expires_at) VALUES(?,?,?)
|
|
236
|
+
ON CONFLICT(fingerprint) DO UPDATE SET expires_at=excluded.expires_at`).run(certFingerprint, text, expiresAt);
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
readKey(certFingerprint, identity3, minimumDeletionWatermark) {
|
|
240
|
+
fingerprint(certFingerprint);
|
|
241
|
+
const text = identityText(identity3);
|
|
242
|
+
watermark(minimumDeletionWatermark);
|
|
243
|
+
return this.transaction(() => {
|
|
244
|
+
const cert = this.db.prepare("SELECT identity,expires_at,state FROM certificates WHERE fingerprint=?").get(certFingerprint);
|
|
245
|
+
const seat = this.db.prepare("SELECT identity,state,secret_file,deletion_watermark FROM seat_keys WHERE key_id=?").get(identity3.keyId);
|
|
246
|
+
if (!cert || cert.state !== "active" || cert.identity !== text || Number(cert.expires_at) <= Date.now() || !seat || seat.identity !== text || seat.state !== "active")
|
|
247
|
+
throw new Error("KEY_SERVICE_DENIED");
|
|
248
|
+
const current = Number(seat.deletion_watermark);
|
|
249
|
+
watermark(current);
|
|
250
|
+
if (current < minimumDeletionWatermark) throw new Error("KEY_SERVICE_WATERMARK_BEHIND");
|
|
251
|
+
if (typeof seat.secret_file !== "string" || !/^[a-f0-9-]{36}\.key$/.test(seat.secret_file))
|
|
252
|
+
throw new Error("KEY_SERVICE_INVALID_KEY_FILE");
|
|
253
|
+
assertPrivateStat(lstatSync2(this.secrets), true);
|
|
254
|
+
const key = readPrivateFile(join2(this.secrets, seat.secret_file), 32);
|
|
255
|
+
if (key.length !== 32) {
|
|
256
|
+
key.fill(0);
|
|
257
|
+
throw new Error("KEY_SERVICE_INVALID_KEY_FILE");
|
|
258
|
+
}
|
|
259
|
+
return { key, deletionWatermark: current };
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
advanceWatermark(keyId, value) {
|
|
263
|
+
watermark(value);
|
|
264
|
+
this.transaction(() => {
|
|
265
|
+
const row = this.db.prepare("SELECT deletion_watermark FROM seat_keys WHERE key_id=?").get(keyId);
|
|
266
|
+
if (!row) throw new Error("KEY_SERVICE_DENIED");
|
|
267
|
+
if (Number(row.deletion_watermark) > value) throw new Error("KEY_SERVICE_WATERMARK_ROLLBACK");
|
|
268
|
+
this.db.prepare("UPDATE seat_keys SET deletion_watermark=? WHERE key_id=?").run(value, keyId);
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
/** Host preflight accepts the original identity even after revocation, so
|
|
272
|
+
* durable exit retries can finish without reenrolling or replacing a key. */
|
|
273
|
+
assertIdentity(identity3) {
|
|
274
|
+
const text = identityText(identity3);
|
|
275
|
+
const row = this.db.prepare("SELECT identity FROM seat_keys WHERE key_id=?").get(identity3.keyId);
|
|
276
|
+
if (!row || row.identity !== text) throw new Error("KEY_SERVICE_DENIED");
|
|
277
|
+
}
|
|
278
|
+
revoke(identity3) {
|
|
279
|
+
this.transaction(() => {
|
|
280
|
+
this.assertIdentity(identity3);
|
|
281
|
+
this.db.prepare("UPDATE seat_keys SET state='revoked' WHERE key_id=? AND identity=?").run(identity3.keyId, identityText(identity3));
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
/** Owner management only. Keep the revoked identity tombstone so a retry or
|
|
285
|
+
* old key ID cannot provision a replacement after its secret is removed. */
|
|
286
|
+
destroy(identity3) {
|
|
287
|
+
const text = identityText(identity3);
|
|
288
|
+
const filename = this.transaction(() => {
|
|
289
|
+
const row = this.db.prepare("SELECT identity,secret_file FROM seat_keys WHERE key_id=?").get(identity3.keyId);
|
|
290
|
+
if (!row || row.identity !== text || !/^[-a-f0-9]{36}\.key$/.test(String(row.secret_file))) throw new Error("KEY_SERVICE_DENIED");
|
|
291
|
+
this.db.prepare("UPDATE seat_keys SET state='revoked' WHERE key_id=?").run(identity3.keyId);
|
|
292
|
+
this.db.prepare("UPDATE certificates SET state='revoked' WHERE identity=?").run(text);
|
|
293
|
+
return String(row.secret_file);
|
|
294
|
+
});
|
|
295
|
+
const file = join2(this.secrets, filename);
|
|
296
|
+
try {
|
|
297
|
+
assertPrivateStat(lstatSync2(file), false);
|
|
298
|
+
unlinkSync2(file);
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (error.code !== "ENOENT") throw error;
|
|
301
|
+
}
|
|
302
|
+
if (process.platform !== "win32") {
|
|
303
|
+
const fd = openSync2(this.secrets, constants2.O_RDONLY);
|
|
304
|
+
try {
|
|
305
|
+
fsyncSync2(fd);
|
|
306
|
+
} finally {
|
|
307
|
+
closeSync2(fd);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return { destroyed: true };
|
|
311
|
+
}
|
|
312
|
+
revokeCertificate(certFingerprint) {
|
|
313
|
+
fingerprint(certFingerprint);
|
|
314
|
+
const result = this.db.prepare("UPDATE certificates SET state='revoked' WHERE fingerprint=?").run(certFingerprint);
|
|
315
|
+
if (result.changes !== 1) throw new Error("KEY_SERVICE_DENIED");
|
|
316
|
+
}
|
|
317
|
+
status() {
|
|
318
|
+
return this.db.prepare("SELECT key_id,state,deletion_watermark FROM seat_keys ORDER BY key_id").all().map((row) => ({ ...row }));
|
|
319
|
+
}
|
|
320
|
+
close() {
|
|
321
|
+
if (!this.closed) {
|
|
322
|
+
this.db.close();
|
|
323
|
+
this.closed = true;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
// src/continuity/retirement.ts
|
|
329
|
+
var identity = (value) => JSON.stringify([value.tenantId, value.companionId, value.seatId]);
|
|
330
|
+
var sha = (value) => createHash("sha256").update(value).digest("hex");
|
|
331
|
+
var LocalSeatResource = class {
|
|
332
|
+
constructor(path2, identity3) {
|
|
333
|
+
this.path = path2;
|
|
334
|
+
this.identity = identity3;
|
|
335
|
+
if (!isAbsolute(path2) || resolve2(path2) !== path2 || path2.split("/").filter(Boolean).length < 3) throw new Error("TRAVEL_RETIREMENT_PATH");
|
|
336
|
+
this.id = "directory-" + sha(path2);
|
|
337
|
+
}
|
|
338
|
+
id;
|
|
339
|
+
check() {
|
|
340
|
+
if (!existsSync(this.path)) return false;
|
|
341
|
+
const stat = lstatSync3(this.path);
|
|
342
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync2(this.path) !== this.path || process.platform !== "win32" && stat.uid !== process.getuid()) throw new Error("TRAVEL_RETIREMENT_PATH");
|
|
343
|
+
if (identity(JSON.parse(readPrivateFile(join3(this.path, ".travel-seat-resource.json"), 65536).toString())) !== identity(this.identity)) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
async inventory() {
|
|
347
|
+
return this.inventoryNow();
|
|
348
|
+
}
|
|
349
|
+
inventoryNow() {
|
|
350
|
+
if (!this.check()) return [];
|
|
351
|
+
const result = [];
|
|
352
|
+
const visit = (directory) => {
|
|
353
|
+
for (const item of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
354
|
+
const path2 = join3(directory, item.name), version = relative(this.path, path2);
|
|
355
|
+
if (item.isSymbolicLink()) result.push({ version, digest: sha(readlinkSync(path2)) });
|
|
356
|
+
else if (item.isDirectory()) visit(path2);
|
|
357
|
+
else if (item.isFile()) {
|
|
358
|
+
if (item.name === ".travel-seat-resource.json" && identity(JSON.parse(readPrivateFile(path2, 65536).toString())) !== identity(this.identity)) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
|
|
359
|
+
result.push({ version, digest: sha(readFileSync3(path2)) });
|
|
360
|
+
} else throw new Error("TRAVEL_RETIREMENT_PATH");
|
|
361
|
+
if (result.length > 1e6) throw new Error("TRAVEL_RETIREMENT_BUDGET");
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
visit(this.path);
|
|
365
|
+
return result;
|
|
366
|
+
}
|
|
367
|
+
async purge(expectedInventory) {
|
|
368
|
+
const allowed = new Map(expectedInventory.map((item) => [item.version, item.digest]));
|
|
369
|
+
if (this.inventoryNow().some((item) => allowed.get(item.version) !== item.digest)) throw new Error("TRAVEL_RETIREMENT_RESOURCE_CHANGED");
|
|
370
|
+
if (this.check()) rmSync(this.path, { recursive: true });
|
|
371
|
+
if (existsSync(this.path)) throw new Error("TRAVEL_RETIREMENT_PENDING");
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
var TravelRetirement = class {
|
|
375
|
+
constructor(options) {
|
|
376
|
+
this.options = options;
|
|
377
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(options.jobId) || options.resources.some((resource) => identity(resource.identity) !== identity(options.identity)) || new Set(options.resources.map((resource) => resource.id)).size !== options.resources.length) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
|
|
378
|
+
preparePrivateDirectory(options.directory);
|
|
379
|
+
const ownerFile = join3(options.directory, "owner.sqlite");
|
|
380
|
+
preparePrivateDatabase(ownerFile);
|
|
381
|
+
this.owner = new DatabaseSync3(ownerFile);
|
|
382
|
+
try {
|
|
383
|
+
this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER);BEGIN IMMEDIATE");
|
|
384
|
+
} catch (error) {
|
|
385
|
+
this.owner.close();
|
|
386
|
+
throw new Error("TRAVEL_RETIREMENT_BUSY", { cause: error });
|
|
387
|
+
}
|
|
388
|
+
const file = join3(options.directory, "retirement.sqlite");
|
|
389
|
+
preparePrivateDatabase(file);
|
|
390
|
+
this.db = new DatabaseSync3(file);
|
|
391
|
+
try {
|
|
392
|
+
this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS job(id TEXT PRIMARY KEY,binding TEXT NOT NULL,state TEXT NOT NULL,stopped INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS resources(id TEXT PRIMARY KEY,inventory TEXT,state TEXT NOT NULL)");
|
|
393
|
+
const binding = JSON.stringify([identity(options.identity), options.resources.map((resource) => [resource.id, resource.path ?? null]).sort(), options.accountOwnerRequestedKeyDestruction === true]);
|
|
394
|
+
const prior = this.db.prepare("SELECT * FROM job").all();
|
|
395
|
+
if (prior.length && (prior.length !== 1 || prior[0].id !== options.jobId || prior[0].binding !== binding)) throw new Error("TRAVEL_RETIREMENT_ID_COLLISION");
|
|
396
|
+
if (!prior.length) this.db.prepare("INSERT INTO job(id,binding,state) VALUES(?,?,'RETIRING')").run(options.jobId, binding);
|
|
397
|
+
} catch (error) {
|
|
398
|
+
this.db.close();
|
|
399
|
+
this.owner.close();
|
|
400
|
+
throw error;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
db;
|
|
404
|
+
owner;
|
|
405
|
+
active;
|
|
406
|
+
status() {
|
|
407
|
+
const row = this.db.prepare("SELECT id,state,stopped FROM job").get();
|
|
408
|
+
return { jobId: String(row.id), state: String(row.state), nodesStopped: row.stopped === 1 };
|
|
409
|
+
}
|
|
410
|
+
run() {
|
|
411
|
+
return this.active ??= this.execute().finally(() => {
|
|
412
|
+
this.active = void 0;
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
async execute() {
|
|
416
|
+
let status = this.status();
|
|
417
|
+
if (status.state === "PURGED") return status;
|
|
418
|
+
await this.options.retire();
|
|
419
|
+
if (!status.nodesStopped) {
|
|
420
|
+
await this.options.stopNodes();
|
|
421
|
+
this.db.prepare("UPDATE job SET stopped=1").run();
|
|
422
|
+
}
|
|
423
|
+
if (status.state === "RETIRING") {
|
|
424
|
+
this.db.prepare("UPDATE job SET state='RECOVERY_ONLY'").run();
|
|
425
|
+
status = this.status();
|
|
426
|
+
}
|
|
427
|
+
const verifyRecovery = async (required = false) => {
|
|
428
|
+
const recovered = await this.options.verifyLocalRecovery();
|
|
429
|
+
if (!recovered) {
|
|
430
|
+
if (required) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
if (recovered.loaded !== true || identity(recovered.identity) !== identity(this.options.identity) || !isAbsolute(recovered.ordinaryStateDir) || ![recovered.checkpointDigest, recovered.channelReceiptsDigest].every((value) => /^[a-f0-9]{64}$/.test(value))) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
|
|
434
|
+
for (const resource of this.options.resources) {
|
|
435
|
+
if (resource.path) {
|
|
436
|
+
const local = resolve2(recovered.ordinaryStateDir), path2 = resolve2(resource.path), journal = resolve2(this.options.directory);
|
|
437
|
+
if ([local, journal].some((p) => p === path2 || p.startsWith(path2 + "/") || path2.startsWith(p + "/"))) throw new Error("TRAVEL_RETIREMENT_LOCAL_OVERLAP");
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return recovered;
|
|
441
|
+
};
|
|
442
|
+
if (!await verifyRecovery()) return this.status();
|
|
443
|
+
if (this.status().state === "RECOVERY_ONLY") this.db.prepare("UPDATE job SET state='PURGING'").run();
|
|
444
|
+
if (this.status().state === "PURGING") {
|
|
445
|
+
for (const resource of this.options.resources) {
|
|
446
|
+
const current = await resource.inventory();
|
|
447
|
+
let row = this.db.prepare("SELECT * FROM resources WHERE id=?").get(resource.id);
|
|
448
|
+
if (row?.state === "PURGED") {
|
|
449
|
+
if (current.length) throw new Error("TRAVEL_RETIREMENT_RESOURCE_REAPPEARED");
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
if (!row) {
|
|
453
|
+
this.db.prepare("INSERT INTO resources VALUES(?,?,'PURGING')").run(resource.id, JSON.stringify(current));
|
|
454
|
+
row = this.db.prepare("SELECT * FROM resources WHERE id=?").get(resource.id);
|
|
455
|
+
}
|
|
456
|
+
const original = JSON.parse(String(row.inventory));
|
|
457
|
+
if (current.some((item) => !original.some((known) => item.version === known.version && item.digest === known.digest))) throw new Error("TRAVEL_RETIREMENT_RESOURCE_CHANGED");
|
|
458
|
+
await verifyRecovery(true);
|
|
459
|
+
await resource.purge(original);
|
|
460
|
+
if ((await resource.inventory()).length) throw new Error("TRAVEL_RETIREMENT_PROVIDER_PENDING");
|
|
461
|
+
this.db.prepare("UPDATE resources SET state='PURGED' WHERE id=?").run(resource.id);
|
|
462
|
+
}
|
|
463
|
+
this.db.prepare("UPDATE job SET state='KEY_DELETION_PENDING'").run();
|
|
464
|
+
}
|
|
465
|
+
await verifyRecovery(true);
|
|
466
|
+
const revoked = await this.options.revokeKey();
|
|
467
|
+
if (revoked?.revoked !== true) throw new Error("TRAVEL_RETIREMENT_KEY_PENDING");
|
|
468
|
+
if (this.options.accountOwnerRequestedKeyDestruction === true) {
|
|
469
|
+
await verifyRecovery(true);
|
|
470
|
+
if (!this.options.destroyKey || (await this.options.destroyKey()).destroyed !== true) throw new Error("TRAVEL_RETIREMENT_KEY_PENDING");
|
|
471
|
+
}
|
|
472
|
+
this.db.prepare("UPDATE job SET state='PURGED'").run();
|
|
473
|
+
return this.status();
|
|
474
|
+
}
|
|
475
|
+
close() {
|
|
476
|
+
if (this.active) throw new Error("TRAVEL_RETIREMENT_BUSY");
|
|
477
|
+
this.db.close();
|
|
478
|
+
this.owner.close();
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
// src/continuity/local-exit.ts
|
|
483
|
+
import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync5, readdirSync as readdirSync3, realpathSync as realpathSync4, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
|
|
484
|
+
import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
|
|
485
|
+
import { isAbsolute as isAbsolute2, join as join6, dirname as dirname3, resolve as resolve3 } from "node:path";
|
|
486
|
+
import { createHash as createHash4, verify as verify2 } from "node:crypto";
|
|
487
|
+
|
|
488
|
+
// src/continuity/runtime-lock.ts
|
|
489
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
490
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
491
|
+
import { closeSync as closeSync3, lstatSync as lstatSync4, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
|
|
492
|
+
import { join as join4 } from "node:path";
|
|
493
|
+
import { createRequire } from "node:module";
|
|
494
|
+
var sqlite;
|
|
495
|
+
function openSQLite(file, options = {}) {
|
|
496
|
+
return new (sqlite ??= createRequire(import.meta.url)("node:sqlite")).DatabaseSync(file, options);
|
|
497
|
+
}
|
|
498
|
+
var bootId = randomUUID2();
|
|
499
|
+
var checkpointHandles = /* @__PURE__ */ new Set();
|
|
500
|
+
var recoveryWriterLocks = new AsyncLocalStorage();
|
|
501
|
+
function openControl(stateDir, create = true, busyTimeoutMs = 0) {
|
|
502
|
+
if (create) mkdirSync3(stateDir, { recursive: true });
|
|
503
|
+
const state = realpathSync3(stateDir);
|
|
504
|
+
if (process.platform !== "win32" && lstatSync4(state).uid !== process.getuid()) throw new Error("CONTROL_OWNER_MISMATCH: run travel as the engine data owner, without sudo");
|
|
505
|
+
const directory = join4(state, ".continuity");
|
|
506
|
+
if (create) mkdirSync3(directory, { recursive: true, mode: 448 });
|
|
507
|
+
if (lstatSync4(directory).isSymbolicLink()) throw new Error("UNSAFE_CONTROL_DIRECTORY");
|
|
508
|
+
assertControlPermissions(directory);
|
|
509
|
+
const file = join4(directory, "runtime.sqlite");
|
|
510
|
+
if (create) {
|
|
511
|
+
try {
|
|
512
|
+
closeSync3(openSync3(file, "wx", 384));
|
|
513
|
+
} catch (error) {
|
|
514
|
+
if (error.code !== "EEXIST") throw error;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
assertControlPermissions(file);
|
|
518
|
+
for (const name of [file, file + "-journal", file + "-wal", file + "-shm"]) {
|
|
519
|
+
try {
|
|
520
|
+
if (!lstatSync4(name).isFile() || lstatSync4(name).isSymbolicLink()) throw new Error("UNSAFE_CONTROL_FILE");
|
|
521
|
+
} catch (error) {
|
|
522
|
+
if (error.code !== "ENOENT") throw error;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
const db = openSQLite(file);
|
|
526
|
+
try {
|
|
527
|
+
db.exec(`PRAGMA busy_timeout=${busyTimeoutMs}; PRAGMA synchronous=FULL;
|
|
528
|
+
CREATE TABLE IF NOT EXISTS writers (
|
|
529
|
+
id TEXT PRIMARY KEY, pid INTEGER NOT NULL, boot_id TEXT NOT NULL,
|
|
530
|
+
kind TEXT NOT NULL, registered_at TEXT NOT NULL
|
|
531
|
+
)`);
|
|
532
|
+
return db;
|
|
533
|
+
} catch (error) {
|
|
534
|
+
db.close();
|
|
535
|
+
throw normalize(error);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
function assertControlPermissions(file) {
|
|
539
|
+
const info = lstatSync4(file);
|
|
540
|
+
if (process.platform !== "win32" && (info.uid !== process.getuid() || info.mode & 63))
|
|
541
|
+
throw new Error("CONTROL_PERMISSIONS: use the engine data owner; repair .continuity ownership and private permissions while stopped");
|
|
542
|
+
}
|
|
543
|
+
function normalize(error) {
|
|
544
|
+
return /database is locked|database table is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(String(error)) ? new Error("CHECKPOINT_BUSY", { cause: error }) : error;
|
|
545
|
+
}
|
|
546
|
+
function assertDead(pid, kind = "registered") {
|
|
547
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error(`WRITER_STATE_UNKNOWN: ${kind}; use travel status`);
|
|
548
|
+
try {
|
|
549
|
+
process.kill(pid, 0);
|
|
550
|
+
} catch (error) {
|
|
551
|
+
if (error.code === "ESRCH") return;
|
|
552
|
+
throw new Error(`WRITER_STATE_UNKNOWN: ${kind}, pid=${pid}; use travel status`, { cause: error });
|
|
553
|
+
}
|
|
554
|
+
throw new Error(`WRITER_ACTIVE: ${kind}, pid=${pid}; use travel status`);
|
|
555
|
+
}
|
|
556
|
+
async function withCheckpointLock(stateDir, operation) {
|
|
557
|
+
const db = openControl(stateDir);
|
|
558
|
+
try {
|
|
559
|
+
db.exec("BEGIN IMMEDIATE");
|
|
560
|
+
checkpointHandles.add(db);
|
|
561
|
+
for (const row of db.prepare("SELECT pid,kind FROM writers").all()) assertDead(Number(row.pid), String(row.kind));
|
|
562
|
+
for (const name of [".engine.pid", ".bg-worker.pid"]) {
|
|
563
|
+
let value;
|
|
564
|
+
try {
|
|
565
|
+
value = readFileSync4(join4(stateDir, name), "utf8").trim();
|
|
566
|
+
} catch (error) {
|
|
567
|
+
if (error.code === "ENOENT") continue;
|
|
568
|
+
throw new Error("WRITER_STATE_UNKNOWN", { cause: error });
|
|
569
|
+
}
|
|
570
|
+
if (!/^[1-9][0-9]*$/.test(value)) throw new Error(`WRITER_STATE_UNKNOWN: ${name}; use travel status`);
|
|
571
|
+
assertDead(Number(value), name);
|
|
572
|
+
}
|
|
573
|
+
db.exec("DELETE FROM writers");
|
|
574
|
+
const result = await operation();
|
|
575
|
+
db.exec("COMMIT");
|
|
576
|
+
return result;
|
|
577
|
+
} catch (error) {
|
|
578
|
+
throw normalize(error);
|
|
579
|
+
} finally {
|
|
580
|
+
checkpointHandles.delete(db);
|
|
581
|
+
db.close();
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// src/continuity/local-dedupe.ts
|
|
586
|
+
import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
|
|
587
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
588
|
+
import { dirname as dirname2 } from "node:path";
|
|
589
|
+
var sha2 = (value) => createHash2("sha256").update(value).digest("hex");
|
|
590
|
+
var hash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
591
|
+
var PlatformReceiptStore = class {
|
|
592
|
+
db;
|
|
593
|
+
constructor(file, namespace) {
|
|
594
|
+
if (!namespace || namespace.length > 1024) throw new Error("PLATFORM_RECEIPT_IDENTITY");
|
|
595
|
+
preparePrivateDirectory(dirname2(file));
|
|
596
|
+
preparePrivateDatabase(file);
|
|
597
|
+
this.db = new DatabaseSync4(file);
|
|
598
|
+
try {
|
|
599
|
+
this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS binding(namespace TEXT NOT NULL);CREATE TABLE IF NOT EXISTS inputs(id TEXT PRIMARY KEY,state TEXT NOT NULL);CREATE TABLE IF NOT EXISTS effects(id TEXT PRIMARY KEY,body TEXT NOT NULL);CREATE TABLE IF NOT EXISTS imports(digest TEXT PRIMARY KEY,identity TEXT NOT NULL)");
|
|
600
|
+
const binding = this.db.prepare("SELECT namespace FROM binding").all();
|
|
601
|
+
if (!binding.length) this.db.prepare("INSERT INTO binding VALUES(?)").run(namespace);
|
|
602
|
+
else if (binding.length !== 1 || binding[0].namespace !== namespace) throw new Error("PLATFORM_RECEIPT_IDENTITY");
|
|
603
|
+
} catch (error) {
|
|
604
|
+
this.db.close();
|
|
605
|
+
throw error;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
has(platformId) {
|
|
609
|
+
return !!this.db.prepare("SELECT 1 FROM inputs WHERE id=?").get(sha2(platformId));
|
|
610
|
+
}
|
|
611
|
+
remember(platformId) {
|
|
612
|
+
if (!platformId || platformId.length > 512) throw new Error("PLATFORM_RECEIPT_ID");
|
|
613
|
+
this.db.prepare("INSERT OR IGNORE INTO inputs VALUES(?,'SEEN')").run(sha2(platformId));
|
|
614
|
+
}
|
|
615
|
+
effect(id) {
|
|
616
|
+
const row = this.db.prepare("SELECT body FROM effects WHERE id=?").get(id);
|
|
617
|
+
return row ? JSON.parse(String(row.body)) : void 0;
|
|
618
|
+
}
|
|
619
|
+
importTravelReceipt(receipt) {
|
|
620
|
+
const { digest, ...body } = receipt;
|
|
621
|
+
if (receipt.format !== "engine7-travel-exit-dedupe-v1" || sha2(JSON.stringify(body)) !== digest || !hash(receipt.checkpointDigest) || !Number.isSafeInteger(receipt.deletionWatermark) || receipt.deletionWatermark < 0 || !Array.isArray(receipt.inputs) || !Array.isArray(receipt.effects)) throw new Error("PLATFORM_RECEIPT_INVALID");
|
|
622
|
+
const identity3 = JSON.stringify(receipt.identity);
|
|
623
|
+
if (this.db.prepare("SELECT 1 FROM imports WHERE identity<>? LIMIT 1").get(identity3)) throw new Error("PLATFORM_RECEIPT_IDENTITY");
|
|
624
|
+
for (const input of receipt.inputs) {
|
|
625
|
+
if (["DONE", "CANCELLED"].includes(String(input.state))) continue;
|
|
626
|
+
const effects = receipt.effects.filter((effect) => effect.eventId === input.id);
|
|
627
|
+
if (!effects.length || effects.some((effect) => !["SENT", "UNKNOWN", "CANCELLED"].includes(String(effect.state)))) throw new Error("PLATFORM_RECEIPT_PENDING");
|
|
628
|
+
}
|
|
629
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
630
|
+
try {
|
|
631
|
+
for (const input of receipt.inputs) {
|
|
632
|
+
if (!hash(input.platformIdHash) || !hash(input.id)) throw new Error("PLATFORM_RECEIPT_INVALID");
|
|
633
|
+
this.db.prepare("INSERT OR IGNORE INTO inputs VALUES(?,?)").run(input.platformIdHash, String(input.state));
|
|
634
|
+
}
|
|
635
|
+
for (const effect of receipt.effects) {
|
|
636
|
+
if (!hash(effect.id) || !hash(effect.eventId) || !["PRODUCED", "INTENT", "SENT", "FAILED_NOT_SENT", "UNKNOWN", "CANCELLED"].includes(String(effect.state))) throw new Error("PLATFORM_RECEIPT_INVALID");
|
|
637
|
+
const prior = this.effect(String(effect.id)), serialized = JSON.stringify(effect);
|
|
638
|
+
if (prior && JSON.stringify(prior) !== serialized) throw new Error("PLATFORM_RECEIPT_COLLISION");
|
|
639
|
+
this.db.prepare("INSERT OR IGNORE INTO effects VALUES(?,?)").run(String(effect.id), serialized);
|
|
640
|
+
}
|
|
641
|
+
this.db.prepare("INSERT OR IGNORE INTO imports VALUES(?,?)").run(digest, identity3);
|
|
642
|
+
this.db.exec("COMMIT");
|
|
643
|
+
} catch (error) {
|
|
644
|
+
this.db.exec("ROLLBACK");
|
|
645
|
+
throw error;
|
|
646
|
+
}
|
|
647
|
+
return { digest, identity: receipt.identity, loaded: true, unknownEffects: receipt.effects.filter((effect) => effect.state === "UNKNOWN").length };
|
|
648
|
+
}
|
|
649
|
+
close() {
|
|
650
|
+
this.db.close();
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
|
|
654
|
+
// src/continuity/local-exit-proof.ts
|
|
655
|
+
import { createHash as createHash3, verify } from "node:crypto";
|
|
656
|
+
import { createReadStream, mkdirSync as mkdirSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
657
|
+
import { join as join5, relative as relative2 } from "node:path";
|
|
658
|
+
var hash2 = (value) => createHash3("sha256").update(value).digest("hex");
|
|
659
|
+
var equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
660
|
+
function copyLocalExitPath(source, path2) {
|
|
661
|
+
const name = relative2(source, path2).replaceAll("\\", "/");
|
|
662
|
+
return !/^(?:\.travel-|\.runtime-publication)|^(?:\.engine\.pid|\.bg-worker\.pid)$|(?:^|\/)\.continuity\/(?:travel-|runtime\.sqlite|(?:engine|data)-config\.json$|(?:mem7|calendar|proactive|session-events|legacy-memory-[^/]+|topics-vectors-[^/]+)-replication\.json$)/.test(name);
|
|
663
|
+
}
|
|
664
|
+
async function localExitFilesDigest(root, ordinary = false) {
|
|
665
|
+
const files = [];
|
|
666
|
+
const visit = async (directory) => {
|
|
667
|
+
for (const entry of readdirSync2(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
668
|
+
const file = join5(directory, entry.name);
|
|
669
|
+
if (ordinary ? relative2(root, file).replaceAll("\\", "/") === ".continuity/travel-exit-receipt.json" : !copyLocalExitPath(root, file)) continue;
|
|
670
|
+
if (entry.isSymbolicLink()) throw new Error("TRAVEL_EXIT_PATH");
|
|
671
|
+
if (entry.isDirectory()) {
|
|
672
|
+
await visit(file);
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
if (!entry.isFile() || files.length >= 1e6) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
676
|
+
const digest = createHash3("sha256");
|
|
677
|
+
for await (const chunk of createReadStream(file)) digest.update(chunk);
|
|
678
|
+
files.push({ path: relative2(root, file).replaceAll("\\", "/"), sha256: digest.digest("hex") });
|
|
679
|
+
}
|
|
680
|
+
};
|
|
681
|
+
await visit(root);
|
|
682
|
+
return hash2(JSON.stringify(files));
|
|
683
|
+
}
|
|
684
|
+
async function currentBinding(stateDir, authority, principal) {
|
|
685
|
+
const activation = JSON.parse(readPrivateFile(join5(stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString());
|
|
686
|
+
const permit = activation.permit, { signature, ...signed } = permit;
|
|
687
|
+
if (activation.format !== "engine7-runtime-activation-v1" || !verify(null, Buffer.from(JSON.stringify(signed)), authority.publicKey, Buffer.from(signature, "base64")) || permit.nodeId !== principal.nodeId || activation.nodeId !== principal.nodeId || principal.role !== "LOCAL" || ["tenantId", "companionId", "seatId"].some((field) => permit[field] !== principal[field] || activation.identity[field] !== permit[field])) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
688
|
+
const control = await authority.status(principal);
|
|
689
|
+
if (control.activeNodeId !== permit.nodeId || control.activeBootId !== permit.bootId || control.authorityBootId !== permit.authorityBootId || control.epoch !== permit.epoch || control.deletionWatermark !== permit.deletionWatermark) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
690
|
+
return {
|
|
691
|
+
nodeId: permit.nodeId,
|
|
692
|
+
bootId: permit.bootId,
|
|
693
|
+
authorityBootId: permit.authorityBootId,
|
|
694
|
+
epoch: permit.epoch,
|
|
695
|
+
checkpointDigest: control.checkpointDigest,
|
|
696
|
+
deletionWatermark: control.deletionWatermark
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
async function verifyStoppedLocalExitProof(options) {
|
|
700
|
+
let proof;
|
|
701
|
+
try {
|
|
702
|
+
proof = JSON.parse(readPrivateFile(join5(options.stateDir, ".continuity/travel-exit-source.json"), 65536).toString());
|
|
703
|
+
} catch {
|
|
704
|
+
throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
705
|
+
}
|
|
706
|
+
const { digest, ...body } = proof;
|
|
707
|
+
const binding = await currentBinding(options.stateDir, options.authority, options.principal);
|
|
708
|
+
if (proof.format !== "engine7-stopped-local-exit-v1" || digest !== hash2(JSON.stringify(body)) || proof.checkpointDigest !== options.checkpointDigest || Object.entries(binding).some(([key, value]) => proof[key] !== value) || proof.filesDigest !== await localExitFilesDigest(options.stateDir)) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
709
|
+
return { binding, filesDigest: String(proof.filesDigest), check: async () => {
|
|
710
|
+
if (!equal(binding, await currentBinding(options.stateDir, options.authority, options.principal)) || proof.filesDigest !== await localExitFilesDigest(options.stateDir)) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
711
|
+
} };
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// src/continuity/local-exit.ts
|
|
715
|
+
var identity2 = (value) => JSON.stringify([value.tenantId, value.companionId, value.seatId]);
|
|
716
|
+
var sha3 = (value) => createHash4("sha256").update(value).digest("hex");
|
|
717
|
+
function detachReplication(directory) {
|
|
718
|
+
for (const entry of readdirSync3(directory, { withFileTypes: true })) {
|
|
719
|
+
const file = join6(directory, entry.name);
|
|
720
|
+
if (entry.isSymbolicLink()) throw new Error("TRAVEL_EXIT_PATH");
|
|
721
|
+
if (entry.isDirectory()) {
|
|
722
|
+
detachReplication(file);
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
if (!entry.isFile()) throw new Error("TRAVEL_EXIT_PATH");
|
|
726
|
+
if (!/\.(?:db|sqlite)$/.test(entry.name)) continue;
|
|
727
|
+
const db = new DatabaseSync5(file);
|
|
728
|
+
try {
|
|
729
|
+
if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='e7_replication_control'").get()) continue;
|
|
730
|
+
db.exec("BEGIN IMMEDIATE");
|
|
731
|
+
try {
|
|
732
|
+
for (const row of db.prepare("SELECT name FROM sqlite_master WHERE type='trigger' AND name GLOB 'writer_guard_replication_*'").all()) db.exec('DROP TRIGGER "' + String(row.name).replaceAll('"', '""') + '"');
|
|
733
|
+
db.exec("DROP TABLE e7_replication_outbox;DROP TABLE e7_replication_inbox;DROP TABLE e7_replication_control;COMMIT");
|
|
734
|
+
} catch (error) {
|
|
735
|
+
db.exec("ROLLBACK");
|
|
736
|
+
throw error;
|
|
737
|
+
}
|
|
738
|
+
} finally {
|
|
739
|
+
db.close();
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
async function createOrdinaryLocalRecovery(options) {
|
|
744
|
+
const source = resolve3(options.stateDir), destination = resolve3(options.destination);
|
|
745
|
+
if (!isAbsolute2(options.destination) || source !== options.stateDir || destination !== options.destination || realpathSync4(source) !== source || destination === source || destination.startsWith(source + "/") || source.startsWith(destination + "/") || realpathSync4(dirname3(destination)) !== dirname3(destination)) throw new Error("TRAVEL_EXIT_PATH");
|
|
746
|
+
const activation = JSON.parse(readFileSync5(join6(source, ".travel-active.json"), "utf8")), permit = activation.permit, { signature, ...signed } = permit;
|
|
747
|
+
if (activation.format !== "engine7-runtime-activation-v1" || identity2(activation.identity) !== identity2(options.identity) || identity2(permit) !== identity2(options.identity) || permit.nodeId !== options.localNodeId || activation.nodeId !== options.localNodeId || !verify2(null, Buffer.from(JSON.stringify(signed)), options.publicKey, Buffer.from(signature, "base64")) || identity2(options.dedupeReceipt.identity) !== identity2(options.identity) || options.dedupeReceipt.checkpointDigest !== options.checkpointDigest || options.dedupeReceipt.deletionWatermark !== permit.deletionWatermark) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
748
|
+
return withCheckpointLock(source, async () => {
|
|
749
|
+
if (!options.authority || !options.principal || options.authority.publicKey !== options.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
750
|
+
const proof = await verifyStoppedLocalExitProof({ ...options, stateDir: source });
|
|
751
|
+
if (existsSync2(destination)) {
|
|
752
|
+
if (realpathSync4(destination) !== destination) throw new Error("TRAVEL_EXIT_PATH");
|
|
753
|
+
let receipt;
|
|
754
|
+
try {
|
|
755
|
+
receipt = JSON.parse(readPrivateFile(join6(destination, ".continuity/travel-exit-receipt.json"), 65536).toString());
|
|
756
|
+
} catch {
|
|
757
|
+
throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
758
|
+
}
|
|
759
|
+
const { digest, ...body } = receipt, generation = receipt.sourceGeneration;
|
|
760
|
+
if (receipt.format !== "engine7-ordinary-local-recovery-v2" || digest !== sha3(JSON.stringify(body)) || identity2(receipt.identity) !== identity2(options.identity) || receipt.loaded !== true || receipt.ordinaryStateDir !== destination || receipt.checkpointDigest !== proof.binding.checkpointDigest || receipt.deletionWatermark !== proof.binding.deletionWatermark || receipt.sourceFilesDigest !== proof.filesDigest || receipt.channelReceiptsDigest !== options.dedupeReceipt.digest || !generation || generation.nodeId !== proof.binding.nodeId || generation.bootId !== proof.binding.bootId || generation.authorityBootId !== proof.binding.authorityBootId || generation.epoch !== proof.binding.epoch || receipt.ordinaryFilesDigest !== await localExitFilesDigest(destination, true)) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
761
|
+
await proof.check();
|
|
762
|
+
return receipt;
|
|
763
|
+
}
|
|
764
|
+
try {
|
|
765
|
+
mkdirSync5(destination, { mode: 448 });
|
|
766
|
+
cpSync(source, destination, { recursive: true, force: false, errorOnExist: true, filter: (path2) => copyLocalExitPath(source, path2) });
|
|
767
|
+
detachReplication(destination);
|
|
768
|
+
const store = new PlatformReceiptStore(join6(destination, ".continuity/feishu-receipts.sqlite"), options.platformNamespace);
|
|
769
|
+
try {
|
|
770
|
+
store.importTravelReceipt(options.dedupeReceipt);
|
|
771
|
+
} finally {
|
|
772
|
+
store.close();
|
|
773
|
+
}
|
|
774
|
+
const receipt = {
|
|
775
|
+
format: "engine7-ordinary-local-recovery-v2",
|
|
776
|
+
identity: options.identity,
|
|
777
|
+
loaded: true,
|
|
778
|
+
checkpointDigest: proof.binding.checkpointDigest,
|
|
779
|
+
deletionWatermark: proof.binding.deletionWatermark,
|
|
780
|
+
sourceFilesDigest: proof.filesDigest,
|
|
781
|
+
ordinaryStateDir: destination,
|
|
782
|
+
channelReceiptsDigest: options.dedupeReceipt.digest,
|
|
783
|
+
sourceGeneration: { nodeId: proof.binding.nodeId, bootId: proof.binding.bootId, authorityBootId: proof.binding.authorityBootId, epoch: proof.binding.epoch }
|
|
784
|
+
};
|
|
785
|
+
await proof.check();
|
|
786
|
+
const body = { ...receipt, ordinaryFilesDigest: await localExitFilesDigest(destination, true) };
|
|
787
|
+
const result = { ...body, digest: sha3(JSON.stringify(body)) };
|
|
788
|
+
writeFileSync3(join6(destination, ".continuity/travel-exit-receipt.json"), JSON.stringify(result), { mode: 384, flag: "wx", flush: true });
|
|
789
|
+
return result;
|
|
790
|
+
} catch (error) {
|
|
791
|
+
if (existsSync2(destination)) rmSync2(destination, { recursive: true });
|
|
792
|
+
throw error;
|
|
793
|
+
}
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// src/continuity/authority-client.ts
|
|
798
|
+
import { Agent, request } from "node:https";
|
|
799
|
+
var publicErrors = /* @__PURE__ */ new Set([
|
|
800
|
+
"TRAVEL_HEARTBEAT_REPLAY",
|
|
801
|
+
"TRAVEL_BOOT_MISMATCH",
|
|
802
|
+
"TRAVEL_BOOT_RETIRED",
|
|
803
|
+
"TRAVEL_LEASE_EXPIRED",
|
|
804
|
+
"TRAVEL_STALE_PERMIT",
|
|
805
|
+
"TRAVEL_DELETION_BARRIER",
|
|
806
|
+
"TRAVEL_BOOT_REQUIRED",
|
|
807
|
+
"TRAVEL_NOT_READY",
|
|
808
|
+
"TRAVEL_READINESS_BARRIER",
|
|
809
|
+
"TRAVEL_LEASE_HELD",
|
|
810
|
+
"TRAVEL_INVALID_PERMIT",
|
|
811
|
+
"TRAVEL_HANDOFF_STATE",
|
|
812
|
+
"TRAVEL_HANDOFF_FROZEN",
|
|
813
|
+
"TRAVEL_HANDOFF_NOT_SAFE",
|
|
814
|
+
"TRAVEL_HANDOFF_NOT_FOUND",
|
|
815
|
+
"TRAVEL_HANDOFF_COMMITTED",
|
|
816
|
+
"TRAVEL_TARGET_OFFLINE",
|
|
817
|
+
"TRAVEL_ID_COLLISION",
|
|
818
|
+
"TRAVEL_ANCESTRY_GAP"
|
|
819
|
+
]);
|
|
820
|
+
var readActions = /* @__PURE__ */ new Set(["status", "identity", "deletionsSince", "verifyAncestor", "assertPermit", "handoffStatus", "retirementStatus", "recoveryBranchStatus"]);
|
|
821
|
+
var TravelReportClient = class {
|
|
822
|
+
constructor(options) {
|
|
823
|
+
this.options = options;
|
|
824
|
+
try {
|
|
825
|
+
this.url = new URL(options.url);
|
|
826
|
+
} catch {
|
|
827
|
+
throw new Error("TRAVEL_CONTROL_TLS_REQUIRED");
|
|
828
|
+
}
|
|
829
|
+
if (this.url.protocol !== "https:" || !["/api/engine7/report", "/travel/control/v1", "/travel/manage/v1"].includes(this.url.pathname) || this.url.username || this.url.password || this.url.search || this.url.hash) throw new Error("TRAVEL_CONTROL_TLS_REQUIRED");
|
|
830
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(options.nodeId) || !/^e7t_[a-f0-9]{64}$/.test(options.credential) || !!options.cert !== !!options.key) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
|
|
831
|
+
this.timeout = options.timeoutMs ?? 8e3;
|
|
832
|
+
if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
|
|
833
|
+
this.key = options.key ? Buffer.from(options.key) : void 0;
|
|
834
|
+
this.agent = new Agent({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 1 });
|
|
835
|
+
}
|
|
836
|
+
agent;
|
|
837
|
+
key;
|
|
838
|
+
url;
|
|
839
|
+
timeout;
|
|
840
|
+
pending = /* @__PURE__ */ new Set();
|
|
841
|
+
closed = false;
|
|
842
|
+
call(input) {
|
|
843
|
+
return this.attempt(input);
|
|
844
|
+
}
|
|
845
|
+
attempt(input, retryStale = true, deadline = performance.now() + this.timeout, wireBody) {
|
|
846
|
+
if (this.closed) return Promise.reject(new Error("TRAVEL_CONTROL_CLOSED"));
|
|
847
|
+
if (this.pending.size) return Promise.reject(new Error("TRAVEL_CONTROL_BUSY"));
|
|
848
|
+
const body = wireBody ?? Buffer.from(JSON.stringify({ travel: { version: 1, ...input } }));
|
|
849
|
+
if (body.length > (input?.action === "recordRecoveryBranch" ? 40 * 1024 * 1024 : 65536)) return Promise.reject(new Error("TRAVEL_CONTROL_INVALID_REQUEST"));
|
|
850
|
+
const unavailable = () => new Error(this.closed ? "TRAVEL_CONTROL_CLOSED" : "TRAVEL_CONTROL_UNAVAILABLE");
|
|
851
|
+
const remaining = deadline - performance.now();
|
|
852
|
+
if (remaining <= 0) return Promise.reject(unavailable());
|
|
853
|
+
return new Promise((resolve5, reject) => {
|
|
854
|
+
let complete = false, responseStarted = false;
|
|
855
|
+
const finish = (error, value) => {
|
|
856
|
+
if (complete) return;
|
|
857
|
+
complete = true;
|
|
858
|
+
clearTimeout(timer);
|
|
859
|
+
this.pending.delete(req);
|
|
860
|
+
if (error) reject(error);
|
|
861
|
+
else resolve5(value);
|
|
862
|
+
};
|
|
863
|
+
const req = request(this.url, { method: "POST", agent: this.agent, headers: {
|
|
864
|
+
Authorization: "Bearer " + this.options.credential,
|
|
865
|
+
"X-Engine7-Travel-Node": this.options.nodeId,
|
|
866
|
+
"Content-Type": "application/json",
|
|
867
|
+
"Content-Length": body.length
|
|
868
|
+
} }, (res) => {
|
|
869
|
+
responseStarted = true;
|
|
870
|
+
const chunks = [];
|
|
871
|
+
let bytes = 0;
|
|
872
|
+
res.on("data", (chunk) => {
|
|
873
|
+
bytes += chunk.length;
|
|
874
|
+
if (bytes > 65536) {
|
|
875
|
+
finish(new Error("TRAVEL_CONTROL_INVALID_RESPONSE"));
|
|
876
|
+
req.destroy();
|
|
877
|
+
} else chunks.push(chunk);
|
|
878
|
+
});
|
|
879
|
+
res.once("error", () => finish(unavailable()));
|
|
880
|
+
res.once("end", () => {
|
|
881
|
+
if (this.closed) {
|
|
882
|
+
finish(unavailable());
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
let value;
|
|
886
|
+
try {
|
|
887
|
+
value = JSON.parse(Buffer.concat(chunks).toString());
|
|
888
|
+
} catch {
|
|
889
|
+
finish(new Error("TRAVEL_CONTROL_INVALID_RESPONSE"));
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
if (res.statusCode !== 200) {
|
|
893
|
+
finish(new Error(res.statusCode === 401 || res.statusCode === 403 ? "TRAVEL_AUTH_DENIED" : res.statusCode === 503 ? "TRAVEL_CONTROL_BUSY" : publicErrors.has(value?.error) ? value.error : "TRAVEL_CONTROL_REFUSED"));
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
if (!value || typeof value !== "object" || Object.keys(value).length !== 1 || !value.travel || typeof value.travel !== "object" || Array.isArray(value.travel) || value.travel.version !== 1) {
|
|
897
|
+
finish(new Error("TRAVEL_CONTROL_INVALID_RESPONSE"));
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
finish(void 0, value.travel);
|
|
901
|
+
});
|
|
902
|
+
});
|
|
903
|
+
this.pending.add(req);
|
|
904
|
+
const timer = setTimeout(() => {
|
|
905
|
+
finish(unavailable());
|
|
906
|
+
req.destroy();
|
|
907
|
+
}, remaining);
|
|
908
|
+
req.once("error", (error) => {
|
|
909
|
+
if (complete) return;
|
|
910
|
+
if (retryStale && !this.closed && !responseStarted && readActions.has(input?.action) && req.reusedSocket && error.code === "ECONNRESET") {
|
|
911
|
+
complete = true;
|
|
912
|
+
clearTimeout(timer);
|
|
913
|
+
this.pending.delete(req);
|
|
914
|
+
resolve5(this.attempt(input, false, deadline, body));
|
|
915
|
+
} else finish(unavailable());
|
|
916
|
+
});
|
|
917
|
+
req.once("close", () => {
|
|
918
|
+
clearTimeout(timer);
|
|
919
|
+
this.pending.delete(req);
|
|
920
|
+
});
|
|
921
|
+
req.end(body);
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
register(bootId2) {
|
|
925
|
+
return this.call({ action: "register", bootId: bootId2 });
|
|
926
|
+
}
|
|
927
|
+
heartbeat(input) {
|
|
928
|
+
return this.call({ action: "heartbeat", ...input });
|
|
929
|
+
}
|
|
930
|
+
status() {
|
|
931
|
+
return this.call({ action: "status" });
|
|
932
|
+
}
|
|
933
|
+
close() {
|
|
934
|
+
if (this.closed) return;
|
|
935
|
+
this.closed = true;
|
|
936
|
+
for (const req of this.pending) req.destroy();
|
|
937
|
+
this.agent.destroy();
|
|
938
|
+
this.key?.fill(0);
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
var TravelManagementClient = class extends TravelReportClient {
|
|
942
|
+
tail = Promise.resolve();
|
|
943
|
+
queued = 0;
|
|
944
|
+
call(input) {
|
|
945
|
+
if (this.queued >= 16) return Promise.reject(new Error("TRAVEL_CONTROL_BUSY"));
|
|
946
|
+
this.queued++;
|
|
947
|
+
const operation = this.tail.then(() => super.call(input));
|
|
948
|
+
this.tail = operation.catch(() => {
|
|
949
|
+
});
|
|
950
|
+
return operation.finally(() => {
|
|
951
|
+
this.queued--;
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
constructor(options) {
|
|
955
|
+
let url;
|
|
956
|
+
try {
|
|
957
|
+
url = new URL(options.url);
|
|
958
|
+
} catch {
|
|
959
|
+
throw new Error("TRAVEL_CONTROL_TLS_REQUIRED");
|
|
960
|
+
}
|
|
961
|
+
if (url.pathname !== "/travel/manage/v1") throw new Error("TRAVEL_MANAGEMENT_ENDPOINT_REQUIRED");
|
|
962
|
+
super(options);
|
|
963
|
+
}
|
|
964
|
+
async verifyAncestor(ancestor, descendant) {
|
|
965
|
+
await this.call({ action: "verifyAncestor", ancestor, descendant });
|
|
966
|
+
}
|
|
967
|
+
async identity() {
|
|
968
|
+
return this.call({ action: "identity" });
|
|
969
|
+
}
|
|
970
|
+
async deletionsSince(after, maximum = 32) {
|
|
971
|
+
return (await this.call({ action: "deletionsSince", after, maximum })).deletions;
|
|
972
|
+
}
|
|
973
|
+
async publishCheckpoint(permit, digest, parent) {
|
|
974
|
+
await this.call({ action: "publishCheckpoint", permit, digest, parent });
|
|
975
|
+
}
|
|
976
|
+
async recordRecoveryBranch(permit, chain, proof) {
|
|
977
|
+
await this.call({ action: "recordRecoveryBranch", permit, chain, proof });
|
|
978
|
+
}
|
|
979
|
+
async recoveryBranchStatus(common, local) {
|
|
980
|
+
return this.call({ action: "recoveryBranchStatus", common, local });
|
|
981
|
+
}
|
|
982
|
+
async assertPermit(permit, operation) {
|
|
983
|
+
await this.call({ action: "assertPermit", permit, operation });
|
|
984
|
+
}
|
|
985
|
+
async acquire(ready) {
|
|
986
|
+
return (await this.call({ action: "acquire", ready })).permit;
|
|
987
|
+
}
|
|
988
|
+
async retire(jobId) {
|
|
989
|
+
await this.call({ action: "retire", jobId });
|
|
990
|
+
}
|
|
991
|
+
retirementStatus() {
|
|
992
|
+
return this.call({ action: "retirementStatus" });
|
|
993
|
+
}
|
|
994
|
+
beginHandoff(permit, transferId, targetNodeId) {
|
|
995
|
+
return this.call({ action: "beginHandoff", permit, transferId, targetNodeId });
|
|
996
|
+
}
|
|
997
|
+
freezeHandoff(permit, transferId, boundary) {
|
|
998
|
+
return this.call({ action: "freezeHandoff", permit, transferId, boundary });
|
|
999
|
+
}
|
|
1000
|
+
readyHandoff(transferId, ready) {
|
|
1001
|
+
return this.call({ action: "readyHandoff", transferId, ready });
|
|
1002
|
+
}
|
|
1003
|
+
commitHandoff(transferId) {
|
|
1004
|
+
return this.call({ action: "commitHandoff", transferId });
|
|
1005
|
+
}
|
|
1006
|
+
handoffStatus(transferId) {
|
|
1007
|
+
return this.call({ action: "handoffStatus", transferId });
|
|
1008
|
+
}
|
|
1009
|
+
abortHandoff(transferId) {
|
|
1010
|
+
return this.call({ action: "abortHandoff", transferId });
|
|
1011
|
+
}
|
|
1012
|
+
};
|
|
1013
|
+
|
|
1014
|
+
// src/continuity/retirement-main.ts
|
|
1015
|
+
var command = promisify(execFile);
|
|
1016
|
+
var sha4 = (value) => createHash5("sha256").update(value).digest("hex");
|
|
1017
|
+
var path = (value) => {
|
|
1018
|
+
if (typeof value !== "string" || !isAbsolute3(value) || resolve4(value) !== value) throw new Error("TRAVEL_RETIREMENT_PATH");
|
|
1019
|
+
return value;
|
|
1020
|
+
};
|
|
1021
|
+
async function runTravelRetirementCli(args) {
|
|
1022
|
+
if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-retire run|recover-local --config /absolute/private-config.json" };
|
|
1023
|
+
if (args.length !== 3 || !["run", "recover-local"].includes(args[0]) || args[1] !== "--config") throw new Error("TRAVEL_RETIREMENT_INVALID_COMMAND");
|
|
1024
|
+
const config = JSON.parse(readPrivateFile(path(args[2]), 4 * 1024 * 1024).toString());
|
|
1025
|
+
if (args[0] === "recover-local") {
|
|
1026
|
+
const client2 = new TravelManagementClient({ ...config.control, ca: readFileSync6(path(config.tls.caFile)), cert: readFileSync6(path(config.tls.certFile)), key: readPrivateFile(path(config.tls.keyFile), 65536) });
|
|
1027
|
+
try {
|
|
1028
|
+
const { principal, publicKey } = await client2.retirementStatus();
|
|
1029
|
+
if (publicKey !== config.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
1030
|
+
return await createOrdinaryLocalRecovery({ ...config, principal, authority: { publicKey: config.publicKey, status: async () => {
|
|
1031
|
+
const current = await client2.retirementStatus();
|
|
1032
|
+
if (JSON.stringify(current.principal) !== JSON.stringify(principal) || current.publicKey !== publicKey || !current.source || current.source.checkpointDigest !== current.checkpointDigest || current.source.deletionWatermark !== current.deletionWatermark) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
1033
|
+
return current.source;
|
|
1034
|
+
} }, dedupeReceipt: JSON.parse(readPrivateFile(path(config.dedupeReceiptFile), 32 * 1024 * 1024).toString()) });
|
|
1035
|
+
} finally {
|
|
1036
|
+
client2.close();
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
if (!Array.isArray(config.resources) || !Array.isArray(config.stopServices) || config.stopServices.some((service) => typeof service !== "string" || !/^engine7-travel[-a-zA-Z0-9_.@]+\.service$/.test(service))) throw new Error("TRAVEL_RETIREMENT_CONFIG");
|
|
1040
|
+
if (!config.stopServices.length && config.nodesAlreadyStopped !== true) throw new Error("TRAVEL_RETIREMENT_STOP_REQUIRED");
|
|
1041
|
+
const client = new TravelManagementClient({ ...config.control, ca: readFileSync6(path(config.tls.caFile)), cert: readFileSync6(path(config.tls.certFile)), key: readPrivateFile(path(config.tls.keyFile), 65536) });
|
|
1042
|
+
let job, keys;
|
|
1043
|
+
try {
|
|
1044
|
+
const control = await client.retirementStatus();
|
|
1045
|
+
if (JSON.stringify(control.identity) !== JSON.stringify(config.identity)) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
|
|
1046
|
+
if (config.keyIdentity?.tenantId !== config.identity.tenantId || config.keyIdentity.companionId !== config.identity.companionId || config.keyIdentity.seatId !== config.identity.seatId) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
|
|
1047
|
+
keys = new KeyServiceStore(path(config.keyStoreDirectory));
|
|
1048
|
+
keys.assertIdentity(config.keyIdentity);
|
|
1049
|
+
const verifyLocalRecovery = async () => {
|
|
1050
|
+
const current = await client.retirementStatus(), source = current.source;
|
|
1051
|
+
if (current.retired !== true || current.jobId !== config.jobId || !source || current.publicKey !== control.publicKey || JSON.stringify(current.identity) !== JSON.stringify(control.identity) || JSON.stringify(current.principal) !== JSON.stringify(control.principal) || source.checkpointDigest !== current.checkpointDigest || source.deletionWatermark !== current.deletionWatermark) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
|
|
1052
|
+
if (!existsSync3(path(config.localRecoveryReceiptFile))) return null;
|
|
1053
|
+
const receipt = JSON.parse(readPrivateFile(config.localRecoveryReceiptFile, 65536).toString()), { digest, ...body } = receipt;
|
|
1054
|
+
const generation = receipt.sourceGeneration;
|
|
1055
|
+
if (receipt.format !== "engine7-ordinary-local-recovery-v2" || sha4(JSON.stringify(body)) !== digest || receipt.checkpointDigest !== current.checkpointDigest || JSON.stringify(receipt.identity) !== JSON.stringify(current.identity) || receipt.deletionWatermark !== current.deletionWatermark || !generation || generation.nodeId !== source.activeNodeId || generation.bootId !== source.activeBootId || generation.authorityBootId !== source.authorityBootId || generation.epoch !== source.epoch || typeof generation.nodeId !== "string" || typeof generation.bootId !== "string" || typeof generation.authorityBootId !== "string" || !Number.isSafeInteger(generation.epoch) || receipt.loaded !== true || ![receipt.channelReceiptsDigest, receipt.sourceFilesDigest].every((value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value))) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
|
|
1056
|
+
return receipt;
|
|
1057
|
+
};
|
|
1058
|
+
job = new TravelRetirement({
|
|
1059
|
+
directory: path(config.directory),
|
|
1060
|
+
identity: config.identity,
|
|
1061
|
+
jobId: config.jobId,
|
|
1062
|
+
retire: () => client.retire(config.jobId),
|
|
1063
|
+
stopNodes: async () => {
|
|
1064
|
+
if (config.stopServices.length) await command("systemctl", ["stop", ...config.stopServices]);
|
|
1065
|
+
},
|
|
1066
|
+
verifyLocalRecovery,
|
|
1067
|
+
resources: config.resources.map((resource) => new LocalSeatResource(path(resource.directory), config.identity)),
|
|
1068
|
+
revokeKey: async () => {
|
|
1069
|
+
keys.revoke(config.keyIdentity);
|
|
1070
|
+
return { revoked: true };
|
|
1071
|
+
},
|
|
1072
|
+
accountOwnerRequestedKeyDestruction: config.accountOwnerRequestedKeyDestruction === true,
|
|
1073
|
+
destroyKey: async () => keys.destroy(config.keyIdentity)
|
|
1074
|
+
});
|
|
1075
|
+
return await job.run();
|
|
1076
|
+
} finally {
|
|
1077
|
+
job?.close();
|
|
1078
|
+
keys?.close();
|
|
1079
|
+
client.close();
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
if (process.argv[1] && /[\\/](retirement-main\.ts|travel-retire\.mjs)$/.test(fileURLToPath(import.meta.url)) && resolve4(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
1083
|
+
runTravelRetirementCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
|
|
1084
|
+
process.stderr.write("TRAVEL_RETIREMENT_REFUSED\n");
|
|
1085
|
+
process.exitCode = 1;
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
export {
|
|
1089
|
+
LocalSeatResource,
|
|
1090
|
+
PlatformReceiptStore,
|
|
1091
|
+
TravelRetirement,
|
|
1092
|
+
createOrdinaryLocalRecovery,
|
|
1093
|
+
runTravelRetirementCli
|
|
1094
|
+
};
|