engine7 7.1.133 → 7.1.137
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/auth-server.mjs +632 -0
- package/dist/bg-worker.mjs +31663 -28486
- package/dist/cc-desktop.mjs +951 -0
- package/dist/cli.mjs +41495 -30171
- package/dist/engine-startup.mjs +54213 -40973
- package/dist/main.mjs +50129 -36887
- package/dist/recall-worker.mjs +20446 -0
- package/dist/sqlite-maintenance-worker.mjs +1166 -124
- package/dist/stop-history-worker.mjs +180 -0
- package/dist/topics-worker.mjs +3353 -1078
- package/dist/travel-authority.mjs +1068 -0
- package/dist/travel-console.mjs +2206 -0
- package/dist/travel-controller.mjs +1883 -0
- package/dist/travel-data.mjs +7253 -0
- package/dist/travel-gateway.mjs +3259 -0
- package/dist/travel-key-service.mjs +483 -0
- package/dist/travel-node-data.mjs +4936 -0
- package/dist/travel-node.mjs +21258 -0
- package/dist/travel-retire.mjs +1095 -0
- package/dist/web-console.mjs +3355 -0
- package/package.json +32 -17
- package/templates/config.template.json +45 -0
- package/templates/skills/auth-connect/SKILL.md +22 -0
- package/templates/skills/email/SKILL.md +119 -115
- package/templates/skills/email/scripts/email-config-path.test.js +52 -0
- package/templates/skills/email/scripts/email-config.d.ts +4 -0
- package/templates/skills/email/scripts/email-config.js +6 -3
- package/templates/skills/pptx/SKILL.md +5 -0
- package/templates/skills/pptx/assets/engine7-aurora/field.png +0 -0
- package/templates/skills/pptx/assets/engine7-aurora/hero.png +0 -0
- package/templates/skills/pptx/assets/engine7-aurora/wordmark.png +0 -0
- package/templates/skills/pptx/examples/engine7-aurora.cjs +190 -0
- package/templates/skills/pptx/package-lock.json +171 -0
- package/templates/skills/pptx/package.json +12 -0
- package/templates/skills/pptx/scripts/engine7-aurora.cjs +132 -0
- package/templates/skills/pptx/styles/engine7-aurora.md +136 -0
- package/templates/skills/pptx/tests/engine7-aurora.test.cjs +116 -0
- package/templates/workspace/AGENTS.md +2 -9
- package/templates/workspace/RULES.md +22 -0
- package/templates/workspace/hooks/loop-detector.mjs +37 -0
- package/templates/workspace/souls/unnamed.md +10 -0
|
@@ -0,0 +1,1883 @@
|
|
|
1
|
+
const require=(await import('node:module')).createRequire(import.meta.url)
|
|
2
|
+
|
|
3
|
+
// src/continuity/controller-main.ts
|
|
4
|
+
import { readFileSync as readFileSync3 } from "node:fs";
|
|
5
|
+
import { isAbsolute, resolve as resolve2 } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
// src/continuity/controller.ts
|
|
9
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
10
|
+
import { join as join2 } from "node:path";
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
12
|
+
|
|
13
|
+
// src/continuity/publication-objects.ts
|
|
14
|
+
import { DatabaseSync } from "node:sqlite";
|
|
15
|
+
import {
|
|
16
|
+
constants,
|
|
17
|
+
openSync,
|
|
18
|
+
closeSync,
|
|
19
|
+
fstatSync,
|
|
20
|
+
fsyncSync,
|
|
21
|
+
readSync,
|
|
22
|
+
writeSync,
|
|
23
|
+
lstatSync,
|
|
24
|
+
realpathSync,
|
|
25
|
+
mkdirSync,
|
|
26
|
+
readFileSync,
|
|
27
|
+
writeFileSync,
|
|
28
|
+
linkSync,
|
|
29
|
+
unlinkSync
|
|
30
|
+
} from "node:fs";
|
|
31
|
+
import { join, dirname, resolve } from "node:path";
|
|
32
|
+
var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
|
|
33
|
+
var HASH = /^[a-f0-9]{64}$/;
|
|
34
|
+
var MAGIC = Buffer.from("E7P1");
|
|
35
|
+
var noFollow = constants.O_NOFOLLOW ?? 0;
|
|
36
|
+
function validateObjectRef(ref) {
|
|
37
|
+
if (!ref || !HASH.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > PUBLICATION_CHUNK_BYTES)
|
|
38
|
+
throw new Error("PUBLICATION_INVALID_OBJECT");
|
|
39
|
+
}
|
|
40
|
+
function validateFileContent(file) {
|
|
41
|
+
if (!file || !HASH.test(file.sha256) || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || !Array.isArray(file.chunks) || file.chunks.length > 1e6) throw new Error("PUBLICATION_INVALID_FILE");
|
|
42
|
+
let total = 0;
|
|
43
|
+
for (const ref of file.chunks) {
|
|
44
|
+
validateObjectRef(ref);
|
|
45
|
+
total += ref.bytes;
|
|
46
|
+
}
|
|
47
|
+
if (total !== file.bytes || !Number.isSafeInteger(total)) throw new Error("PUBLICATION_INVALID_FILE");
|
|
48
|
+
}
|
|
49
|
+
function assertPrivateDirectory(path2) {
|
|
50
|
+
const info = lstatSync(path2);
|
|
51
|
+
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path2) !== resolve(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
52
|
+
throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
53
|
+
}
|
|
54
|
+
function syncDir(path2) {
|
|
55
|
+
if (process.platform === "win32") return;
|
|
56
|
+
const fd = openSync(path2, constants.O_RDONLY);
|
|
57
|
+
try {
|
|
58
|
+
fsyncSync(fd);
|
|
59
|
+
} finally {
|
|
60
|
+
closeSync(fd);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function preparePrivateDirectory(path2) {
|
|
64
|
+
const missing = [];
|
|
65
|
+
let parent = resolve(path2);
|
|
66
|
+
for (; ; ) {
|
|
67
|
+
try {
|
|
68
|
+
lstatSync(parent);
|
|
69
|
+
break;
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error.code !== "ENOENT") throw error;
|
|
72
|
+
}
|
|
73
|
+
missing.push(parent);
|
|
74
|
+
parent = dirname(parent);
|
|
75
|
+
}
|
|
76
|
+
if (realpathSync(parent) !== parent) throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
77
|
+
for (const directory of missing.reverse()) {
|
|
78
|
+
try {
|
|
79
|
+
mkdirSync(directory, { mode: 448 });
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error.code !== "EEXIST") throw error;
|
|
82
|
+
}
|
|
83
|
+
assertPrivateDirectory(directory);
|
|
84
|
+
syncDir(dirname(directory));
|
|
85
|
+
}
|
|
86
|
+
assertPrivateDirectory(path2);
|
|
87
|
+
}
|
|
88
|
+
function preparePrivateDatabase(path2) {
|
|
89
|
+
for (const file of [path2, path2 + "-journal", path2 + "-wal", path2 + "-shm"]) {
|
|
90
|
+
try {
|
|
91
|
+
const info2 = lstatSync(file);
|
|
92
|
+
if (!info2.isFile() || info2.isSymbolicLink() || process.platform !== "win32" && (info2.mode & 63 || info2.uid !== process.getuid()))
|
|
93
|
+
throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
|
|
94
|
+
} catch (error) {
|
|
95
|
+
if (error.code !== "ENOENT") throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
const fd = openSync(path2, "wx", 384);
|
|
100
|
+
closeSync(fd);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error.code !== "EEXIST") throw error;
|
|
103
|
+
}
|
|
104
|
+
const info = lstatSync(path2);
|
|
105
|
+
if (!info.isFile() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
106
|
+
throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
|
|
107
|
+
syncDir(dirname(path2));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// src/continuity/controller.ts
|
|
111
|
+
var TravelController = class {
|
|
112
|
+
constructor(options) {
|
|
113
|
+
this.options = options;
|
|
114
|
+
const nodes = Object.values(options.nodes), preferred = options.nodes[options.preferredNodeId];
|
|
115
|
+
if (nodes.length !== 2 || !preferred || nodes.some((node) => options.nodes[node.principal.nodeId] !== node || ["tenantId", "companionId", "seatId"].some((key) => node.principal[key] !== preferred.principal[key])) || new Set(nodes.map((node) => node.principal.role)).size !== 2) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
116
|
+
this.interval = options.intervalMs ?? 1e3;
|
|
117
|
+
for (const value of [this.interval, options.healthyForMs ?? 12e4, options.handbackCooldownMs ?? 6e5]) if (!Number.isSafeInteger(value) || value < 0 || value > 36e5) throw new Error("TRAVEL_CONTROLLER_TIMING");
|
|
118
|
+
if (this.interval < 100) throw new Error("TRAVEL_CONTROLLER_TIMING");
|
|
119
|
+
this.clock = options.monotonicNow ?? (() => Number(process.hrtime.bigint() / 1000000n));
|
|
120
|
+
preparePrivateDirectory(options.directory);
|
|
121
|
+
const ownerFile = join2(options.directory, "controller-owner.sqlite");
|
|
122
|
+
preparePrivateDatabase(ownerFile);
|
|
123
|
+
this.owner = new DatabaseSync2(ownerFile);
|
|
124
|
+
try {
|
|
125
|
+
this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
|
|
126
|
+
} catch {
|
|
127
|
+
this.owner.close();
|
|
128
|
+
throw new Error("TRAVEL_CONTROLLER_BUSY");
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
const file = join2(options.directory, "controller.sqlite");
|
|
132
|
+
preparePrivateDatabase(file);
|
|
133
|
+
this.db = new DatabaseSync2(file);
|
|
134
|
+
this.db.exec(`PRAGMA synchronous=FULL;PRAGMA journal_mode=WAL;
|
|
135
|
+
CREATE TABLE IF NOT EXISTS binding(identity TEXT NOT NULL);
|
|
136
|
+
CREATE TABLE IF NOT EXISTS preferences(id INTEGER PRIMARY KEY CHECK(id=1),node TEXT NOT NULL);
|
|
137
|
+
CREATE TABLE IF NOT EXISTS automatic(id INTEGER PRIMARY KEY CHECK(id=1),enabled INTEGER NOT NULL CHECK(enabled IN (0,1)));
|
|
138
|
+
CREATE TABLE IF NOT EXISTS jobs(id TEXT PRIMARY KEY,source TEXT,target TEXT NOT NULL,state TEXT NOT NULL,checkpoint TEXT);
|
|
139
|
+
CREATE TABLE IF NOT EXISTS abort_recoveries(id TEXT PRIMARY KEY,node TEXT NOT NULL,boot TEXT NOT NULL,authority_boot TEXT NOT NULL,epoch INTEGER NOT NULL,checkpoint TEXT NOT NULL);
|
|
140
|
+
CREATE TABLE IF NOT EXISTS starts(node TEXT NOT NULL,boot TEXT NOT NULL,epoch INTEGER NOT NULL,checkpoint TEXT NOT NULL,PRIMARY KEY(node,boot,epoch));`);
|
|
141
|
+
const identity = JSON.stringify(nodes.map((node) => [node.principal.tenantId, node.principal.companionId, node.principal.seatId, node.principal.nodeId, node.principal.role]).sort());
|
|
142
|
+
const binding = this.db.prepare("SELECT identity FROM binding").all();
|
|
143
|
+
if (!binding.length) this.db.prepare("INSERT INTO binding VALUES(?)").run(identity);
|
|
144
|
+
else if (binding.length !== 1 || binding[0].identity !== identity) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
145
|
+
this.db.prepare("INSERT OR IGNORE INTO preferences VALUES(1,?)").run(options.preferredNodeId);
|
|
146
|
+
this.db.exec("INSERT OR IGNORE INTO automatic VALUES(1,1)");
|
|
147
|
+
if (!options.nodes[this.preferredNodeId()]) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
148
|
+
if (this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_CONTROLLER_RECOVERY_REQUIRED");
|
|
149
|
+
} catch (error) {
|
|
150
|
+
this.db?.close();
|
|
151
|
+
this.owner.close();
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
db;
|
|
156
|
+
owner;
|
|
157
|
+
active;
|
|
158
|
+
timer;
|
|
159
|
+
running = false;
|
|
160
|
+
closed = false;
|
|
161
|
+
lastError = null;
|
|
162
|
+
healthySince = null;
|
|
163
|
+
lastReturnAt = null;
|
|
164
|
+
clock;
|
|
165
|
+
interval;
|
|
166
|
+
preferredNodeId() {
|
|
167
|
+
return String(this.db.prepare("SELECT node FROM preferences WHERE id=1").get().node);
|
|
168
|
+
}
|
|
169
|
+
status() {
|
|
170
|
+
return { running: this.running, inFlight: !!this.active, lastError: this.lastError, job: this.job(), preferredNodeId: this.preferredNodeId(), automatic: this.db.prepare("SELECT enabled FROM automatic WHERE id=1").get().enabled === 1 };
|
|
171
|
+
}
|
|
172
|
+
setAutomatic(enabled) {
|
|
173
|
+
if (this.closed) throw new Error("TRAVEL_CONTROLLER_CLOSED");
|
|
174
|
+
if (typeof enabled !== "boolean") throw new Error("TRAVEL_CONTROLLER_CONFIG");
|
|
175
|
+
this.db.prepare("UPDATE automatic SET enabled=? WHERE id=1").run(enabled ? 1 : 0);
|
|
176
|
+
}
|
|
177
|
+
job() {
|
|
178
|
+
return this.db.prepare("SELECT * FROM jobs WHERE state NOT IN ('DONE','ABORTED') ORDER BY rowid LIMIT 1").get();
|
|
179
|
+
}
|
|
180
|
+
requestHandback(transferId) {
|
|
181
|
+
this.requestTransfer(this.options.preferredNodeId, transferId);
|
|
182
|
+
}
|
|
183
|
+
/** Explicit owner choice retains its target across restarts. Replaying a
|
|
184
|
+
* completed ID does not overwrite a newer choice or enqueue another move. */
|
|
185
|
+
requestTransfer(targetNodeId, transferId) {
|
|
186
|
+
if (this.closed) throw new Error("TRAVEL_CONTROLLER_CLOSED");
|
|
187
|
+
if (!this.options.nodes[targetNodeId]) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
188
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(transferId)) throw new Error("TRAVEL_INVALID_ID");
|
|
189
|
+
const prior = this.db.prepare("SELECT target FROM jobs WHERE id=?").get(transferId);
|
|
190
|
+
if (prior) {
|
|
191
|
+
if (prior.target !== targetNodeId) throw new Error("TRAVEL_ID_COLLISION");
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (this.job()) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
195
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
196
|
+
try {
|
|
197
|
+
this.db.prepare("INSERT INTO jobs VALUES(?,NULL,?,'REQUESTED',NULL)").run(transferId, targetNodeId);
|
|
198
|
+
this.db.prepare("UPDATE preferences SET node=? WHERE id=1").run(targetNodeId);
|
|
199
|
+
this.db.exec("COMMIT");
|
|
200
|
+
} catch (error) {
|
|
201
|
+
this.db.exec("ROLLBACK");
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
tick() {
|
|
206
|
+
if (this.closed) return Promise.reject(new Error("TRAVEL_CONTROLLER_CLOSED"));
|
|
207
|
+
if (this.active) return this.active;
|
|
208
|
+
const operation = this.round().catch((error) => {
|
|
209
|
+
this.lastError = error instanceof Error && /^TRAVEL_[A-Z_]+$/.test(error.message) ? error.message : "TRAVEL_CONTROLLER_OPERATION_FAILED";
|
|
210
|
+
});
|
|
211
|
+
this.active = operation.finally(() => {
|
|
212
|
+
this.active = void 0;
|
|
213
|
+
});
|
|
214
|
+
return this.active;
|
|
215
|
+
}
|
|
216
|
+
async launch(node, permit, checkpoint) {
|
|
217
|
+
const prior = this.db.prepare("SELECT checkpoint FROM starts WHERE node=? AND boot=? AND epoch=?").get(permit.nodeId, permit.bootId, permit.epoch);
|
|
218
|
+
if (prior) {
|
|
219
|
+
if (prior.checkpoint !== checkpoint) throw new Error("TRAVEL_CONTROLLER_GENERATION_COLLISION");
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
await node.start(permit, checkpoint);
|
|
223
|
+
this.db.prepare("INSERT INTO starts VALUES(?,?,?,?)").run(permit.nodeId, permit.bootId, permit.epoch, checkpoint);
|
|
224
|
+
}
|
|
225
|
+
async round() {
|
|
226
|
+
this.lastError = null;
|
|
227
|
+
const job = this.job();
|
|
228
|
+
if (job) {
|
|
229
|
+
await this.advance(job);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
if (!this.status().automatic) return;
|
|
233
|
+
const preferred = this.options.nodes[this.preferredNodeId()];
|
|
234
|
+
const status = await this.options.authority.status(preferred.principal);
|
|
235
|
+
if (status.activeNodeId && !status.expired) {
|
|
236
|
+
const active = this.options.nodes[status.activeNodeId];
|
|
237
|
+
if (!active) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
238
|
+
const observed = await active.observe();
|
|
239
|
+
if (!observed.connected) {
|
|
240
|
+
this.healthySince = null;
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (!observed.running) {
|
|
244
|
+
await active.stop();
|
|
245
|
+
this.healthySince = null;
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
{
|
|
249
|
+
const standby = Object.values(this.options.nodes).find((node2) => node2 !== active);
|
|
250
|
+
if ((await standby.observe()).connected && !await this.replicate(active, standby)) return;
|
|
251
|
+
}
|
|
252
|
+
if (status.activeNodeId !== preferred.principal.nodeId) {
|
|
253
|
+
const local = await preferred.observe(), now = this.clock();
|
|
254
|
+
if (!local.connected) {
|
|
255
|
+
this.healthySince = null;
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
this.healthySince ??= now;
|
|
259
|
+
if (now - this.healthySince >= (this.options.healthyForMs ?? 12e4) && (!this.lastReturnAt || now - this.lastReturnAt >= (this.options.handbackCooldownMs ?? 6e5))) this.requestTransfer(preferred.principal.nodeId, "return-" + randomUUID());
|
|
260
|
+
} else this.healthySince = null;
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
this.healthySince = null;
|
|
264
|
+
const candidates = Object.values(this.options.nodes).sort((a, b) => Number(a.principal.nodeId === status.activeNodeId) - Number(b.principal.nodeId === status.activeNodeId) || Number(a.principal.role !== "CLOUD") - Number(b.principal.role !== "CLOUD"));
|
|
265
|
+
let node;
|
|
266
|
+
for (const candidate of candidates) if ((await candidate.observe()).connected === true) {
|
|
267
|
+
node = candidate;
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
if (!node) return;
|
|
271
|
+
await node.pinBranch(status.checkpointDigest);
|
|
272
|
+
const ready = await node.prepare(status.checkpointDigest);
|
|
273
|
+
const latest = await this.options.authority.status(node.principal);
|
|
274
|
+
if (latest.authorityBootId !== status.authorityBootId || latest.epoch !== status.epoch || latest.checkpointDigest !== status.checkpointDigest || latest.deletionWatermark !== status.deletionWatermark || latest.activeNodeId && !latest.expired) return;
|
|
275
|
+
const permit = await this.options.authority.acquire(node.principal, ready);
|
|
276
|
+
await this.launch(node, permit, status.checkpointDigest);
|
|
277
|
+
}
|
|
278
|
+
async replicate(source, target) {
|
|
279
|
+
if (!source.replicationOffer || !source.connectReplica || !target.replicaProfile || !target.bootstrapReplica) return true;
|
|
280
|
+
const offer = await source.replicationOffer();
|
|
281
|
+
if (!offer) return true;
|
|
282
|
+
if (offer.principal.nodeId !== source.principal.nodeId) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
283
|
+
const assertSource = async () => {
|
|
284
|
+
const permit = await source.permit();
|
|
285
|
+
if (["nodeId", "bootId", "authorityBootId", "epoch"].some((field) => permit[field] !== offer.permit[field])) throw new Error("TRAVEL_CONTROLLER_COMMIT_SUPERSEDED");
|
|
286
|
+
await this.options.authority.assertPermit(permit, "CONTROL");
|
|
287
|
+
return permit;
|
|
288
|
+
};
|
|
289
|
+
let profile = await target.replicaProfile();
|
|
290
|
+
if (!profile || JSON.stringify(profile) !== JSON.stringify(offer.profile)) {
|
|
291
|
+
await target.stop(await assertSource());
|
|
292
|
+
await target.bootstrapReplica({ ...offer, permitSupplier: () => source.permit() });
|
|
293
|
+
profile = await target.replicaProfile();
|
|
294
|
+
}
|
|
295
|
+
if (!profile || JSON.stringify(profile) !== JSON.stringify(offer.profile)) throw new Error("TRAVEL_CONTROLLER_REPLICA");
|
|
296
|
+
await assertSource();
|
|
297
|
+
await source.connectReplica(profile);
|
|
298
|
+
const recovered = await source.recoverBranches?.();
|
|
299
|
+
return !recovered || recovered.unresolvedCritical === 0;
|
|
300
|
+
}
|
|
301
|
+
async advance(job) {
|
|
302
|
+
const target = this.options.nodes[job.target], control = this.options.authority;
|
|
303
|
+
if (!target) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
304
|
+
if (job.state === "REQUESTED") {
|
|
305
|
+
const status = await control.status(target.principal);
|
|
306
|
+
if (!status.activeNodeId || status.expired) throw new Error("TRAVEL_CONTROLLER_SOURCE_OFFLINE");
|
|
307
|
+
if (status.activeNodeId === job.target) {
|
|
308
|
+
this.db.prepare("UPDATE jobs SET state='DONE' WHERE id=?").run(job.id);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const source2 = this.options.nodes[status.activeNodeId];
|
|
312
|
+
if (!source2) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
313
|
+
if (!await this.replicate(source2, target)) return;
|
|
314
|
+
this.db.prepare("UPDATE jobs SET source=?,state='PREPARING' WHERE id=?").run(source2.principal.nodeId, job.id);
|
|
315
|
+
await control.beginHandoff(source2.principal, await source2.permit(), job.id, job.target);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
const source = job.source && this.options.nodes[job.source];
|
|
319
|
+
if (!source) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
320
|
+
let result;
|
|
321
|
+
try {
|
|
322
|
+
result = await control.handoffStatus(target.principal, job.id);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
if (error instanceof Error && error.message === "TRAVEL_HANDOFF_NOT_FOUND") result = await control.beginHandoff(source.principal, await source.permit(), job.id, job.target);
|
|
325
|
+
else throw error;
|
|
326
|
+
}
|
|
327
|
+
if (result.state === "ABORTED") {
|
|
328
|
+
const recovery = this.db.prepare("SELECT * FROM abort_recoveries WHERE id=?").get(job.id);
|
|
329
|
+
if (!recovery) await source.stop();
|
|
330
|
+
const status = await control.status(source.principal);
|
|
331
|
+
if (recovery) {
|
|
332
|
+
if (status.activeNodeId === recovery.node && status.activeBootId === recovery.boot && status.authorityBootId === recovery.authority_boot && status.epoch === recovery.epoch && !status.expired) {
|
|
333
|
+
const permit = (await source.observe()).running ? await source.permit() : await control.acquire(source.principal, await source.prepare(String(recovery.checkpoint)));
|
|
334
|
+
if (permit.epoch !== recovery.epoch || permit.bootId !== recovery.boot || permit.authorityBootId !== recovery.authority_boot) throw new Error("TRAVEL_CONTROLLER_COMMIT_SUPERSEDED");
|
|
335
|
+
await this.launch(source, permit, String(recovery.checkpoint));
|
|
336
|
+
}
|
|
337
|
+
this.db.prepare("UPDATE jobs SET state='ABORTED' WHERE id=?").run(job.id);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
if ((!status.activeNodeId || status.expired) && (await source.observe()).connected) {
|
|
341
|
+
await source.pinBranch(status.checkpointDigest);
|
|
342
|
+
const ready = await source.prepare(status.checkpointDigest);
|
|
343
|
+
const latest = await control.status(source.principal);
|
|
344
|
+
if (latest.authorityBootId !== status.authorityBootId || latest.epoch !== status.epoch || latest.checkpointDigest !== status.checkpointDigest || latest.deletionWatermark !== status.deletionWatermark || latest.activeNodeId && !latest.expired) return;
|
|
345
|
+
const permit = await control.acquire(source.principal, ready);
|
|
346
|
+
this.db.prepare("INSERT INTO abort_recoveries VALUES(?,?,?,?,?,?)").run(job.id, permit.nodeId, permit.bootId, permit.authorityBootId, permit.epoch, status.checkpointDigest);
|
|
347
|
+
await this.launch(source, permit, status.checkpointDigest);
|
|
348
|
+
}
|
|
349
|
+
this.db.prepare("UPDATE jobs SET state='ABORTED' WHERE id=?").run(job.id);
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
if (["FROZEN_AT_H", "TARGET_READY"].includes(result.state) && !(await target.observe()).connected) {
|
|
353
|
+
await control.abortHandoff(source.principal, job.id);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
if (result.state === "PREPARING") {
|
|
357
|
+
const status = await control.status(source.principal);
|
|
358
|
+
if (status.expired || status.activeNodeId !== source.principal.nodeId) {
|
|
359
|
+
await control.abortHandoff(source.principal, job.id);
|
|
360
|
+
this.db.prepare("UPDATE jobs SET state='ABORTED' WHERE id=?").run(job.id);
|
|
361
|
+
await source.stop();
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const boundary = await source.safeBoundary(job.id);
|
|
365
|
+
if (!boundary || !boundary.safeBoundary || !boundary.effectsSettled) return;
|
|
366
|
+
await target.pinBranch(boundary.checkpointDigest);
|
|
367
|
+
await source.pinBranch(boundary.checkpointDigest);
|
|
368
|
+
result = await control.freezeHandoff(source.principal, await source.permit(), job.id, boundary);
|
|
369
|
+
} else if (result.state === "FROZEN_AT_H") {
|
|
370
|
+
await target.pinBranch(result.checkpointDigest);
|
|
371
|
+
const ready = await target.prepare(result.checkpointDigest);
|
|
372
|
+
result = await control.readyHandoff(target.principal, job.id, ready);
|
|
373
|
+
} else if (result.state === "TARGET_READY") result = await control.commitHandoff(target.principal, job.id);
|
|
374
|
+
else if (result.state === "COMMITTED") {
|
|
375
|
+
const status = await control.status(target.principal), permit = result.permit;
|
|
376
|
+
if (!permit) throw new Error("TRAVEL_CONTROLLER_COMMIT_SUPERSEDED");
|
|
377
|
+
if (status.expired || status.activeNodeId !== target.principal.nodeId || status.activeBootId !== permit.bootId || status.epoch !== permit.epoch || status.authorityBootId !== permit.authorityBootId) {
|
|
378
|
+
this.db.prepare("UPDATE jobs SET state='DONE',checkpoint=? WHERE id=?").run(result.checkpointDigest, job.id);
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
const fresh = await control.acquire(target.principal, await target.prepare(result.checkpointDigest));
|
|
382
|
+
await source.stop(fresh);
|
|
383
|
+
await this.launch(target, fresh, result.checkpointDigest);
|
|
384
|
+
this.db.prepare("UPDATE jobs SET state='DONE',checkpoint=? WHERE id=?").run(result.checkpointDigest, job.id);
|
|
385
|
+
this.lastReturnAt = this.clock();
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
this.db.prepare("UPDATE jobs SET state=?,checkpoint=? WHERE id=?").run(result.state, result.checkpointDigest, job.id);
|
|
389
|
+
}
|
|
390
|
+
start() {
|
|
391
|
+
if (this.running || this.closed) return;
|
|
392
|
+
this.running = true;
|
|
393
|
+
this.schedule(0);
|
|
394
|
+
}
|
|
395
|
+
schedule(delay) {
|
|
396
|
+
if (!this.running) return;
|
|
397
|
+
this.timer = setTimeout(() => {
|
|
398
|
+
this.timer = void 0;
|
|
399
|
+
const started = this.clock();
|
|
400
|
+
void this.tick().finally(() => this.schedule(this.interval - (this.clock() - started) % this.interval));
|
|
401
|
+
}, delay);
|
|
402
|
+
}
|
|
403
|
+
async stop() {
|
|
404
|
+
this.running = false;
|
|
405
|
+
if (this.timer) clearTimeout(this.timer);
|
|
406
|
+
this.timer = void 0;
|
|
407
|
+
await this.active;
|
|
408
|
+
}
|
|
409
|
+
close() {
|
|
410
|
+
if (this.closed) return;
|
|
411
|
+
if (this.active) throw new Error("TRAVEL_CONTROLLER_BUSY");
|
|
412
|
+
this.running = false;
|
|
413
|
+
if (this.timer) clearTimeout(this.timer);
|
|
414
|
+
this.closed = true;
|
|
415
|
+
try {
|
|
416
|
+
this.db.close();
|
|
417
|
+
} finally {
|
|
418
|
+
this.owner.close();
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
// src/continuity/controller-authority-client.ts
|
|
424
|
+
var RemoteTravelControllerAuthority = class {
|
|
425
|
+
constructor(nodes) {
|
|
426
|
+
this.nodes = nodes;
|
|
427
|
+
const entries = Object.entries(nodes), principals = entries.map(([, node]) => node.principal);
|
|
428
|
+
if (entries.length !== 2 || entries.some(([id2, node]) => id2 !== node.principal.nodeId) || new Set(principals.map((node) => node.role)).size !== 2 || principals.some((node) => ["tenantId", "companionId", "seatId"].some((field) => node[field] !== principals[0][field])))
|
|
429
|
+
throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
430
|
+
}
|
|
431
|
+
client(principal) {
|
|
432
|
+
const node = Object.hasOwn(this.nodes, principal.nodeId) ? this.nodes[principal.nodeId] : void 0;
|
|
433
|
+
if (!node || ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].some((field) => node.principal[field] !== principal[field]))
|
|
434
|
+
throw new Error("TRAVEL_AUTH_DENIED");
|
|
435
|
+
return node.client;
|
|
436
|
+
}
|
|
437
|
+
async status(principal) {
|
|
438
|
+
return this.client(principal).status();
|
|
439
|
+
}
|
|
440
|
+
async retirementStatus(principal) {
|
|
441
|
+
return this.client(principal).retirementStatus();
|
|
442
|
+
}
|
|
443
|
+
async assertPermit(permit, operation) {
|
|
444
|
+
const node = Object.hasOwn(this.nodes, permit.nodeId) ? this.nodes[permit.nodeId] : void 0;
|
|
445
|
+
if (!node || ["tenantId", "companionId", "seatId"].some((field) => node.principal[field] !== permit[field])) throw new Error("TRAVEL_AUTH_DENIED");
|
|
446
|
+
await node.client.assertPermit(permit, operation);
|
|
447
|
+
}
|
|
448
|
+
async acquire(principal, ready) {
|
|
449
|
+
return this.client(principal).acquire(ready);
|
|
450
|
+
}
|
|
451
|
+
async beginHandoff(principal, permit, transferId, targetNodeId) {
|
|
452
|
+
return this.client(principal).beginHandoff(permit, transferId, targetNodeId);
|
|
453
|
+
}
|
|
454
|
+
async freezeHandoff(principal, permit, transferId, boundary) {
|
|
455
|
+
return this.client(principal).freezeHandoff(permit, transferId, boundary);
|
|
456
|
+
}
|
|
457
|
+
async readyHandoff(principal, transferId, ready) {
|
|
458
|
+
return this.client(principal).readyHandoff(transferId, ready);
|
|
459
|
+
}
|
|
460
|
+
async commitHandoff(principal, transferId) {
|
|
461
|
+
return this.client(principal).commitHandoff(transferId);
|
|
462
|
+
}
|
|
463
|
+
async handoffStatus(principal, transferId) {
|
|
464
|
+
return this.client(principal).handoffStatus(transferId);
|
|
465
|
+
}
|
|
466
|
+
async abortHandoff(principal, transferId) {
|
|
467
|
+
return this.client(principal).abortHandoff(transferId);
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
// src/continuity/authority-client.ts
|
|
472
|
+
import { Agent, request } from "node:https";
|
|
473
|
+
var publicErrors = /* @__PURE__ */ new Set([
|
|
474
|
+
"TRAVEL_HEARTBEAT_REPLAY",
|
|
475
|
+
"TRAVEL_BOOT_MISMATCH",
|
|
476
|
+
"TRAVEL_BOOT_RETIRED",
|
|
477
|
+
"TRAVEL_LEASE_EXPIRED",
|
|
478
|
+
"TRAVEL_STALE_PERMIT",
|
|
479
|
+
"TRAVEL_DELETION_BARRIER",
|
|
480
|
+
"TRAVEL_BOOT_REQUIRED",
|
|
481
|
+
"TRAVEL_NOT_READY",
|
|
482
|
+
"TRAVEL_READINESS_BARRIER",
|
|
483
|
+
"TRAVEL_LEASE_HELD",
|
|
484
|
+
"TRAVEL_INVALID_PERMIT",
|
|
485
|
+
"TRAVEL_HANDOFF_STATE",
|
|
486
|
+
"TRAVEL_HANDOFF_FROZEN",
|
|
487
|
+
"TRAVEL_HANDOFF_NOT_SAFE",
|
|
488
|
+
"TRAVEL_HANDOFF_NOT_FOUND",
|
|
489
|
+
"TRAVEL_HANDOFF_COMMITTED",
|
|
490
|
+
"TRAVEL_TARGET_OFFLINE",
|
|
491
|
+
"TRAVEL_ID_COLLISION",
|
|
492
|
+
"TRAVEL_ANCESTRY_GAP"
|
|
493
|
+
]);
|
|
494
|
+
var readActions = /* @__PURE__ */ new Set(["status", "identity", "deletionsSince", "verifyAncestor", "assertPermit", "handoffStatus", "retirementStatus", "recoveryBranchStatus"]);
|
|
495
|
+
var TravelReportClient = class {
|
|
496
|
+
constructor(options) {
|
|
497
|
+
this.options = options;
|
|
498
|
+
try {
|
|
499
|
+
this.url = new URL(options.url);
|
|
500
|
+
} catch {
|
|
501
|
+
throw new Error("TRAVEL_CONTROL_TLS_REQUIRED");
|
|
502
|
+
}
|
|
503
|
+
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");
|
|
504
|
+
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");
|
|
505
|
+
this.timeout = options.timeoutMs ?? 8e3;
|
|
506
|
+
if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
|
|
507
|
+
this.key = options.key ? Buffer.from(options.key) : void 0;
|
|
508
|
+
this.agent = new Agent({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 1 });
|
|
509
|
+
}
|
|
510
|
+
agent;
|
|
511
|
+
key;
|
|
512
|
+
url;
|
|
513
|
+
timeout;
|
|
514
|
+
pending = /* @__PURE__ */ new Set();
|
|
515
|
+
closed = false;
|
|
516
|
+
call(input) {
|
|
517
|
+
return this.attempt(input);
|
|
518
|
+
}
|
|
519
|
+
attempt(input, retryStale = true, deadline = performance.now() + this.timeout, wireBody) {
|
|
520
|
+
if (this.closed) return Promise.reject(new Error("TRAVEL_CONTROL_CLOSED"));
|
|
521
|
+
if (this.pending.size) return Promise.reject(new Error("TRAVEL_CONTROL_BUSY"));
|
|
522
|
+
const body = wireBody ?? Buffer.from(JSON.stringify({ travel: { version: 1, ...input } }));
|
|
523
|
+
if (body.length > (input?.action === "recordRecoveryBranch" ? 40 * 1024 * 1024 : 65536)) return Promise.reject(new Error("TRAVEL_CONTROL_INVALID_REQUEST"));
|
|
524
|
+
const unavailable = () => new Error(this.closed ? "TRAVEL_CONTROL_CLOSED" : "TRAVEL_CONTROL_UNAVAILABLE");
|
|
525
|
+
const remaining = deadline - performance.now();
|
|
526
|
+
if (remaining <= 0) return Promise.reject(unavailable());
|
|
527
|
+
return new Promise((resolve3, reject) => {
|
|
528
|
+
let complete = false, responseStarted = false;
|
|
529
|
+
const finish = (error, value) => {
|
|
530
|
+
if (complete) return;
|
|
531
|
+
complete = true;
|
|
532
|
+
clearTimeout(timer);
|
|
533
|
+
this.pending.delete(req);
|
|
534
|
+
if (error) reject(error);
|
|
535
|
+
else resolve3(value);
|
|
536
|
+
};
|
|
537
|
+
const req = request(this.url, { method: "POST", agent: this.agent, headers: {
|
|
538
|
+
Authorization: "Bearer " + this.options.credential,
|
|
539
|
+
"X-Engine7-Travel-Node": this.options.nodeId,
|
|
540
|
+
"Content-Type": "application/json",
|
|
541
|
+
"Content-Length": body.length
|
|
542
|
+
} }, (res) => {
|
|
543
|
+
responseStarted = true;
|
|
544
|
+
const chunks = [];
|
|
545
|
+
let bytes = 0;
|
|
546
|
+
res.on("data", (chunk) => {
|
|
547
|
+
bytes += chunk.length;
|
|
548
|
+
if (bytes > 65536) {
|
|
549
|
+
finish(new Error("TRAVEL_CONTROL_INVALID_RESPONSE"));
|
|
550
|
+
req.destroy();
|
|
551
|
+
} else chunks.push(chunk);
|
|
552
|
+
});
|
|
553
|
+
res.once("error", () => finish(unavailable()));
|
|
554
|
+
res.once("end", () => {
|
|
555
|
+
if (this.closed) {
|
|
556
|
+
finish(unavailable());
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
let value;
|
|
560
|
+
try {
|
|
561
|
+
value = JSON.parse(Buffer.concat(chunks).toString());
|
|
562
|
+
} catch {
|
|
563
|
+
finish(new Error("TRAVEL_CONTROL_INVALID_RESPONSE"));
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
if (res.statusCode !== 200) {
|
|
567
|
+
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"));
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
if (!value || typeof value !== "object" || Object.keys(value).length !== 1 || !value.travel || typeof value.travel !== "object" || Array.isArray(value.travel) || value.travel.version !== 1) {
|
|
571
|
+
finish(new Error("TRAVEL_CONTROL_INVALID_RESPONSE"));
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
finish(void 0, value.travel);
|
|
575
|
+
});
|
|
576
|
+
});
|
|
577
|
+
this.pending.add(req);
|
|
578
|
+
const timer = setTimeout(() => {
|
|
579
|
+
finish(unavailable());
|
|
580
|
+
req.destroy();
|
|
581
|
+
}, remaining);
|
|
582
|
+
req.once("error", (error) => {
|
|
583
|
+
if (complete) return;
|
|
584
|
+
if (retryStale && !this.closed && !responseStarted && readActions.has(input?.action) && req.reusedSocket && error.code === "ECONNRESET") {
|
|
585
|
+
complete = true;
|
|
586
|
+
clearTimeout(timer);
|
|
587
|
+
this.pending.delete(req);
|
|
588
|
+
resolve3(this.attempt(input, false, deadline, body));
|
|
589
|
+
} else finish(unavailable());
|
|
590
|
+
});
|
|
591
|
+
req.once("close", () => {
|
|
592
|
+
clearTimeout(timer);
|
|
593
|
+
this.pending.delete(req);
|
|
594
|
+
});
|
|
595
|
+
req.end(body);
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
register(bootId) {
|
|
599
|
+
return this.call({ action: "register", bootId });
|
|
600
|
+
}
|
|
601
|
+
heartbeat(input) {
|
|
602
|
+
return this.call({ action: "heartbeat", ...input });
|
|
603
|
+
}
|
|
604
|
+
status() {
|
|
605
|
+
return this.call({ action: "status" });
|
|
606
|
+
}
|
|
607
|
+
close() {
|
|
608
|
+
if (this.closed) return;
|
|
609
|
+
this.closed = true;
|
|
610
|
+
for (const req of this.pending) req.destroy();
|
|
611
|
+
this.agent.destroy();
|
|
612
|
+
this.key?.fill(0);
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
var TravelManagementClient = class extends TravelReportClient {
|
|
616
|
+
tail = Promise.resolve();
|
|
617
|
+
queued = 0;
|
|
618
|
+
call(input) {
|
|
619
|
+
if (this.queued >= 16) return Promise.reject(new Error("TRAVEL_CONTROL_BUSY"));
|
|
620
|
+
this.queued++;
|
|
621
|
+
const operation = this.tail.then(() => super.call(input));
|
|
622
|
+
this.tail = operation.catch(() => {
|
|
623
|
+
});
|
|
624
|
+
return operation.finally(() => {
|
|
625
|
+
this.queued--;
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
constructor(options) {
|
|
629
|
+
let url;
|
|
630
|
+
try {
|
|
631
|
+
url = new URL(options.url);
|
|
632
|
+
} catch {
|
|
633
|
+
throw new Error("TRAVEL_CONTROL_TLS_REQUIRED");
|
|
634
|
+
}
|
|
635
|
+
if (url.pathname !== "/travel/manage/v1") throw new Error("TRAVEL_MANAGEMENT_ENDPOINT_REQUIRED");
|
|
636
|
+
super(options);
|
|
637
|
+
}
|
|
638
|
+
async verifyAncestor(ancestor, descendant) {
|
|
639
|
+
await this.call({ action: "verifyAncestor", ancestor, descendant });
|
|
640
|
+
}
|
|
641
|
+
async identity() {
|
|
642
|
+
return this.call({ action: "identity" });
|
|
643
|
+
}
|
|
644
|
+
async deletionsSince(after, maximum = 32) {
|
|
645
|
+
return (await this.call({ action: "deletionsSince", after, maximum })).deletions;
|
|
646
|
+
}
|
|
647
|
+
async publishCheckpoint(permit, digest2, parent) {
|
|
648
|
+
await this.call({ action: "publishCheckpoint", permit, digest: digest2, parent });
|
|
649
|
+
}
|
|
650
|
+
async recordRecoveryBranch(permit, chain, proof) {
|
|
651
|
+
await this.call({ action: "recordRecoveryBranch", permit, chain, proof });
|
|
652
|
+
}
|
|
653
|
+
async recoveryBranchStatus(common, local) {
|
|
654
|
+
return this.call({ action: "recoveryBranchStatus", common, local });
|
|
655
|
+
}
|
|
656
|
+
async assertPermit(permit, operation) {
|
|
657
|
+
await this.call({ action: "assertPermit", permit, operation });
|
|
658
|
+
}
|
|
659
|
+
async acquire(ready) {
|
|
660
|
+
return (await this.call({ action: "acquire", ready })).permit;
|
|
661
|
+
}
|
|
662
|
+
async retire(jobId) {
|
|
663
|
+
await this.call({ action: "retire", jobId });
|
|
664
|
+
}
|
|
665
|
+
retirementStatus() {
|
|
666
|
+
return this.call({ action: "retirementStatus" });
|
|
667
|
+
}
|
|
668
|
+
beginHandoff(permit, transferId, targetNodeId) {
|
|
669
|
+
return this.call({ action: "beginHandoff", permit, transferId, targetNodeId });
|
|
670
|
+
}
|
|
671
|
+
freezeHandoff(permit, transferId, boundary) {
|
|
672
|
+
return this.call({ action: "freezeHandoff", permit, transferId, boundary });
|
|
673
|
+
}
|
|
674
|
+
readyHandoff(transferId, ready) {
|
|
675
|
+
return this.call({ action: "readyHandoff", transferId, ready });
|
|
676
|
+
}
|
|
677
|
+
commitHandoff(transferId) {
|
|
678
|
+
return this.call({ action: "commitHandoff", transferId });
|
|
679
|
+
}
|
|
680
|
+
handoffStatus(transferId) {
|
|
681
|
+
return this.call({ action: "handoffStatus", transferId });
|
|
682
|
+
}
|
|
683
|
+
abortHandoff(transferId) {
|
|
684
|
+
return this.call({ action: "abortHandoff", transferId });
|
|
685
|
+
}
|
|
686
|
+
};
|
|
687
|
+
|
|
688
|
+
// src/continuity/node-supervisor-client.ts
|
|
689
|
+
import { Agent as Agent2, request as request2 } from "node:https";
|
|
690
|
+
|
|
691
|
+
// src/continuity/publication.ts
|
|
692
|
+
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
693
|
+
import { createHash } from "node:crypto";
|
|
694
|
+
var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
|
|
695
|
+
var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
|
|
696
|
+
var ZERO = "0".repeat(64);
|
|
697
|
+
var HASH2 = /^[a-f0-9]{64}$/;
|
|
698
|
+
var ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
699
|
+
function natural(value) {
|
|
700
|
+
return Number.isSafeInteger(value) && value >= 0;
|
|
701
|
+
}
|
|
702
|
+
function id(value) {
|
|
703
|
+
if (typeof value !== "string" || !ID.test(value)) throw new Error("PUBLICATION_INVALID_ID");
|
|
704
|
+
}
|
|
705
|
+
function exactIds(actual, required, error) {
|
|
706
|
+
if (actual.length !== required.length || new Set(actual).size !== actual.length || actual.some((x) => !required.includes(x))) throw new Error(error);
|
|
707
|
+
}
|
|
708
|
+
function normalizePublicationProfile(value) {
|
|
709
|
+
if (!value?.identity || ["tenantId", "companionId", "seatId"].some((k) => typeof value.identity[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value.identity[k]))) throw new Error("PUBLICATION_INVALID_IDENTITY");
|
|
710
|
+
id(value.baselineId);
|
|
711
|
+
id(value.buildManifestId);
|
|
712
|
+
if (!natural(value.epoch) || !value.epoch || !Array.isArray(value.databaseIds) || !value.databaseIds.length || value.databaseIds.length > 64 || !Array.isArray(value.trees) || !value.trees.length || value.trees.length > 64) throw new Error("PUBLICATION_INVALID_PROFILE");
|
|
713
|
+
value.databaseIds.forEach(id);
|
|
714
|
+
value.trees.forEach((t) => {
|
|
715
|
+
id(t?.id);
|
|
716
|
+
if (!["file", "vector", "session"].includes(t.kind)) throw new Error("PUBLICATION_INVALID_PROFILE");
|
|
717
|
+
});
|
|
718
|
+
if (new Set(value.databaseIds).size !== value.databaseIds.length || new Set(value.trees.map((t) => t.id)).size !== value.trees.length)
|
|
719
|
+
throw new Error("PUBLICATION_INVALID_PROFILE");
|
|
720
|
+
const profile = {
|
|
721
|
+
identity: { tenantId: value.identity.tenantId, companionId: value.identity.companionId, seatId: value.identity.seatId },
|
|
722
|
+
baselineId: value.baselineId,
|
|
723
|
+
epoch: value.epoch,
|
|
724
|
+
buildManifestId: value.buildManifestId,
|
|
725
|
+
databaseIds: [...value.databaseIds].sort(),
|
|
726
|
+
trees: value.trees.map((t) => ({ id: t.id, kind: t.kind })).sort((a, b) => a.id.localeCompare(b.id, "en"))
|
|
727
|
+
};
|
|
728
|
+
Object.freeze(profile.identity);
|
|
729
|
+
Object.freeze(profile.databaseIds);
|
|
730
|
+
profile.trees.forEach(Object.freeze);
|
|
731
|
+
Object.freeze(profile.trees);
|
|
732
|
+
return Object.freeze(profile);
|
|
733
|
+
}
|
|
734
|
+
function validatePublicationPath(path2) {
|
|
735
|
+
if (typeof path2 !== "string" || !path2 || path2.length > 2048 || path2.normalize("NFC") !== path2 || /[\x00-\x1f<>:"|?*\\]/.test(path2) || path2.split("/").some((p) => !p || p === "." || p === ".." || /[. ]$/.test(p) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(p)))
|
|
736
|
+
throw new Error("PUBLICATION_INVALID_PATH");
|
|
737
|
+
}
|
|
738
|
+
function normalizePublication(value) {
|
|
739
|
+
if (!value || value.format !== "engine7-publication-v1" || !natural(value.sequence) || !value.sequence || !HASH2.test(value.parentDigest) || !natural(value.deletionWatermark) || !Array.isArray(value.databases) || !Array.isArray(value.trees)) throw new Error("PUBLICATION_INVALID_MANIFEST");
|
|
740
|
+
const profile = normalizePublicationProfile(value.profile);
|
|
741
|
+
exactIds(value.databases.map((d) => d?.databaseId), profile.databaseIds, "PUBLICATION_INCOMPLETE_DATABASES");
|
|
742
|
+
exactIds(value.trees.map((t) => t?.id), profile.trees.map((t) => t.id), "PUBLICATION_INCOMPLETE_TREES");
|
|
743
|
+
const databases = value.databases.map((d) => {
|
|
744
|
+
if (!d.head || !natural(d.head.sequence) || !HASH2.test(d.head.digest)) throw new Error("PUBLICATION_INVALID_DATABASE_HEAD");
|
|
745
|
+
return { databaseId: d.databaseId, head: { sequence: d.head.sequence, digest: d.head.digest } };
|
|
746
|
+
}).sort((a, b) => a.databaseId.localeCompare(b.databaseId, "en"));
|
|
747
|
+
let paths = 0;
|
|
748
|
+
const trees = value.trees.map((tree) => {
|
|
749
|
+
if (!Array.isArray(tree.files) || !Array.isArray(tree.directories) || (paths += tree.files.length + tree.directories.length) > 1e5)
|
|
750
|
+
throw new Error("PUBLICATION_INVALID_TREE");
|
|
751
|
+
const occupied = /* @__PURE__ */ new Map();
|
|
752
|
+
const claim = (path2, kind) => {
|
|
753
|
+
validatePublicationPath(path2);
|
|
754
|
+
const folded = path2.toLowerCase();
|
|
755
|
+
if (occupied.has(folded)) throw new Error("PUBLICATION_PATH_COLLISION");
|
|
756
|
+
occupied.set(folded, kind);
|
|
757
|
+
};
|
|
758
|
+
const directories = tree.directories.map((path2) => {
|
|
759
|
+
claim(path2, "directory");
|
|
760
|
+
return path2;
|
|
761
|
+
}).sort();
|
|
762
|
+
const files = tree.files.map((file) => {
|
|
763
|
+
claim(file?.path, "file");
|
|
764
|
+
validateFileContent(file.content);
|
|
765
|
+
if (![384, 448].includes(file.mode)) throw new Error("PUBLICATION_INVALID_MODE");
|
|
766
|
+
return { path: file.path, mode: file.mode, content: {
|
|
767
|
+
bytes: file.content.bytes,
|
|
768
|
+
sha256: file.content.sha256,
|
|
769
|
+
chunks: file.content.chunks.map((r) => ({ sha256: r.sha256, bytes: r.bytes }))
|
|
770
|
+
} };
|
|
771
|
+
}).sort((a, b) => a.path.localeCompare(b.path, "en"));
|
|
772
|
+
for (const path2 of occupied.keys()) {
|
|
773
|
+
const parts = path2.split("/");
|
|
774
|
+
for (let i = 1; i < parts.length; i++) if (occupied.get(parts.slice(0, i).join("/")) === "file") throw new Error("PUBLICATION_PATH_COLLISION");
|
|
775
|
+
}
|
|
776
|
+
return { id: tree.id, directories, files };
|
|
777
|
+
}).sort((a, b) => a.id.localeCompare(b.id, "en"));
|
|
778
|
+
const normalized = {
|
|
779
|
+
format: "engine7-publication-v1",
|
|
780
|
+
profile,
|
|
781
|
+
sequence: value.sequence,
|
|
782
|
+
parentDigest: value.parentDigest,
|
|
783
|
+
deletionWatermark: value.deletionWatermark,
|
|
784
|
+
databases,
|
|
785
|
+
trees
|
|
786
|
+
};
|
|
787
|
+
if (Buffer.byteLength(JSON.stringify(normalized)) > PUBLICATION_MANIFEST_BYTES) throw new Error("PUBLICATION_MANIFEST_TOO_LARGE");
|
|
788
|
+
return normalized;
|
|
789
|
+
}
|
|
790
|
+
function publicationDigest(manifest) {
|
|
791
|
+
return createHash("sha256").update(JSON.stringify(normalizePublication(manifest))).digest("hex");
|
|
792
|
+
}
|
|
793
|
+
function unpackReplicationCommit(body) {
|
|
794
|
+
if (body.length > PUBLICATION_COMMIT_BYTES) throw new Error("PUBLICATION_COMMIT_TOO_LARGE");
|
|
795
|
+
const value = JSON.parse(Buffer.from(body).toString());
|
|
796
|
+
if (typeof value?.changeset !== "string" || value.changeset.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value.changeset))
|
|
797
|
+
throw new Error("PUBLICATION_INVALID_COMMIT");
|
|
798
|
+
const changeset = Buffer.from(value.changeset, "base64");
|
|
799
|
+
if (changeset.toString("base64") !== value.changeset) throw new Error("PUBLICATION_INVALID_COMMIT");
|
|
800
|
+
return { ...value, changeset };
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// src/continuity/node-supervisor-protocol.ts
|
|
804
|
+
var nodeSupervisorPath = "/travel/node/v1";
|
|
805
|
+
var nodeSupervisorLimit = 2 * 1024 * 1024;
|
|
806
|
+
var nodeSupervisorErrors = /* @__PURE__ */ new Set([
|
|
807
|
+
"TRAVEL_NODE_BUSY",
|
|
808
|
+
"TRAVEL_NODE_CLOSED",
|
|
809
|
+
"TRAVEL_NODE_CANCELLED",
|
|
810
|
+
"TRAVEL_NODE_BOOT_MISMATCH",
|
|
811
|
+
"TRAVEL_NODE_CHECKPOINT",
|
|
812
|
+
"TRAVEL_NODE_GENERATION_COLLISION",
|
|
813
|
+
"TRAVEL_NODE_KEY_UNAVAILABLE",
|
|
814
|
+
"TRAVEL_NODE_KEY_BARRIER",
|
|
815
|
+
"TRAVEL_NODE_IDENTITY",
|
|
816
|
+
"TRAVEL_NODE_REPLICA_NOT_READY",
|
|
817
|
+
"TRAVEL_NODE_RECOVERY_REQUIRED",
|
|
818
|
+
"TRAVEL_NODE_REPLICATION_PEER",
|
|
819
|
+
"TRAVEL_NODE_EFFECT_BARRIER",
|
|
820
|
+
"TRAVEL_PERMIT_REQUIRED",
|
|
821
|
+
"TRAVEL_AUTH_DENIED",
|
|
822
|
+
"TRAVEL_LEASE_EXPIRED",
|
|
823
|
+
"TRAVEL_STALE_PERMIT",
|
|
824
|
+
"TRAVEL_DELETION_BARRIER",
|
|
825
|
+
"TRAVEL_HANDOFF_STATE",
|
|
826
|
+
"TRAVEL_HANDOFF_NOT_FOUND",
|
|
827
|
+
"TRAVEL_INVALID_PERMIT",
|
|
828
|
+
"TRAVEL_CONTROL_BUSY",
|
|
829
|
+
"TRAVEL_CONTROL_UNAVAILABLE"
|
|
830
|
+
]);
|
|
831
|
+
var nodeSupervisorId = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value);
|
|
832
|
+
var nodeSupervisorRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
833
|
+
var fields = {
|
|
834
|
+
observe: [],
|
|
835
|
+
prepare: ["checkpointDigest"],
|
|
836
|
+
pinBranch: ["checkpointDigest"],
|
|
837
|
+
permit: [],
|
|
838
|
+
safeBoundary: ["transferId"],
|
|
839
|
+
start: ["permit", "checkpointDigest"],
|
|
840
|
+
stop: [],
|
|
841
|
+
replicationOffer: [],
|
|
842
|
+
replicaProfile: [],
|
|
843
|
+
bootstrapReplica: ["request"],
|
|
844
|
+
connectReplica: ["profile"],
|
|
845
|
+
recoverBranches: []
|
|
846
|
+
};
|
|
847
|
+
function exact(value, allowed, required = allowed) {
|
|
848
|
+
return Object.keys(value).every((key) => allowed.includes(key)) && required.every((key) => Object.hasOwn(value, key));
|
|
849
|
+
}
|
|
850
|
+
var digest = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
851
|
+
function validNodeSupervisorInput(value) {
|
|
852
|
+
if (!nodeSupervisorRecord(value) || value.version !== 1 || !nodeSupervisorId(value.nodeId) || !nodeSupervisorId(value.action) || !Object.hasOwn(fields, value.action)) return false;
|
|
853
|
+
const required = fields[value.action], optional = value.action === "stop" ? ["expectedSource"] : [];
|
|
854
|
+
if (!exact(value, ["version", "nodeId", "bootId", "action", ...required, ...optional], ["version", "nodeId", "action", ...required])) return false;
|
|
855
|
+
if (value.action !== "observe" && !nodeSupervisorId(value.bootId) || Object.hasOwn(value, "bootId") && !nodeSupervisorId(value.bootId)) return false;
|
|
856
|
+
if (Object.hasOwn(value, "checkpointDigest") && !digest(value.checkpointDigest) || Object.hasOwn(value, "transferId") && !nodeSupervisorId(value.transferId)) return false;
|
|
857
|
+
for (const key of ["permit", "expectedSource"]) if (Object.hasOwn(value, key) && !nodeSupervisorRecord(value[key])) return false;
|
|
858
|
+
if (value.action === "connectReplica") {
|
|
859
|
+
const profile = value.profile;
|
|
860
|
+
if (!nodeSupervisorRecord(profile) || !exact(profile, ["identity", "baselineId", "epoch", "buildManifestId", "databaseIds", "trees"]) || !nodeSupervisorRecord(profile.identity) || !exact(profile.identity, ["tenantId", "companionId", "seatId"]) || !Array.isArray(profile.trees) || profile.trees.some((tree) => !nodeSupervisorRecord(tree) || !exact(tree, ["id", "kind"]))) return false;
|
|
861
|
+
try {
|
|
862
|
+
normalizePublicationProfile(profile);
|
|
863
|
+
} catch {
|
|
864
|
+
return false;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
if (value.action === "bootstrapReplica") {
|
|
868
|
+
const r = value.request;
|
|
869
|
+
if (!nodeSupervisorRecord(r) || !exact(r, ["id", "archiveId", "archiveDigest", "expectedDigest", "parentCheckpointDigest", "principal", "permit"], ["id", "archiveId", "archiveDigest", "expectedDigest", "principal", "permit"]) || !nodeSupervisorId(r.id) || !nodeSupervisorId(r.archiveId) || !digest(r.archiveDigest) || !digest(r.expectedDigest) || Object.hasOwn(r, "parentCheckpointDigest") && !digest(r.parentCheckpointDigest) || !nodeSupervisorRecord(r.permit) || !nodeSupervisorRecord(r.principal) || !exact(r.principal, ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"]) || !["LOCAL", "CLOUD"].includes(String(r.principal.role))) return false;
|
|
870
|
+
}
|
|
871
|
+
return true;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// src/continuity/node-supervisor-client.ts
|
|
875
|
+
var RemoteTravelNodeSupervisor = class {
|
|
876
|
+
constructor(options) {
|
|
877
|
+
this.options = options;
|
|
878
|
+
this.principal = Object.freeze({ ...options.principal });
|
|
879
|
+
try {
|
|
880
|
+
this.url = new URL(options.url);
|
|
881
|
+
} catch {
|
|
882
|
+
throw new Error("TRAVEL_NODE_TLS_REQUIRED");
|
|
883
|
+
}
|
|
884
|
+
if (this.url.protocol !== "https:" || this.url.pathname !== nodeSupervisorPath || this.url.username || this.url.password || this.url.search || this.url.hash) throw new Error("TRAVEL_NODE_TLS_REQUIRED");
|
|
885
|
+
if (!nodeSupervisorId(this.principal.nodeId) || !/^e7t_[a-f0-9]{64}$/.test(options.credential) || ![options.ca, options.cert, options.key].every((value) => Buffer.isBuffer(value) && value.length > 0 && value.length <= 65536)) throw new Error("TRAVEL_NODE_CLIENT_CONFIG");
|
|
886
|
+
this.timeout = options.timeoutMs ?? 18e4;
|
|
887
|
+
if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e5) throw new Error("TRAVEL_NODE_CLIENT_CONFIG");
|
|
888
|
+
this.key = Buffer.from(options.key);
|
|
889
|
+
const agent = () => new Agent2({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 1 });
|
|
890
|
+
this.agents = { observe: agent(), permit: agent(), operation: agent(), stop: agent() };
|
|
891
|
+
}
|
|
892
|
+
principal;
|
|
893
|
+
url;
|
|
894
|
+
agents;
|
|
895
|
+
key;
|
|
896
|
+
pending = /* @__PURE__ */ new Map();
|
|
897
|
+
timeout;
|
|
898
|
+
bootId;
|
|
899
|
+
observeQuery;
|
|
900
|
+
permitQuery;
|
|
901
|
+
closed = false;
|
|
902
|
+
call(action, args = {}, discover = false) {
|
|
903
|
+
if (this.closed) return Promise.reject(new Error("TRAVEL_NODE_CLOSED"));
|
|
904
|
+
const slot = action === "stop" ? "stop" : action === "observe" ? "observe" : action === "permit" ? "permit" : "operation";
|
|
905
|
+
if ([...this.pending.values()].includes(slot)) return Promise.reject(new Error("TRAVEL_NODE_BUSY"));
|
|
906
|
+
const body = Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
|
|
907
|
+
if (body.length > nodeSupervisorLimit) return Promise.reject(new Error("TRAVEL_NODE_INVALID_REQUEST"));
|
|
908
|
+
const unavailable = () => new Error(this.closed ? "TRAVEL_NODE_CLOSED" : "TRAVEL_NODE_UNAVAILABLE");
|
|
909
|
+
return new Promise((resolve3, reject) => {
|
|
910
|
+
const req = request2(this.url, { method: "POST", agent: this.agents[slot], headers: {
|
|
911
|
+
Authorization: "Bearer " + this.options.credential,
|
|
912
|
+
"X-Engine7-Travel-Node": this.principal.nodeId,
|
|
913
|
+
"Content-Type": "application/json",
|
|
914
|
+
"Content-Length": body.length
|
|
915
|
+
} }, (res) => {
|
|
916
|
+
const parts = [];
|
|
917
|
+
let bytes = 0;
|
|
918
|
+
res.on("data", (part) => {
|
|
919
|
+
bytes += part.length;
|
|
920
|
+
if (bytes > nodeSupervisorLimit) {
|
|
921
|
+
req.destroy();
|
|
922
|
+
reject(new Error("TRAVEL_NODE_INVALID_RESPONSE"));
|
|
923
|
+
} else parts.push(part);
|
|
924
|
+
});
|
|
925
|
+
res.once("error", () => reject(unavailable()));
|
|
926
|
+
res.once("end", () => {
|
|
927
|
+
cleanup();
|
|
928
|
+
if (this.closed) {
|
|
929
|
+
reject(unavailable());
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
let envelope;
|
|
933
|
+
try {
|
|
934
|
+
envelope = JSON.parse(Buffer.concat(parts).toString());
|
|
935
|
+
} catch {
|
|
936
|
+
reject(new Error("TRAVEL_NODE_INVALID_RESPONSE"));
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
if (res.statusCode !== 200) {
|
|
940
|
+
reject(new Error(res.statusCode === 403 || res.statusCode === 401 ? "TRAVEL_AUTH_DENIED" : res.statusCode === 503 ? "TRAVEL_NODE_BUSY" : nodeSupervisorErrors.has(envelope?.error) ? envelope.error : "TRAVEL_NODE_REFUSED"));
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
const response = envelope?.node;
|
|
944
|
+
if (!nodeSupervisorRecord(envelope) || Object.keys(envelope).length !== 1 || !nodeSupervisorRecord(response) || response.version !== 1 || response.nodeId !== this.principal.nodeId || !nodeSupervisorId(response.bootId) || !Object.hasOwn(response, "result") || !discover && response.bootId !== this.bootId) {
|
|
945
|
+
reject(new Error("TRAVEL_NODE_INVALID_RESPONSE"));
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
if (discover) this.bootId = response.bootId;
|
|
949
|
+
resolve3(response.result);
|
|
950
|
+
});
|
|
951
|
+
});
|
|
952
|
+
this.pending.set(req, slot);
|
|
953
|
+
const timer = setTimeout(() => {
|
|
954
|
+
req.destroy();
|
|
955
|
+
reject(unavailable());
|
|
956
|
+
}, slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
|
|
957
|
+
const cleanup = () => {
|
|
958
|
+
clearTimeout(timer);
|
|
959
|
+
this.pending.delete(req);
|
|
960
|
+
};
|
|
961
|
+
req.once("error", () => {
|
|
962
|
+
cleanup();
|
|
963
|
+
reject(unavailable());
|
|
964
|
+
});
|
|
965
|
+
req.once("close", cleanup);
|
|
966
|
+
req.end(body);
|
|
967
|
+
});
|
|
968
|
+
}
|
|
969
|
+
async invoke(action, args = {}) {
|
|
970
|
+
if (!this.bootId) {
|
|
971
|
+
const observed = await this.observe();
|
|
972
|
+
if (observed.connected !== true) throw new Error("TRAVEL_NODE_UNAVAILABLE");
|
|
973
|
+
}
|
|
974
|
+
return this.call(action, args);
|
|
975
|
+
}
|
|
976
|
+
observe() {
|
|
977
|
+
return this.observeQuery ??= (async () => {
|
|
978
|
+
try {
|
|
979
|
+
const result = await this.call("observe", {}, true);
|
|
980
|
+
if (!result || ["connected", "running", "busy"].some((key) => typeof result[key] !== "boolean")) throw new Error("TRAVEL_NODE_INVALID_RESPONSE");
|
|
981
|
+
return { connected: result.connected, running: result.running, busy: result.busy };
|
|
982
|
+
} catch {
|
|
983
|
+
return { connected: false, running: false, busy: false };
|
|
984
|
+
}
|
|
985
|
+
})().finally(() => {
|
|
986
|
+
this.observeQuery = void 0;
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
prepare(checkpointDigest) {
|
|
990
|
+
return this.invoke("prepare", { checkpointDigest });
|
|
991
|
+
}
|
|
992
|
+
async pinBranch(checkpointDigest) {
|
|
993
|
+
await this.invoke("pinBranch", { checkpointDigest });
|
|
994
|
+
}
|
|
995
|
+
permit() {
|
|
996
|
+
return this.permitQuery ??= this.invoke("permit").finally(() => {
|
|
997
|
+
this.permitQuery = void 0;
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
safeBoundary(transferId) {
|
|
1001
|
+
return this.invoke("safeBoundary", { transferId });
|
|
1002
|
+
}
|
|
1003
|
+
async start(permit, checkpointDigest) {
|
|
1004
|
+
await this.invoke("start", { permit, checkpointDigest });
|
|
1005
|
+
}
|
|
1006
|
+
async stop(expectedSource) {
|
|
1007
|
+
await this.invoke("stop", expectedSource ? { expectedSource } : {});
|
|
1008
|
+
}
|
|
1009
|
+
replicationOffer() {
|
|
1010
|
+
return this.invoke("replicationOffer");
|
|
1011
|
+
}
|
|
1012
|
+
replicaProfile() {
|
|
1013
|
+
return this.invoke("replicaProfile");
|
|
1014
|
+
}
|
|
1015
|
+
async bootstrapReplica(request5) {
|
|
1016
|
+
const wire = {
|
|
1017
|
+
id: request5.id,
|
|
1018
|
+
archiveId: request5.archiveId,
|
|
1019
|
+
archiveDigest: request5.archiveDigest,
|
|
1020
|
+
expectedDigest: request5.expectedDigest,
|
|
1021
|
+
parentCheckpointDigest: request5.parentCheckpointDigest,
|
|
1022
|
+
principal: request5.principal,
|
|
1023
|
+
permit: request5.permit
|
|
1024
|
+
};
|
|
1025
|
+
await this.invoke("bootstrapReplica", { request: wire });
|
|
1026
|
+
}
|
|
1027
|
+
connectReplica(profile) {
|
|
1028
|
+
return this.invoke("connectReplica", { profile });
|
|
1029
|
+
}
|
|
1030
|
+
recoverBranches() {
|
|
1031
|
+
return this.invoke("recoverBranches");
|
|
1032
|
+
}
|
|
1033
|
+
close() {
|
|
1034
|
+
if (this.closed) return;
|
|
1035
|
+
this.closed = true;
|
|
1036
|
+
for (const req of this.pending.keys()) req.destroy();
|
|
1037
|
+
for (const agent of Object.values(this.agents)) agent.destroy();
|
|
1038
|
+
this.key.fill(0);
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
|
|
1042
|
+
// src/continuity/key-service-store.ts
|
|
1043
|
+
import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
|
|
1044
|
+
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";
|
|
1045
|
+
function assertPrivateStat(stat, directory) {
|
|
1046
|
+
if ((directory ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
1047
|
+
throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
|
|
1048
|
+
}
|
|
1049
|
+
function readPrivateFile(path2, maximumBytes = 65536) {
|
|
1050
|
+
assertPrivateStat(lstatSync2(path2), false);
|
|
1051
|
+
const fd = openSync2(path2, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
|
|
1052
|
+
try {
|
|
1053
|
+
const stat = fstatSync2(fd);
|
|
1054
|
+
assertPrivateStat(stat, false);
|
|
1055
|
+
if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
|
|
1056
|
+
return readFileSync2(fd);
|
|
1057
|
+
} finally {
|
|
1058
|
+
closeSync2(fd);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
// src/continuity/node-supervisor-server.ts
|
|
1063
|
+
import { createServer } from "node:https";
|
|
1064
|
+
function createTravelNodeSupervisorServer(options) {
|
|
1065
|
+
const { node, bootId, managementFingerprints, authorize, peer, bodyTimeoutMs = 5e3, ...tls } = options;
|
|
1066
|
+
const fingerprints = new Set(managementFingerprints.map((value) => value.replaceAll(":", "").toLowerCase()));
|
|
1067
|
+
if (!nodeSupervisorId(bootId) || !fingerprints.size || [...fingerprints].some((value) => !/^[a-f0-9]{64}$/.test(value)) || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 100 || bodyTimeoutMs > 3e4) throw new Error("TRAVEL_NODE_LISTENER_CONFIG");
|
|
1068
|
+
const samePrincipal = (principal) => ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].every((key) => principal[key] === node.principal[key]);
|
|
1069
|
+
if (peer && (peer.principal.nodeId === node.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key) => peer.principal[key] !== node.principal[key]))) throw new Error("TRAVEL_NODE_LISTENER_IDENTITY");
|
|
1070
|
+
const active = { read: 0, operation: 0, stop: 0 };
|
|
1071
|
+
const server = createServer({ ...tls, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
|
|
1072
|
+
res.setHeader("Content-Type", "application/json");
|
|
1073
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1074
|
+
const reply = (status, value) => {
|
|
1075
|
+
if (!res.destroyed && !res.writableEnded) {
|
|
1076
|
+
res.statusCode = status;
|
|
1077
|
+
res.end(JSON.stringify(value));
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
if (req.method !== "POST" || req.url !== nodeSupervisorPath) {
|
|
1081
|
+
reply(404, { error: "TRAVEL_NODE_NOT_FOUND" });
|
|
1082
|
+
req.resume();
|
|
1083
|
+
return;
|
|
1084
|
+
}
|
|
1085
|
+
let credential;
|
|
1086
|
+
try {
|
|
1087
|
+
const socket = req.socket, fp = (socket.getPeerCertificate().fingerprint256 ?? "").replaceAll(":", "").toLowerCase();
|
|
1088
|
+
const authorization = req.headers.authorization;
|
|
1089
|
+
if (!socket.authorized || !fingerprints.has(fp) || req.rawHeaders.filter((_, i) => i % 2 === 0 && req.rawHeaders[i].toLowerCase() === "authorization").length !== 1 || typeof authorization !== "string" || !/^Bearer e7t_[a-f0-9]{64}$/.test(authorization) || req.headers["x-engine7-travel-node"] !== node.principal.nodeId) throw new Error();
|
|
1090
|
+
credential = authorization.slice(7);
|
|
1091
|
+
if (!samePrincipal(await authorize(credential))) throw new Error();
|
|
1092
|
+
} catch {
|
|
1093
|
+
reply(403, { error: "TRAVEL_AUTH_DENIED" });
|
|
1094
|
+
req.resume();
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
const timer = setTimeout(() => req.destroy(), bodyTimeoutMs);
|
|
1098
|
+
timer.unref();
|
|
1099
|
+
let slot;
|
|
1100
|
+
try {
|
|
1101
|
+
const chunks = [];
|
|
1102
|
+
let bytes = 0;
|
|
1103
|
+
for await (const part of req) {
|
|
1104
|
+
bytes += part.length;
|
|
1105
|
+
if (bytes > nodeSupervisorLimit) {
|
|
1106
|
+
reply(400, { error: "TRAVEL_NODE_INVALID_REQUEST" });
|
|
1107
|
+
req.resume();
|
|
1108
|
+
return;
|
|
1109
|
+
}
|
|
1110
|
+
chunks.push(part);
|
|
1111
|
+
}
|
|
1112
|
+
clearTimeout(timer);
|
|
1113
|
+
let envelope;
|
|
1114
|
+
try {
|
|
1115
|
+
envelope = JSON.parse(Buffer.concat(chunks).toString());
|
|
1116
|
+
} catch {
|
|
1117
|
+
reply(400, { error: "TRAVEL_NODE_INVALID_REQUEST" });
|
|
1118
|
+
return;
|
|
1119
|
+
}
|
|
1120
|
+
if (!envelope || Object.keys(envelope).length !== 1 || !validNodeSupervisorInput(envelope.node) || envelope.node.nodeId !== node.principal.nodeId) {
|
|
1121
|
+
reply(400, { error: "TRAVEL_NODE_INVALID_REQUEST" });
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
const input = envelope.node;
|
|
1125
|
+
if (input.action !== "observe" && input.bootId !== bootId) throw new Error("TRAVEL_NODE_BOOT_MISMATCH");
|
|
1126
|
+
const requested = input.action === "stop" ? "stop" : ["observe", "permit"].includes(input.action) ? "read" : "operation";
|
|
1127
|
+
if (active[requested] >= (requested === "read" ? 4 : 1)) {
|
|
1128
|
+
reply(503, { error: "TRAVEL_NODE_BUSY" });
|
|
1129
|
+
return;
|
|
1130
|
+
}
|
|
1131
|
+
slot = requested;
|
|
1132
|
+
active[slot]++;
|
|
1133
|
+
if (!samePrincipal(await authorize(credential))) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1134
|
+
let result;
|
|
1135
|
+
switch (input.action) {
|
|
1136
|
+
case "observe":
|
|
1137
|
+
result = await node.observe();
|
|
1138
|
+
break;
|
|
1139
|
+
case "prepare":
|
|
1140
|
+
result = await node.prepare(input.checkpointDigest);
|
|
1141
|
+
break;
|
|
1142
|
+
case "pinBranch":
|
|
1143
|
+
await node.pinBranch(input.checkpointDigest);
|
|
1144
|
+
break;
|
|
1145
|
+
case "permit":
|
|
1146
|
+
result = await node.permit();
|
|
1147
|
+
break;
|
|
1148
|
+
case "safeBoundary":
|
|
1149
|
+
result = await node.safeBoundary(input.transferId);
|
|
1150
|
+
break;
|
|
1151
|
+
case "start":
|
|
1152
|
+
await node.start(input.permit, input.checkpointDigest);
|
|
1153
|
+
break;
|
|
1154
|
+
case "stop":
|
|
1155
|
+
await node.stop(input.expectedSource);
|
|
1156
|
+
break;
|
|
1157
|
+
case "replicationOffer":
|
|
1158
|
+
result = await node.replicationOffer?.() ?? null;
|
|
1159
|
+
break;
|
|
1160
|
+
case "replicaProfile":
|
|
1161
|
+
result = await node.replicaProfile?.() ?? null;
|
|
1162
|
+
break;
|
|
1163
|
+
case "bootstrapReplica": {
|
|
1164
|
+
const request5 = input.request;
|
|
1165
|
+
if (!peer || !node.bootstrapReplica || ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].some((key) => request5.principal[key] !== peer.principal[key])) throw new Error("TRAVEL_NODE_IDENTITY");
|
|
1166
|
+
await node.bootstrapReplica({ ...request5, permitSupplier: () => peer.permit() });
|
|
1167
|
+
break;
|
|
1168
|
+
}
|
|
1169
|
+
case "connectReplica":
|
|
1170
|
+
if (!node.connectReplica) throw new Error("TRAVEL_NODE_REPLICATION_PEER");
|
|
1171
|
+
await node.connectReplica(input.profile);
|
|
1172
|
+
break;
|
|
1173
|
+
case "recoverBranches":
|
|
1174
|
+
if (!node.recoverBranches) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
1175
|
+
result = await node.recoverBranches();
|
|
1176
|
+
break;
|
|
1177
|
+
}
|
|
1178
|
+
const body = JSON.stringify({ node: { version: 1, nodeId: node.principal.nodeId, bootId, result: result ?? null } });
|
|
1179
|
+
if (Buffer.byteLength(body) > nodeSupervisorLimit) throw new Error("TRAVEL_NODE_RESPONSE_LIMIT");
|
|
1180
|
+
if (!res.destroyed && !res.writableEnded) {
|
|
1181
|
+
res.statusCode = 200;
|
|
1182
|
+
res.end(body);
|
|
1183
|
+
}
|
|
1184
|
+
} catch (error) {
|
|
1185
|
+
const code = error instanceof Error && nodeSupervisorErrors.has(error.message) ? error.message : "TRAVEL_NODE_REFUSED";
|
|
1186
|
+
const reason = error instanceof Error ? /^(?:TRAVEL|RECOVERY|RUNTIME|PUBLICATION|REPLICATION|KEY_SERVICE)_[A-Z_]+/.exec(error.message)?.[0] : void 0;
|
|
1187
|
+
if (slot === "operation" || slot === "stop") process.stderr.write("[travel-node] " + (reason ?? code) + "\n");
|
|
1188
|
+
reply(code === "TRAVEL_AUTH_DENIED" ? 403 : 409, { error: code });
|
|
1189
|
+
} finally {
|
|
1190
|
+
clearTimeout(timer);
|
|
1191
|
+
if (slot) active[slot]--;
|
|
1192
|
+
}
|
|
1193
|
+
});
|
|
1194
|
+
server.headersTimeout = 5e3;
|
|
1195
|
+
server.requestTimeout = bodyTimeoutMs;
|
|
1196
|
+
server.keepAliveTimeout = 1e4;
|
|
1197
|
+
server.maxConnections = 16;
|
|
1198
|
+
server.maxRequestsPerSocket = 256;
|
|
1199
|
+
server.on("tlsClientError", () => {
|
|
1200
|
+
});
|
|
1201
|
+
return server;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
// src/continuity/node-authority-client.ts
|
|
1205
|
+
import { createPublicKey } from "node:crypto";
|
|
1206
|
+
|
|
1207
|
+
// src/continuity/node-data-authority.ts
|
|
1208
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1209
|
+
var fields2 = ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"];
|
|
1210
|
+
var equal = (left, right) => !!left && fields2.every((field) => left[field] === right[field]);
|
|
1211
|
+
var RemoteTravelDataAuthority = class {
|
|
1212
|
+
remote = true;
|
|
1213
|
+
reads = /* @__PURE__ */ new Map();
|
|
1214
|
+
grants;
|
|
1215
|
+
constructor(grants) {
|
|
1216
|
+
if (!grants.length || grants.length > 2 || new Set(grants.map((grant) => grant.credential)).size !== grants.length || grants.some((grant) => !/^e7t_[a-f0-9]{64}$/.test(grant.credential) || createHash2("sha256").update(grant.credential).digest("hex") !== grant.principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1217
|
+
this.grants = grants.map((grant) => ({ ...grant, principal: Object.freeze({ ...grant.principal }) }));
|
|
1218
|
+
}
|
|
1219
|
+
async authenticate(credential) {
|
|
1220
|
+
const grant = this.grants.find((grant2) => grant2.credential === credential);
|
|
1221
|
+
if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1222
|
+
return Object.freeze({ ...(await this.read(grant)).principal });
|
|
1223
|
+
}
|
|
1224
|
+
grant(principal) {
|
|
1225
|
+
const grant = this.grants.find((grant2) => equal(principal, grant2.principal));
|
|
1226
|
+
if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1227
|
+
return grant;
|
|
1228
|
+
}
|
|
1229
|
+
read(grant) {
|
|
1230
|
+
const inFlight = this.reads.get(grant.client);
|
|
1231
|
+
if (inFlight) return inFlight;
|
|
1232
|
+
const pending = grant.client.identity().then((value) => {
|
|
1233
|
+
if (!value || !equal(value.principal, grant.principal)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1234
|
+
const status = value.status;
|
|
1235
|
+
if (!status || !Number.isSafeInteger(status.deletionWatermark) || status.deletionWatermark < 0 || !Number.isSafeInteger(status.epoch) || status.epoch < 1 || !["expired", "frozen"].every((field) => typeof status[field] === "boolean") || typeof status.authorityBootId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(status.authorityBootId) || typeof status.checkpointDigest !== "string" || !/^[a-f0-9]{64}$/.test(status.checkpointDigest) || typeof status.buildManifestId !== "string" || !status.buildManifestId || [status.activeNodeId, status.activeBootId].some((id2) => id2 !== null && (typeof id2 !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(id2)))) throw new Error("TRAVEL_CONTROL_INVALID_RESPONSE");
|
|
1236
|
+
return value;
|
|
1237
|
+
}).finally(() => {
|
|
1238
|
+
this.reads.delete(grant.client);
|
|
1239
|
+
});
|
|
1240
|
+
this.reads.set(grant.client, pending);
|
|
1241
|
+
return pending;
|
|
1242
|
+
}
|
|
1243
|
+
async status(principal) {
|
|
1244
|
+
return (await this.read(this.grant(principal))).status;
|
|
1245
|
+
}
|
|
1246
|
+
async assertPermit(...[permit, operation]) {
|
|
1247
|
+
const grant = this.grants.find((grant2) => !!permit && ["tenantId", "companionId", "seatId", "nodeId"].every((field) => permit[field] === grant2.principal[field]));
|
|
1248
|
+
if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1249
|
+
await grant.client.assertPermit(permit, operation);
|
|
1250
|
+
}
|
|
1251
|
+
async verifyAncestor(principal, ancestor, descendant) {
|
|
1252
|
+
await this.grant(principal).client.verifyAncestor(ancestor, descendant);
|
|
1253
|
+
}
|
|
1254
|
+
};
|
|
1255
|
+
|
|
1256
|
+
// src/continuity/node-authority-client.ts
|
|
1257
|
+
var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteTravelDataAuthority {
|
|
1258
|
+
constructor(publicKey, nodeGrants) {
|
|
1259
|
+
super(nodeGrants);
|
|
1260
|
+
this.publicKey = publicKey;
|
|
1261
|
+
this.nodeGrants = nodeGrants;
|
|
1262
|
+
}
|
|
1263
|
+
static async open(options) {
|
|
1264
|
+
try {
|
|
1265
|
+
if (createPublicKey(options.publicKey).asymmetricKeyType !== "ed25519") throw new Error();
|
|
1266
|
+
} catch {
|
|
1267
|
+
throw new Error("TRAVEL_NODE_SIGNER_REQUIRED");
|
|
1268
|
+
}
|
|
1269
|
+
const remote = new _RemoteTravelNodeAuthority(options.publicKey, options.grants);
|
|
1270
|
+
for (const grant of options.grants) {
|
|
1271
|
+
const identity = await grant.client.identity();
|
|
1272
|
+
if (identity.publicKey !== options.publicKey) throw new Error("TRAVEL_NODE_SIGNER_MISMATCH");
|
|
1273
|
+
await remote.authenticate(grant.credential);
|
|
1274
|
+
}
|
|
1275
|
+
return remote;
|
|
1276
|
+
}
|
|
1277
|
+
client(principal) {
|
|
1278
|
+
const grant = this.nodeGrants.find((value) => ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].every((field) => value.principal[field] === principal[field]));
|
|
1279
|
+
if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1280
|
+
return grant.client;
|
|
1281
|
+
}
|
|
1282
|
+
async handoffStatus(principal, id2) {
|
|
1283
|
+
return this.client(principal).handoffStatus(id2);
|
|
1284
|
+
}
|
|
1285
|
+
async publishCheckpoint(principal, permit, digest2, parent) {
|
|
1286
|
+
await this.client(principal).publishCheckpoint(permit, digest2, parent);
|
|
1287
|
+
}
|
|
1288
|
+
async deletionsSince(principal, after) {
|
|
1289
|
+
if (!Number.isSafeInteger(after) || after < 0) throw new Error("TRAVEL_INVALID_DELETION_WATERMARK");
|
|
1290
|
+
const client = this.client(principal), floor = (await this.status(principal)).deletionWatermark, result = [];
|
|
1291
|
+
while (after < floor) {
|
|
1292
|
+
const page = await client.deletionsSince(after);
|
|
1293
|
+
if (!Array.isArray(page) || !page.length || page.length > 32 || page.some((entry, index) => entry.watermark !== after + index + 1)) throw new Error("TRAVEL_CONTROL_INVALID_RESPONSE");
|
|
1294
|
+
result.push(...page.filter((entry) => entry.watermark <= floor));
|
|
1295
|
+
after = page[page.length - 1].watermark;
|
|
1296
|
+
if (result.length > 1e6) throw new Error("TRAVEL_CONTROL_INVALID_RESPONSE");
|
|
1297
|
+
}
|
|
1298
|
+
return result;
|
|
1299
|
+
}
|
|
1300
|
+
async recordRecoveryBranch(principal, permit, chain, proof) {
|
|
1301
|
+
if (!proof) throw new Error("RECOVERY_BRANCH_PROOF_REQUIRED");
|
|
1302
|
+
await this.client(principal).recordRecoveryBranch(permit, chain, proof);
|
|
1303
|
+
}
|
|
1304
|
+
async recoveryBranchStatus(principal, common, local) {
|
|
1305
|
+
return this.client(principal).recoveryBranchStatus(common, local);
|
|
1306
|
+
}
|
|
1307
|
+
};
|
|
1308
|
+
|
|
1309
|
+
// src/continuity/node-data-server.ts
|
|
1310
|
+
import { createServer as createServer4 } from "node:https";
|
|
1311
|
+
|
|
1312
|
+
// src/continuity/publication-transport.ts
|
|
1313
|
+
import { createServer as createServer2, request as request3, Agent as Agent3 } from "node:https";
|
|
1314
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
1315
|
+
var BODY_LIMIT = PUBLICATION_MANIFEST_BYTES + 65536;
|
|
1316
|
+
var safeCode = (error) => error instanceof Error && /^(PUBLICATION|REPLICATION)_[A-Z_]+$/.test(error.message) ? error.message : "PUBLICATION_OPERATION_FAILED";
|
|
1317
|
+
var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
1318
|
+
function decodeChunk(value) {
|
|
1319
|
+
if (typeof value !== "string" || value.length > 1398104 || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value))
|
|
1320
|
+
throw new Error("PUBLICATION_INVALID_OBJECT");
|
|
1321
|
+
const body = Buffer.from(value, "base64");
|
|
1322
|
+
if (body.toString("base64") !== value) throw new Error("PUBLICATION_INVALID_OBJECT");
|
|
1323
|
+
return body;
|
|
1324
|
+
}
|
|
1325
|
+
function createPublicationServer(options) {
|
|
1326
|
+
const { receiver: fixedReceiver, currentReceiver, assertAvailable = () => {
|
|
1327
|
+
}, preservePublished, allowedFingerprint, ...tls } = options;
|
|
1328
|
+
if (!fixedReceiver && !currentReceiver || fixedReceiver && currentReceiver) throw new Error("PUBLICATION_INVALID_RECEIVER");
|
|
1329
|
+
const fingerprint = allowedFingerprint?.replaceAll(":", "").toLowerCase();
|
|
1330
|
+
if (!/^[a-f0-9]{64}$/.test(fingerprint)) throw new Error("PUBLICATION_INVALID_CERTIFICATE");
|
|
1331
|
+
let inFlight = 0;
|
|
1332
|
+
let mutating = false;
|
|
1333
|
+
const server = createServer2({ ...tls, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
|
|
1334
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1335
|
+
res.setHeader("Content-Type", "application/json");
|
|
1336
|
+
const fail = (status, error) => {
|
|
1337
|
+
res.statusCode = status;
|
|
1338
|
+
res.end(JSON.stringify({ error }));
|
|
1339
|
+
};
|
|
1340
|
+
const socket = req.socket;
|
|
1341
|
+
if (!socket.authorized || socket.getPeerCertificate().fingerprint256?.replaceAll(":", "").toLowerCase() !== fingerprint) {
|
|
1342
|
+
res.setHeader("Connection", "close");
|
|
1343
|
+
req.resume();
|
|
1344
|
+
fail(403, "PUBLICATION_DENIED");
|
|
1345
|
+
return;
|
|
1346
|
+
}
|
|
1347
|
+
if (req.method !== "POST" || req.url !== "/travel/sync/v1") {
|
|
1348
|
+
req.resume();
|
|
1349
|
+
fail(404, "PUBLICATION_NOT_FOUND");
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
if (inFlight >= 2) {
|
|
1353
|
+
req.resume();
|
|
1354
|
+
fail(429, "PUBLICATION_BUSY");
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
inFlight++;
|
|
1358
|
+
try {
|
|
1359
|
+
const [receiver] = await Promise.all([Promise.resolve().then(() => currentReceiver ? currentReceiver() : fixedReceiver), Promise.resolve().then(assertAvailable)]);
|
|
1360
|
+
if (!receiver) {
|
|
1361
|
+
req.resume();
|
|
1362
|
+
fail(503, "PUBLICATION_NOT_READY");
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
const check = async () => {
|
|
1366
|
+
const [latest] = await Promise.all([Promise.resolve().then(() => currentReceiver ? currentReceiver() : fixedReceiver), Promise.resolve().then(assertAvailable)]);
|
|
1367
|
+
if (latest !== receiver) throw new Error("PUBLICATION_RECEIVER_CHANGED");
|
|
1368
|
+
};
|
|
1369
|
+
let size = 0;
|
|
1370
|
+
const chunks = [];
|
|
1371
|
+
for await (const chunk of req) {
|
|
1372
|
+
size += chunk.length;
|
|
1373
|
+
if (size > BODY_LIMIT) {
|
|
1374
|
+
res.setHeader("Connection", "close");
|
|
1375
|
+
req.resume();
|
|
1376
|
+
fail(413, "PUBLICATION_REQUEST_TOO_LARGE");
|
|
1377
|
+
return;
|
|
1378
|
+
}
|
|
1379
|
+
chunks.push(chunk);
|
|
1380
|
+
}
|
|
1381
|
+
const value = JSON.parse(Buffer.concat(chunks).toString());
|
|
1382
|
+
await check();
|
|
1383
|
+
try {
|
|
1384
|
+
if (!same(normalizePublicationProfile(value.profile), receiver.profile)) throw new Error();
|
|
1385
|
+
} catch {
|
|
1386
|
+
fail(403, "PUBLICATION_DENIED");
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
let result;
|
|
1390
|
+
const mutate = async (operation, after = false) => {
|
|
1391
|
+
if (mutating) throw new Error("PUBLICATION_BUSY");
|
|
1392
|
+
mutating = true;
|
|
1393
|
+
try {
|
|
1394
|
+
await preservePublished?.(receiver);
|
|
1395
|
+
await check();
|
|
1396
|
+
const result2 = await operation();
|
|
1397
|
+
if (after) await preservePublished?.(receiver);
|
|
1398
|
+
await check();
|
|
1399
|
+
return result2;
|
|
1400
|
+
} finally {
|
|
1401
|
+
mutating = false;
|
|
1402
|
+
}
|
|
1403
|
+
};
|
|
1404
|
+
switch (value.operation) {
|
|
1405
|
+
case "status":
|
|
1406
|
+
result = preservePublished ? await mutate(() => receiver.status()) : await receiver.status();
|
|
1407
|
+
break;
|
|
1408
|
+
case "replication-status":
|
|
1409
|
+
result = await receiver.replicationStatus();
|
|
1410
|
+
break;
|
|
1411
|
+
case "missing": {
|
|
1412
|
+
if (!Array.isArray(value.refs) || value.refs.length > 128) throw new Error("PUBLICATION_INVALID_OBJECT_LIST");
|
|
1413
|
+
const missing = await Promise.all(value.refs.map(async (ref) => {
|
|
1414
|
+
await check();
|
|
1415
|
+
validateObjectRef(ref);
|
|
1416
|
+
return await receiver.objects.has(ref) ? null : ref.sha256;
|
|
1417
|
+
}));
|
|
1418
|
+
result = missing.filter((ref) => ref !== null);
|
|
1419
|
+
break;
|
|
1420
|
+
}
|
|
1421
|
+
case "object": {
|
|
1422
|
+
validateObjectRef(value.ref);
|
|
1423
|
+
const body = decodeChunk(value.body);
|
|
1424
|
+
if (body.length !== value.ref.bytes || createHash3("sha256").update(body).digest("hex") !== value.ref.sha256) throw new Error("PUBLICATION_OBJECT_MISMATCH");
|
|
1425
|
+
await check();
|
|
1426
|
+
result = await receiver.objects.put(body);
|
|
1427
|
+
break;
|
|
1428
|
+
}
|
|
1429
|
+
case "commit": {
|
|
1430
|
+
const encoded = await receiver.objects.readContent(value.content, PUBLICATION_COMMIT_BYTES);
|
|
1431
|
+
await check();
|
|
1432
|
+
result = await mutate(() => receiver.receiveCommit(unpackReplicationCommit(encoded)));
|
|
1433
|
+
break;
|
|
1434
|
+
}
|
|
1435
|
+
case "manifest":
|
|
1436
|
+
result = await receiver.receive(value.manifest);
|
|
1437
|
+
break;
|
|
1438
|
+
case "publish":
|
|
1439
|
+
result = await mutate(() => receiver.publish(value.sequence), true);
|
|
1440
|
+
break;
|
|
1441
|
+
default:
|
|
1442
|
+
throw new Error("PUBLICATION_INVALID_OPERATION");
|
|
1443
|
+
}
|
|
1444
|
+
await check();
|
|
1445
|
+
res.end(JSON.stringify({ profile: receiver.profile, result }));
|
|
1446
|
+
} catch (error) {
|
|
1447
|
+
if (!res.writableEnded) fail(400, safeCode(error));
|
|
1448
|
+
} finally {
|
|
1449
|
+
inFlight--;
|
|
1450
|
+
}
|
|
1451
|
+
});
|
|
1452
|
+
server.requestTimeout = 15e3;
|
|
1453
|
+
server.headersTimeout = 1e4;
|
|
1454
|
+
server.keepAliveTimeout = 1e4;
|
|
1455
|
+
server.maxConnections = 8;
|
|
1456
|
+
server.maxRequestsPerSocket = 1024;
|
|
1457
|
+
server.setTimeout(15e3, (socket) => socket.destroy());
|
|
1458
|
+
server.on("tlsClientError", () => {
|
|
1459
|
+
});
|
|
1460
|
+
return server;
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
// src/continuity/recovery-archive-transfer.ts
|
|
1464
|
+
import { Agent as Agent4, createServer as createServer3, request as request4 } from "node:https";
|
|
1465
|
+
|
|
1466
|
+
// src/continuity/recovery-archive.ts
|
|
1467
|
+
import { DatabaseSync as DatabaseSync5, backup } from "node:sqlite";
|
|
1468
|
+
|
|
1469
|
+
// src/continuity/crypto.ts
|
|
1470
|
+
var MAGIC2 = Buffer.from("E7OBJ001");
|
|
1471
|
+
var HEADER_SIZE = MAGIC2.length + 12;
|
|
1472
|
+
|
|
1473
|
+
// src/continuity/recovery-archive.ts
|
|
1474
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
1475
|
+
var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
1476
|
+
var FORMAT = "engine7-runtime-recovery-archive-v1";
|
|
1477
|
+
var MAX_METADATA = 16 * 1024 * 1024;
|
|
1478
|
+
var same2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
1479
|
+
function validateRecoveryArchiveEntry(entry, identity) {
|
|
1480
|
+
if (!entry || Object.keys(entry).some((key) => !["format", "id", "kind", "manifest", "databases", "publication", "receipt"].includes(key)) || entry.format !== FORMAT || !ID2.test(entry.id) || !["COMMON", "LOCAL", "REMOTE"].includes(entry.kind)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
|
|
1481
|
+
const manifest = normalizePublication(entry.manifest), manifestDigest = publicationDigest(manifest);
|
|
1482
|
+
if (!same2(manifest.profile.identity, identity)) throw new Error("RECOVERY_IDENTITY_MISMATCH");
|
|
1483
|
+
if (!Array.isArray(entry.databases) || !same2(entry.databases.map((db) => db.databaseId), manifest.profile.databaseIds)) throw new Error("RECOVERY_INCOMPLETE_DATABASES");
|
|
1484
|
+
for (const db of entry.databases) {
|
|
1485
|
+
if (Object.keys(db).some((key) => !["databaseId", "role", "schemaHash", "content"].includes(key)) || db.role !== (entry.kind === "LOCAL" ? "source" : "replica") || !/^[a-f0-9]{64}$/.test(db.schemaHash)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
|
|
1486
|
+
validateFileContent(db.content);
|
|
1487
|
+
}
|
|
1488
|
+
const publication = { state: "PUBLISHED", sequence: manifest.sequence, digest: manifestDigest, deletionWatermark: manifest.deletionWatermark, activationAllowed: false };
|
|
1489
|
+
if (entry.kind === "LOCAL" ? entry.publication !== void 0 : !same2(entry.publication, publication)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
|
|
1490
|
+
const value = { format: FORMAT, id: entry.id, kind: entry.kind, manifest, databases: entry.databases, ...entry.publication ? { publication: entry.publication } : {} };
|
|
1491
|
+
const body = Buffer.from(JSON.stringify(value));
|
|
1492
|
+
if (body.length > MAX_METADATA) throw new Error("RECOVERY_METADATA_TOO_LARGE");
|
|
1493
|
+
const digest2 = createHash4("sha256").update(body).digest("hex");
|
|
1494
|
+
const receipt = {
|
|
1495
|
+
state: "PRESERVED",
|
|
1496
|
+
id: entry.id,
|
|
1497
|
+
kind: entry.kind,
|
|
1498
|
+
digest: digest2,
|
|
1499
|
+
manifestDigest,
|
|
1500
|
+
deletionWatermark: manifest.deletionWatermark,
|
|
1501
|
+
activationAllowed: false,
|
|
1502
|
+
...entry.publication ? { publication: entry.publication } : {}
|
|
1503
|
+
};
|
|
1504
|
+
if (!same2(entry.receipt, receipt)) throw new Error("RECOVERY_ARCHIVE_DIGEST");
|
|
1505
|
+
return { value, body, receipt };
|
|
1506
|
+
}
|
|
1507
|
+
function checkRecoveryDeletion(manifest, current, previous = 0) {
|
|
1508
|
+
const watermark = current();
|
|
1509
|
+
if (!Number.isSafeInteger(watermark) || watermark < previous || watermark < 0) throw new Error("RECOVERY_INVALID_DELETION_WATERMARK");
|
|
1510
|
+
if (watermark > manifest.deletionWatermark) throw new Error("RECOVERY_DELETION_BARRIER");
|
|
1511
|
+
return watermark;
|
|
1512
|
+
}
|
|
1513
|
+
async function checkRecoveryDeletionAsync(manifest, current, previous = 0) {
|
|
1514
|
+
const floor = await current();
|
|
1515
|
+
return checkRecoveryDeletion(manifest, () => floor, previous);
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
// src/continuity/recovery-archive-transfer.ts
|
|
1519
|
+
var endpoint = "/travel/archives/v1";
|
|
1520
|
+
var metadataLimit = 16 * 1024 * 1024;
|
|
1521
|
+
var requestLimit = 65536;
|
|
1522
|
+
var objectGroupLimit = 8;
|
|
1523
|
+
var partBodyLimit = 65536;
|
|
1524
|
+
var validId = (id2) => typeof id2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(id2);
|
|
1525
|
+
function validateObjectParts(value) {
|
|
1526
|
+
if (!Array.isArray(value) || value.length < 1 || value.length > objectGroupLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
|
|
1527
|
+
let total = 0;
|
|
1528
|
+
for (const part of value) {
|
|
1529
|
+
if (!part || Object.keys(part).length !== 3) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
|
|
1530
|
+
validateObjectRef(part.ref);
|
|
1531
|
+
if (Object.keys(part.ref).length !== 2 || !Number.isSafeInteger(part.offset) || part.offset < 0 || !Number.isSafeInteger(part.bytes) || part.bytes < 1 || part.bytes > part.ref.bytes - part.offset) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
|
|
1532
|
+
total += part.bytes;
|
|
1533
|
+
}
|
|
1534
|
+
if (total > partBodyLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
|
|
1535
|
+
return value;
|
|
1536
|
+
}
|
|
1537
|
+
function validateObjectGroup(value) {
|
|
1538
|
+
if (!Array.isArray(value) || value.length < 1 || value.length > objectGroupLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
|
|
1539
|
+
const hashes = /* @__PURE__ */ new Set();
|
|
1540
|
+
for (const ref of value) {
|
|
1541
|
+
validateObjectRef(ref);
|
|
1542
|
+
if (Object.keys(ref).length !== 2 || hashes.has(ref.sha256)) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
|
|
1543
|
+
hashes.add(ref.sha256);
|
|
1544
|
+
}
|
|
1545
|
+
return value;
|
|
1546
|
+
}
|
|
1547
|
+
function validCommon(value) {
|
|
1548
|
+
return !!value && Object.keys(value).length === 2 && Number.isSafeInteger(value.sequence) && value.sequence >= 1 && typeof value.digest === "string" && /^[a-f0-9]{64}$/.test(value.digest);
|
|
1549
|
+
}
|
|
1550
|
+
function validateManifests(value) {
|
|
1551
|
+
if (!Array.isArray(value) || value.length > 4094) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
|
|
1552
|
+
return value.map((manifest) => normalizePublication(manifest));
|
|
1553
|
+
}
|
|
1554
|
+
function validateCatalog(value) {
|
|
1555
|
+
if (!Array.isArray(value) || value.length > 4096) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
|
|
1556
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1557
|
+
for (const receipt of value) {
|
|
1558
|
+
if (!receipt || !validId(receipt.id) || ids.has(receipt.id) || receipt.state !== "PRESERVED" || receipt.activationAllowed !== false || !["COMMON", "LOCAL", "REMOTE"].includes(receipt.kind) || ![receipt.digest, receipt.manifestDigest].every((value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/.test(value2)) || !Number.isSafeInteger(receipt.deletionWatermark) || receipt.deletionWatermark < 0 || Object.keys(receipt).some((key) => !["id", "state", "kind", "digest", "manifestDigest", "deletionWatermark", "activationAllowed", "publication"].includes(key))) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
|
|
1559
|
+
const publication = receipt.publication;
|
|
1560
|
+
if (receipt.kind === "LOCAL" ? publication !== void 0 : !publication || publication.state !== "PUBLISHED" || publication.activationAllowed !== false || publication.digest !== receipt.manifestDigest || publication.deletionWatermark !== receipt.deletionWatermark || !Number.isSafeInteger(publication.sequence) || publication.sequence < 1 || Object.keys(publication).some((key) => !["state", "sequence", "digest", "deletionWatermark", "activationAllowed"].includes(key))) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
|
|
1561
|
+
ids.add(receipt.id);
|
|
1562
|
+
}
|
|
1563
|
+
return value;
|
|
1564
|
+
}
|
|
1565
|
+
function refs(entry) {
|
|
1566
|
+
const result = /* @__PURE__ */ new Map();
|
|
1567
|
+
for (const file of [...entry.databases.map((db) => db.content), ...entry.manifest.trees.flatMap((tree) => tree.files.map((file2) => file2.content))]) for (const ref of file.chunks) {
|
|
1568
|
+
const prior = result.get(ref.sha256);
|
|
1569
|
+
if (prior && prior.bytes !== ref.bytes) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
|
|
1570
|
+
result.set(ref.sha256, ref);
|
|
1571
|
+
}
|
|
1572
|
+
return result;
|
|
1573
|
+
}
|
|
1574
|
+
function createRecoveryArchiveServer(options) {
|
|
1575
|
+
const { archive: fixedArchive, resolveArchive, listReceipts, readManifests, readManifestEvidence, identity = options.archive?.objects.identity, authority, allowedPeers, assertAvailable, bodyTimeoutMs = 5e3, ...tls } = options;
|
|
1576
|
+
if (!identity || !fixedArchive && !resolveArchive || fixedArchive && resolveArchive) throw new Error("RECOVERY_TRANSFER_CONFIG");
|
|
1577
|
+
if (typeof assertAvailable !== "function" || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 10 || bodyTimeoutMs > 3e4) throw new Error("RECOVERY_TRANSFER_CONFIG");
|
|
1578
|
+
const peers = new Map(Object.entries(allowedPeers).map(([fingerprint, credential]) => [fingerprint.replaceAll(":", "").toLowerCase(), credential]));
|
|
1579
|
+
if (!peers.size || [...peers.keys()].some((key) => !/^[a-f0-9]{64}$/.test(key))) throw new Error("RECOVERY_TRANSFER_CONFIG");
|
|
1580
|
+
const busy = /* @__PURE__ */ new Map();
|
|
1581
|
+
const server = createServer3({ ...tls, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
|
|
1582
|
+
const started = Date.now(), timings = {};
|
|
1583
|
+
let phase = "authenticate", action = "unknown", failure;
|
|
1584
|
+
const mark = (next) => {
|
|
1585
|
+
timings[phase] = Date.now() - started;
|
|
1586
|
+
phase = next;
|
|
1587
|
+
};
|
|
1588
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1589
|
+
const refuse = (status, error) => {
|
|
1590
|
+
if (!res.writableEnded && !res.destroyed) {
|
|
1591
|
+
res.statusCode = status;
|
|
1592
|
+
res.setHeader("Content-Type", "application/json");
|
|
1593
|
+
res.end(JSON.stringify({ error }));
|
|
1594
|
+
}
|
|
1595
|
+
};
|
|
1596
|
+
const socket = req.socket, fingerprint = (socket.getPeerCertificate().fingerprint256 ?? "").replaceAll(":", "").toLowerCase(), credential = peers.get(fingerprint);
|
|
1597
|
+
let principal;
|
|
1598
|
+
try {
|
|
1599
|
+
if (!socket.authorized || !credential) throw new Error();
|
|
1600
|
+
[principal] = await Promise.all([authority.authenticate(credential), assertAvailable()]);
|
|
1601
|
+
if (["tenantId", "companionId", "seatId"].some((key) => principal[key] !== identity[key])) throw new Error();
|
|
1602
|
+
} catch {
|
|
1603
|
+
refuse(403, "RECOVERY_TRANSFER_DENIED");
|
|
1604
|
+
req.resume();
|
|
1605
|
+
return;
|
|
1606
|
+
}
|
|
1607
|
+
if (req.method !== "POST" || req.url !== endpoint) {
|
|
1608
|
+
refuse(404, "RECOVERY_TRANSFER_NOT_FOUND");
|
|
1609
|
+
req.resume();
|
|
1610
|
+
return;
|
|
1611
|
+
}
|
|
1612
|
+
const header = req.headers["x-engine7-recovery-archive"];
|
|
1613
|
+
const archiveDigest = typeof header === "string" && /^[a-f0-9]{64}$/.test(header) ? header : void 0;
|
|
1614
|
+
if (header !== void 0 && !archiveDigest) {
|
|
1615
|
+
refuse(409, "RECOVERY_TRANSFER_REFUSED");
|
|
1616
|
+
req.resume();
|
|
1617
|
+
return;
|
|
1618
|
+
}
|
|
1619
|
+
const slots = busy.get(fingerprint) ?? /* @__PURE__ */ new Set();
|
|
1620
|
+
if (slots.size >= 2 || slots.size && (!archiveDigest || [...slots].some((slot2) => slot2.archiveDigest !== archiveDigest)) || !slots.size && busy.size >= 4) {
|
|
1621
|
+
refuse(503, "RECOVERY_TRANSFER_BUSY");
|
|
1622
|
+
req.resume();
|
|
1623
|
+
return;
|
|
1624
|
+
}
|
|
1625
|
+
const slot = { archiveDigest };
|
|
1626
|
+
slots.add(slot);
|
|
1627
|
+
busy.set(fingerprint, slots);
|
|
1628
|
+
mark("body");
|
|
1629
|
+
const timer = setTimeout(() => {
|
|
1630
|
+
refuse(408, "RECOVERY_TRANSFER_REFUSED");
|
|
1631
|
+
req.destroy();
|
|
1632
|
+
}, bodyTimeoutMs);
|
|
1633
|
+
try {
|
|
1634
|
+
const chunks = [];
|
|
1635
|
+
let bytes = 0;
|
|
1636
|
+
for await (const chunk of req) {
|
|
1637
|
+
bytes += chunk.length;
|
|
1638
|
+
if (bytes > requestLimit) throw new Error();
|
|
1639
|
+
chunks.push(Buffer.from(chunk));
|
|
1640
|
+
}
|
|
1641
|
+
clearTimeout(timer);
|
|
1642
|
+
const input = JSON.parse(Buffer.concat(chunks).toString());
|
|
1643
|
+
if (archiveDigest && input?.action !== "parts") throw new Error();
|
|
1644
|
+
action = ["list", "read", "object", "objects", "parts", "manifests", "manifest-page"].includes(input?.action) ? input.action : "invalid";
|
|
1645
|
+
mark("resolve");
|
|
1646
|
+
if (input?.version === 1 && input.action === "list") {
|
|
1647
|
+
if (Object.keys(input).some((key) => !["version", "action"].includes(key))) throw new Error();
|
|
1648
|
+
const receipts = validateCatalog(await (listReceipts?.() ?? fixedArchive?.list({ maximum: 4096 }) ?? Promise.reject(new Error())));
|
|
1649
|
+
const [control2] = await Promise.all([authority.status(principal), assertAvailable()]), current = control2.deletionWatermark;
|
|
1650
|
+
if (receipts.some((receipt) => receipt.deletionWatermark < current)) throw new Error();
|
|
1651
|
+
const body2 = Buffer.from(JSON.stringify(receipts));
|
|
1652
|
+
if (body2.length > metadataLimit) throw new Error();
|
|
1653
|
+
res.setHeader("Content-Type", "application/json");
|
|
1654
|
+
res.setHeader("Content-Length", body2.length);
|
|
1655
|
+
res.end(body2);
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
const ancestry = ["manifests", "manifest-page"].includes(input?.action), paged = input?.action === "manifest-page";
|
|
1659
|
+
if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : input.action === "objects" ? ["refs"] : input.action === "parts" ? ["parts"] : ancestry ? ["common"] : []].includes(key))) throw new Error();
|
|
1660
|
+
await Promise.all([assertAvailable(), authority.status(principal)]);
|
|
1661
|
+
if (ancestry && !validCommon(input.common)) throw new Error();
|
|
1662
|
+
const evidence = ancestry && readManifestEvidence ? await readManifestEvidence(input.id, input.common, paged ? 4 : void 0) : void 0;
|
|
1663
|
+
const archive = evidence ? void 0 : resolveArchive ? await resolveArchive(input.id) : fixedArchive;
|
|
1664
|
+
mark("entry");
|
|
1665
|
+
if (archive && ["tenantId", "companionId", "seatId"].some((key) => archive.objects.identity[key] !== identity[key])) throw new Error();
|
|
1666
|
+
const entry = evidence?.entry ?? await archive.read(input.id);
|
|
1667
|
+
if (entry.id !== input.id) throw new Error();
|
|
1668
|
+
if (archiveDigest) {
|
|
1669
|
+
validateRecoveryArchiveEntry(entry, { tenantId: identity.tenantId, companionId: identity.companionId, seatId: identity.seatId });
|
|
1670
|
+
if (entry.receipt.digest !== archiveDigest) throw new Error();
|
|
1671
|
+
}
|
|
1672
|
+
if (evidence) validateRecoveryArchiveEntry(entry, { tenantId: identity.tenantId, companionId: identity.companionId, seatId: identity.seatId });
|
|
1673
|
+
const floor = (await authority.status(principal)).deletionWatermark;
|
|
1674
|
+
await checkRecoveryDeletionAsync(entry.manifest, () => floor);
|
|
1675
|
+
mark("content");
|
|
1676
|
+
let body;
|
|
1677
|
+
if (ancestry) {
|
|
1678
|
+
if (!evidence && !readManifests || entry.kind !== "LOCAL") throw new Error();
|
|
1679
|
+
const originals = validateManifests(evidence?.manifests ?? await readManifests(input.id, input.common));
|
|
1680
|
+
const manifests = paged ? originals.slice(0, 4) : originals, end = entry.manifest;
|
|
1681
|
+
if (end.sequence < input.common.sequence || end.sequence - input.common.sequence - 1 > 4094 || manifests.length !== (paged ? Math.min(4, Math.max(0, end.sequence - input.common.sequence - 1)) : Math.max(0, end.sequence - input.common.sequence - 1))) throw new Error();
|
|
1682
|
+
let parent = input.common.digest, sequence = input.common.sequence;
|
|
1683
|
+
const complete = end.sequence - input.common.sequence <= manifests.length + 1;
|
|
1684
|
+
for (const manifest of [...manifests, ...complete && end.sequence !== sequence ? [end] : []]) {
|
|
1685
|
+
if (manifest.sequence !== ++sequence || manifest.parentDigest !== parent || JSON.stringify(manifest.profile) !== JSON.stringify(end.profile)) throw new Error();
|
|
1686
|
+
parent = publicationDigest(manifest);
|
|
1687
|
+
}
|
|
1688
|
+
if (complete && parent !== entry.receipt.manifestDigest) throw new Error();
|
|
1689
|
+
body = Buffer.from(JSON.stringify(paged ? { manifests, end } : manifests));
|
|
1690
|
+
if (body.length > 32 * 1024 * 1024) throw new Error();
|
|
1691
|
+
res.setHeader("Content-Type", "application/json");
|
|
1692
|
+
} else if (input.action === "read") {
|
|
1693
|
+
body = Buffer.from(JSON.stringify(entry));
|
|
1694
|
+
if (body.length > metadataLimit) throw new Error();
|
|
1695
|
+
res.setHeader("Content-Type", "application/json");
|
|
1696
|
+
} else if (input.action === "parts") {
|
|
1697
|
+
const group = validateObjectParts(input.parts), allowed = refs(entry), parts = [];
|
|
1698
|
+
if (group.some((part) => allowed.get(part.ref.sha256)?.bytes !== part.ref.bytes)) throw new Error();
|
|
1699
|
+
for (const part of group) {
|
|
1700
|
+
const content = await archive.objects.read(part.ref);
|
|
1701
|
+
parts.push(content.subarray(part.offset, part.offset + part.bytes));
|
|
1702
|
+
}
|
|
1703
|
+
body = Buffer.concat(parts);
|
|
1704
|
+
res.setHeader("Content-Type", "application/octet-stream");
|
|
1705
|
+
} else if (input.action === "objects") {
|
|
1706
|
+
const group = validateObjectGroup(input.refs), allowed = refs(entry);
|
|
1707
|
+
if (group.some((ref) => allowed.get(ref.sha256)?.bytes !== ref.bytes)) throw new Error();
|
|
1708
|
+
const parts = [];
|
|
1709
|
+
for (const ref of group) parts.push(await archive.objects.read(ref));
|
|
1710
|
+
body = Buffer.concat(parts);
|
|
1711
|
+
res.setHeader("Content-Type", "application/octet-stream");
|
|
1712
|
+
} else {
|
|
1713
|
+
validateObjectRef(input.ref);
|
|
1714
|
+
if (Object.keys(input.ref).length !== 2 || refs(entry).get(input.ref.sha256)?.bytes !== input.ref.bytes) throw new Error();
|
|
1715
|
+
body = await archive.objects.read(input.ref);
|
|
1716
|
+
res.setHeader("Content-Type", "application/octet-stream");
|
|
1717
|
+
}
|
|
1718
|
+
mark("final-floor");
|
|
1719
|
+
const [control] = await Promise.all([authority.status(principal), assertAvailable()]), latest = control.deletionWatermark;
|
|
1720
|
+
await checkRecoveryDeletionAsync(entry.manifest, () => latest, floor);
|
|
1721
|
+
mark("reply");
|
|
1722
|
+
res.setHeader("Content-Length", body.length);
|
|
1723
|
+
res.end(body);
|
|
1724
|
+
} catch (error) {
|
|
1725
|
+
failure = error instanceof Error && /^[A-Z][A-Z0-9_]{0,95}$/.test(error.message) ? error.message : "OTHER";
|
|
1726
|
+
refuse(409, "RECOVERY_TRANSFER_REFUSED");
|
|
1727
|
+
} finally {
|
|
1728
|
+
clearTimeout(timer);
|
|
1729
|
+
slots.delete(slot);
|
|
1730
|
+
if (!slots.size) busy.delete(fingerprint);
|
|
1731
|
+
if (failure || Date.now() - started >= 5e3) process.stderr.write("[travel-archive] " + JSON.stringify({ at: Date.now(), action, phase, elapsedMs: Date.now() - started, timings, failure }) + "\n");
|
|
1732
|
+
}
|
|
1733
|
+
});
|
|
1734
|
+
server.headersTimeout = 5e3;
|
|
1735
|
+
server.requestTimeout = 1e4;
|
|
1736
|
+
server.keepAliveTimeout = 1e4;
|
|
1737
|
+
server.maxConnections = 16;
|
|
1738
|
+
server.maxRequestsPerSocket = 256;
|
|
1739
|
+
server.on("tlsClientError", () => {
|
|
1740
|
+
});
|
|
1741
|
+
return server;
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
// src/continuity/node-data-server.ts
|
|
1745
|
+
async function createTravelNodeDataServer(options) {
|
|
1746
|
+
const { node, authority, allowedPeers, ...tls } = options;
|
|
1747
|
+
const entries = Object.entries(allowedPeers);
|
|
1748
|
+
if (entries.length !== 1) throw new Error("TRAVEL_NODE_LISTENER_CONFIG");
|
|
1749
|
+
const [fingerprint, credential] = entries[0], peer = await authority.authenticate(credential);
|
|
1750
|
+
if (peer.nodeId === node.principal.nodeId || ["tenantId", "companionId", "seatId"].some((field) => peer[field] !== node.principal[field])) throw new Error("TRAVEL_NODE_LISTENER_IDENTITY");
|
|
1751
|
+
const assertAvailable = () => node.assertDataAvailable();
|
|
1752
|
+
const publication = createPublicationServer({
|
|
1753
|
+
...tls,
|
|
1754
|
+
allowedFingerprint: fingerprint,
|
|
1755
|
+
currentReceiver: () => node.currentReceiver(),
|
|
1756
|
+
preservePublished: (receiver) => node.preservePublishedReceiver(receiver),
|
|
1757
|
+
assertAvailable: async () => {
|
|
1758
|
+
const [current] = await Promise.all([Promise.resolve().then(() => authority.authenticate(credential)), Promise.resolve().then(() => authority.status(peer)), assertAvailable()]);
|
|
1759
|
+
if (["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].some((field) => current[field] !== peer[field])) throw new Error("PUBLICATION_DENIED");
|
|
1760
|
+
}
|
|
1761
|
+
});
|
|
1762
|
+
const archive = createRecoveryArchiveServer({
|
|
1763
|
+
...tls,
|
|
1764
|
+
authority,
|
|
1765
|
+
allowedPeers,
|
|
1766
|
+
identity: node.principal,
|
|
1767
|
+
assertAvailable,
|
|
1768
|
+
resolveArchive: (id2) => node.resolveDataArchive(id2),
|
|
1769
|
+
listReceipts: () => node.listDataArchiveReceipts(),
|
|
1770
|
+
readManifestEvidence: (id2, common, maximum) => node.readRecoveryManifestEvidence(common, id2, maximum)
|
|
1771
|
+
});
|
|
1772
|
+
const server = createServer4({ ...tls, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, (req, res) => {
|
|
1773
|
+
if (req.url === "/travel/sync/v1") publication.emit("request", req, res);
|
|
1774
|
+
else if (req.url === "/travel/archives/v1") archive.emit("request", req, res);
|
|
1775
|
+
else {
|
|
1776
|
+
req.resume();
|
|
1777
|
+
res.statusCode = 404;
|
|
1778
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1779
|
+
res.end();
|
|
1780
|
+
}
|
|
1781
|
+
});
|
|
1782
|
+
server.headersTimeout = 5e3;
|
|
1783
|
+
server.requestTimeout = 15e3;
|
|
1784
|
+
server.keepAliveTimeout = 1e4;
|
|
1785
|
+
server.maxConnections = 16;
|
|
1786
|
+
server.maxRequestsPerSocket = 256;
|
|
1787
|
+
server.setTimeout(15e3, (socket) => socket.destroy());
|
|
1788
|
+
server.on("tlsClientError", () => {
|
|
1789
|
+
});
|
|
1790
|
+
return server;
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
// src/continuity/controller-main.ts
|
|
1794
|
+
var path = (value) => {
|
|
1795
|
+
if (typeof value !== "string" || !isAbsolute(value) || resolve2(value) !== value) throw new Error("TRAVEL_CONTROLLER_PATH");
|
|
1796
|
+
return value;
|
|
1797
|
+
};
|
|
1798
|
+
function openTravelController(input) {
|
|
1799
|
+
if (!nodeSupervisorRecord(input) || !nodeSupervisorRecord(input.nodes) || Object.keys(input.nodes).length !== 2 || !nodeSupervisorRecord(input.tls)) throw new Error("TRAVEL_CONTROLLER_CONFIG");
|
|
1800
|
+
const config = input;
|
|
1801
|
+
const nodes = {}, grants = {};
|
|
1802
|
+
const privateKey = readPrivateFile(path(config.tls?.keyFile), 65536);
|
|
1803
|
+
const closeClients = () => {
|
|
1804
|
+
for (const node of Object.values(nodes)) node.close();
|
|
1805
|
+
for (const grant of Object.values(grants)) grant.client.close();
|
|
1806
|
+
privateKey.fill(0);
|
|
1807
|
+
};
|
|
1808
|
+
try {
|
|
1809
|
+
const tls = { ca: readFileSync3(path(config.tls?.caFile)), cert: readFileSync3(path(config.tls?.certFile)), key: privateKey };
|
|
1810
|
+
for (const [nodeId, value] of Object.entries(config.nodes)) {
|
|
1811
|
+
if (!nodeSupervisorId(nodeId) || !nodeSupervisorRecord(value) || !nodeSupervisorRecord(value.principal) || value.principal.nodeId !== nodeId) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
1812
|
+
const principal = value.principal;
|
|
1813
|
+
nodes[nodeId] = new RemoteTravelNodeSupervisor({ url: value.url, principal, credential: value.credential, ...tls, timeoutMs: config.nodeTimeoutMs });
|
|
1814
|
+
grants[nodeId] = { principal, client: new TravelManagementClient({ url: value.authorityUrl, nodeId, credential: value.credential, ...tls, timeoutMs: config.authorityTimeoutMs }) };
|
|
1815
|
+
}
|
|
1816
|
+
const authority = new RemoteTravelControllerAuthority(grants);
|
|
1817
|
+
const controller = new TravelController({
|
|
1818
|
+
directory: path(config.directory),
|
|
1819
|
+
authority,
|
|
1820
|
+
nodes,
|
|
1821
|
+
preferredNodeId: config.preferredNodeId,
|
|
1822
|
+
intervalMs: config.intervalMs,
|
|
1823
|
+
healthyForMs: config.healthyForMs,
|
|
1824
|
+
handbackCooldownMs: config.handbackCooldownMs
|
|
1825
|
+
});
|
|
1826
|
+
let closing;
|
|
1827
|
+
const close = () => closing ??= (async () => {
|
|
1828
|
+
try {
|
|
1829
|
+
await controller.stop();
|
|
1830
|
+
controller.close();
|
|
1831
|
+
} finally {
|
|
1832
|
+
closeClients();
|
|
1833
|
+
}
|
|
1834
|
+
})();
|
|
1835
|
+
return { controller, nodes, authority, close };
|
|
1836
|
+
} catch (error) {
|
|
1837
|
+
closeClients();
|
|
1838
|
+
throw error;
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
async function runTravelControllerCli(args) {
|
|
1842
|
+
if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-controller serve|tick|handback --config /absolute/private-config.json [--transfer-id ID]" };
|
|
1843
|
+
const [action, flag, file, ...rest] = args;
|
|
1844
|
+
if (!["serve", "tick", "handback"].includes(action) || flag !== "--config" || !file) throw new Error("TRAVEL_CONTROLLER_INVALID_COMMAND");
|
|
1845
|
+
if (action === "handback" ? rest.length !== 2 || rest[0] !== "--transfer-id" || !nodeSupervisorId(rest[1]) : rest.length !== 0) throw new Error("TRAVEL_CONTROLLER_INVALID_COMMAND");
|
|
1846
|
+
const service = openTravelController(JSON.parse(readPrivateFile(path(file), 65536).toString()));
|
|
1847
|
+
if (action === "serve") {
|
|
1848
|
+
let closing = false;
|
|
1849
|
+
const stop = () => {
|
|
1850
|
+
if (closing) return;
|
|
1851
|
+
closing = true;
|
|
1852
|
+
void service.close().then(() => process.exit(0), () => process.exit(1));
|
|
1853
|
+
};
|
|
1854
|
+
process.once("SIGTERM", stop);
|
|
1855
|
+
process.once("SIGINT", stop);
|
|
1856
|
+
service.controller.start();
|
|
1857
|
+
return service.controller.status();
|
|
1858
|
+
}
|
|
1859
|
+
try {
|
|
1860
|
+
if (action === "handback") service.controller.requestHandback(rest[1]);
|
|
1861
|
+
else await service.controller.tick();
|
|
1862
|
+
const status = service.controller.status();
|
|
1863
|
+
if (status.lastError) process.exitCode = 1;
|
|
1864
|
+
return status;
|
|
1865
|
+
} finally {
|
|
1866
|
+
await service.close();
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test(fileURLToPath(import.meta.url)) && resolve2(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
1870
|
+
runTravelControllerCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
|
|
1871
|
+
process.stderr.write("TRAVEL_CONTROLLER_REFUSED\n");
|
|
1872
|
+
process.exitCode = 1;
|
|
1873
|
+
});
|
|
1874
|
+
}
|
|
1875
|
+
export {
|
|
1876
|
+
RemoteTravelDataAuthority,
|
|
1877
|
+
RemoteTravelNodeAuthority,
|
|
1878
|
+
TravelManagementClient,
|
|
1879
|
+
createTravelNodeDataServer,
|
|
1880
|
+
createTravelNodeSupervisorServer,
|
|
1881
|
+
openTravelController,
|
|
1882
|
+
runTravelControllerCli
|
|
1883
|
+
};
|