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,1068 @@
|
|
|
1
|
+
const require=(await import('node:module')).createRequire(import.meta.url)
|
|
2
|
+
|
|
3
|
+
// src/continuity/authority-main.ts
|
|
4
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
|
|
5
|
+
import { isAbsolute, join as join3, resolve as resolve2 } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
// src/continuity/authority.ts
|
|
9
|
+
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
10
|
+
import { createHash, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, verify } from "node:crypto";
|
|
11
|
+
import { existsSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
12
|
+
import { join as join2 } from "node:path";
|
|
13
|
+
|
|
14
|
+
// src/continuity/publication-objects.ts
|
|
15
|
+
import { DatabaseSync } from "node:sqlite";
|
|
16
|
+
import {
|
|
17
|
+
constants,
|
|
18
|
+
openSync,
|
|
19
|
+
closeSync,
|
|
20
|
+
fstatSync,
|
|
21
|
+
fsyncSync,
|
|
22
|
+
readSync,
|
|
23
|
+
writeSync,
|
|
24
|
+
lstatSync,
|
|
25
|
+
realpathSync,
|
|
26
|
+
mkdirSync,
|
|
27
|
+
readFileSync,
|
|
28
|
+
writeFileSync,
|
|
29
|
+
linkSync,
|
|
30
|
+
unlinkSync
|
|
31
|
+
} from "node:fs";
|
|
32
|
+
import { join, dirname, resolve } from "node:path";
|
|
33
|
+
var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
|
|
34
|
+
var HASH = /^[a-f0-9]{64}$/;
|
|
35
|
+
var MAGIC = Buffer.from("E7P1");
|
|
36
|
+
var noFollow = constants.O_NOFOLLOW ?? 0;
|
|
37
|
+
function validateObjectRef(ref) {
|
|
38
|
+
if (!ref || !HASH.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > PUBLICATION_CHUNK_BYTES)
|
|
39
|
+
throw new Error("PUBLICATION_INVALID_OBJECT");
|
|
40
|
+
}
|
|
41
|
+
function validateFileContent(file) {
|
|
42
|
+
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");
|
|
43
|
+
let total = 0;
|
|
44
|
+
for (const ref of file.chunks) {
|
|
45
|
+
validateObjectRef(ref);
|
|
46
|
+
total += ref.bytes;
|
|
47
|
+
}
|
|
48
|
+
if (total !== file.bytes || !Number.isSafeInteger(total)) throw new Error("PUBLICATION_INVALID_FILE");
|
|
49
|
+
}
|
|
50
|
+
function assertPrivateDirectory(path2) {
|
|
51
|
+
const info = lstatSync(path2);
|
|
52
|
+
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path2) !== resolve(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
53
|
+
throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
54
|
+
}
|
|
55
|
+
function syncDir(path2) {
|
|
56
|
+
if (process.platform === "win32") return;
|
|
57
|
+
const fd = openSync(path2, constants.O_RDONLY);
|
|
58
|
+
try {
|
|
59
|
+
fsyncSync(fd);
|
|
60
|
+
} finally {
|
|
61
|
+
closeSync(fd);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function preparePrivateDirectory(path2) {
|
|
65
|
+
const missing = [];
|
|
66
|
+
let parent = resolve(path2);
|
|
67
|
+
for (; ; ) {
|
|
68
|
+
try {
|
|
69
|
+
lstatSync(parent);
|
|
70
|
+
break;
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error.code !== "ENOENT") throw error;
|
|
73
|
+
}
|
|
74
|
+
missing.push(parent);
|
|
75
|
+
parent = dirname(parent);
|
|
76
|
+
}
|
|
77
|
+
if (realpathSync(parent) !== parent) throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
78
|
+
for (const directory of missing.reverse()) {
|
|
79
|
+
try {
|
|
80
|
+
mkdirSync(directory, { mode: 448 });
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error.code !== "EEXIST") throw error;
|
|
83
|
+
}
|
|
84
|
+
assertPrivateDirectory(directory);
|
|
85
|
+
syncDir(dirname(directory));
|
|
86
|
+
}
|
|
87
|
+
assertPrivateDirectory(path2);
|
|
88
|
+
}
|
|
89
|
+
function preparePrivateDatabase(path2) {
|
|
90
|
+
for (const file of [path2, path2 + "-journal", path2 + "-wal", path2 + "-shm"]) {
|
|
91
|
+
try {
|
|
92
|
+
const info2 = lstatSync(file);
|
|
93
|
+
if (!info2.isFile() || info2.isSymbolicLink() || process.platform !== "win32" && (info2.mode & 63 || info2.uid !== process.getuid()))
|
|
94
|
+
throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (error.code !== "ENOENT") throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
const fd = openSync(path2, "wx", 384);
|
|
101
|
+
closeSync(fd);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (error.code !== "EEXIST") throw error;
|
|
104
|
+
}
|
|
105
|
+
const info = lstatSync(path2);
|
|
106
|
+
if (!info.isFile() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
107
|
+
throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
|
|
108
|
+
syncDir(dirname(path2));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// src/continuity/key-service-store.ts
|
|
112
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
113
|
+
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";
|
|
114
|
+
function assertPrivateStat(stat, directory) {
|
|
115
|
+
if ((directory ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
116
|
+
throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
|
|
117
|
+
}
|
|
118
|
+
function readPrivateFile(path2, maximumBytes = 65536) {
|
|
119
|
+
assertPrivateStat(lstatSync2(path2), false);
|
|
120
|
+
const fd = openSync2(path2, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
|
|
121
|
+
try {
|
|
122
|
+
const stat = fstatSync2(fd);
|
|
123
|
+
assertPrivateStat(stat, false);
|
|
124
|
+
if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
|
|
125
|
+
return readFileSync2(fd);
|
|
126
|
+
} finally {
|
|
127
|
+
closeSync2(fd);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// src/continuity/authority.ts
|
|
132
|
+
var ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
133
|
+
var HASH2 = /^[a-f0-9]{64}$/;
|
|
134
|
+
var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
135
|
+
var hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
136
|
+
function id(value) {
|
|
137
|
+
if (typeof value !== "string" || !ID.test(value)) throw new Error("TRAVEL_INVALID_ID");
|
|
138
|
+
}
|
|
139
|
+
function natural(value) {
|
|
140
|
+
if (!Number.isSafeInteger(value) || Number(value) < 0) throw new Error("TRAVEL_INVALID_NUMBER");
|
|
141
|
+
}
|
|
142
|
+
function identityText(identity) {
|
|
143
|
+
if (!identity) throw new Error("TRAVEL_INVALID_ID");
|
|
144
|
+
id(identity.tenantId);
|
|
145
|
+
id(identity.companionId);
|
|
146
|
+
id(identity.seatId);
|
|
147
|
+
return JSON.stringify([identity.tenantId, identity.companionId, identity.seatId]);
|
|
148
|
+
}
|
|
149
|
+
function unsignedPermit(permit) {
|
|
150
|
+
const { signature, ...body } = permit;
|
|
151
|
+
return Buffer.from(JSON.stringify(body));
|
|
152
|
+
}
|
|
153
|
+
function verifyTravelPermit(permit, publicKey) {
|
|
154
|
+
try {
|
|
155
|
+
return typeof permit.signature === "string" && verify(null, unsignedPermit(permit), publicKey, Buffer.from(permit.signature, "base64"));
|
|
156
|
+
} catch {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
var TravelAuthority = class {
|
|
161
|
+
authorityBootId = randomUUID();
|
|
162
|
+
publicKey;
|
|
163
|
+
signingKey;
|
|
164
|
+
db;
|
|
165
|
+
owner;
|
|
166
|
+
monotonicNow;
|
|
167
|
+
wallNow;
|
|
168
|
+
leaseMs;
|
|
169
|
+
deadlines = /* @__PURE__ */ new Map();
|
|
170
|
+
healthy = /* @__PURE__ */ new Map();
|
|
171
|
+
leaseSequence = 0;
|
|
172
|
+
closed = false;
|
|
173
|
+
constructor(options) {
|
|
174
|
+
this.monotonicNow = options.monotonicNow ?? (() => Number(process.hrtime.bigint() / 1000000n));
|
|
175
|
+
this.wallNow = options.wallNow ?? Date.now;
|
|
176
|
+
this.leaseMs = options.leaseMs ?? 3e4;
|
|
177
|
+
if (!Number.isSafeInteger(this.leaseMs) || this.leaseMs < 100 || this.leaseMs > 3e5) throw new Error("TRAVEL_INVALID_LEASE");
|
|
178
|
+
preparePrivateDirectory(options.directory);
|
|
179
|
+
const ownerFile = join2(options.directory, "authority-owner.sqlite");
|
|
180
|
+
preparePrivateDatabase(ownerFile);
|
|
181
|
+
this.owner = new DatabaseSync3(ownerFile);
|
|
182
|
+
try {
|
|
183
|
+
this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY); BEGIN IMMEDIATE");
|
|
184
|
+
} catch (error) {
|
|
185
|
+
this.owner.close();
|
|
186
|
+
throw new Error("TRAVEL_AUTHORITY_BUSY", { cause: error });
|
|
187
|
+
}
|
|
188
|
+
const path2 = join2(options.directory, "authority.sqlite"), keyFile = join2(options.directory, "authority-signing.pem");
|
|
189
|
+
try {
|
|
190
|
+
const present = existsSync(path2), keyPresent = existsSync(keyFile);
|
|
191
|
+
if (present !== keyPresent) throw new Error("TRAVEL_AUTHORITY_RECOVERY_REQUIRED");
|
|
192
|
+
if (!keyPresent) {
|
|
193
|
+
const keys = generateKeyPairSync("ed25519");
|
|
194
|
+
writeFileSync2(keyFile, keys.privateKey.export({ format: "pem", type: "pkcs8" }), { mode: 384, flag: "wx", flush: true });
|
|
195
|
+
}
|
|
196
|
+
this.signingKey = readPrivateFile(keyFile).toString();
|
|
197
|
+
this.publicKey = createPublicKey(this.signingKey).export({ format: "pem", type: "spki" }).toString();
|
|
198
|
+
preparePrivateDatabase(path2);
|
|
199
|
+
this.db = new DatabaseSync3(path2);
|
|
200
|
+
this.db.exec(`PRAGMA busy_timeout=1000; PRAGMA synchronous=FULL;
|
|
201
|
+
CREATE TABLE IF NOT EXISTS seats(identity TEXT PRIMARY KEY,epoch INTEGER NOT NULL,active_node TEXT,active_boot TEXT,
|
|
202
|
+
floor INTEGER NOT NULL,checkpoint TEXT NOT NULL,build TEXT NOT NULL,retired TEXT,frozen INTEGER NOT NULL DEFAULT 0);
|
|
203
|
+
CREATE TABLE IF NOT EXISTS nodes(identity TEXT NOT NULL,node_id TEXT NOT NULL,role TEXT NOT NULL,credential_hash TEXT UNIQUE NOT NULL,
|
|
204
|
+
boot TEXT,sequence INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(identity,node_id));
|
|
205
|
+
CREATE TABLE IF NOT EXISTS boots(identity TEXT NOT NULL,node_id TEXT NOT NULL,boot TEXT NOT NULL,PRIMARY KEY(identity,node_id,boot));
|
|
206
|
+
CREATE TABLE IF NOT EXISTS deletions(companion TEXT NOT NULL,id TEXT NOT NULL,body TEXT NOT NULL,watermark INTEGER NOT NULL,
|
|
207
|
+
PRIMARY KEY(companion,id),UNIQUE(companion,watermark));
|
|
208
|
+
CREATE TABLE IF NOT EXISTS handoffs(identity TEXT NOT NULL,id TEXT NOT NULL,source TEXT NOT NULL,target TEXT NOT NULL,
|
|
209
|
+
source_epoch INTEGER NOT NULL,target_boot TEXT,state TEXT NOT NULL,checkpoint TEXT,result TEXT,PRIMARY KEY(identity,id));
|
|
210
|
+
CREATE TABLE IF NOT EXISTS checkpoints(identity TEXT NOT NULL,digest TEXT NOT NULL,parent TEXT,epoch INTEGER NOT NULL,
|
|
211
|
+
PRIMARY KEY(identity,digest));
|
|
212
|
+
CREATE TABLE IF NOT EXISTS recovery_branches(identity TEXT NOT NULL,common TEXT NOT NULL,local TEXT NOT NULL,
|
|
213
|
+
chain TEXT NOT NULL,PRIMARY KEY(identity,common,local));`);
|
|
214
|
+
this.db.exec("CREATE TABLE IF NOT EXISTS retirement_sources(identity TEXT PRIMARY KEY,body TEXT NOT NULL)");
|
|
215
|
+
if (this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_AUTHORITY_CORRUPT");
|
|
216
|
+
this.transaction(() => {
|
|
217
|
+
this.db.exec("UPDATE seats SET epoch=epoch+1,active_node=NULL,active_boot=NULL,frozen=0 WHERE retired IS NULL");
|
|
218
|
+
this.db.exec("UPDATE handoffs SET state='ABORTED' WHERE state NOT IN ('COMMITTED','ABORTED')");
|
|
219
|
+
});
|
|
220
|
+
} catch (error) {
|
|
221
|
+
this.db?.close();
|
|
222
|
+
this.owner.close();
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
transaction(operation) {
|
|
227
|
+
if (this.closed) throw new Error("TRAVEL_AUTHORITY_CLOSED");
|
|
228
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
229
|
+
try {
|
|
230
|
+
const result = operation();
|
|
231
|
+
this.db.exec("COMMIT");
|
|
232
|
+
return result;
|
|
233
|
+
} catch (error) {
|
|
234
|
+
this.db.exec("ROLLBACK");
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
seat(identity, allowRetired = false) {
|
|
239
|
+
const row = this.db.prepare("SELECT * FROM seats WHERE identity=?").get(identityText(identity));
|
|
240
|
+
if (!row) throw new Error("TRAVEL_AUTH_DENIED");
|
|
241
|
+
if (row.retired && !allowRetired) throw new Error("TRAVEL_SEAT_RETIRED");
|
|
242
|
+
return row;
|
|
243
|
+
}
|
|
244
|
+
principal(principal) {
|
|
245
|
+
const text = identityText(principal);
|
|
246
|
+
const node = this.db.prepare("SELECT * FROM nodes WHERE identity=? AND node_id=? AND credential_hash=?").get(text, principal.nodeId, principal.credentialHash);
|
|
247
|
+
if (!node || node.role !== principal.role) throw new Error("TRAVEL_AUTH_DENIED");
|
|
248
|
+
this.seat(principal);
|
|
249
|
+
return node;
|
|
250
|
+
}
|
|
251
|
+
provisionSeat(identity, nodes, baseline) {
|
|
252
|
+
const text = identityText(identity);
|
|
253
|
+
if (!HASH2.test(baseline.checkpointDigest)) throw new Error("TRAVEL_INVALID_CHECKPOINT");
|
|
254
|
+
id(baseline.buildManifestId);
|
|
255
|
+
const entries = Object.entries(nodes);
|
|
256
|
+
if (entries.length < 1 || entries.length > 16) throw new Error("TRAVEL_INVALID_NODES");
|
|
257
|
+
return this.transaction(() => {
|
|
258
|
+
if (this.db.prepare("SELECT 1 FROM seats WHERE identity=?").get(text)) throw new Error("TRAVEL_SEAT_EXISTS");
|
|
259
|
+
const companion = JSON.stringify([identity.tenantId, identity.companionId]);
|
|
260
|
+
const floor = Number(this.db.prepare("SELECT COALESCE(MAX(watermark),0) AS floor FROM deletions WHERE companion=?").get(companion).floor);
|
|
261
|
+
this.db.prepare("INSERT INTO seats VALUES(?,1,NULL,NULL,?,?,?,NULL,0)").run(text, floor, baseline.checkpointDigest, baseline.buildManifestId);
|
|
262
|
+
this.db.prepare("INSERT INTO checkpoints VALUES(?,?,NULL,1)").run(text, baseline.checkpointDigest);
|
|
263
|
+
const credentials = {};
|
|
264
|
+
for (const [node, role] of entries) {
|
|
265
|
+
id(node);
|
|
266
|
+
if (!["LOCAL", "CLOUD"].includes(role)) throw new Error("TRAVEL_INVALID_NODES");
|
|
267
|
+
const credential = "e7t_" + randomBytes(32).toString("hex");
|
|
268
|
+
this.db.prepare("INSERT INTO nodes(identity,node_id,role,credential_hash) VALUES(?,?,?,?)").run(text, node, role, hash(credential));
|
|
269
|
+
credentials[node] = credential;
|
|
270
|
+
}
|
|
271
|
+
return credentials;
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
authenticate(credential) {
|
|
275
|
+
return this.authenticateNode(credential, false);
|
|
276
|
+
}
|
|
277
|
+
authenticateRetirement(credential) {
|
|
278
|
+
return this.authenticateNode(credential, true);
|
|
279
|
+
}
|
|
280
|
+
authenticateNode(credential, allowRetired) {
|
|
281
|
+
if (typeof credential !== "string" || !/^e7t_[a-f0-9]{64}$/.test(credential)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
282
|
+
const row = this.db.prepare("SELECT identity,node_id,role,credential_hash FROM nodes WHERE credential_hash=?").get(hash(credential));
|
|
283
|
+
if (!row) throw new Error("TRAVEL_AUTH_DENIED");
|
|
284
|
+
const [tenantId, companionId, seatId] = JSON.parse(String(row.identity));
|
|
285
|
+
const principal = { tenantId, companionId, seatId, nodeId: String(row.node_id), role: row.role, credentialHash: String(row.credential_hash) };
|
|
286
|
+
this.seat(principal, allowRetired);
|
|
287
|
+
return principal;
|
|
288
|
+
}
|
|
289
|
+
register(principal, bootId) {
|
|
290
|
+
id(bootId);
|
|
291
|
+
this.transaction(() => {
|
|
292
|
+
const node = this.principal(principal), text = identityText(principal);
|
|
293
|
+
if (node.boot === bootId) {
|
|
294
|
+
this.healthy.set(text + principal.nodeId, this.monotonicNow() + this.leaseMs);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
if (this.db.prepare("SELECT 1 FROM boots WHERE identity=? AND node_id=? AND boot=?").get(text, principal.nodeId, bootId)) throw new Error("TRAVEL_BOOT_RETIRED");
|
|
298
|
+
this.db.prepare("INSERT INTO boots VALUES(?,?,?)").run(text, principal.nodeId, bootId);
|
|
299
|
+
this.db.prepare("UPDATE nodes SET boot=?,sequence=0 WHERE identity=? AND node_id=?").run(bootId, text, principal.nodeId);
|
|
300
|
+
const seat = this.seat(principal);
|
|
301
|
+
if (seat.active_node === principal.nodeId) {
|
|
302
|
+
this.db.prepare("UPDATE seats SET epoch=epoch+1,active_node=NULL,active_boot=NULL,frozen=0 WHERE identity=?").run(text);
|
|
303
|
+
this.deadlines.delete(text);
|
|
304
|
+
this.db.prepare("UPDATE handoffs SET state='ABORTED' WHERE identity=? AND state NOT IN ('COMMITTED','ABORTED')").run(text);
|
|
305
|
+
}
|
|
306
|
+
this.healthy.set(text + principal.nodeId, this.monotonicNow() + this.leaseMs);
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
readiness(row, ready) {
|
|
310
|
+
if (!ready || ready.volumeVerified !== true || ready.capabilitiesVerified !== true || ready.effectsLoaded !== true || ready.unresolvedCritical !== 0) throw new Error("TRAVEL_NOT_READY");
|
|
311
|
+
natural(ready.deletionWatermark);
|
|
312
|
+
if (ready.checkpointDigest !== row.checkpoint || ready.deletionWatermark !== row.floor || ready.buildManifestId !== row.build) throw new Error("TRAVEL_READINESS_BARRIER");
|
|
313
|
+
}
|
|
314
|
+
issue(identity, row) {
|
|
315
|
+
const text = identityText(identity), expiresAt = this.deadlines.get(text);
|
|
316
|
+
const body = {
|
|
317
|
+
tenantId: identity.tenantId,
|
|
318
|
+
companionId: identity.companionId,
|
|
319
|
+
seatId: identity.seatId,
|
|
320
|
+
nodeId: row.active_node,
|
|
321
|
+
bootId: row.active_boot,
|
|
322
|
+
authorityBootId: this.authorityBootId,
|
|
323
|
+
epoch: Number(row.epoch),
|
|
324
|
+
deletionWatermark: Number(row.floor),
|
|
325
|
+
leaseSequence: ++this.leaseSequence,
|
|
326
|
+
expiresAt,
|
|
327
|
+
validForMs: Math.max(0, Math.floor(expiresAt - this.monotonicNow()))
|
|
328
|
+
};
|
|
329
|
+
return { ...body, signature: sign(null, Buffer.from(JSON.stringify(body)), this.signingKey).toString("base64") };
|
|
330
|
+
}
|
|
331
|
+
acquire(principal, ready) {
|
|
332
|
+
return this.transaction(() => {
|
|
333
|
+
const node = this.principal(principal), text = identityText(principal), row = this.seat(principal);
|
|
334
|
+
if (!node.boot) throw new Error("TRAVEL_BOOT_REQUIRED");
|
|
335
|
+
this.readiness(row, ready);
|
|
336
|
+
if (row.frozen) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
337
|
+
if (row.active_node && (this.deadlines.get(text) ?? 0) > this.monotonicNow() && row.active_node !== principal.nodeId) throw new Error("TRAVEL_LEASE_HELD");
|
|
338
|
+
if (row.active_node && ((this.deadlines.get(text) ?? 0) <= this.monotonicNow() || row.active_boot !== node.boot)) row.epoch++;
|
|
339
|
+
row.active_node = principal.nodeId;
|
|
340
|
+
row.active_boot = String(node.boot);
|
|
341
|
+
this.db.prepare("UPDATE seats SET epoch=?,active_node=?,active_boot=? WHERE identity=?").run(row.epoch, row.active_node, row.active_boot, text);
|
|
342
|
+
this.deadlines.set(text, this.monotonicNow() + this.leaseMs);
|
|
343
|
+
this.healthy.set(text + principal.nodeId, this.monotonicNow() + this.leaseMs);
|
|
344
|
+
return this.issue(principal, row);
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
assertPermit(permit, operation) {
|
|
348
|
+
if (!verifyTravelPermit(permit, this.publicKey)) throw new Error("TRAVEL_INVALID_PERMIT");
|
|
349
|
+
const row = this.seat(permit), text = identityText(permit);
|
|
350
|
+
if (permit.authorityBootId !== this.authorityBootId || permit.epoch !== Number(row.epoch) || permit.nodeId !== row.active_node || permit.bootId !== row.active_boot) throw new Error("TRAVEL_STALE_PERMIT");
|
|
351
|
+
if (permit.expiresAt <= this.monotonicNow() || (this.deadlines.get(text) ?? 0) <= this.monotonicNow()) throw new Error("TRAVEL_LEASE_EXPIRED");
|
|
352
|
+
if (operation !== "CONTROL" && row.frozen) throw new Error("TRAVEL_HANDOFF_FROZEN");
|
|
353
|
+
if (operation !== "CONTROL" && permit.deletionWatermark !== Number(row.floor)) throw new Error("TRAVEL_DELETION_BARRIER");
|
|
354
|
+
}
|
|
355
|
+
heartbeat(principal, request) {
|
|
356
|
+
return this.transaction(() => {
|
|
357
|
+
const node = this.principal(principal), text = identityText(principal), seat = this.seat(principal);
|
|
358
|
+
natural(request.sequence);
|
|
359
|
+
if (request.bootId !== node.boot) throw new Error("TRAVEL_BOOT_MISMATCH");
|
|
360
|
+
if (request.sequence <= Number(node.sequence)) throw new Error("TRAVEL_HEARTBEAT_REPLAY");
|
|
361
|
+
let permit;
|
|
362
|
+
if (request.permit) {
|
|
363
|
+
this.assertPermit(request.permit, "CONTROL");
|
|
364
|
+
if (request.permit.nodeId !== principal.nodeId || !same(identityText(request.permit), text)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
365
|
+
const floor = request.deletionWatermark ?? request.permit.deletionWatermark;
|
|
366
|
+
if (floor !== Number(seat.floor)) throw new Error("TRAVEL_DELETION_BARRIER");
|
|
367
|
+
this.deadlines.set(text, this.monotonicNow() + this.leaseMs);
|
|
368
|
+
permit = this.issue(principal, seat);
|
|
369
|
+
}
|
|
370
|
+
this.db.prepare("UPDATE nodes SET sequence=? WHERE identity=? AND node_id=?").run(request.sequence, text, principal.nodeId);
|
|
371
|
+
this.healthy.set(text + principal.nodeId, this.monotonicNow() + this.leaseMs);
|
|
372
|
+
return {
|
|
373
|
+
authorityBootId: this.authorityBootId,
|
|
374
|
+
epoch: Number(seat.epoch),
|
|
375
|
+
activeNodeId: seat.active_node,
|
|
376
|
+
deletionWatermark: Number(seat.floor),
|
|
377
|
+
checkpointDigest: seat.checkpoint,
|
|
378
|
+
buildManifestId: seat.build,
|
|
379
|
+
frozen: !!seat.frozen,
|
|
380
|
+
...permit ? { permit } : {}
|
|
381
|
+
};
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
status(principal) {
|
|
385
|
+
this.principal(principal);
|
|
386
|
+
const seat = this.seat(principal), text = identityText(principal);
|
|
387
|
+
return {
|
|
388
|
+
authorityBootId: this.authorityBootId,
|
|
389
|
+
epoch: Number(seat.epoch),
|
|
390
|
+
activeNodeId: seat.active_node,
|
|
391
|
+
activeBootId: seat.active_boot,
|
|
392
|
+
expired: (this.deadlines.get(text) ?? 0) <= this.monotonicNow(),
|
|
393
|
+
deletionWatermark: Number(seat.floor),
|
|
394
|
+
checkpointDigest: seat.checkpoint,
|
|
395
|
+
buildManifestId: seat.build,
|
|
396
|
+
frozen: !!seat.frozen
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
publishCheckpoint(principal, permit, checkpointDigest, parentDigest) {
|
|
400
|
+
if (!HASH2.test(checkpointDigest) || !HASH2.test(parentDigest)) throw new Error("TRAVEL_INVALID_CHECKPOINT");
|
|
401
|
+
this.transaction(() => {
|
|
402
|
+
this.principal(principal);
|
|
403
|
+
this.assertPermit(permit, "PUBLISH");
|
|
404
|
+
if (principal.nodeId !== permit.nodeId || identityText(principal) !== identityText(permit)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
405
|
+
const row = this.seat(principal), text = identityText(principal);
|
|
406
|
+
const prior = this.db.prepare("SELECT parent,epoch FROM checkpoints WHERE identity=? AND digest=?").get(text, checkpointDigest);
|
|
407
|
+
if (prior) {
|
|
408
|
+
if (prior.parent !== parentDigest) throw new Error("TRAVEL_ID_COLLISION");
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (row.checkpoint !== parentDigest) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
412
|
+
this.db.prepare("INSERT INTO checkpoints VALUES(?,?,?,?)").run(text, checkpointDigest, parentDigest, permit.epoch);
|
|
413
|
+
this.db.prepare("UPDATE seats SET checkpoint=? WHERE identity=?").run(checkpointDigest, text);
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
verifyAncestor(principal, ancestor, descendant) {
|
|
417
|
+
this.principal(principal);
|
|
418
|
+
const text = identityText(principal), seen = /* @__PURE__ */ new Set();
|
|
419
|
+
while (true) {
|
|
420
|
+
if (seen.has(descendant)) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
421
|
+
seen.add(descendant);
|
|
422
|
+
const row = this.db.prepare("SELECT parent FROM checkpoints WHERE identity=? AND digest=?").get(text, descendant);
|
|
423
|
+
if (!row) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
424
|
+
if (descendant === ancestor) return;
|
|
425
|
+
if (!row.parent) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
426
|
+
descendant = String(row.parent);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
/** Trusted archive adapter calls this after authenticating each sealed link.
|
|
430
|
+
* Evidence ancestry grants neither a published checkpoint nor an old lease. */
|
|
431
|
+
recordRecoveryBranch(principal, permit, chain) {
|
|
432
|
+
if (!Array.isArray(chain) || chain.length < 1 || chain.length > 4096 || chain.some((d) => !HASH2.test(d)) || new Set(chain).size !== chain.length) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
433
|
+
this.transaction(() => {
|
|
434
|
+
this.principal(principal);
|
|
435
|
+
this.assertPermit(permit, "WRITE");
|
|
436
|
+
if (principal.nodeId !== permit.nodeId || identityText(principal) !== identityText(permit)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
437
|
+
this.verifyAncestor(principal, chain[0], this.seat(principal).checkpoint);
|
|
438
|
+
const identity = identityText(principal), local = chain[chain.length - 1], body = JSON.stringify(chain);
|
|
439
|
+
const prior = this.db.prepare("SELECT chain FROM recovery_branches WHERE identity=? AND common=? AND local=?").get(identity, chain[0], local);
|
|
440
|
+
if (prior && prior.chain !== body) throw new Error("TRAVEL_ID_COLLISION");
|
|
441
|
+
this.db.prepare("INSERT OR IGNORE INTO recovery_branches VALUES(?,?,?,?)").run(identity, chain[0], local, body);
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
recoveryBranchStatus(principal, common, local) {
|
|
445
|
+
this.principal(principal);
|
|
446
|
+
const row = this.db.prepare("SELECT chain FROM recovery_branches WHERE identity=? AND common=? AND local=?").get(identityText(principal), common, local);
|
|
447
|
+
if (!row) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
448
|
+
return { chain: JSON.parse(String(row.chain)) };
|
|
449
|
+
}
|
|
450
|
+
beginHandoff(principal, permit, transferId, targetNodeId) {
|
|
451
|
+
id(transferId);
|
|
452
|
+
id(targetNodeId);
|
|
453
|
+
return this.transaction(() => {
|
|
454
|
+
this.principal(principal);
|
|
455
|
+
this.assertPermit(permit, "CONTROL");
|
|
456
|
+
const text = identityText(principal);
|
|
457
|
+
if (permit.nodeId !== principal.nodeId || identityText(permit) !== text || targetNodeId === principal.nodeId) throw new Error("TRAVEL_AUTH_DENIED");
|
|
458
|
+
const previous = this.db.prepare("SELECT source,target FROM handoffs WHERE identity=? AND id=?").get(text, transferId);
|
|
459
|
+
if (previous) {
|
|
460
|
+
if (previous.source !== principal.nodeId || previous.target !== targetNodeId) throw new Error("TRAVEL_ID_COLLISION");
|
|
461
|
+
return this.handoffStatus(principal, transferId);
|
|
462
|
+
}
|
|
463
|
+
if (!this.db.prepare("SELECT 1 FROM nodes WHERE identity=? AND node_id=?").get(text, targetNodeId)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
464
|
+
if (this.db.prepare("SELECT 1 FROM handoffs WHERE identity=? AND state NOT IN ('COMMITTED','ABORTED')").get(text)) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
465
|
+
this.db.prepare("INSERT INTO handoffs VALUES(?,?,?,?,?,NULL,'PREPARING',NULL,NULL)").run(text, transferId, principal.nodeId, targetNodeId, permit.epoch);
|
|
466
|
+
return this.handoffStatus(principal, transferId);
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
freezeHandoff(principal, permit, transferId, boundary) {
|
|
470
|
+
return this.transaction(() => {
|
|
471
|
+
this.principal(principal);
|
|
472
|
+
this.assertPermit(permit, "CONTROL");
|
|
473
|
+
if (boundary.safeBoundary !== true || boundary.effectsSettled !== true) throw new Error("TRAVEL_HANDOFF_NOT_SAFE");
|
|
474
|
+
if (!HASH2.test(boundary.checkpointDigest)) throw new Error("TRAVEL_INVALID_CHECKPOINT");
|
|
475
|
+
const h = this.handoffRow(principal, transferId), text = identityText(principal);
|
|
476
|
+
if (h.source !== principal.nodeId || permit.nodeId !== principal.nodeId || identityText(permit) !== text || Number(h.source_epoch) !== permit.epoch) throw new Error("TRAVEL_AUTH_DENIED");
|
|
477
|
+
if (h.state !== "PREPARING") {
|
|
478
|
+
if (h.checkpoint !== boundary.checkpointDigest || !["FROZEN_AT_H", "TARGET_READY"].includes(String(h.state))) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
479
|
+
return this.handoffStatus(principal, transferId);
|
|
480
|
+
}
|
|
481
|
+
const seat = this.seat(principal);
|
|
482
|
+
if (seat.checkpoint !== boundary.checkpointDigest) {
|
|
483
|
+
this.db.prepare("INSERT INTO checkpoints VALUES(?,?,?,?)").run(text, boundary.checkpointDigest, seat.checkpoint, permit.epoch);
|
|
484
|
+
}
|
|
485
|
+
this.db.prepare("UPDATE seats SET checkpoint=?,frozen=1 WHERE identity=?").run(boundary.checkpointDigest, text);
|
|
486
|
+
this.db.prepare("UPDATE handoffs SET state='FROZEN_AT_H',checkpoint=? WHERE identity=? AND id=?").run(boundary.checkpointDigest, text, transferId);
|
|
487
|
+
return this.handoffStatus(principal, transferId);
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
readyHandoff(principal, transferId, ready) {
|
|
491
|
+
return this.transaction(() => {
|
|
492
|
+
const node = this.principal(principal), h = this.handoffRow(principal, transferId), text = identityText(principal);
|
|
493
|
+
if (h.target !== principal.nodeId) throw new Error("TRAVEL_AUTH_DENIED");
|
|
494
|
+
if (!["FROZEN_AT_H", "TARGET_READY"].includes(String(h.state))) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
495
|
+
this.readiness(this.seat(principal), ready);
|
|
496
|
+
this.db.prepare("UPDATE handoffs SET state='TARGET_READY',target_boot=? WHERE identity=? AND id=?").run(String(node.boot), text, transferId);
|
|
497
|
+
this.healthy.set(text + principal.nodeId, this.monotonicNow() + this.leaseMs);
|
|
498
|
+
return this.handoffStatus(principal, transferId);
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
commitHandoff(principal, transferId) {
|
|
502
|
+
return this.transaction(() => {
|
|
503
|
+
const node = this.principal(principal), h = this.handoffRow(principal, transferId), text = identityText(principal);
|
|
504
|
+
if (h.target !== principal.nodeId) throw new Error("TRAVEL_AUTH_DENIED");
|
|
505
|
+
if (h.state === "COMMITTED") return JSON.parse(String(h.result));
|
|
506
|
+
if (h.state !== "TARGET_READY") throw new Error("TRAVEL_HANDOFF_STATE");
|
|
507
|
+
if (h.target_boot !== node.boot || (this.healthy.get(text + principal.nodeId) ?? 0) <= this.monotonicNow()) throw new Error("TRAVEL_TARGET_OFFLINE");
|
|
508
|
+
const seat = this.seat(principal);
|
|
509
|
+
if (Number(h.source_epoch) !== Number(seat.epoch) || h.source !== seat.active_node || h.checkpoint !== seat.checkpoint || !seat.frozen) throw new Error("TRAVEL_HANDOFF_STATE");
|
|
510
|
+
seat.epoch++;
|
|
511
|
+
seat.active_node = principal.nodeId;
|
|
512
|
+
seat.active_boot = String(node.boot);
|
|
513
|
+
seat.frozen = 0;
|
|
514
|
+
this.db.prepare("UPDATE seats SET epoch=?,active_node=?,active_boot=?,frozen=0 WHERE identity=?").run(seat.epoch, seat.active_node, seat.active_boot, text);
|
|
515
|
+
this.deadlines.set(text, this.monotonicNow() + this.leaseMs);
|
|
516
|
+
const result = { transferId, state: "COMMITTED", sourceNodeId: String(h.source), targetNodeId: String(h.target), checkpointDigest: String(h.checkpoint), permit: this.issue(principal, seat) };
|
|
517
|
+
this.db.prepare("UPDATE handoffs SET state='COMMITTED',result=? WHERE identity=? AND id=?").run(JSON.stringify(result), text, transferId);
|
|
518
|
+
return result;
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
abortHandoff(principal, transferId) {
|
|
522
|
+
return this.transaction(() => {
|
|
523
|
+
this.principal(principal);
|
|
524
|
+
const h = this.handoffRow(principal, transferId), text = identityText(principal);
|
|
525
|
+
if (h.source !== principal.nodeId) throw new Error("TRAVEL_AUTH_DENIED");
|
|
526
|
+
if (h.state === "COMMITTED") throw new Error("TRAVEL_HANDOFF_COMMITTED");
|
|
527
|
+
if (h.state === "ABORTED") return this.handoffStatus(principal, transferId);
|
|
528
|
+
this.db.prepare("UPDATE handoffs SET state='ABORTED' WHERE identity=? AND id=?").run(text, transferId);
|
|
529
|
+
const changed = this.db.prepare("UPDATE seats SET frozen=0,epoch=epoch+1 WHERE identity=? AND epoch=? AND active_node=?").run(text, Number(h.source_epoch), principal.nodeId);
|
|
530
|
+
if (changed.changes) this.deadlines.delete(text);
|
|
531
|
+
return this.handoffStatus(principal, transferId);
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
handoffRow(principal, transferId) {
|
|
535
|
+
id(transferId);
|
|
536
|
+
const row = this.db.prepare("SELECT * FROM handoffs WHERE identity=? AND id=?").get(identityText(principal), transferId);
|
|
537
|
+
if (!row) throw new Error("TRAVEL_HANDOFF_NOT_FOUND");
|
|
538
|
+
return row;
|
|
539
|
+
}
|
|
540
|
+
handoffStatus(principal, transferId) {
|
|
541
|
+
this.principal(principal);
|
|
542
|
+
const h = this.handoffRow(principal, transferId);
|
|
543
|
+
if (h.source !== principal.nodeId && h.target !== principal.nodeId) throw new Error("TRAVEL_AUTH_DENIED");
|
|
544
|
+
if (h.state === "COMMITTED") return JSON.parse(String(h.result));
|
|
545
|
+
return { transferId, state: h.state, sourceNodeId: String(h.source), targetNodeId: String(h.target), checkpointDigest: h.checkpoint === null ? null : String(h.checkpoint) };
|
|
546
|
+
}
|
|
547
|
+
recordDeletion(principal, permit, input) {
|
|
548
|
+
id(input.id);
|
|
549
|
+
id(input.sourceId);
|
|
550
|
+
id(input.scopeId);
|
|
551
|
+
natural(input.version);
|
|
552
|
+
if (!input.version) throw new Error("TRAVEL_INVALID_NUMBER");
|
|
553
|
+
return this.transaction(() => {
|
|
554
|
+
this.principal(principal);
|
|
555
|
+
this.assertPermit(permit, "CONTROL");
|
|
556
|
+
if (permit.nodeId !== principal.nodeId || identityText(permit) !== identityText(principal)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
557
|
+
const companion = JSON.stringify([principal.tenantId, principal.companionId]), body = JSON.stringify(input);
|
|
558
|
+
const previous = this.db.prepare("SELECT body,watermark FROM deletions WHERE companion=? AND id=?").get(companion, input.id);
|
|
559
|
+
if (previous) {
|
|
560
|
+
if (previous.body !== body) throw new Error("TRAVEL_ID_COLLISION");
|
|
561
|
+
return { ...input, watermark: Number(previous.watermark) };
|
|
562
|
+
}
|
|
563
|
+
const floor = Number(this.db.prepare("SELECT COALESCE(MAX(watermark),0) AS floor FROM deletions WHERE companion=?").get(companion).floor) + 1;
|
|
564
|
+
this.db.prepare("INSERT INTO deletions VALUES(?,?,?,?)").run(companion, input.id, body, floor);
|
|
565
|
+
for (const row of this.db.prepare("SELECT identity FROM seats").all()) {
|
|
566
|
+
const ids = JSON.parse(String(row.identity));
|
|
567
|
+
if (ids[0] === principal.tenantId && ids[1] === principal.companionId) this.db.prepare("UPDATE seats SET floor=? WHERE identity=?").run(floor, String(row.identity));
|
|
568
|
+
}
|
|
569
|
+
return { ...input, watermark: floor };
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
deletionsSince(principal, after) {
|
|
573
|
+
this.principal(principal);
|
|
574
|
+
natural(after);
|
|
575
|
+
const companion = JSON.stringify([principal.tenantId, principal.companionId]);
|
|
576
|
+
return this.db.prepare("SELECT body,watermark FROM deletions WHERE companion=? AND watermark>? ORDER BY watermark").all(companion, after).map((row) => ({ ...JSON.parse(String(row.body)), watermark: Number(row.watermark) }));
|
|
577
|
+
}
|
|
578
|
+
retire(identity, jobId) {
|
|
579
|
+
id(jobId);
|
|
580
|
+
this.transaction(() => {
|
|
581
|
+
const row = this.seat(identity, true), text = identityText(identity);
|
|
582
|
+
if (row.retired && row.retired !== jobId) throw new Error("TRAVEL_ID_COLLISION");
|
|
583
|
+
if (!row.retired) {
|
|
584
|
+
const source = {
|
|
585
|
+
authorityBootId: this.authorityBootId,
|
|
586
|
+
epoch: Number(row.epoch),
|
|
587
|
+
activeNodeId: row.active_node,
|
|
588
|
+
activeBootId: row.active_boot,
|
|
589
|
+
checkpointDigest: row.checkpoint,
|
|
590
|
+
buildManifestId: row.build,
|
|
591
|
+
deletionWatermark: Number(row.floor),
|
|
592
|
+
expired: true,
|
|
593
|
+
frozen: true
|
|
594
|
+
};
|
|
595
|
+
this.db.prepare("INSERT INTO retirement_sources VALUES(?,?)").run(text, JSON.stringify(source));
|
|
596
|
+
this.db.prepare("UPDATE seats SET epoch=epoch+1,active_node=NULL,active_boot=NULL,retired=?,frozen=1 WHERE identity=?").run(jobId, text);
|
|
597
|
+
}
|
|
598
|
+
this.deadlines.delete(text);
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
retirementStatus(principal) {
|
|
602
|
+
const node = this.db.prepare("SELECT role FROM nodes WHERE identity=? AND node_id=? AND credential_hash=?").get(identityText(principal), principal.nodeId, principal.credentialHash);
|
|
603
|
+
if (!node || node.role !== principal.role) throw new Error("TRAVEL_AUTH_DENIED");
|
|
604
|
+
const row = this.seat(principal, true);
|
|
605
|
+
const saved = this.db.prepare("SELECT body FROM retirement_sources WHERE identity=?").get(identityText(principal));
|
|
606
|
+
const source = row.retired ? saved ? JSON.parse(String(saved.body)) : null : this.status(principal);
|
|
607
|
+
return {
|
|
608
|
+
identity: { tenantId: principal.tenantId, companionId: principal.companionId, seatId: principal.seatId },
|
|
609
|
+
principal,
|
|
610
|
+
publicKey: this.publicKey,
|
|
611
|
+
source,
|
|
612
|
+
jobId: row.retired,
|
|
613
|
+
retired: row.retired !== null,
|
|
614
|
+
epoch: Number(row.epoch),
|
|
615
|
+
checkpointDigest: row.checkpoint,
|
|
616
|
+
deletionWatermark: Number(row.floor)
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
close() {
|
|
620
|
+
if (!this.closed) {
|
|
621
|
+
this.closed = true;
|
|
622
|
+
this.db.close();
|
|
623
|
+
this.owner.close();
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
// src/continuity/publication.ts
|
|
629
|
+
import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
|
|
630
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
631
|
+
var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
|
|
632
|
+
var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
|
|
633
|
+
var ZERO = "0".repeat(64);
|
|
634
|
+
var HASH3 = /^[a-f0-9]{64}$/;
|
|
635
|
+
var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
636
|
+
function natural2(value) {
|
|
637
|
+
return Number.isSafeInteger(value) && value >= 0;
|
|
638
|
+
}
|
|
639
|
+
function id2(value) {
|
|
640
|
+
if (typeof value !== "string" || !ID2.test(value)) throw new Error("PUBLICATION_INVALID_ID");
|
|
641
|
+
}
|
|
642
|
+
function exactIds(actual, required, error) {
|
|
643
|
+
if (actual.length !== required.length || new Set(actual).size !== actual.length || actual.some((x) => !required.includes(x))) throw new Error(error);
|
|
644
|
+
}
|
|
645
|
+
function normalizePublicationProfile(value) {
|
|
646
|
+
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");
|
|
647
|
+
id2(value.baselineId);
|
|
648
|
+
id2(value.buildManifestId);
|
|
649
|
+
if (!natural2(value.epoch) || !value.epoch || !Array.isArray(value.databaseIds) || !value.databaseIds.length || value.databaseIds.length > 64 || !Array.isArray(value.trees) || !value.trees.length || value.trees.length > 64) throw new Error("PUBLICATION_INVALID_PROFILE");
|
|
650
|
+
value.databaseIds.forEach(id2);
|
|
651
|
+
value.trees.forEach((t) => {
|
|
652
|
+
id2(t?.id);
|
|
653
|
+
if (!["file", "vector", "session"].includes(t.kind)) throw new Error("PUBLICATION_INVALID_PROFILE");
|
|
654
|
+
});
|
|
655
|
+
if (new Set(value.databaseIds).size !== value.databaseIds.length || new Set(value.trees.map((t) => t.id)).size !== value.trees.length)
|
|
656
|
+
throw new Error("PUBLICATION_INVALID_PROFILE");
|
|
657
|
+
const profile = {
|
|
658
|
+
identity: { tenantId: value.identity.tenantId, companionId: value.identity.companionId, seatId: value.identity.seatId },
|
|
659
|
+
baselineId: value.baselineId,
|
|
660
|
+
epoch: value.epoch,
|
|
661
|
+
buildManifestId: value.buildManifestId,
|
|
662
|
+
databaseIds: [...value.databaseIds].sort(),
|
|
663
|
+
trees: value.trees.map((t) => ({ id: t.id, kind: t.kind })).sort((a, b) => a.id.localeCompare(b.id, "en"))
|
|
664
|
+
};
|
|
665
|
+
Object.freeze(profile.identity);
|
|
666
|
+
Object.freeze(profile.databaseIds);
|
|
667
|
+
profile.trees.forEach(Object.freeze);
|
|
668
|
+
Object.freeze(profile.trees);
|
|
669
|
+
return Object.freeze(profile);
|
|
670
|
+
}
|
|
671
|
+
function validatePublicationPath(path2) {
|
|
672
|
+
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)))
|
|
673
|
+
throw new Error("PUBLICATION_INVALID_PATH");
|
|
674
|
+
}
|
|
675
|
+
function normalizePublication(value) {
|
|
676
|
+
if (!value || value.format !== "engine7-publication-v1" || !natural2(value.sequence) || !value.sequence || !HASH3.test(value.parentDigest) || !natural2(value.deletionWatermark) || !Array.isArray(value.databases) || !Array.isArray(value.trees)) throw new Error("PUBLICATION_INVALID_MANIFEST");
|
|
677
|
+
const profile = normalizePublicationProfile(value.profile);
|
|
678
|
+
exactIds(value.databases.map((d) => d?.databaseId), profile.databaseIds, "PUBLICATION_INCOMPLETE_DATABASES");
|
|
679
|
+
exactIds(value.trees.map((t) => t?.id), profile.trees.map((t) => t.id), "PUBLICATION_INCOMPLETE_TREES");
|
|
680
|
+
const databases = value.databases.map((d) => {
|
|
681
|
+
if (!d.head || !natural2(d.head.sequence) || !HASH3.test(d.head.digest)) throw new Error("PUBLICATION_INVALID_DATABASE_HEAD");
|
|
682
|
+
return { databaseId: d.databaseId, head: { sequence: d.head.sequence, digest: d.head.digest } };
|
|
683
|
+
}).sort((a, b) => a.databaseId.localeCompare(b.databaseId, "en"));
|
|
684
|
+
let paths = 0;
|
|
685
|
+
const trees = value.trees.map((tree) => {
|
|
686
|
+
if (!Array.isArray(tree.files) || !Array.isArray(tree.directories) || (paths += tree.files.length + tree.directories.length) > 1e5)
|
|
687
|
+
throw new Error("PUBLICATION_INVALID_TREE");
|
|
688
|
+
const occupied = /* @__PURE__ */ new Map();
|
|
689
|
+
const claim = (path2, kind) => {
|
|
690
|
+
validatePublicationPath(path2);
|
|
691
|
+
const folded = path2.toLowerCase();
|
|
692
|
+
if (occupied.has(folded)) throw new Error("PUBLICATION_PATH_COLLISION");
|
|
693
|
+
occupied.set(folded, kind);
|
|
694
|
+
};
|
|
695
|
+
const directories = tree.directories.map((path2) => {
|
|
696
|
+
claim(path2, "directory");
|
|
697
|
+
return path2;
|
|
698
|
+
}).sort();
|
|
699
|
+
const files = tree.files.map((file) => {
|
|
700
|
+
claim(file?.path, "file");
|
|
701
|
+
validateFileContent(file.content);
|
|
702
|
+
if (![384, 448].includes(file.mode)) throw new Error("PUBLICATION_INVALID_MODE");
|
|
703
|
+
return { path: file.path, mode: file.mode, content: {
|
|
704
|
+
bytes: file.content.bytes,
|
|
705
|
+
sha256: file.content.sha256,
|
|
706
|
+
chunks: file.content.chunks.map((r) => ({ sha256: r.sha256, bytes: r.bytes }))
|
|
707
|
+
} };
|
|
708
|
+
}).sort((a, b) => a.path.localeCompare(b.path, "en"));
|
|
709
|
+
for (const path2 of occupied.keys()) {
|
|
710
|
+
const parts = path2.split("/");
|
|
711
|
+
for (let i = 1; i < parts.length; i++) if (occupied.get(parts.slice(0, i).join("/")) === "file") throw new Error("PUBLICATION_PATH_COLLISION");
|
|
712
|
+
}
|
|
713
|
+
return { id: tree.id, directories, files };
|
|
714
|
+
}).sort((a, b) => a.id.localeCompare(b.id, "en"));
|
|
715
|
+
const normalized = {
|
|
716
|
+
format: "engine7-publication-v1",
|
|
717
|
+
profile,
|
|
718
|
+
sequence: value.sequence,
|
|
719
|
+
parentDigest: value.parentDigest,
|
|
720
|
+
deletionWatermark: value.deletionWatermark,
|
|
721
|
+
databases,
|
|
722
|
+
trees
|
|
723
|
+
};
|
|
724
|
+
if (Buffer.byteLength(JSON.stringify(normalized)) > PUBLICATION_MANIFEST_BYTES) throw new Error("PUBLICATION_MANIFEST_TOO_LARGE");
|
|
725
|
+
return normalized;
|
|
726
|
+
}
|
|
727
|
+
function publicationDigest(manifest) {
|
|
728
|
+
return createHash2("sha256").update(JSON.stringify(normalizePublication(manifest))).digest("hex");
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// src/continuity/authority-server.ts
|
|
732
|
+
import { createServer } from "node:https";
|
|
733
|
+
var limit = 65536;
|
|
734
|
+
var identifier = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
735
|
+
var errors = /* @__PURE__ */ new Set([
|
|
736
|
+
"TRAVEL_HEARTBEAT_REPLAY",
|
|
737
|
+
"TRAVEL_BOOT_MISMATCH",
|
|
738
|
+
"TRAVEL_BOOT_RETIRED",
|
|
739
|
+
"TRAVEL_LEASE_EXPIRED",
|
|
740
|
+
"TRAVEL_STALE_PERMIT",
|
|
741
|
+
"TRAVEL_DELETION_BARRIER",
|
|
742
|
+
"TRAVEL_SEAT_RETIRED",
|
|
743
|
+
"TRAVEL_BOOT_REQUIRED",
|
|
744
|
+
"TRAVEL_NOT_READY",
|
|
745
|
+
"TRAVEL_READINESS_BARRIER",
|
|
746
|
+
"TRAVEL_LEASE_HELD",
|
|
747
|
+
"TRAVEL_INVALID_PERMIT",
|
|
748
|
+
"TRAVEL_AUTH_DENIED",
|
|
749
|
+
"TRAVEL_HANDOFF_STATE",
|
|
750
|
+
"TRAVEL_HANDOFF_FROZEN",
|
|
751
|
+
"TRAVEL_HANDOFF_NOT_SAFE",
|
|
752
|
+
"TRAVEL_HANDOFF_NOT_FOUND",
|
|
753
|
+
"TRAVEL_HANDOFF_COMMITTED",
|
|
754
|
+
"TRAVEL_TARGET_OFFLINE",
|
|
755
|
+
"TRAVEL_ID_COLLISION",
|
|
756
|
+
"TRAVEL_ANCESTRY_GAP"
|
|
757
|
+
]);
|
|
758
|
+
var managementFields = {
|
|
759
|
+
retire: ["jobId"],
|
|
760
|
+
retirementStatus: [],
|
|
761
|
+
status: [],
|
|
762
|
+
identity: [],
|
|
763
|
+
verifyAncestor: ["ancestor", "descendant"],
|
|
764
|
+
deletionsSince: ["after", "maximum"],
|
|
765
|
+
publishCheckpoint: ["permit", "digest", "parent"],
|
|
766
|
+
recordRecoveryBranch: ["permit", "chain", "proof"],
|
|
767
|
+
recoveryBranchStatus: ["common", "local"],
|
|
768
|
+
assertPermit: ["permit", "operation"],
|
|
769
|
+
acquire: ["ready"],
|
|
770
|
+
beginHandoff: ["permit", "transferId", "targetNodeId"],
|
|
771
|
+
freezeHandoff: ["permit", "transferId", "boundary"],
|
|
772
|
+
readyHandoff: ["transferId", "ready"],
|
|
773
|
+
commitHandoff: ["transferId"],
|
|
774
|
+
handoffStatus: ["transferId"],
|
|
775
|
+
abortHandoff: ["transferId"]
|
|
776
|
+
};
|
|
777
|
+
var retirementAction = (value) => value === "retire" || value === "retirementStatus";
|
|
778
|
+
var record = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
779
|
+
function validManagement(input) {
|
|
780
|
+
if (input.action === "retire" && !(typeof input.jobId === "string" && identifier.test(input.jobId))) return false;
|
|
781
|
+
if (!Object.hasOwn(managementFields, String(input.action))) return false;
|
|
782
|
+
const fields = managementFields[String(input.action)];
|
|
783
|
+
if (!fields || Object.keys(input).some((key) => !["version", "action", ...fields].includes(key)) || fields.some((key) => !Object.hasOwn(input, key))) return false;
|
|
784
|
+
for (const key of ["ancestor", "descendant", "digest", "parent", "common", "local"]) if (Object.hasOwn(input, key) && (typeof input[key] !== "string" || !/^[a-f0-9]{64}$/.test(input[key]))) return false;
|
|
785
|
+
for (const key of ["transferId", "targetNodeId"]) if (Object.hasOwn(input, key) && (typeof input[key] !== "string" || !identifier.test(input[key]))) return false;
|
|
786
|
+
if (input.action === "deletionsSince" && (!Number.isSafeInteger(input.after) || Number(input.after) < 0 || !Number.isSafeInteger(input.maximum) || Number(input.maximum) < 1 || Number(input.maximum) > 32)) return false;
|
|
787
|
+
if (input.action === "recordRecoveryBranch" && (!Array.isArray(input.chain) || input.chain.length < 1 || input.chain.length > 4096 || input.chain.some((value) => typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) || !Array.isArray(input.proof) || input.proof.length !== input.chain.length)) return false;
|
|
788
|
+
if (Object.hasOwn(input, "permit") && !record(input.permit)) return false;
|
|
789
|
+
if (Object.hasOwn(input, "operation") && !["WRITE", "SEND", "TOOL", "INPUT", "PUBLISH", "CONTROL"].includes(String(input.operation))) return false;
|
|
790
|
+
if (Object.hasOwn(input, "ready") && (!record(input.ready) || Object.keys(input.ready).some((key) => !["checkpointDigest", "deletionWatermark", "buildManifestId", "volumeVerified", "capabilitiesVerified", "effectsLoaded", "unresolvedCritical"].includes(key)))) return false;
|
|
791
|
+
if (Object.hasOwn(input, "boundary") && (!record(input.boundary) || Object.keys(input.boundary).some((key) => !["checkpointDigest", "safeBoundary", "effectsSettled"].includes(key)))) return false;
|
|
792
|
+
return true;
|
|
793
|
+
}
|
|
794
|
+
function createTravelAuthorityServer(options) {
|
|
795
|
+
const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls } = options;
|
|
796
|
+
const proxies = /* @__PURE__ */ new Set(), peers = /* @__PURE__ */ new Map(), managers = /* @__PURE__ */ new Map();
|
|
797
|
+
const fingerprint = (value) => {
|
|
798
|
+
const normalized = value.replaceAll(":", "").toLowerCase();
|
|
799
|
+
if (!/^[a-f0-9]{64}$/.test(normalized)) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
800
|
+
return normalized;
|
|
801
|
+
};
|
|
802
|
+
for (const value of proxyFingerprints) {
|
|
803
|
+
const fp = fingerprint(value);
|
|
804
|
+
if (proxies.has(fp)) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
805
|
+
proxies.add(fp);
|
|
806
|
+
}
|
|
807
|
+
for (const [value, credential] of Object.entries(allowedPeers)) {
|
|
808
|
+
const fp = fingerprint(value);
|
|
809
|
+
if (proxies.has(fp) || peers.has(fp)) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
810
|
+
peers.set(fp, authority.authenticateRetirement(credential));
|
|
811
|
+
}
|
|
812
|
+
for (const [value, credentials] of Object.entries(managementPeers)) {
|
|
813
|
+
const fp = fingerprint(value);
|
|
814
|
+
if (managers.has(fp) || !Array.isArray(credentials) || !credentials.length || credentials.length > 128) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
815
|
+
const grants = new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash));
|
|
816
|
+
if (grants.size !== credentials.length) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
817
|
+
managers.set(fp, grants);
|
|
818
|
+
}
|
|
819
|
+
if (!Number.isSafeInteger(maximumInFlight) || maximumInFlight < 1 || maximumInFlight > 64 || !proxies.size && !peers.size && !managers.size && !Object.keys(retirementPeers).length) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
820
|
+
if (!Number.isSafeInteger(requestTimeoutMs) || requestTimeoutMs < 100 || requestTimeoutMs > 3e4) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
821
|
+
const recoveryGrants = /* @__PURE__ */ new Map();
|
|
822
|
+
for (const [value, credentials] of Object.entries(recoveryPeers)) {
|
|
823
|
+
const fp = fingerprint(value);
|
|
824
|
+
if (!Array.isArray(credentials) || !credentials.length || credentials.some((credential) => !managers.get(fp)?.has(authority.authenticateRetirement(credential).credentialHash))) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
825
|
+
recoveryGrants.set(fp, new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash)));
|
|
826
|
+
}
|
|
827
|
+
const retirees = /* @__PURE__ */ new Map();
|
|
828
|
+
for (const [value, credentials] of Object.entries(retirementPeers)) {
|
|
829
|
+
const fp = fingerprint(value);
|
|
830
|
+
if (!Array.isArray(credentials) || !credentials.length) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
831
|
+
retirees.set(fp, new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash)));
|
|
832
|
+
}
|
|
833
|
+
const reports = /* @__PURE__ */ new Set(), management = /* @__PURE__ */ new Set();
|
|
834
|
+
const server = createServer({ ...tls, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
|
|
835
|
+
res.setHeader("Content-Type", "application/json");
|
|
836
|
+
res.setHeader("Cache-Control", "no-store");
|
|
837
|
+
const reply = (status, value) => {
|
|
838
|
+
res.statusCode = status;
|
|
839
|
+
res.end(JSON.stringify(value));
|
|
840
|
+
};
|
|
841
|
+
const managing = req.url === "/travel/manage/v1", active = managing ? management : reports;
|
|
842
|
+
if (req.method !== "POST" || !managing && req.url !== "/travel/control/v1") {
|
|
843
|
+
reply(404, { error: "TRAVEL_CONTROL_NOT_FOUND" });
|
|
844
|
+
req.resume();
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
let principal, credential, peerFingerprint;
|
|
848
|
+
try {
|
|
849
|
+
const socket = req.socket, fp = (socket.getPeerCertificate().fingerprint256 ?? "").replaceAll(":", "").toLowerCase();
|
|
850
|
+
if (!socket.authorized || !managing && !proxies.has(fp) && !peers.has(fp) || req.rawHeaders.filter((_, i) => i % 2 === 0 && req.rawHeaders[i].toLowerCase() === "authorization").length !== 1) throw new Error();
|
|
851
|
+
const authorization = req.headers.authorization;
|
|
852
|
+
if (typeof authorization !== "string" || !/^Bearer e7t_[a-f0-9]{64}$/.test(authorization)) throw new Error();
|
|
853
|
+
peerFingerprint = fp;
|
|
854
|
+
credential = authorization.slice(7);
|
|
855
|
+
principal = retirees.has(fp) && managing ? authority.authenticateRetirement(credential) : authority.authenticate(credential);
|
|
856
|
+
if (managing) {
|
|
857
|
+
if (!managers.get(fp)?.has(principal.credentialHash) && !retirees.get(fp)?.has(principal.credentialHash) || req.headers["x-engine7-travel-node"] !== principal.nodeId) throw new Error();
|
|
858
|
+
} else if (proxies.has(fp)) {
|
|
859
|
+
if (req.headers["x-engine7-travel-node"] !== principal.nodeId) throw new Error();
|
|
860
|
+
} else if (peers.get(fp).credentialHash !== principal.credentialHash) throw new Error();
|
|
861
|
+
} catch {
|
|
862
|
+
reply(403, { error: "TRAVEL_AUTH_DENIED" });
|
|
863
|
+
req.resume();
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
if (active.size >= maximumInFlight || active.has(principal.credentialHash)) {
|
|
867
|
+
reply(503, { error: "TRAVEL_CONTROL_BUSY" });
|
|
868
|
+
req.resume();
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
active.add(principal.credentialHash);
|
|
872
|
+
const deadline = setTimeout(() => req.destroy(), requestTimeoutMs);
|
|
873
|
+
deadline.unref();
|
|
874
|
+
try {
|
|
875
|
+
const chunks = [];
|
|
876
|
+
let bytes = 0;
|
|
877
|
+
for await (const part of req) {
|
|
878
|
+
bytes += part.length;
|
|
879
|
+
if (bytes > (managing ? 40 * 1024 * 1024 : limit)) {
|
|
880
|
+
res.setHeader("Connection", "close");
|
|
881
|
+
reply(400, { error: "TRAVEL_CONTROL_INVALID_REQUEST" });
|
|
882
|
+
req.resume();
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
chunks.push(part);
|
|
886
|
+
}
|
|
887
|
+
let envelope;
|
|
888
|
+
try {
|
|
889
|
+
envelope = JSON.parse(Buffer.concat(chunks).toString());
|
|
890
|
+
} catch {
|
|
891
|
+
reply(400, { error: "TRAVEL_CONTROL_INVALID_REQUEST" });
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
const input = envelope?.travel, keys = input?.action === "register" ? ["version", "action", "bootId"] : input?.action === "heartbeat" ? ["version", "action", "bootId", "sequence", "permit", "deletionWatermark"] : ["version", "action"];
|
|
895
|
+
const validAction = managing ? record(input) && validManagement(input) : ["register", "heartbeat", "status"].includes(input?.action) && Object.keys(input).every((key) => keys.includes(key)) && (input.action === "status" || typeof input.bootId === "string" && identifier.test(input.bootId));
|
|
896
|
+
if (!envelope || typeof envelope !== "object" || Array.isArray(envelope) || Object.keys(envelope).length !== 1 || !input || typeof input !== "object" || Array.isArray(input) || input.version !== 1 || !validAction) {
|
|
897
|
+
reply(400, { error: "TRAVEL_CONTROL_INVALID_REQUEST" });
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
if (managing && retirementAction(input.action)) {
|
|
901
|
+
if (!retirees.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
902
|
+
principal = authority.authenticateRetirement(credential);
|
|
903
|
+
} else {
|
|
904
|
+
if (managing && !managers.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
905
|
+
principal = authority.authenticate(credential);
|
|
906
|
+
}
|
|
907
|
+
let result;
|
|
908
|
+
if (managing) {
|
|
909
|
+
if (input.permit && ["tenantId", "companionId", "seatId", "nodeId"].some((key) => input.permit[key] !== principal[key])) throw new Error("TRAVEL_AUTH_DENIED");
|
|
910
|
+
switch (input.action) {
|
|
911
|
+
case "retire":
|
|
912
|
+
authority.retire(principal, input.jobId);
|
|
913
|
+
result = {};
|
|
914
|
+
break;
|
|
915
|
+
case "retirementStatus":
|
|
916
|
+
result = authority.retirementStatus(principal);
|
|
917
|
+
break;
|
|
918
|
+
case "status":
|
|
919
|
+
result = authority.status(principal);
|
|
920
|
+
break;
|
|
921
|
+
case "identity":
|
|
922
|
+
result = { principal, status: authority.status(principal), publicKey: authority.publicKey };
|
|
923
|
+
break;
|
|
924
|
+
case "verifyAncestor":
|
|
925
|
+
authority.verifyAncestor(principal, input.ancestor, input.descendant);
|
|
926
|
+
result = {};
|
|
927
|
+
break;
|
|
928
|
+
case "deletionsSince":
|
|
929
|
+
result = { deletions: authority.deletionsSince(principal, input.after).slice(0, input.maximum) };
|
|
930
|
+
break;
|
|
931
|
+
case "publishCheckpoint":
|
|
932
|
+
authority.publishCheckpoint(principal, input.permit, input.digest, input.parent);
|
|
933
|
+
result = {};
|
|
934
|
+
break;
|
|
935
|
+
case "recoveryBranchStatus":
|
|
936
|
+
result = authority.recoveryBranchStatus(principal, input.common, input.local);
|
|
937
|
+
break;
|
|
938
|
+
case "recordRecoveryBranch": {
|
|
939
|
+
if (!recoveryGrants.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
|
|
940
|
+
const proof = input.proof.map((value) => normalizePublication(value));
|
|
941
|
+
const profile = JSON.stringify(proof[0].profile);
|
|
942
|
+
if (proof.some((manifest, index) => publicationDigest(manifest) !== input.chain[index] || JSON.stringify(manifest.profile) !== profile || index > 0 && (manifest.parentDigest !== input.chain[index - 1] || manifest.sequence !== proof[index - 1].sequence + 1)) || ["tenantId", "companionId", "seatId"].some((field) => proof[0].profile.identity[field] !== principal[field])) throw new Error("TRAVEL_ANCESTRY_GAP");
|
|
943
|
+
authority.recordRecoveryBranch(principal, input.permit, input.chain);
|
|
944
|
+
result = {};
|
|
945
|
+
break;
|
|
946
|
+
}
|
|
947
|
+
case "assertPermit":
|
|
948
|
+
authority.assertPermit(input.permit, input.operation);
|
|
949
|
+
result = {};
|
|
950
|
+
break;
|
|
951
|
+
case "acquire":
|
|
952
|
+
result = { permit: authority.acquire(principal, input.ready) };
|
|
953
|
+
break;
|
|
954
|
+
case "beginHandoff":
|
|
955
|
+
result = authority.beginHandoff(principal, input.permit, input.transferId, input.targetNodeId);
|
|
956
|
+
break;
|
|
957
|
+
case "freezeHandoff":
|
|
958
|
+
result = authority.freezeHandoff(principal, input.permit, input.transferId, input.boundary);
|
|
959
|
+
break;
|
|
960
|
+
case "readyHandoff":
|
|
961
|
+
result = authority.readyHandoff(principal, input.transferId, input.ready);
|
|
962
|
+
break;
|
|
963
|
+
case "commitHandoff":
|
|
964
|
+
result = authority.commitHandoff(principal, input.transferId);
|
|
965
|
+
break;
|
|
966
|
+
case "handoffStatus":
|
|
967
|
+
result = authority.handoffStatus(principal, input.transferId);
|
|
968
|
+
break;
|
|
969
|
+
case "abortHandoff":
|
|
970
|
+
result = authority.abortHandoff(principal, input.transferId);
|
|
971
|
+
break;
|
|
972
|
+
}
|
|
973
|
+
} else if (input.action === "register") {
|
|
974
|
+
authority.register(principal, input.bootId);
|
|
975
|
+
result = authority.status(principal);
|
|
976
|
+
} else if (input.action === "heartbeat") result = authority.heartbeat(principal, input);
|
|
977
|
+
else result = authority.status(principal);
|
|
978
|
+
reply(200, { travel: { version: 1, ...result } });
|
|
979
|
+
} catch (error) {
|
|
980
|
+
const code = error instanceof Error && errors.has(error.message) ? error.message : "TRAVEL_CONTROL_REFUSED";
|
|
981
|
+
if (!res.writableEnded && !res.destroyed) reply(managing && code === "TRAVEL_AUTH_DENIED" ? 403 : 409, { error: code });
|
|
982
|
+
} finally {
|
|
983
|
+
clearTimeout(deadline);
|
|
984
|
+
active.delete(principal.credentialHash);
|
|
985
|
+
}
|
|
986
|
+
});
|
|
987
|
+
server.headersTimeout = 3e3;
|
|
988
|
+
server.requestTimeout = requestTimeoutMs;
|
|
989
|
+
server.keepAliveTimeout = 1e4;
|
|
990
|
+
server.maxConnections = 64;
|
|
991
|
+
server.maxRequestsPerSocket = 64;
|
|
992
|
+
server.on("tlsClientError", () => {
|
|
993
|
+
});
|
|
994
|
+
return server;
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
// src/continuity/authority-main.ts
|
|
998
|
+
function path(value) {
|
|
999
|
+
if (typeof value !== "string" || !isAbsolute(value)) throw new Error("TRAVEL_CONTROL_ABSOLUTE_PATH_REQUIRED");
|
|
1000
|
+
return resolve2(value);
|
|
1001
|
+
}
|
|
1002
|
+
async function startTravelAuthorityService(config) {
|
|
1003
|
+
if (!Number.isSafeInteger(config?.port) || config.port < 0 || config.port > 65535 || typeof config.host !== "string" || !config.host) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
|
|
1004
|
+
const directory = path(config.authorityDir);
|
|
1005
|
+
if (!existsSync2(join3(directory, "authority.sqlite")) || !existsSync2(join3(directory, "authority-signing.pem"))) throw new Error("TRAVEL_CONTROL_REGISTRATION_REQUIRED");
|
|
1006
|
+
const authority = new TravelAuthority({ directory, leaseMs: config.leaseMs });
|
|
1007
|
+
let server, key, closing;
|
|
1008
|
+
const close = () => closing ??= (async () => {
|
|
1009
|
+
try {
|
|
1010
|
+
if (server) {
|
|
1011
|
+
server.closeAllConnections();
|
|
1012
|
+
await new Promise((resolve3) => server.close(() => resolve3()));
|
|
1013
|
+
}
|
|
1014
|
+
} finally {
|
|
1015
|
+
authority.close();
|
|
1016
|
+
key?.fill(0);
|
|
1017
|
+
}
|
|
1018
|
+
})();
|
|
1019
|
+
try {
|
|
1020
|
+
key = readPrivateFile(path(config.tls?.keyFile), 16384);
|
|
1021
|
+
server = createTravelAuthorityServer({
|
|
1022
|
+
authority,
|
|
1023
|
+
key,
|
|
1024
|
+
cert: readFileSync3(path(config.tls?.certFile)),
|
|
1025
|
+
ca: readFileSync3(path(config.tls?.caFile)),
|
|
1026
|
+
proxyFingerprints: config.proxyFingerprints,
|
|
1027
|
+
allowedPeers: config.allowedPeers,
|
|
1028
|
+
managementPeers: config.managementPeers,
|
|
1029
|
+
recoveryPeers: config.recoveryPeers,
|
|
1030
|
+
retirementPeers: config.retirementPeers,
|
|
1031
|
+
maximumInFlight: config.maximumInFlight,
|
|
1032
|
+
requestTimeoutMs: config.requestTimeoutMs
|
|
1033
|
+
});
|
|
1034
|
+
await new Promise((resolve3, reject) => {
|
|
1035
|
+
server.once("error", reject);
|
|
1036
|
+
server.listen(config.port, config.host, resolve3);
|
|
1037
|
+
});
|
|
1038
|
+
const status = () => ({ ready: true, port: server.address().port, authorityBootId: authority.authorityBootId });
|
|
1039
|
+
return { server, authority, close, status };
|
|
1040
|
+
} catch (error) {
|
|
1041
|
+
await close();
|
|
1042
|
+
throw error;
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
async function runTravelAuthorityCli(args) {
|
|
1046
|
+
if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-authority serve --config /absolute/private-config.json" };
|
|
1047
|
+
if (args.length !== 3 || args[0] !== "serve" || args[1] !== "--config") throw new Error("TRAVEL_CONTROL_INVALID_COMMAND");
|
|
1048
|
+
const service = await startTravelAuthorityService(JSON.parse(readPrivateFile(path(args[2]), 65536).toString()));
|
|
1049
|
+
let closing = false;
|
|
1050
|
+
const stop = () => {
|
|
1051
|
+
if (closing) return;
|
|
1052
|
+
closing = true;
|
|
1053
|
+
void service.close().then(() => process.exit(0), () => process.exit(1));
|
|
1054
|
+
};
|
|
1055
|
+
process.once("SIGTERM", stop);
|
|
1056
|
+
process.once("SIGINT", stop);
|
|
1057
|
+
return service.status();
|
|
1058
|
+
}
|
|
1059
|
+
if (process.argv[1] && resolve2(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
1060
|
+
runTravelAuthorityCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
|
|
1061
|
+
process.stderr.write("TRAVEL_CONTROL_REFUSED\n");
|
|
1062
|
+
process.exitCode = 1;
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
export {
|
|
1066
|
+
runTravelAuthorityCli,
|
|
1067
|
+
startTravelAuthorityService
|
|
1068
|
+
};
|