inferative 0.2.0 → 0.3.2
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 +4 -5
- package/dist/{backup-cli-VBRvtEF4.mjs → backup-cli-CieguMav.mjs} +1610 -140
- package/dist/bin.mjs +90 -81
- package/dist/{database-load-DtoThqg4.mjs → database-load-m_JValnc.mjs} +1 -1
- package/dist/heximon.inputs.json +67 -46
- package/dist/{mysql-load-Cal8mOLJ.mjs → mysql-load-D5w8rWRx.mjs} +1 -1
- package/dist/{mysql-session-D5QviPsD.mjs → mysql-session-BJ0k7zws.mjs} +19 -9
- package/dist/{pg-load-gKCdo5wI.mjs → pg-load-BFCk8dau.mjs} +2 -2
- package/dist/{pg-session-CfrvvW7D.mjs → pg-session-D3UKJzIv.mjs} +17 -8
- package/dist/scope-sql-CaOv1V5P.mjs +61 -0
- package/package.json +16 -16
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { t as CliVersion } from "./cli-version-CrMjrmRM.mjs";
|
|
2
2
|
import { n as DatabaseSession, t as DatabaseDialect } from "./database-session-CZpfIBpG.mjs";
|
|
3
|
-
import { t as PgSession } from "./pg-session-
|
|
3
|
+
import { t as PgSession } from "./pg-session-D3UKJzIv.mjs";
|
|
4
4
|
import { n as FileStoreLocations, t as FileStoreKind } from "./file-store-location-BkdOnIKm.mjs";
|
|
5
5
|
import { t as R2FileStore } from "./r2-file-store-Bhga1xfP.mjs";
|
|
6
6
|
import { closeSync, cpSync, createReadStream, createWriteStream, existsSync, linkSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
7
7
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
8
|
-
import { RootSecret } from "@inferative/base/config";
|
|
9
|
-
import { parseEnv } from "node:util";
|
|
10
8
|
import { createHash, randomUUID } from "node:crypto";
|
|
9
|
+
import { parseEnv } from "node:util";
|
|
10
|
+
import { DeploymentSecret, RootSecret, RootSecretPurpose } from "@inferative/base/config";
|
|
11
|
+
import { ModelHistorySeals, SealedTextCipher, SecretTransfer, SecretTransferKey } from "@inferative/base/sealing";
|
|
11
12
|
import { Decrypter, Encrypter, generateX25519Identity, identityToRecipient } from "age-encryption";
|
|
12
13
|
import { tmpdir } from "node:os";
|
|
13
|
-
import { SecretStoreKeys } from "@inferative/base/secrets";
|
|
14
|
+
import { SecretEnvelope, SecretKeyRing, SecretLookupStatus, SecretStoreKeys } from "@inferative/base/secrets";
|
|
14
15
|
import { finished, pipeline } from "node:stream/promises";
|
|
15
16
|
import { createGunzip, createGzip } from "node:zlib";
|
|
16
17
|
//#region src/backup/archive-encryption.ts
|
|
@@ -179,13 +180,452 @@ var ArchiveEncryption = class ArchiveEncryption {
|
|
|
179
180
|
}
|
|
180
181
|
};
|
|
181
182
|
//#endregion
|
|
183
|
+
//#region src/backup/organization-scope.ts
|
|
184
|
+
/** How the rows of a table belong to an organization. */
|
|
185
|
+
const ScopeRuleKind = {
|
|
186
|
+
/** A row belongs when one of the rule's columns holds the organization id, or a link names it. */
|
|
187
|
+
Organization: "organization",
|
|
188
|
+
/** A row belongs when a link names it: it follows a row of another table that belongs. */
|
|
189
|
+
Follow: "follow",
|
|
190
|
+
/** Every row: data of the deployment that the rows of each organization name. */
|
|
191
|
+
Shared: "shared",
|
|
192
|
+
/** No row: state of the running deployment, which the target makes again. */
|
|
193
|
+
LeftOut: "left-out",
|
|
194
|
+
/** No row: a sign-in means of a person, which other organizations of the person share. The person sets it again. */
|
|
195
|
+
Credential: "credential",
|
|
196
|
+
/** A value of the secret store belongs when a kept row names its reference, or its reference starts with the id. */
|
|
197
|
+
SecretStore: "secret-store"
|
|
198
|
+
};
|
|
199
|
+
/**
|
|
200
|
+
* The rows of one organization in a database: what an organization backup writes and what its check compares. A table
|
|
201
|
+
* with an `organization_id` column keeps the rows of the organization. Every other table needs a rule in
|
|
202
|
+
* {@link rules}: its rows follow the rows of another table, or the whole table is kept as shared data of the
|
|
203
|
+
* deployment, or no row is kept. A table with neither the column nor a rule stops the backup, so a new table of a
|
|
204
|
+
* library never leaves the rows of other organizations in the archive. The conditions run as SQL in the snapshot.
|
|
205
|
+
*/
|
|
206
|
+
var OrganizationScope = class OrganizationScope {
|
|
207
|
+
/** The table of the organizations. */
|
|
208
|
+
static organizationsTable = "organizations";
|
|
209
|
+
/** The column that names the organization of a row. */
|
|
210
|
+
static organizationColumn = "organization_id";
|
|
211
|
+
/** The column of a row that names a value of the secret store. */
|
|
212
|
+
static secretReferenceColumn = "secret_reference";
|
|
213
|
+
/** What an organization id holds: letters, digits and hyphens, so that it can stand in SQL and in a key. */
|
|
214
|
+
static idPattern = /^[A-Za-z0-9-]{1,64}$/u;
|
|
215
|
+
/** The key prefixes of the file store whose objects belong to the organization of the id that follows them. */
|
|
216
|
+
static objectPrefixes = ["files/", "assistant-attachments/"];
|
|
217
|
+
/**
|
|
218
|
+
* The reference prefixes of the secret store whose values belong to the organization of the id that follows them
|
|
219
|
+
* (`connectors/<organization>/…`). Only this position counts, so an id that is a part of another reference selects
|
|
220
|
+
* no value of another organization.
|
|
221
|
+
*/
|
|
222
|
+
static secretPrefixes = [
|
|
223
|
+
"connectors/",
|
|
224
|
+
"models/connections/",
|
|
225
|
+
"models/proxies/",
|
|
226
|
+
"agents/variables/"
|
|
227
|
+
];
|
|
228
|
+
/**
|
|
229
|
+
* The password hash that the archive writes for each member: no algorithm makes it, so no password opens it, and
|
|
230
|
+
* each member sets a new password on the target.
|
|
231
|
+
*/
|
|
232
|
+
static lockedPassword = "!";
|
|
233
|
+
/** The rules of the tables that have no `organization_id` column, and of those whose rows other tables add. */
|
|
234
|
+
static rules = new Map(Object.entries({
|
|
235
|
+
organizations: {
|
|
236
|
+
kind: ScopeRuleKind.Organization,
|
|
237
|
+
columns: ["id"]
|
|
238
|
+
},
|
|
239
|
+
users: {
|
|
240
|
+
kind: ScopeRuleKind.Follow,
|
|
241
|
+
links: [{
|
|
242
|
+
column: "id",
|
|
243
|
+
table: "organization_memberships",
|
|
244
|
+
parentColumn: "user_id"
|
|
245
|
+
}],
|
|
246
|
+
blanked: {
|
|
247
|
+
password_hash: OrganizationScope.lockedPassword,
|
|
248
|
+
password_reset_token_hash: null,
|
|
249
|
+
password_reset_requested_at: null
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
oauth_identities: { kind: ScopeRuleKind.Credential },
|
|
253
|
+
passkeys: { kind: ScopeRuleKind.Credential },
|
|
254
|
+
recovery_codes: { kind: ScopeRuleKind.Credential },
|
|
255
|
+
totp_credentials: { kind: ScopeRuleKind.Credential },
|
|
256
|
+
audit_log: {
|
|
257
|
+
kind: ScopeRuleKind.Organization,
|
|
258
|
+
columns: ["org_id"]
|
|
259
|
+
},
|
|
260
|
+
visibility_grants: {
|
|
261
|
+
kind: ScopeRuleKind.Organization,
|
|
262
|
+
columns: ["grantor_organization_id", "grantee_organization_id"]
|
|
263
|
+
},
|
|
264
|
+
oauth_clients: {
|
|
265
|
+
kind: ScopeRuleKind.Follow,
|
|
266
|
+
links: [
|
|
267
|
+
{
|
|
268
|
+
column: "id",
|
|
269
|
+
table: "oauth_access_tokens",
|
|
270
|
+
parentColumn: "client_id"
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
column: "id",
|
|
274
|
+
table: "oauth_refresh_tokens",
|
|
275
|
+
parentColumn: "client_id"
|
|
276
|
+
},
|
|
277
|
+
{
|
|
278
|
+
column: "id",
|
|
279
|
+
table: "oauth_authorization_codes",
|
|
280
|
+
parentColumn: "client_id"
|
|
281
|
+
},
|
|
282
|
+
{
|
|
283
|
+
column: "id",
|
|
284
|
+
table: "oauth_consent_requests",
|
|
285
|
+
parentColumn: "client_id"
|
|
286
|
+
}
|
|
287
|
+
]
|
|
288
|
+
},
|
|
289
|
+
installations: { kind: ScopeRuleKind.Shared },
|
|
290
|
+
permission_catalog: { kind: ScopeRuleKind.Shared },
|
|
291
|
+
catalog_versions: { kind: ScopeRuleKind.Shared },
|
|
292
|
+
sessions: { kind: ScopeRuleKind.LeftOut },
|
|
293
|
+
refresh_tokens: { kind: ScopeRuleKind.LeftOut },
|
|
294
|
+
webauthn_challenges: { kind: ScopeRuleKind.LeftOut },
|
|
295
|
+
instances: { kind: ScopeRuleKind.LeftOut },
|
|
296
|
+
instance_enrollments: { kind: ScopeRuleKind.LeftOut },
|
|
297
|
+
notification_channel_preferences: OrganizationScope.followsUser("recipient_id"),
|
|
298
|
+
tier_plans: { kind: ScopeRuleKind.Shared },
|
|
299
|
+
secret_envelopes: { kind: ScopeRuleKind.SecretStore },
|
|
300
|
+
outbox: { kind: ScopeRuleKind.LeftOut },
|
|
301
|
+
command_claims: { kind: ScopeRuleKind.LeftOut },
|
|
302
|
+
durable_timers: { kind: ScopeRuleKind.LeftOut },
|
|
303
|
+
key_locks: { kind: ScopeRuleKind.LeftOut },
|
|
304
|
+
chats: {
|
|
305
|
+
kind: ScopeRuleKind.Organization,
|
|
306
|
+
columns: ["organization_id"],
|
|
307
|
+
links: [
|
|
308
|
+
{
|
|
309
|
+
column: "id",
|
|
310
|
+
table: "assistant_sessions",
|
|
311
|
+
parentColumn: "conversation_id"
|
|
312
|
+
},
|
|
313
|
+
{
|
|
314
|
+
column: "id",
|
|
315
|
+
table: "assistant_attachments",
|
|
316
|
+
parentColumn: "chat_id"
|
|
317
|
+
},
|
|
318
|
+
{
|
|
319
|
+
column: "id",
|
|
320
|
+
table: "assistant_room_consultations",
|
|
321
|
+
parentColumn: "room_id"
|
|
322
|
+
},
|
|
323
|
+
{
|
|
324
|
+
column: "id",
|
|
325
|
+
table: "assistant_room_followers",
|
|
326
|
+
parentColumn: "room_id"
|
|
327
|
+
}
|
|
328
|
+
]
|
|
329
|
+
},
|
|
330
|
+
assistant_sessions: {
|
|
331
|
+
kind: ScopeRuleKind.Organization,
|
|
332
|
+
columns: ["organization_id"],
|
|
333
|
+
links: [{
|
|
334
|
+
column: "id",
|
|
335
|
+
table: "assistant_session_tokens",
|
|
336
|
+
parentColumn: "session_id"
|
|
337
|
+
}]
|
|
338
|
+
},
|
|
339
|
+
assistant_queued_messages: OrganizationScope.follows("chat_id", "chats"),
|
|
340
|
+
chat_events: OrganizationScope.follows("chat_id", "chats"),
|
|
341
|
+
assistant_session_commands: OrganizationScope.followsSession(),
|
|
342
|
+
assistant_session_credentials: OrganizationScope.followsSession(),
|
|
343
|
+
assistant_session_epochs: OrganizationScope.followsSession(),
|
|
344
|
+
assistant_session_events: OrganizationScope.followsSession(),
|
|
345
|
+
assistant_session_label_generations: OrganizationScope.followsSession(),
|
|
346
|
+
assistant_session_model_history: OrganizationScope.followsSession(),
|
|
347
|
+
assistant_session_principals: OrganizationScope.followsSession(),
|
|
348
|
+
assistant_session_quarantine: OrganizationScope.followsSession(),
|
|
349
|
+
assistant_session_reads: OrganizationScope.followsSession(),
|
|
350
|
+
assistant_session_redactions: OrganizationScope.followsSession(),
|
|
351
|
+
assistant_session_requests: OrganizationScope.followsSession(),
|
|
352
|
+
assistant_session_step_intents: OrganizationScope.followsSession(),
|
|
353
|
+
assistant_tool_operations: OrganizationScope.followsSession(),
|
|
354
|
+
assistant_session_redaction_removals: {
|
|
355
|
+
kind: ScopeRuleKind.Follow,
|
|
356
|
+
links: [{
|
|
357
|
+
column: "secret_reference",
|
|
358
|
+
table: "assistant_session_redactions",
|
|
359
|
+
parentColumn: "secret_reference"
|
|
360
|
+
}]
|
|
361
|
+
},
|
|
362
|
+
dashboard_pins: OrganizationScope.follows("dashboard_id", "dashboards"),
|
|
363
|
+
assistant_api_run_starts: { kind: ScopeRuleKind.LeftOut },
|
|
364
|
+
workflow_events: { kind: ScopeRuleKind.LeftOut },
|
|
365
|
+
workflow_instances: { kind: ScopeRuleKind.LeftOut },
|
|
366
|
+
workflow_steps: { kind: ScopeRuleKind.LeftOut },
|
|
367
|
+
agent_runner_commands: OrganizationScope.followsRunnerLink(),
|
|
368
|
+
agent_runner_evidence_contents: OrganizationScope.followsRunnerLink(),
|
|
369
|
+
agent_runner_memory_ledgers: OrganizationScope.followsRunnerLink(),
|
|
370
|
+
agent_runner_reports: OrganizationScope.followsRunnerLink(),
|
|
371
|
+
agent_runner_signals: OrganizationScope.followsRunnerLink(),
|
|
372
|
+
agent_runner_slots: OrganizationScope.followsRunnerLink(),
|
|
373
|
+
agent_skill_revisions: { kind: ScopeRuleKind.Shared },
|
|
374
|
+
agent_roster_cursors: { kind: ScopeRuleKind.LeftOut },
|
|
375
|
+
connector_catalog_entries: { kind: ScopeRuleKind.Shared },
|
|
376
|
+
content_job_cursor: { kind: ScopeRuleKind.LeftOut },
|
|
377
|
+
backup_fences: { kind: ScopeRuleKind.LeftOut },
|
|
378
|
+
file_upload_parts: OrganizationScope.follows("session_id", "file_upload_sessions"),
|
|
379
|
+
taxonomy_term_translations: OrganizationScope.follows("term_id", "taxonomy_terms"),
|
|
380
|
+
translation_reviews: {
|
|
381
|
+
kind: ScopeRuleKind.Follow,
|
|
382
|
+
links: [
|
|
383
|
+
"content_entries",
|
|
384
|
+
"files",
|
|
385
|
+
"file_galleries",
|
|
386
|
+
"channels",
|
|
387
|
+
"taxonomy_vocabularies",
|
|
388
|
+
"taxonomy_terms"
|
|
389
|
+
].map((table) => ({
|
|
390
|
+
column: "entity_id",
|
|
391
|
+
table,
|
|
392
|
+
parentColumn: "id"
|
|
393
|
+
}))
|
|
394
|
+
},
|
|
395
|
+
sample_records: { kind: ScopeRuleKind.Shared },
|
|
396
|
+
bouts: { kind: ScopeRuleKind.Shared },
|
|
397
|
+
user_profiles: OrganizationScope.followsUser("id"),
|
|
398
|
+
video_assets: OrganizationScope.follows("video_id", "videos")
|
|
399
|
+
}));
|
|
400
|
+
/** The organization. */
|
|
401
|
+
organizationId;
|
|
402
|
+
sql;
|
|
403
|
+
defaultSchema;
|
|
404
|
+
/** Each table of the database by name, with its rule. */
|
|
405
|
+
tables;
|
|
406
|
+
aliasCount = 0;
|
|
407
|
+
/**
|
|
408
|
+
* @param session - The database: its dialect writes the conditions.
|
|
409
|
+
* @param tables - The tables of the database.
|
|
410
|
+
* @param organizationId - The organization.
|
|
411
|
+
* @throws When the id holds other characters than letters, digits and hyphens, when a table has no rule, or when a
|
|
412
|
+
* rule names a column that its table lacks.
|
|
413
|
+
*/
|
|
414
|
+
constructor(session, tables, organizationId) {
|
|
415
|
+
OrganizationScope.requireId(organizationId);
|
|
416
|
+
this.organizationId = organizationId;
|
|
417
|
+
this.sql = session.scopeSql;
|
|
418
|
+
this.defaultSchema = session.defaultSchema;
|
|
419
|
+
const ruled = /* @__PURE__ */ new Map();
|
|
420
|
+
const unknown = [];
|
|
421
|
+
for (const table of tables) {
|
|
422
|
+
const rule = this.ruleOf(table);
|
|
423
|
+
if (rule === void 0) unknown.push(DatabaseSession.displayName(table.schema, table.name));
|
|
424
|
+
else ruled.set(table.name, {
|
|
425
|
+
table,
|
|
426
|
+
rule
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
if (unknown.length > 0) throw new Error(`The organization backup does not know which rows of ${unknown.length === 1 ? "the table" : "the tables"} ${unknown.join(", ")} belong to an organization. Use the inferative command of the release that the install runs.`);
|
|
430
|
+
this.tables = ruled;
|
|
431
|
+
for (const { table, rule } of ruled.values()) this.checkColumns(table, rule);
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* @param organizationId - The id that a command line gives.
|
|
435
|
+
* @throws When it holds other characters than letters, digits and hyphens.
|
|
436
|
+
*/
|
|
437
|
+
static requireId(organizationId) {
|
|
438
|
+
if (!OrganizationScope.idPattern.test(organizationId)) throw new Error("The organization id holds characters other than letters, digits and hyphens, or more than 64 of them.");
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Stops the backup when the snapshot holds no organization with the id, before a row is read. It needs the open
|
|
442
|
+
* snapshot of {@link DatabaseSession.beginSnapshot}.
|
|
443
|
+
*
|
|
444
|
+
* @param session - The database of the scope.
|
|
445
|
+
* @throws When the database has no organizations table or no organization with the id.
|
|
446
|
+
*/
|
|
447
|
+
async requireOrganization(session) {
|
|
448
|
+
const organizations = this.tables.get(OrganizationScope.organizationsTable);
|
|
449
|
+
if (organizations !== void 0) {
|
|
450
|
+
const rows = session.rows(organizations.table, this.filterOf(organizations.table));
|
|
451
|
+
const first = await rows.next();
|
|
452
|
+
await rows.return(void 0);
|
|
453
|
+
if (first.done !== true) return;
|
|
454
|
+
}
|
|
455
|
+
throw new Error(`The database holds no organization with the id ${this.organizationId}, so the organization backup reads nothing.`);
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* @param organizationId - The organization.
|
|
459
|
+
* @param key - The key of an object of the file store.
|
|
460
|
+
* @returns Whether the key names the organization, so that the object belongs also when no kept row names it.
|
|
461
|
+
*/
|
|
462
|
+
static isObjectKeyOf(organizationId, key) {
|
|
463
|
+
return OrganizationScope.objectPrefixes.some((prefix) => key.startsWith(`${prefix}${organizationId}/`));
|
|
464
|
+
}
|
|
465
|
+
/** See {@link isObjectKeyOf}. */
|
|
466
|
+
hasObjectKey(key) {
|
|
467
|
+
return OrganizationScope.isObjectKeyOf(this.organizationId, key);
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* @param table - A table of the database.
|
|
471
|
+
* @returns Whether the archive holds no row of the table.
|
|
472
|
+
*/
|
|
473
|
+
isLeftOut(table) {
|
|
474
|
+
return OrganizationScope.keepsNoRow(this.entryOf(table).rule);
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* @param kind - {@link ScopeRuleKind.LeftOut} or {@link ScopeRuleKind.Credential}.
|
|
478
|
+
* @returns The number of tables of the database with a rule of the kind.
|
|
479
|
+
*/
|
|
480
|
+
countOf(kind) {
|
|
481
|
+
return [...this.tables.values()].filter(({ rule }) => rule.kind === kind).length;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* @param table - A table of the database.
|
|
485
|
+
* @returns The columns whose value the archive replaces, by their position in a row of the table.
|
|
486
|
+
*/
|
|
487
|
+
blankedOf(table) {
|
|
488
|
+
const { rule } = this.entryOf(table);
|
|
489
|
+
return Object.entries(rule.blanked ?? {}).map(([name, value]) => ({
|
|
490
|
+
index: table.columns.findIndex((column) => column.name === name),
|
|
491
|
+
value
|
|
492
|
+
}));
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* @param table - A table of the database whose rows are not left out.
|
|
496
|
+
* @returns The filter of the rows that belong, or `undefined` when every row is kept.
|
|
497
|
+
*/
|
|
498
|
+
filterOf(table) {
|
|
499
|
+
const { rule } = this.entryOf(table);
|
|
500
|
+
if (rule.kind === ScopeRuleKind.Shared) return;
|
|
501
|
+
const alias = this.nextAlias();
|
|
502
|
+
return {
|
|
503
|
+
alias,
|
|
504
|
+
condition: this.conditionOf(table.name, alias, /* @__PURE__ */ new Set())
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* @param name - A table of the default schema.
|
|
509
|
+
* @returns The filter of its rows that belong, as {@link filterOf} gives it, or `undefined` when the database has
|
|
510
|
+
* no such table.
|
|
511
|
+
*/
|
|
512
|
+
filterOfTable(name) {
|
|
513
|
+
const entry = this.tables.get(name);
|
|
514
|
+
return entry === void 0 ? void 0 : this.filterOf(entry.table);
|
|
515
|
+
}
|
|
516
|
+
entryOf(table) {
|
|
517
|
+
const entry = this.tables.get(table.name);
|
|
518
|
+
if (entry === void 0 || table.schema !== entry.table.schema) throw new Error(`The table ${DatabaseSession.displayName(table.schema, table.name)} is not a table of the backup.`);
|
|
519
|
+
return entry;
|
|
520
|
+
}
|
|
521
|
+
ruleOf(table) {
|
|
522
|
+
if (table.schema !== this.defaultSchema) return;
|
|
523
|
+
const rule = OrganizationScope.rules.get(table.name);
|
|
524
|
+
if (rule !== void 0) return rule;
|
|
525
|
+
return table.columns.some((column) => column.name === OrganizationScope.organizationColumn) ? {
|
|
526
|
+
kind: ScopeRuleKind.Organization,
|
|
527
|
+
columns: [OrganizationScope.organizationColumn]
|
|
528
|
+
} : void 0;
|
|
529
|
+
}
|
|
530
|
+
/** @throws When a rule names a column that its table or the table of a link lacks. */
|
|
531
|
+
checkColumns(table, rule) {
|
|
532
|
+
for (const name of rule.columns ?? []) OrganizationScope.columnOf(table, name);
|
|
533
|
+
for (const link of rule.links ?? []) {
|
|
534
|
+
const parent = this.tables.get(link.table);
|
|
535
|
+
OrganizationScope.columnOf(table, link.column);
|
|
536
|
+
if (parent !== void 0) OrganizationScope.columnOf(parent.table, link.parentColumn);
|
|
537
|
+
}
|
|
538
|
+
for (const name of Object.keys(rule.blanked ?? {})) OrganizationScope.columnOf(table, name);
|
|
539
|
+
if (rule.kind === ScopeRuleKind.SecretStore) OrganizationScope.columnOf(table, "reference");
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* @param name - The table.
|
|
543
|
+
* @param alias - Its alias in the condition.
|
|
544
|
+
* @param visiting - The tables whose condition holds this one; a rule that names one of them again is a cycle.
|
|
545
|
+
* @returns The SQL condition of the rows of the table that belong.
|
|
546
|
+
*/
|
|
547
|
+
conditionOf(name, alias, visiting) {
|
|
548
|
+
const entry = this.tables.get(name);
|
|
549
|
+
if (entry === void 0 || OrganizationScope.keepsNoRow(entry.rule)) return "1 = 0";
|
|
550
|
+
if (entry.rule.kind === ScopeRuleKind.Shared) return "1 = 1";
|
|
551
|
+
if (visiting.has(name)) throw new Error(`The rules of the organization backup name the table ${name} in a cycle.`);
|
|
552
|
+
const inner = /* @__PURE__ */ new Set([...visiting, name]);
|
|
553
|
+
const { table, rule } = entry;
|
|
554
|
+
const parts = (rule.columns ?? []).map((column) => `${this.sql.key(alias, OrganizationScope.columnOf(table, column))} = ${this.sql.literal(this.organizationId)}`);
|
|
555
|
+
for (const link of rule.links ?? []) {
|
|
556
|
+
const part = this.linkCondition(table, alias, link, inner);
|
|
557
|
+
if (part !== void 0) parts.push(part);
|
|
558
|
+
}
|
|
559
|
+
if (rule.kind === ScopeRuleKind.SecretStore) parts.push(...this.secretConditions(table, alias, inner));
|
|
560
|
+
return parts.length === 0 ? "1 = 0" : parts.map((part) => `(${part})`).join(" OR ");
|
|
561
|
+
}
|
|
562
|
+
/** @returns The condition of one link, or `undefined` when the database lacks the table it names. */
|
|
563
|
+
linkCondition(table, alias, link, visiting) {
|
|
564
|
+
const parent = this.tables.get(link.table);
|
|
565
|
+
if (parent === void 0 || OrganizationScope.keepsNoRow(parent.rule)) return;
|
|
566
|
+
const parentAlias = this.nextAlias();
|
|
567
|
+
return `${this.sql.key(alias, OrganizationScope.columnOf(table, link.column))} IN (SELECT ${this.sql.key(parentAlias, OrganizationScope.columnOf(parent.table, link.parentColumn))} FROM ${this.sql.table(parent.table.schema, parent.table.name)} AS ${parentAlias} WHERE ${this.conditionOf(link.table, parentAlias, visiting)})`;
|
|
568
|
+
}
|
|
569
|
+
/** @returns The conditions of a value of the secret store: a kept row names it, or its reference starts with the id. */
|
|
570
|
+
secretConditions(table, alias, visiting) {
|
|
571
|
+
const reference = OrganizationScope.columnOf(table, "reference");
|
|
572
|
+
const parts = OrganizationScope.secretPrefixes.map((prefix) => this.sql.startsWith(alias, reference, `${prefix}${this.organizationId}/`));
|
|
573
|
+
for (const { table: candidate } of this.tables.values()) if (candidate.name !== table.name && candidate.columns.some((column) => column.name === OrganizationScope.secretReferenceColumn)) {
|
|
574
|
+
const part = this.linkCondition(table, alias, {
|
|
575
|
+
column: "reference",
|
|
576
|
+
table: candidate.name,
|
|
577
|
+
parentColumn: OrganizationScope.secretReferenceColumn
|
|
578
|
+
}, visiting);
|
|
579
|
+
if (part !== void 0) parts.push(part);
|
|
580
|
+
}
|
|
581
|
+
return parts;
|
|
582
|
+
}
|
|
583
|
+
nextAlias() {
|
|
584
|
+
this.aliasCount += 1;
|
|
585
|
+
return `scope_${String(this.aliasCount)}`;
|
|
586
|
+
}
|
|
587
|
+
static keepsNoRow(rule) {
|
|
588
|
+
return rule.kind === ScopeRuleKind.LeftOut || rule.kind === ScopeRuleKind.Credential;
|
|
589
|
+
}
|
|
590
|
+
/** @throws When the table lacks the column. */
|
|
591
|
+
static columnOf(table, name) {
|
|
592
|
+
const column = table.columns.find((candidate) => candidate.name === name);
|
|
593
|
+
if (column === void 0) throw new Error(`The table ${DatabaseSession.displayName(table.schema, table.name)} has no column ${name}, so the organization backup cannot tell which of its rows belong to the organization. Use the inferative command of the release that the install runs.`);
|
|
594
|
+
return column;
|
|
595
|
+
}
|
|
596
|
+
static follows(column, table) {
|
|
597
|
+
return {
|
|
598
|
+
kind: ScopeRuleKind.Follow,
|
|
599
|
+
links: [{
|
|
600
|
+
column,
|
|
601
|
+
table,
|
|
602
|
+
parentColumn: "id"
|
|
603
|
+
}]
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
static followsUser(column) {
|
|
607
|
+
return OrganizationScope.follows(column, "users");
|
|
608
|
+
}
|
|
609
|
+
static followsSession() {
|
|
610
|
+
return OrganizationScope.follows("session_id", "assistant_sessions");
|
|
611
|
+
}
|
|
612
|
+
static followsRunnerLink() {
|
|
613
|
+
return OrganizationScope.follows("attachment_id", "agent_runner_attachments");
|
|
614
|
+
}
|
|
615
|
+
};
|
|
616
|
+
//#endregion
|
|
182
617
|
//#region src/backup/backup-manifest.ts
|
|
183
618
|
/** The names and the version of the archive format. */
|
|
184
619
|
var BackupManifest = class BackupManifest {
|
|
185
620
|
/** The value of the `format` field. */
|
|
186
621
|
static format = "inferative-backup";
|
|
187
|
-
/** The version of the format that
|
|
622
|
+
/** The version of the format of an archive that keeps every sealed value as the source holds it. */
|
|
188
623
|
static formatVersion = 1;
|
|
624
|
+
/**
|
|
625
|
+
* The version of the format of an archive whose sealed values moved to a transfer key ({@link BackupTransfer}). An
|
|
626
|
+
* older tool refuses it, so it never restores the moved values as they are.
|
|
627
|
+
*/
|
|
628
|
+
static transferFormatVersion = 2;
|
|
189
629
|
/** The dialects of the databases that this tool reads and restores. */
|
|
190
630
|
static dialects = /* @__PURE__ */ new Set([DatabaseDialect.Postgres, DatabaseDialect.Mysql]);
|
|
191
631
|
/** The entry that holds the manifest. It is the last entry. */
|
|
@@ -210,10 +650,22 @@ var BackupManifest = class BackupManifest {
|
|
|
210
650
|
static parse(text) {
|
|
211
651
|
const data = JSON.parse(text);
|
|
212
652
|
if (data.format !== BackupManifest.format) throw new Error("The archive holds no Inferative backup manifest.");
|
|
213
|
-
|
|
653
|
+
const version = data.transfer === void 0 ? BackupManifest.formatVersion : BackupManifest.transferFormatVersion;
|
|
654
|
+
if (data.formatVersion !== version) throw new Error(`The archive has format version ${String(data.formatVersion)}; this tool reads version ${BackupManifest.formatVersion}, and version ${BackupManifest.transferFormatVersion} for an archive whose sealed values moved to a transfer key.`);
|
|
655
|
+
if (data.transfer !== void 0 && !BackupManifest.isTransfer(data.transfer)) throw new Error("The archive names its transfer in a form that this tool does not read.");
|
|
656
|
+
if (data.transfer !== void 0 && data.organization === void 0) throw new Error("The archive moves sealed values, and names no organization.");
|
|
214
657
|
if (!BackupManifest.dialects.has(data.database?.dialect ?? "")) throw new Error("The archive holds a database of a dialect that this tool cannot restore.");
|
|
658
|
+
if (data.organization !== void 0) {
|
|
659
|
+
if (typeof data.organization !== "string") throw new Error("The archive names its organization in a form that this tool does not read.");
|
|
660
|
+
OrganizationScope.requireId(data.organization);
|
|
661
|
+
}
|
|
215
662
|
return data;
|
|
216
663
|
}
|
|
664
|
+
/** @returns Whether a value has the shape of {@link BackupTransfer}. */
|
|
665
|
+
static isTransfer(value) {
|
|
666
|
+
const transfer = value;
|
|
667
|
+
return typeof transfer === "object" && transfer !== null && typeof transfer.recipient === "string" && typeof transfer.movePublicKey === "string" && Array.isArray(transfer.kinds) && transfer.kinds.every((kind) => typeof kind.kind === "string" && typeof kind.values === "number" && typeof kind.digest === "string") && Array.isArray(transfer.unreadable) && transfer.unreadable.every((item) => typeof item.kind === "string" && typeof item.id === "string");
|
|
668
|
+
}
|
|
217
669
|
/**
|
|
218
670
|
* @param manifest - The manifest of an archive.
|
|
219
671
|
* @param dialect - The dialect of the database to restore into or to compare with.
|
|
@@ -263,7 +715,7 @@ var DatabaseSessions = class DatabaseSessions {
|
|
|
263
715
|
*/
|
|
264
716
|
static async open(address) {
|
|
265
717
|
if (DatabaseSessions.requiredDialectOf(address) === DatabaseDialect.Mysql) {
|
|
266
|
-
const { MysqlSession } = await import("./mysql-session-
|
|
718
|
+
const { MysqlSession } = await import("./mysql-session-BJ0k7zws.mjs");
|
|
267
719
|
return MysqlSession.open(address);
|
|
268
720
|
}
|
|
269
721
|
return PgSession.open(address);
|
|
@@ -276,7 +728,7 @@ var DatabaseSessions = class DatabaseSessions {
|
|
|
276
728
|
*/
|
|
277
729
|
static async migrate(address, folder) {
|
|
278
730
|
if (DatabaseSessions.requiredDialectOf(address) === DatabaseDialect.Mysql) {
|
|
279
|
-
const { MysqlSession } = await import("./mysql-session-
|
|
731
|
+
const { MysqlSession } = await import("./mysql-session-BJ0k7zws.mjs");
|
|
280
732
|
await MysqlSession.migrate(address, folder);
|
|
281
733
|
return;
|
|
282
734
|
}
|
|
@@ -422,16 +874,18 @@ var FileStoreContent = class FileStoreContent {
|
|
|
422
874
|
return { ...custom };
|
|
423
875
|
}
|
|
424
876
|
/**
|
|
425
|
-
* Reads every object of the store and hashes its bytes.
|
|
877
|
+
* Reads every object of the store, or the objects of the keys that a test keeps, and hashes its bytes.
|
|
426
878
|
*
|
|
427
879
|
* @param store - The store.
|
|
428
|
-
* @
|
|
880
|
+
* @param isKept - Which keys to read, before their metadata or bytes are read; every key when absent.
|
|
881
|
+
* @returns The facts of each object read, by key, and their content.
|
|
429
882
|
*/
|
|
430
|
-
static async read(store) {
|
|
883
|
+
static async read(store, isKept) {
|
|
431
884
|
const objects = /* @__PURE__ */ new Map();
|
|
432
885
|
const digest = new ContentDigest();
|
|
433
886
|
let bytes = 0;
|
|
434
887
|
for (const key of await store.list()) {
|
|
888
|
+
if (isKept !== void 0 && !isKept(key)) continue;
|
|
435
889
|
const metadata = await store.stat(key);
|
|
436
890
|
const stream = await store.getStream(key);
|
|
437
891
|
if (metadata === null || stream === null) continue;
|
|
@@ -463,71 +917,6 @@ var FileStoreContent = class FileStoreContent {
|
|
|
463
917
|
}
|
|
464
918
|
};
|
|
465
919
|
//#endregion
|
|
466
|
-
//#region src/backup/backup-comparison.ts
|
|
467
|
-
/** Compares what a database or a store holds with what the backup recorded, and names each difference. */
|
|
468
|
-
var BackupComparison = class BackupComparison {
|
|
469
|
-
/** The most differences one comparison names; the rest are counted. */
|
|
470
|
-
static shownLimit = 20;
|
|
471
|
-
/**
|
|
472
|
-
* @param expected - The content the backup recorded.
|
|
473
|
-
* @param actual - The content of the database.
|
|
474
|
-
* @returns One line for each difference; none when the two are the same.
|
|
475
|
-
*/
|
|
476
|
-
static database(expected, actual) {
|
|
477
|
-
const differences = [];
|
|
478
|
-
if (expected.schemaDigest !== actual.schemaDigest) differences.push(`The schema differs from the schema of the backup (${actual.schemaLines} lines, the backup has ${expected.schemaLines}).`);
|
|
479
|
-
const actualTables = new Map(actual.tables.map((table) => [DatabaseSession.displayName(table.schema, table.name), table]));
|
|
480
|
-
for (const table of expected.tables) {
|
|
481
|
-
const name = DatabaseSession.displayName(table.schema, table.name);
|
|
482
|
-
const found = actualTables.get(name);
|
|
483
|
-
actualTables.delete(name);
|
|
484
|
-
if (found === void 0) differences.push(`The table ${name} is missing.`);
|
|
485
|
-
else if (found.rows !== table.rows) differences.push(`The table ${name} has ${found.rows} rows; the backup has ${table.rows}.`);
|
|
486
|
-
else if (found.digest !== table.digest) differences.push(`The rows of the table ${name} differ from the backup.`);
|
|
487
|
-
}
|
|
488
|
-
for (const name of actualTables.keys()) differences.push(`The table ${name} is not in the backup.`);
|
|
489
|
-
differences.push(...BackupComparison.sequences(expected.sequences, actual.sequences));
|
|
490
|
-
if (JSON.stringify(expected.migrations) !== JSON.stringify(actual.migrations)) differences.push(`The migrations journal differs: ${actual.migrations.length} rows, head ${BackupComparison.headOf(actual)}; the backup has ${expected.migrations.length}, head ${BackupComparison.headOf(expected)}.`);
|
|
491
|
-
return BackupComparison.limited(differences);
|
|
492
|
-
}
|
|
493
|
-
/**
|
|
494
|
-
* @param expected - The objects the backup recorded, by key.
|
|
495
|
-
* @param actual - The objects of the store, by key.
|
|
496
|
-
* @returns One line for each difference; none when the two are the same.
|
|
497
|
-
*/
|
|
498
|
-
static files(expected, actual) {
|
|
499
|
-
const differences = [];
|
|
500
|
-
for (const [key, object] of expected) {
|
|
501
|
-
const found = actual.get(key);
|
|
502
|
-
if (found === void 0) differences.push(`The object ${key} is missing.`);
|
|
503
|
-
else if (FileStoreContent.lineOf(found) !== FileStoreContent.lineOf(object)) differences.push(`The object ${key} differs from the backup.`);
|
|
504
|
-
}
|
|
505
|
-
for (const key of actual.keys()) if (!expected.has(key)) differences.push(`The object ${key} is not in the backup.`);
|
|
506
|
-
return BackupComparison.limited(differences);
|
|
507
|
-
}
|
|
508
|
-
/** @returns The name of the last migration of a journal, or `none`. */
|
|
509
|
-
static headOf(content) {
|
|
510
|
-
return content.migrations.at(-1)?.name ?? "none";
|
|
511
|
-
}
|
|
512
|
-
static sequences(expected, actual) {
|
|
513
|
-
const differences = [];
|
|
514
|
-
const actualByName = new Map(actual.map((state) => [DatabaseSession.displayName(state.schema, state.name), state]));
|
|
515
|
-
for (const state of expected) {
|
|
516
|
-
const name = DatabaseSession.displayName(state.schema, state.name);
|
|
517
|
-
const found = actualByName.get(name);
|
|
518
|
-
actualByName.delete(name);
|
|
519
|
-
if (found === void 0) differences.push(`The sequence ${name} is missing.`);
|
|
520
|
-
else if (found.lastValue !== state.lastValue || found.isCalled !== state.isCalled) differences.push(`The sequence ${name} is at ${found.lastValue}; the backup has ${state.lastValue}.`);
|
|
521
|
-
}
|
|
522
|
-
for (const name of actualByName.keys()) differences.push(`The sequence ${name} is not in the backup.`);
|
|
523
|
-
return differences;
|
|
524
|
-
}
|
|
525
|
-
static limited(differences) {
|
|
526
|
-
if (differences.length <= BackupComparison.shownLimit) return differences;
|
|
527
|
-
return [...differences.slice(0, BackupComparison.shownLimit), `And ${differences.length - BackupComparison.shownLimit} more differences.`];
|
|
528
|
-
}
|
|
529
|
-
};
|
|
530
|
-
//#endregion
|
|
531
920
|
//#region src/backup/secret-store-check.ts
|
|
532
921
|
/**
|
|
533
922
|
* Checks the values of the database secret store against the keys of a host: the key of its root secret
|
|
@@ -539,6 +928,8 @@ var BackupComparison = class BackupComparison {
|
|
|
539
928
|
var SecretStoreCheck = class SecretStoreCheck {
|
|
540
929
|
/** The variable that holds the listed keys of a host. */
|
|
541
930
|
static keysVariable = "INFERATIVE_SECRETS_KEYS";
|
|
931
|
+
/** The variable that holds a model history key of a host. */
|
|
932
|
+
static historyKeyVariable = DeploymentSecret.variableOf("assistant.historyEncryptionKey");
|
|
542
933
|
/** The prefix of the key id of a root's key. */
|
|
543
934
|
static rootKeyPrefix = "root-";
|
|
544
935
|
/**
|
|
@@ -549,10 +940,12 @@ var SecretStoreCheck = class SecretStoreCheck {
|
|
|
549
940
|
const listed = SecretStoreCheck.valueOf(env[SecretStoreCheck.keysVariable]);
|
|
550
941
|
const root = SecretStoreCheck.valueOf(env[RootSecret.variable]);
|
|
551
942
|
const previousRoot = SecretStoreCheck.valueOf(env[RootSecret.previousVariable]);
|
|
552
|
-
|
|
943
|
+
const historyKey = SecretStoreCheck.valueOf(env[SecretStoreCheck.historyKeyVariable]);
|
|
944
|
+
return listed === void 0 && root === void 0 && previousRoot === void 0 && historyKey === void 0 ? void 0 : {
|
|
553
945
|
...listed === void 0 ? {} : { listed },
|
|
554
946
|
...root === void 0 ? {} : { root },
|
|
555
|
-
...previousRoot === void 0 ? {} : { previousRoot }
|
|
947
|
+
...previousRoot === void 0 ? {} : { previousRoot },
|
|
948
|
+
...historyKey === void 0 ? {} : { historyKey }
|
|
556
949
|
};
|
|
557
950
|
}
|
|
558
951
|
/** The table of the database secret store. */
|
|
@@ -561,10 +954,11 @@ var SecretStoreCheck = class SecretStoreCheck {
|
|
|
561
954
|
static readable = "readable";
|
|
562
955
|
/**
|
|
563
956
|
* @param session - The database.
|
|
957
|
+
* @param scope - The organization whose values to count; every value when absent.
|
|
564
958
|
* @returns The values by key id, or `null` when the database has no secret store table.
|
|
565
959
|
*/
|
|
566
|
-
static async content(session) {
|
|
567
|
-
const found = await session.secretKeyCounts(SecretStoreCheck.table);
|
|
960
|
+
static async content(session, scope) {
|
|
961
|
+
const found = await session.secretKeyCounts(SecretStoreCheck.table, scope?.filterOfTable(SecretStoreCheck.table));
|
|
568
962
|
if (found === void 0) return null;
|
|
569
963
|
return {
|
|
570
964
|
table: DatabaseSession.displayName(found.schema, SecretStoreCheck.table),
|
|
@@ -577,11 +971,13 @@ var SecretStoreCheck = class SecretStoreCheck {
|
|
|
577
971
|
/**
|
|
578
972
|
* @param session - The database.
|
|
579
973
|
* @param hostKeys - The variables of the host's keys.
|
|
974
|
+
* @param scope - The organization whose values to count; every value when absent.
|
|
580
975
|
* @returns For each key id of the stored values, whether the keys read it.
|
|
581
976
|
* @throws When the list does not parse, or a root is not base64 of 32 bytes. The message holds no part of either.
|
|
582
977
|
*/
|
|
583
|
-
static async readability(session, hostKeys) {
|
|
584
|
-
const
|
|
978
|
+
static async readability(session, hostKeys, scope) {
|
|
979
|
+
const filter = scope?.filterOfTable(SecretStoreCheck.table);
|
|
980
|
+
const found = await session.secretKeyCounts(SecretStoreCheck.table, filter);
|
|
585
981
|
if (found === void 0) return [];
|
|
586
982
|
const keys = await SecretStoreCheck.keysOf(hostKeys);
|
|
587
983
|
const results = [];
|
|
@@ -597,7 +993,7 @@ var SecretStoreCheck = class SecretStoreCheck {
|
|
|
597
993
|
});
|
|
598
994
|
continue;
|
|
599
995
|
}
|
|
600
|
-
const sample = await session.secretSample(found.schema, SecretStoreCheck.table, group.keyId);
|
|
996
|
+
const sample = await session.secretSample(found.schema, SecretStoreCheck.table, group.keyId, filter);
|
|
601
997
|
const isOpen = sample !== void 0 && await SecretStoreCheck.opens(material, sample.reference, sample.envelope);
|
|
602
998
|
results.push({
|
|
603
999
|
id: group.keyId,
|
|
@@ -608,15 +1004,30 @@ var SecretStoreCheck = class SecretStoreCheck {
|
|
|
608
1004
|
}
|
|
609
1005
|
return results;
|
|
610
1006
|
}
|
|
1007
|
+
/**
|
|
1008
|
+
* @param hostKeys - The variables of the host's keys.
|
|
1009
|
+
* @returns The root secret of the host; unset when it sets none.
|
|
1010
|
+
* @throws When a root is not base64 of 32 bytes. The message holds no part of it.
|
|
1011
|
+
*/
|
|
1012
|
+
static rootOf(hostKeys) {
|
|
1013
|
+
return RootSecret.open({
|
|
1014
|
+
...hostKeys?.root === void 0 ? {} : { secret: hostKeys.root },
|
|
1015
|
+
...hostKeys?.previousRoot === void 0 ? {} : { secretPrevious: hostKeys.previousRoot }
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
/**
|
|
1019
|
+
* @param hostKeys - The variables of the host's keys.
|
|
1020
|
+
* @returns The keys of the host's secret store, as the base package makes the ring, or `undefined` when none is set.
|
|
1021
|
+
* @throws When the list does not parse, or a root is not base64 of 32 bytes. The message holds no part of either.
|
|
1022
|
+
*/
|
|
1023
|
+
static async definitionsOf(hostKeys) {
|
|
1024
|
+
const listed = hostKeys?.listed === void 0 ? void 0 : SecretStoreCheck.parseKeys(hostKeys.listed);
|
|
1025
|
+
return SecretStoreKeys.of(listed, await SecretStoreCheck.rootOf(hostKeys));
|
|
1026
|
+
}
|
|
611
1027
|
/** @returns The material of each key of the host's ring, by id. */
|
|
612
1028
|
static async keysOf(hostKeys) {
|
|
613
|
-
const root = await RootSecret.open({
|
|
614
|
-
...hostKeys.root === void 0 ? {} : { secret: hostKeys.root },
|
|
615
|
-
...hostKeys.previousRoot === void 0 ? {} : { secretPrevious: hostKeys.previousRoot }
|
|
616
|
-
});
|
|
617
|
-
const listed = hostKeys.listed === void 0 ? void 0 : SecretStoreCheck.parseKeys(hostKeys.listed);
|
|
618
1029
|
const keys = /* @__PURE__ */ new Map();
|
|
619
|
-
for (const key of
|
|
1030
|
+
for (const key of await SecretStoreCheck.definitionsOf(hostKeys) ?? []) keys.set(key.id, Buffer.from(key.material.replaceAll("-", "+").replaceAll("_", "/"), "base64"));
|
|
620
1031
|
return keys;
|
|
621
1032
|
}
|
|
622
1033
|
static parseKeys(keysJson) {
|
|
@@ -629,10 +1040,12 @@ var SecretStoreCheck = class SecretStoreCheck {
|
|
|
629
1040
|
if (!Array.isArray(parsed)) throw new Error(`${SecretStoreCheck.keysVariable} is not a JSON list.`);
|
|
630
1041
|
const keys = [];
|
|
631
1042
|
for (const entry of parsed) {
|
|
632
|
-
const { id, material } = entry ?? {};
|
|
1043
|
+
const { id, material, current, derive } = entry ?? {};
|
|
633
1044
|
if (typeof id === "string" && typeof material === "string") keys.push({
|
|
634
1045
|
id,
|
|
635
|
-
material
|
|
1046
|
+
material,
|
|
1047
|
+
...current === true ? { current: true } : {},
|
|
1048
|
+
...derive === true ? { derive: true } : {}
|
|
636
1049
|
});
|
|
637
1050
|
}
|
|
638
1051
|
return keys;
|
|
@@ -658,6 +1071,404 @@ var SecretStoreCheck = class SecretStoreCheck {
|
|
|
658
1071
|
}
|
|
659
1072
|
};
|
|
660
1073
|
//#endregion
|
|
1074
|
+
//#region src/backup/sealed-values.ts
|
|
1075
|
+
/** The kinds of sealed value that an organization backup moves to the target's transfer key. */
|
|
1076
|
+
const SealedValueKind = {
|
|
1077
|
+
/** A value of the database secret store: a connector token, a model key, a secret variable. */
|
|
1078
|
+
SecretStore: "secret-store",
|
|
1079
|
+
/** A sealed column of a row of the model history. */
|
|
1080
|
+
HistoryColumn: "history-column",
|
|
1081
|
+
/** An object of the model history: a large row, a large event, a tool answer, a large tool result, a page. */
|
|
1082
|
+
HistoryObject: "history-object",
|
|
1083
|
+
/** The verifier of an agent session token, which derives from the history key. */
|
|
1084
|
+
SessionToken: "session-token"
|
|
1085
|
+
};
|
|
1086
|
+
/**
|
|
1087
|
+
* The tables and columns of the libraries that hold sealed values, and the forms that a move gives them. A moved
|
|
1088
|
+
* value names the key id {@link marker}, which no key of a host can have; the restore seals it again under the
|
|
1089
|
+
* target's key. The digests of a moved archive mask each value that the move sealed again ({@link maskerOf}), so the
|
|
1090
|
+
* check compares the other columns, and the sealed content through the keyed digests of the move.
|
|
1091
|
+
*/
|
|
1092
|
+
var SealedTables = class SealedTables {
|
|
1093
|
+
/** The table of the database secret store. */
|
|
1094
|
+
static secretTable = SecretStoreCheck.table;
|
|
1095
|
+
/** The rows of the model history. */
|
|
1096
|
+
static historyTable = "assistant_session_model_history";
|
|
1097
|
+
/** The session tokens, whose verifier derives from the history key. */
|
|
1098
|
+
static tokenTable = "assistant_session_tokens";
|
|
1099
|
+
/** The events of the sessions, whose large payloads are objects of the history. */
|
|
1100
|
+
static eventTable = "assistant_session_events";
|
|
1101
|
+
/** The tool calls of the sessions, whose kept answers are objects of the history. */
|
|
1102
|
+
static toolTable = "assistant_tool_operations";
|
|
1103
|
+
/** The key id of a moved value. It holds a `.`, which a key id of a host cannot hold. */
|
|
1104
|
+
static marker = "transfer.v1";
|
|
1105
|
+
/** What a digest of a moved archive reads in place of a sealed column that holds a value. */
|
|
1106
|
+
static maskedValue = "sealed";
|
|
1107
|
+
/** The variable of an explicit history key, for the message of a key that does not decode. */
|
|
1108
|
+
static historyKeyName = SecretStoreCheck.historyKeyVariable;
|
|
1109
|
+
/**
|
|
1110
|
+
* @param table - A table of the database.
|
|
1111
|
+
* @param names - The columns that the move reads.
|
|
1112
|
+
* @returns The position of each column.
|
|
1113
|
+
* @throws When the table lacks a column: the move would then miss its values.
|
|
1114
|
+
*/
|
|
1115
|
+
static positionsOf(table, names) {
|
|
1116
|
+
const positions = {};
|
|
1117
|
+
for (const name of names) {
|
|
1118
|
+
const position = table.columns.findIndex((column) => column.name === name);
|
|
1119
|
+
if (position === -1) throw new Error(`The table ${DatabaseSession.displayName(table.schema, table.name)} has no column ${name}, so the backup cannot move its sealed values. Use the inferative command of the release that the install runs.`);
|
|
1120
|
+
positions[name] = position;
|
|
1121
|
+
}
|
|
1122
|
+
return positions;
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* What a digest of a moved archive reads for a row: each sealed column that the move sealed again holds
|
|
1126
|
+
* {@link maskedValue}, since the target keeps it under its own keys. A value that the source could not open stays as
|
|
1127
|
+
* the source holds it, so its row is compared as it is; so is a large history row, whose object moves.
|
|
1128
|
+
*
|
|
1129
|
+
* @param table - A table of the snapshot.
|
|
1130
|
+
* @param schema - The schema of the libraries' tables.
|
|
1131
|
+
* @param isUnreadable - Whether the source could not open the value at a place.
|
|
1132
|
+
* @returns What masks a row, or `undefined` for a table with no sealed column.
|
|
1133
|
+
* @throws When the table lacks a column that the move reads.
|
|
1134
|
+
*/
|
|
1135
|
+
static maskerOf(table, schema, isUnreadable) {
|
|
1136
|
+
if (table.schema !== schema) return;
|
|
1137
|
+
const at = SealedTables.valueAt;
|
|
1138
|
+
if (table.name === SealedTables.secretTable) {
|
|
1139
|
+
const positions = SealedTables.positionsOf(table, [
|
|
1140
|
+
"reference",
|
|
1141
|
+
"key_id",
|
|
1142
|
+
"envelope"
|
|
1143
|
+
]);
|
|
1144
|
+
return (row) => isUnreadable(SealedValueKind.SecretStore, at(row, positions["reference"]) ?? "") ? row : SealedTables.masked(row, [positions["key_id"], positions["envelope"]]);
|
|
1145
|
+
}
|
|
1146
|
+
if (table.name === SealedTables.historyTable) {
|
|
1147
|
+
const positions = SealedTables.positionsOf(table, [
|
|
1148
|
+
"session_id",
|
|
1149
|
+
"position",
|
|
1150
|
+
"payload",
|
|
1151
|
+
"outcome",
|
|
1152
|
+
"offload_reference",
|
|
1153
|
+
"key_id"
|
|
1154
|
+
]);
|
|
1155
|
+
return (row) => at(row, positions["offload_reference"]) !== null || isUnreadable(SealedValueKind.HistoryColumn, SealedTables.historyPlaceOf(at(row, positions["session_id"]), at(row, positions["position"]))) ? row : SealedTables.masked(row, [
|
|
1156
|
+
positions["payload"],
|
|
1157
|
+
positions["outcome"],
|
|
1158
|
+
positions["key_id"]
|
|
1159
|
+
]);
|
|
1160
|
+
}
|
|
1161
|
+
if (table.name === SealedTables.tokenTable) {
|
|
1162
|
+
const positions = SealedTables.positionsOf(table, ["verifier_hash"]);
|
|
1163
|
+
return (row) => SealedTables.masked(row, [positions["verifier_hash"]]);
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
/** @returns The place that names a history row: its session and its position. */
|
|
1167
|
+
static historyPlaceOf(sessionId, position) {
|
|
1168
|
+
return `${sessionId ?? ""}/${String(position)}`;
|
|
1169
|
+
}
|
|
1170
|
+
/** @returns The row with each column of the list that holds a value replaced by {@link maskedValue}. */
|
|
1171
|
+
static masked(row, positions) {
|
|
1172
|
+
const copy = [...row];
|
|
1173
|
+
for (const position of positions) if (position !== void 0 && copy[position] !== null && copy[position] !== void 0) copy[position] = SealedTables.maskedValue;
|
|
1174
|
+
return copy;
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* @param object - An object of the store or of the archive, which a move seals again.
|
|
1178
|
+
* @returns The facts that a move keeps: the bytes, the size and the key id change.
|
|
1179
|
+
*/
|
|
1180
|
+
static maskedObject(object) {
|
|
1181
|
+
const custom = { ...object.custom };
|
|
1182
|
+
delete custom[ModelHistorySeals.keyIdField];
|
|
1183
|
+
return {
|
|
1184
|
+
...object,
|
|
1185
|
+
size: 0,
|
|
1186
|
+
sha256: SealedTables.maskedValue,
|
|
1187
|
+
custom
|
|
1188
|
+
};
|
|
1189
|
+
}
|
|
1190
|
+
/** @returns The value at a position of a row; `null` for a column that holds none. */
|
|
1191
|
+
static valueAt(row, position) {
|
|
1192
|
+
return position === void 0 ? null : row[position] ?? null;
|
|
1193
|
+
}
|
|
1194
|
+
/** @returns The ring of the host's secret store, or `undefined` when it sets no key. */
|
|
1195
|
+
static async ringOf(hostKeys) {
|
|
1196
|
+
const definitions = await SecretStoreCheck.definitionsOf(hostKeys);
|
|
1197
|
+
return definitions === void 0 || definitions.length === 0 ? void 0 : SecretKeyRing.from(definitions);
|
|
1198
|
+
}
|
|
1199
|
+
/** @returns The history key of the host (its root's, or the one it set), or `undefined` when it sets none. */
|
|
1200
|
+
static async historyCipherOf(hostKeys) {
|
|
1201
|
+
const root = await SecretStoreCheck.rootOf(hostKeys);
|
|
1202
|
+
return SealedTextCipher.fromKeys(root.keysOf(hostKeys?.historyKey, RootSecretPurpose.ModelHistoryKey), SealedTables.historyKeyName);
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
/**
|
|
1206
|
+
* The objects of the model history of an organization backup: the large tool results of its sessions and the pages of
|
|
1207
|
+
* its conversations, which no row names, and the binding of each object that the history key sealed. It reads the
|
|
1208
|
+
* rows that the backup or the restore writes, so it sends no statement of its own.
|
|
1209
|
+
*/
|
|
1210
|
+
var HistoryObjects = class HistoryObjects {
|
|
1211
|
+
withBindings;
|
|
1212
|
+
sessions = /* @__PURE__ */ new Set();
|
|
1213
|
+
chats = /* @__PURE__ */ new Set();
|
|
1214
|
+
bindings = /* @__PURE__ */ new Map();
|
|
1215
|
+
/**
|
|
1216
|
+
* @param withBindings - Whether to read the binding of each object, which a move needs.
|
|
1217
|
+
*/
|
|
1218
|
+
constructor(withBindings) {
|
|
1219
|
+
this.withBindings = withBindings;
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* @param table - A table of the snapshot or of the archive.
|
|
1223
|
+
* @param schema - The schema of the libraries' tables.
|
|
1224
|
+
* @returns What takes the facts of each row, or `undefined` when the table holds none.
|
|
1225
|
+
* @throws When a move needs a column that the table lacks.
|
|
1226
|
+
*/
|
|
1227
|
+
collectorOf(table, schema) {
|
|
1228
|
+
if (table.schema !== schema) return;
|
|
1229
|
+
if (table.name === "assistant_sessions" || table.name === "chats") {
|
|
1230
|
+
const ids = table.name === "chats" ? this.chats : this.sessions;
|
|
1231
|
+
const position = table.columns.findIndex((column) => column.name === "id");
|
|
1232
|
+
return position === -1 ? void 0 : (row) => {
|
|
1233
|
+
const id = row[position];
|
|
1234
|
+
if (id !== null && id !== void 0) ids.add(id);
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
return this.withBindings ? this.bindingCollectorOf(table) : void 0;
|
|
1238
|
+
}
|
|
1239
|
+
/**
|
|
1240
|
+
* @param key - An object key.
|
|
1241
|
+
* @returns Whether it is a large tool result of a kept session or a page of a kept conversation.
|
|
1242
|
+
*/
|
|
1243
|
+
isKept(key) {
|
|
1244
|
+
const model = ModelHistorySeals.parseModelObjectKey(key);
|
|
1245
|
+
if (model?.kind === "result") return this.sessions.has(model.sessionId);
|
|
1246
|
+
const page = ModelHistorySeals.parseVisualizationKey(key);
|
|
1247
|
+
return page !== void 0 && this.chats.has(page.chatId);
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* @param key - An object key.
|
|
1251
|
+
* @returns The binding that the history key sealed the object under, or `undefined` for an object that it did not
|
|
1252
|
+
* seal: a row names the binding of a large row, a large event and a tool answer, and the key names it for a large
|
|
1253
|
+
* tool result and a page.
|
|
1254
|
+
*/
|
|
1255
|
+
bindingOf(key) {
|
|
1256
|
+
const named = this.bindings.get(key);
|
|
1257
|
+
if (named !== void 0) return named;
|
|
1258
|
+
if (ModelHistorySeals.parseModelObjectKey(key)?.kind === "result") return key;
|
|
1259
|
+
const page = ModelHistorySeals.parseVisualizationKey(key);
|
|
1260
|
+
return page === void 0 ? void 0 : ModelHistorySeals.visualizationBinding(page.chatId, page.visualizationId);
|
|
1261
|
+
}
|
|
1262
|
+
bindingCollectorOf(table) {
|
|
1263
|
+
const bindingOf = HistoryObjects.bindingReaderOf(table);
|
|
1264
|
+
return bindingOf === void 0 ? void 0 : (row) => {
|
|
1265
|
+
const found = bindingOf(row);
|
|
1266
|
+
if (found !== void 0) this.bindings.set(found.key, found.binding);
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
/** @returns What reads the object key and its binding from a row of the table, or `undefined`. */
|
|
1270
|
+
static bindingReaderOf(table) {
|
|
1271
|
+
const at = SealedTables.valueAt;
|
|
1272
|
+
if (table.name === SealedTables.historyTable) {
|
|
1273
|
+
const positions = SealedTables.positionsOf(table, [
|
|
1274
|
+
"session_id",
|
|
1275
|
+
"position",
|
|
1276
|
+
"step_id",
|
|
1277
|
+
"offload_reference"
|
|
1278
|
+
]);
|
|
1279
|
+
return (row) => {
|
|
1280
|
+
const key = at(row, positions["offload_reference"]);
|
|
1281
|
+
return key === null ? void 0 : {
|
|
1282
|
+
key,
|
|
1283
|
+
binding: ModelHistorySeals.rowObjectBinding(at(row, positions["session_id"]) ?? "", Number(at(row, positions["position"])), at(row, positions["step_id"]) ?? "")
|
|
1284
|
+
};
|
|
1285
|
+
};
|
|
1286
|
+
}
|
|
1287
|
+
if (table.name === SealedTables.eventTable) {
|
|
1288
|
+
const positions = SealedTables.positionsOf(table, [
|
|
1289
|
+
"session_id",
|
|
1290
|
+
"sequence",
|
|
1291
|
+
"event_id",
|
|
1292
|
+
"offload_reference"
|
|
1293
|
+
]);
|
|
1294
|
+
return (row) => {
|
|
1295
|
+
const key = at(row, positions["offload_reference"]);
|
|
1296
|
+
return key === null ? void 0 : {
|
|
1297
|
+
key,
|
|
1298
|
+
binding: ModelHistorySeals.eventObjectBinding(at(row, positions["session_id"]) ?? "", Number(at(row, positions["sequence"])), at(row, positions["event_id"]) ?? "")
|
|
1299
|
+
};
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
if (table.name === SealedTables.toolTable) {
|
|
1303
|
+
const positions = SealedTables.positionsOf(table, [
|
|
1304
|
+
"session_id",
|
|
1305
|
+
"operation_id",
|
|
1306
|
+
"result_reference"
|
|
1307
|
+
]);
|
|
1308
|
+
return (row) => {
|
|
1309
|
+
const key = at(row, positions["result_reference"]);
|
|
1310
|
+
return key === null ? void 0 : {
|
|
1311
|
+
key,
|
|
1312
|
+
binding: ModelHistorySeals.toolResultBinding(at(row, positions["session_id"]) ?? "", at(row, positions["operation_id"]) ?? "")
|
|
1313
|
+
};
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
};
|
|
1318
|
+
//#endregion
|
|
1319
|
+
//#region src/backup/backup-comparison.ts
|
|
1320
|
+
/** Compares what a database or a store holds with what the backup recorded, and names each difference. */
|
|
1321
|
+
var BackupComparison = class BackupComparison {
|
|
1322
|
+
/** The most differences one comparison names; the rest are counted. */
|
|
1323
|
+
static shownLimit = 20;
|
|
1324
|
+
/**
|
|
1325
|
+
* @param expected - The content the backup recorded.
|
|
1326
|
+
* @param actual - The content of the database.
|
|
1327
|
+
* @returns One line for each difference; none when the two are the same.
|
|
1328
|
+
*/
|
|
1329
|
+
static database(expected, actual) {
|
|
1330
|
+
const differences = [];
|
|
1331
|
+
if (expected.schemaDigest !== actual.schemaDigest) differences.push(`The schema differs from the schema of the backup (${actual.schemaLines} lines, the backup has ${expected.schemaLines}).`);
|
|
1332
|
+
const actualTables = new Map(actual.tables.map((table) => [DatabaseSession.displayName(table.schema, table.name), table]));
|
|
1333
|
+
for (const table of expected.tables) {
|
|
1334
|
+
const name = DatabaseSession.displayName(table.schema, table.name);
|
|
1335
|
+
const found = actualTables.get(name);
|
|
1336
|
+
actualTables.delete(name);
|
|
1337
|
+
if (found === void 0) differences.push(`The table ${name} is missing.`);
|
|
1338
|
+
else if (found.rows !== table.rows) differences.push(`The table ${name} has ${found.rows} rows; the backup has ${table.rows}.`);
|
|
1339
|
+
else if (found.digest !== table.digest) differences.push(`The rows of the table ${name} differ from the backup.`);
|
|
1340
|
+
}
|
|
1341
|
+
for (const name of actualTables.keys()) differences.push(`The table ${name} is not in the backup.`);
|
|
1342
|
+
differences.push(...BackupComparison.sequences(expected.sequences, actual.sequences));
|
|
1343
|
+
if (JSON.stringify(expected.migrations) !== JSON.stringify(actual.migrations)) differences.push(`The migrations journal differs: ${actual.migrations.length} rows, head ${BackupComparison.headOf(actual)}; the backup has ${expected.migrations.length}, head ${BackupComparison.headOf(expected)}.`);
|
|
1344
|
+
return BackupComparison.limited(differences);
|
|
1345
|
+
}
|
|
1346
|
+
/**
|
|
1347
|
+
* @param expected - The objects the backup recorded, by key.
|
|
1348
|
+
* @param actual - The objects of the store, by key.
|
|
1349
|
+
* @returns One line for each difference; none when the two are the same. An object that a move sealed again is
|
|
1350
|
+
* compared without its bytes and its key id; the check of the move compares its content.
|
|
1351
|
+
*/
|
|
1352
|
+
static files(expected, actual) {
|
|
1353
|
+
const differences = [];
|
|
1354
|
+
for (const [key, object] of expected) {
|
|
1355
|
+
const found = actual.get(key);
|
|
1356
|
+
if (found === void 0) differences.push(`The object ${key} is missing.`);
|
|
1357
|
+
else if (object.transfer === void 0 ? FileStoreContent.lineOf(found) !== FileStoreContent.lineOf(object) : FileStoreContent.lineOf(SealedTables.maskedObject(found)) !== FileStoreContent.lineOf(SealedTables.maskedObject(object))) differences.push(`The object ${key} differs from the backup.`);
|
|
1358
|
+
}
|
|
1359
|
+
for (const key of actual.keys()) if (!expected.has(key)) differences.push(`The object ${key} is not in the backup.`);
|
|
1360
|
+
return BackupComparison.limited(differences);
|
|
1361
|
+
}
|
|
1362
|
+
/** @returns The name of the last migration of a journal, or `none`. */
|
|
1363
|
+
static headOf(content) {
|
|
1364
|
+
return content.migrations.at(-1)?.name ?? "none";
|
|
1365
|
+
}
|
|
1366
|
+
static sequences(expected, actual) {
|
|
1367
|
+
const differences = [];
|
|
1368
|
+
const actualByName = new Map(actual.map((state) => [DatabaseSession.displayName(state.schema, state.name), state]));
|
|
1369
|
+
for (const state of expected) {
|
|
1370
|
+
const name = DatabaseSession.displayName(state.schema, state.name);
|
|
1371
|
+
const found = actualByName.get(name);
|
|
1372
|
+
actualByName.delete(name);
|
|
1373
|
+
if (found === void 0) differences.push(`The sequence ${name} is missing.`);
|
|
1374
|
+
else if (found.lastValue !== state.lastValue || found.isCalled !== state.isCalled) differences.push(`The sequence ${name} is at ${found.lastValue}; the backup has ${state.lastValue}.`);
|
|
1375
|
+
}
|
|
1376
|
+
for (const name of actualByName.keys()) differences.push(`The sequence ${name} is not in the backup.`);
|
|
1377
|
+
return differences;
|
|
1378
|
+
}
|
|
1379
|
+
static limited(differences) {
|
|
1380
|
+
if (differences.length <= BackupComparison.shownLimit) return differences;
|
|
1381
|
+
return [...differences.slice(0, BackupComparison.shownLimit), `And ${differences.length - BackupComparison.shownLimit} more differences.`];
|
|
1382
|
+
}
|
|
1383
|
+
};
|
|
1384
|
+
//#endregion
|
|
1385
|
+
//#region src/backup/sealed-value-tally.ts
|
|
1386
|
+
/** The values of each kind that a move sealed or a check opened, with the order-free sum of their keyed digests. */
|
|
1387
|
+
var SealedValueTally = class SealedValueTally {
|
|
1388
|
+
/** The most unreadable values that a report names; the rest are counted. */
|
|
1389
|
+
static shownLimit = 20;
|
|
1390
|
+
digests = new Map(Object.values(SealedValueKind).map((kind) => [kind, new ContentDigest()]));
|
|
1391
|
+
unreadableValues = [];
|
|
1392
|
+
unreadablePlaces = /* @__PURE__ */ new Set();
|
|
1393
|
+
/**
|
|
1394
|
+
* @param kind - The kind of the value.
|
|
1395
|
+
* @param digest - Its keyed digest ({@link import("@inferative/base/sealing").SecretTransfer.digestOf}).
|
|
1396
|
+
*/
|
|
1397
|
+
add(kind, digest) {
|
|
1398
|
+
this.digests.get(kind)?.add(digest);
|
|
1399
|
+
}
|
|
1400
|
+
/** Names a value that no key opens. */
|
|
1401
|
+
noteUnreadable(kind, id) {
|
|
1402
|
+
this.unreadableValues.push({
|
|
1403
|
+
kind,
|
|
1404
|
+
id
|
|
1405
|
+
});
|
|
1406
|
+
this.unreadablePlaces.add(SealedValueTally.placeOf(kind, id));
|
|
1407
|
+
}
|
|
1408
|
+
/** @returns Whether a value of the kind at the place was named as one that no key opens. */
|
|
1409
|
+
isUnreadable(kind, id) {
|
|
1410
|
+
return this.unreadablePlaces.has(SealedValueTally.placeOf(kind, id));
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* @param values - The values that the manifest names as unreadable.
|
|
1414
|
+
* @returns Whether a value of a kind at a place is one of them.
|
|
1415
|
+
*/
|
|
1416
|
+
static lookupOf(values) {
|
|
1417
|
+
const places = new Set(values.map((value) => SealedValueTally.placeOf(value.kind, value.id)));
|
|
1418
|
+
return (kind, id) => places.has(SealedValueTally.placeOf(kind, id));
|
|
1419
|
+
}
|
|
1420
|
+
static placeOf(kind, id) {
|
|
1421
|
+
return JSON.stringify([kind, id]);
|
|
1422
|
+
}
|
|
1423
|
+
/** @returns The values of each kind, the kinds with no value left out. */
|
|
1424
|
+
kinds() {
|
|
1425
|
+
return [...this.digests.entries()].filter(([, digest]) => digest.count > 0).map(([kind, digest]) => ({
|
|
1426
|
+
kind,
|
|
1427
|
+
values: digest.count,
|
|
1428
|
+
digest: digest.value()
|
|
1429
|
+
}));
|
|
1430
|
+
}
|
|
1431
|
+
/** @returns The values that no key opened. */
|
|
1432
|
+
unreadable() {
|
|
1433
|
+
return [...this.unreadableValues];
|
|
1434
|
+
}
|
|
1435
|
+
/**
|
|
1436
|
+
* @param expected - The kinds that the backup moved.
|
|
1437
|
+
* @returns One line for each kind whose count or content differs; none when they are the same.
|
|
1438
|
+
*/
|
|
1439
|
+
differencesFrom(expected) {
|
|
1440
|
+
const actual = new Map(this.kinds().map((kind) => [kind.kind, kind]));
|
|
1441
|
+
const differences = [];
|
|
1442
|
+
for (const kind of expected) {
|
|
1443
|
+
const found = actual.get(kind.kind);
|
|
1444
|
+
actual.delete(kind.kind);
|
|
1445
|
+
if (found === void 0 || found.values !== kind.values) differences.push(`${SealedValueTally.nameOf(kind.kind)}: ${String(found?.values ?? 0)} values open with the keys of this host; the backup moved ${String(kind.values)}.`);
|
|
1446
|
+
else if (found.digest !== kind.digest) differences.push(`${SealedValueTally.nameOf(kind.kind)}: the values differ from the values that the backup moved.`);
|
|
1447
|
+
}
|
|
1448
|
+
for (const kind of actual.values()) differences.push(`${SealedValueTally.nameOf(kind.kind)}: ${String(kind.values)} values that the backup did not move.`);
|
|
1449
|
+
return differences;
|
|
1450
|
+
}
|
|
1451
|
+
/** @returns The words of a kind for a report. */
|
|
1452
|
+
static nameOf(kind) {
|
|
1453
|
+
switch (kind) {
|
|
1454
|
+
case SealedValueKind.SecretStore: return "secret store values";
|
|
1455
|
+
case SealedValueKind.HistoryColumn: return "model history columns";
|
|
1456
|
+
case SealedValueKind.HistoryObject: return "model history objects";
|
|
1457
|
+
case SealedValueKind.SessionToken: return "session tokens";
|
|
1458
|
+
default: return kind;
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
/**
|
|
1462
|
+
* @param values - The values that no key opened.
|
|
1463
|
+
* @returns The lines that name them, at most {@link shownLimit}, and a count of the rest.
|
|
1464
|
+
*/
|
|
1465
|
+
static linesOf(values) {
|
|
1466
|
+
const lines = values.slice(0, SealedValueTally.shownLimit).map((value) => ` ${SealedValueTally.nameOf(value.kind)}: ${value.id}`);
|
|
1467
|
+
if (values.length > SealedValueTally.shownLimit) lines.push(` And ${String(values.length - SealedValueTally.shownLimit)} more.`);
|
|
1468
|
+
return lines;
|
|
1469
|
+
}
|
|
1470
|
+
};
|
|
1471
|
+
//#endregion
|
|
661
1472
|
//#region src/backup/backup-report.ts
|
|
662
1473
|
/** Prints the facts of a backup, a restore or a check: counts and names, never a value, an address or a key. */
|
|
663
1474
|
var BackupReport = class {
|
|
@@ -666,6 +1477,15 @@ var BackupReport = class {
|
|
|
666
1477
|
constructor(print) {
|
|
667
1478
|
this.print = print;
|
|
668
1479
|
}
|
|
1480
|
+
/**
|
|
1481
|
+
* @param organizationId - The organization of an organization backup.
|
|
1482
|
+
* @param leftOut - How many tables of the running deployment keep no row in it.
|
|
1483
|
+
* @param credentials - How many tables of the members' sign-in means keep no row in it.
|
|
1484
|
+
*/
|
|
1485
|
+
organization(organizationId, leftOut, credentials) {
|
|
1486
|
+
this.print(`Organization: ${organizationId}. The archive holds its rows, the rows that follow them and the shared tables; ${String(leftOut)} tables of the running deployment keep no row.`);
|
|
1487
|
+
this.print(`Members: the archive holds no password, no reset token and no row of the ${String(credentials)} tables of their sign-in means. Each member sets a new password on the target.`);
|
|
1488
|
+
}
|
|
669
1489
|
/** @param content - The content of a database. */
|
|
670
1490
|
database(content) {
|
|
671
1491
|
const rows = content.tables.reduce((sum, table) => sum + table.rows, 0);
|
|
@@ -712,6 +1532,26 @@ var BackupReport = class {
|
|
|
712
1532
|
return results.every((result) => result.status === SecretStoreCheck.readable);
|
|
713
1533
|
}
|
|
714
1534
|
/**
|
|
1535
|
+
* @param transfer - The move of the organization's sealed values, or `undefined` when the archive keeps them.
|
|
1536
|
+
* @param fingerprint - The fingerprint of the target's transfer key.
|
|
1537
|
+
*/
|
|
1538
|
+
transfer(transfer, fingerprint) {
|
|
1539
|
+
if (transfer === void 0) {
|
|
1540
|
+
this.print("Sealed values: the archive keeps them under the keys of this host. A target with another root secret reads them only from a backup with --transfer-key.");
|
|
1541
|
+
return;
|
|
1542
|
+
}
|
|
1543
|
+
const moved = transfer.kinds.reduce((sum, kind) => sum + kind.values, 0);
|
|
1544
|
+
const kinds = transfer.kinds.map((kind) => `${String(kind.values)} ${SealedValueTally.nameOf(kind.kind)}`).join(", ");
|
|
1545
|
+
this.print(moved === 0 ? `Sealed values: none to move to the transfer key ${fingerprint ?? ""}.` : `Sealed values: moved ${String(moved)} to the transfer key ${fingerprint ?? ""} (${kinds}). Only the root secret of the target opens them.`);
|
|
1546
|
+
this.unreadable(transfer.unreadable);
|
|
1547
|
+
}
|
|
1548
|
+
/** @param values - The sealed values that no key of the source opened. */
|
|
1549
|
+
unreadable(values) {
|
|
1550
|
+
if (values.length === 0) return;
|
|
1551
|
+
this.print(`Sealed values: ${String(values.length)} that no key of the source opens stay as the source holds them, so the target cannot read them either:`);
|
|
1552
|
+
SealedValueTally.linesOf(values).forEach((line) => this.print(line));
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
715
1555
|
* @param subject - What was compared, such as `Database`.
|
|
716
1556
|
* @param differences - The differences.
|
|
717
1557
|
* @returns Whether there was none.
|
|
@@ -778,18 +1618,32 @@ var BackupRows = class {
|
|
|
778
1618
|
/**
|
|
779
1619
|
* @param session - A session with an open snapshot.
|
|
780
1620
|
* @param table - A table of the database.
|
|
781
|
-
* @
|
|
1621
|
+
* @param scope - The organization whose rows to read; every organization when absent.
|
|
1622
|
+
* @returns Every row, or every row of the organization with its blanked columns replaced
|
|
1623
|
+
* ({@link OrganizationScope.blankedOf}), but none of the fence table ({@link BackupFence}) and no restore flag
|
|
1624
|
+
* ({@link RestoreHold}).
|
|
782
1625
|
*/
|
|
783
|
-
static async *of(session, table) {
|
|
784
|
-
if (BackupFence.isFenceTable(session, table)) return;
|
|
785
|
-
|
|
1626
|
+
static async *of(session, table, scope) {
|
|
1627
|
+
if (BackupFence.isFenceTable(session, table) || scope?.isLeftOut(table) === true) return;
|
|
1628
|
+
const blanked = scope?.blankedOf(table) ?? [];
|
|
1629
|
+
for await (const row of session.rows(table, scope?.filterOf(table))) {
|
|
1630
|
+
if (RestoreHold.isHoldRow(session, table, row)) continue;
|
|
1631
|
+
if (blanked.length === 0) yield row;
|
|
1632
|
+
else {
|
|
1633
|
+
const copy = [...row];
|
|
1634
|
+
for (const { index, value } of blanked) copy[index] = value;
|
|
1635
|
+
yield copy;
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
786
1638
|
}
|
|
787
1639
|
};
|
|
788
1640
|
//#endregion
|
|
789
1641
|
//#region src/backup/database-content.ts
|
|
790
1642
|
/**
|
|
791
1643
|
* Reads the content of a database in one snapshot: its schema, the digest of each table, the sequences. The rows of
|
|
792
|
-
* the fence table and the restore flags count as none, as a backup holds none ({@link BackupRows}).
|
|
1644
|
+
* the fence table and the restore flags count as none, as a backup holds none ({@link BackupRows}). With an
|
|
1645
|
+
* organization, each table counts the rows that its backup holds ({@link OrganizationScope}). For an archive whose
|
|
1646
|
+
* sealed values moved, the digests mask the values that the move sealed again ({@link SealedTables.maskerOf}).
|
|
793
1647
|
*/
|
|
794
1648
|
var DatabaseContentReader = class DatabaseContentReader {
|
|
795
1649
|
/** @returns The line that the digest of a table adds for one row, and that the backup writes. */
|
|
@@ -798,29 +1652,34 @@ var DatabaseContentReader = class DatabaseContentReader {
|
|
|
798
1652
|
}
|
|
799
1653
|
/**
|
|
800
1654
|
* @param session - An open session with no transaction.
|
|
1655
|
+
* @param organizationId - The organization of an organization backup, or `undefined` for the whole database.
|
|
1656
|
+
* @param transfer - The move of the archive's sealed values, or `undefined` when they did not move.
|
|
801
1657
|
* @returns The content. The snapshot transaction of the session is ended.
|
|
802
1658
|
*/
|
|
803
|
-
static async read(session) {
|
|
1659
|
+
static async read(session, organizationId, transfer) {
|
|
804
1660
|
await session.beginSnapshot();
|
|
805
1661
|
try {
|
|
806
1662
|
const schema = await session.schemaLines();
|
|
807
1663
|
const tables = [];
|
|
808
|
-
|
|
1664
|
+
const listed = await session.tables();
|
|
1665
|
+
const scope = organizationId === void 0 ? void 0 : new OrganizationScope(session, listed, organizationId);
|
|
1666
|
+
await scope?.requireOrganization(session);
|
|
1667
|
+
for (const table of listed) tables.push(await DatabaseContentReader.tableContent(session, table, scope, transfer === void 0 ? void 0 : SealedTables.maskerOf(table, session.defaultSchema, SealedValueTally.lookupOf(transfer.unreadable))));
|
|
809
1668
|
return {
|
|
810
1669
|
schemaDigest: ContentDigest.ofLines(schema),
|
|
811
1670
|
schemaLines: schema.length,
|
|
812
1671
|
tables,
|
|
813
1672
|
sequences: await session.sequences(),
|
|
814
1673
|
migrations: await session.migrations(),
|
|
815
|
-
secrets: await SecretStoreCheck.content(session)
|
|
1674
|
+
secrets: await SecretStoreCheck.content(session, scope)
|
|
816
1675
|
};
|
|
817
1676
|
} finally {
|
|
818
1677
|
await session.abortSnapshot();
|
|
819
1678
|
}
|
|
820
1679
|
}
|
|
821
|
-
static async tableContent(session, table) {
|
|
1680
|
+
static async tableContent(session, table, scope, mask) {
|
|
822
1681
|
const digest = new ContentDigest();
|
|
823
|
-
for await (const row of BackupRows.of(session, table)) digest.add(DatabaseContentReader.lineOf(row));
|
|
1682
|
+
for await (const row of BackupRows.of(session, table, scope)) digest.add(DatabaseContentReader.lineOf(mask === void 0 ? row : mask(row)));
|
|
824
1683
|
return {
|
|
825
1684
|
schema: table.schema,
|
|
826
1685
|
name: table.name,
|
|
@@ -956,6 +1815,169 @@ var RequiredObjects = class RequiredObjects {
|
|
|
956
1815
|
}
|
|
957
1816
|
};
|
|
958
1817
|
//#endregion
|
|
1818
|
+
//#region src/backup/sealed-value-export.ts
|
|
1819
|
+
/**
|
|
1820
|
+
* The side of the source of a move: it opens each sealed value of the organization with the keys of this host and
|
|
1821
|
+
* seals it to the target's transfer key ({@link SecretTransfer}), in the rows and objects that the backup writes. A
|
|
1822
|
+
* value that no key of this host opens stays as the source holds it, and is named. It sends no statement of its own;
|
|
1823
|
+
* the keys of this host never leave it, and no value reaches a line of output.
|
|
1824
|
+
*/
|
|
1825
|
+
var SealedValueExport = class SealedValueExport {
|
|
1826
|
+
transfer;
|
|
1827
|
+
ring;
|
|
1828
|
+
history;
|
|
1829
|
+
objects;
|
|
1830
|
+
tally = new SealedValueTally();
|
|
1831
|
+
constructor(transfer, ring, history, objects) {
|
|
1832
|
+
this.transfer = transfer;
|
|
1833
|
+
this.ring = ring;
|
|
1834
|
+
this.history = history;
|
|
1835
|
+
this.objects = objects;
|
|
1836
|
+
}
|
|
1837
|
+
/**
|
|
1838
|
+
* @param recipient - The text of the target's transfer key.
|
|
1839
|
+
* @param hostKeys - The keys of this host.
|
|
1840
|
+
* @param objects - The objects of the organization's history, with their bindings.
|
|
1841
|
+
* @returns The move.
|
|
1842
|
+
* @throws When the transfer key does not parse, or a key of the host does not decode. No message holds a key.
|
|
1843
|
+
*/
|
|
1844
|
+
static async open(recipient, hostKeys, objects) {
|
|
1845
|
+
return new SealedValueExport(await SecretTransfer.toRecipient(recipient), await SealedTables.ringOf(hostKeys), await SealedTables.historyCipherOf(hostKeys), objects);
|
|
1846
|
+
}
|
|
1847
|
+
/** @returns Whether this backup named the value of a kind at a place as one that no key of this host opens. */
|
|
1848
|
+
isUnreadable(kind, id) {
|
|
1849
|
+
return this.tally.isUnreadable(kind, id);
|
|
1850
|
+
}
|
|
1851
|
+
/** @returns The fingerprint of the target's transfer key. */
|
|
1852
|
+
fingerprint() {
|
|
1853
|
+
return this.transfer.fingerprint;
|
|
1854
|
+
}
|
|
1855
|
+
/**
|
|
1856
|
+
* @param table - A table of the snapshot.
|
|
1857
|
+
* @param schema - The schema of the libraries' tables.
|
|
1858
|
+
* @returns What gives the row that the archive holds, or `undefined` for a table with no sealed value.
|
|
1859
|
+
* @throws When the table lacks a column that the move reads.
|
|
1860
|
+
*/
|
|
1861
|
+
rewriterOf(table, schema) {
|
|
1862
|
+
if (table.schema !== schema) return;
|
|
1863
|
+
if (table.name === SealedTables.secretTable) {
|
|
1864
|
+
const positions = SealedTables.positionsOf(table, [
|
|
1865
|
+
"reference",
|
|
1866
|
+
"key_id",
|
|
1867
|
+
"envelope"
|
|
1868
|
+
]);
|
|
1869
|
+
return (row) => this.secretRow(row, positions);
|
|
1870
|
+
}
|
|
1871
|
+
if (table.name === SealedTables.historyTable) {
|
|
1872
|
+
const positions = SealedTables.positionsOf(table, [
|
|
1873
|
+
"session_id",
|
|
1874
|
+
"position",
|
|
1875
|
+
"payload",
|
|
1876
|
+
"outcome",
|
|
1877
|
+
"offload_reference",
|
|
1878
|
+
"key_id"
|
|
1879
|
+
]);
|
|
1880
|
+
return (row) => this.historyRow(row, positions);
|
|
1881
|
+
}
|
|
1882
|
+
if (table.name === SealedTables.tokenTable) {
|
|
1883
|
+
const positions = SealedTables.positionsOf(table, ["token_id"]);
|
|
1884
|
+
return async (row) => {
|
|
1885
|
+
this.tally.add(SealedValueKind.SessionToken, await this.transfer.digestOf(SealedValueKind.SessionToken, SealedTables.valueAt(row, positions["token_id"]) ?? "", ""));
|
|
1886
|
+
return row;
|
|
1887
|
+
};
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
/**
|
|
1891
|
+
* @param key - The key of an object of the archive.
|
|
1892
|
+
* @param bytes - Its bytes.
|
|
1893
|
+
* @param custom - Its custom metadata.
|
|
1894
|
+
* @returns The object sealed for the target, or `undefined` when the history key did not seal it, or no key of this
|
|
1895
|
+
* host opens it (it is then named).
|
|
1896
|
+
*/
|
|
1897
|
+
async objectOf(key, bytes, custom) {
|
|
1898
|
+
const binding = this.objects.bindingOf(key);
|
|
1899
|
+
if (binding === void 0) return;
|
|
1900
|
+
const plain = await this.openHistory(new TextDecoder().decode(bytes), binding, custom[ModelHistorySeals.keyIdField]);
|
|
1901
|
+
if (plain === void 0) {
|
|
1902
|
+
this.tally.noteUnreadable(SealedValueKind.HistoryObject, key);
|
|
1903
|
+
return;
|
|
1904
|
+
}
|
|
1905
|
+
await this.count(SealedValueKind.HistoryObject, binding, plain);
|
|
1906
|
+
return {
|
|
1907
|
+
bytes: new TextEncoder().encode(await this.transfer.seal(SealedValueKind.HistoryObject, binding, plain)),
|
|
1908
|
+
custom: {
|
|
1909
|
+
...custom,
|
|
1910
|
+
[ModelHistorySeals.keyIdField]: SealedTables.marker
|
|
1911
|
+
},
|
|
1912
|
+
binding
|
|
1913
|
+
};
|
|
1914
|
+
}
|
|
1915
|
+
/** @returns The section of the manifest that the target reads. */
|
|
1916
|
+
section() {
|
|
1917
|
+
return {
|
|
1918
|
+
recipient: this.transfer.recipient,
|
|
1919
|
+
movePublicKey: this.transfer.movePublicKey,
|
|
1920
|
+
kinds: this.tally.kinds(),
|
|
1921
|
+
unreadable: this.tally.unreadable()
|
|
1922
|
+
};
|
|
1923
|
+
}
|
|
1924
|
+
async secretRow(row, positions) {
|
|
1925
|
+
const reference = SealedTables.valueAt(row, positions["reference"]) ?? "";
|
|
1926
|
+
const envelope = SealedTables.valueAt(row, positions["envelope"]) ?? "";
|
|
1927
|
+
const lookup = this.ring === void 0 ? void 0 : await SecretEnvelope.open(this.ring, reference, envelope);
|
|
1928
|
+
if (lookup?.status !== SecretLookupStatus.Found) {
|
|
1929
|
+
this.tally.noteUnreadable(SealedValueKind.SecretStore, reference);
|
|
1930
|
+
return row;
|
|
1931
|
+
}
|
|
1932
|
+
await this.count(SealedValueKind.SecretStore, reference, lookup.value);
|
|
1933
|
+
return SealedValueExport.replaced(row, {
|
|
1934
|
+
[positions["key_id"] ?? -1]: SealedTables.marker,
|
|
1935
|
+
[positions["envelope"] ?? -1]: await this.transfer.seal(SealedValueKind.SecretStore, reference, lookup.value)
|
|
1936
|
+
});
|
|
1937
|
+
}
|
|
1938
|
+
/** An inline row moves its sealed columns; a large row keeps its row, and its object moves. */
|
|
1939
|
+
async historyRow(row, positions) {
|
|
1940
|
+
if (SealedTables.valueAt(row, positions["offload_reference"]) !== null) return row;
|
|
1941
|
+
const sessionId = SealedTables.valueAt(row, positions["session_id"]) ?? "";
|
|
1942
|
+
const position = Number(SealedTables.valueAt(row, positions["position"]));
|
|
1943
|
+
const keyId = SealedTables.valueAt(row, positions["key_id"]) ?? void 0;
|
|
1944
|
+
const changes = { [positions["key_id"] ?? -1]: SealedTables.marker };
|
|
1945
|
+
const moved = [];
|
|
1946
|
+
for (const column of ["payload", "outcome"]) {
|
|
1947
|
+
const sealed = SealedTables.valueAt(row, positions[column]);
|
|
1948
|
+
if (sealed === null) continue;
|
|
1949
|
+
const binding = ModelHistorySeals.rowColumnBinding(sessionId, position, column);
|
|
1950
|
+
const plain = await this.openHistory(sealed, binding, keyId);
|
|
1951
|
+
if (plain === void 0) {
|
|
1952
|
+
this.tally.noteUnreadable(SealedValueKind.HistoryColumn, SealedTables.historyPlaceOf(sessionId, position));
|
|
1953
|
+
return row;
|
|
1954
|
+
}
|
|
1955
|
+
moved.push({
|
|
1956
|
+
binding,
|
|
1957
|
+
plain
|
|
1958
|
+
});
|
|
1959
|
+
changes[positions[column] ?? -1] = await this.transfer.seal(SealedValueKind.HistoryColumn, binding, plain);
|
|
1960
|
+
}
|
|
1961
|
+
for (const { binding, plain } of moved) await this.count(SealedValueKind.HistoryColumn, binding, plain);
|
|
1962
|
+
return SealedValueExport.replaced(row, changes);
|
|
1963
|
+
}
|
|
1964
|
+
/** @returns The plain text of a value that the history key sealed, or `undefined` when no key opens it. */
|
|
1965
|
+
async openHistory(sealed, binding, keyId) {
|
|
1966
|
+
if (this.history === void 0) return;
|
|
1967
|
+
try {
|
|
1968
|
+
return await this.history.decrypt(sealed, binding, keyId);
|
|
1969
|
+
} catch {
|
|
1970
|
+
return;
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
async count(kind, binding, plain) {
|
|
1974
|
+
this.tally.add(kind, await this.transfer.digestOf(kind, binding, plain));
|
|
1975
|
+
}
|
|
1976
|
+
static replaced(row, changes) {
|
|
1977
|
+
return row.map((value, position) => changes[position] ?? value);
|
|
1978
|
+
}
|
|
1979
|
+
};
|
|
1980
|
+
//#endregion
|
|
959
1981
|
//#region src/backup/guarded-writable.ts
|
|
960
1982
|
/**
|
|
961
1983
|
* Writes to a stream and watches it from the start: a failure of the stream (or of the pipeline it feeds) rejects
|
|
@@ -1332,6 +2354,10 @@ var TarReader = class TarReader {
|
|
|
1332
2354
|
* of the snapshot, and each of them that the copy lacks is missing: every object that a committed row needs is in the
|
|
1333
2355
|
* archive or named as missing. With age public keys, the archive bytes are encrypted before they reach the file, the
|
|
1334
2356
|
* `.partial` file included; only the staging folder holds one plain table or object at a time, readable by its owner.
|
|
2357
|
+
* With an organization, the archive holds the rows that belong to it and the objects that they name or whose key
|
|
2358
|
+
* names it, and every other table with no row, so that its restore has the same tables. With a transfer key, each
|
|
2359
|
+
* sealed value of the organization is opened with the keys of this host and sealed for the target, and a value that
|
|
2360
|
+
* no key opens stays as it is and is named.
|
|
1335
2361
|
*/
|
|
1336
2362
|
var BackupCreate = class BackupCreate {
|
|
1337
2363
|
/** Why a required object of the listing has no bytes in the archive. */
|
|
@@ -1342,21 +2368,37 @@ var BackupCreate = class BackupCreate {
|
|
|
1342
2368
|
*/
|
|
1343
2369
|
static async run(options) {
|
|
1344
2370
|
if (existsSync(options.archive)) throw new Error(`The archive ${options.archive} exists already.`);
|
|
2371
|
+
if (options.organization !== void 0) OrganizationScope.requireId(options.organization);
|
|
2372
|
+
if (options.transferKey !== void 0 && options.organization === void 0) throw new Error("A transfer key moves the sealed values of one organization: name the organization.");
|
|
2373
|
+
const scopeWork = options.organization === void 0 ? void 0 : await BackupCreate.scopeWorkOf(options);
|
|
1345
2374
|
if ((options.recipients ?? []).length > 0) ArchiveEncryption.encrypter(options.recipients ?? []);
|
|
1346
2375
|
if (options.files !== void 0) FileStoreLocations.checkReadable(options.files);
|
|
1347
2376
|
const files = options.files === void 0 ? void 0 : await FileStoreLocations.open(options.files);
|
|
1348
2377
|
try {
|
|
1349
|
-
return await BackupCreate.runWith(options, files?.store);
|
|
2378
|
+
return await BackupCreate.runWith(options, files?.store, scopeWork);
|
|
1350
2379
|
} finally {
|
|
1351
2380
|
await files?.close();
|
|
1352
2381
|
}
|
|
1353
2382
|
}
|
|
1354
|
-
|
|
2383
|
+
/** @returns The objects of the organization's history, and the move of its sealed values when a key names one. */
|
|
2384
|
+
static async scopeWorkOf(options) {
|
|
2385
|
+
const history = new HistoryObjects(options.transferKey !== void 0);
|
|
2386
|
+
if (options.transferKey === void 0) return {
|
|
2387
|
+
history,
|
|
2388
|
+
exporter: void 0
|
|
2389
|
+
};
|
|
2390
|
+
await SecretTransferKey.parse(options.transferKey);
|
|
2391
|
+
return {
|
|
2392
|
+
history,
|
|
2393
|
+
exporter: await SealedValueExport.open(options.transferKey, options.secretKeys, history)
|
|
2394
|
+
};
|
|
2395
|
+
}
|
|
2396
|
+
static async runWith(options, store, scopeWork) {
|
|
1355
2397
|
const session = await DatabaseSessions.open(options.databaseAddress);
|
|
1356
2398
|
let fence;
|
|
1357
2399
|
try {
|
|
1358
2400
|
fence = store === void 0 ? void 0 : await BackupCreate.holdFence(options);
|
|
1359
|
-
return await BackupCreate.writeArchive(options, session, store, fence);
|
|
2401
|
+
return await BackupCreate.writeArchive(options, session, store, fence, scopeWork);
|
|
1360
2402
|
} finally {
|
|
1361
2403
|
try {
|
|
1362
2404
|
await session.close();
|
|
@@ -1366,7 +2408,7 @@ var BackupCreate = class BackupCreate {
|
|
|
1366
2408
|
}
|
|
1367
2409
|
}
|
|
1368
2410
|
/** Writes the archive into its own `.partial` file and a staging folder, and publishes it at the end. */
|
|
1369
|
-
static async writeArchive(options, session, store, fence) {
|
|
2411
|
+
static async writeArchive(options, session, store, fence, scopeWork) {
|
|
1370
2412
|
const partial = `${options.archive}.${randomUUID()}.partial`;
|
|
1371
2413
|
let staging;
|
|
1372
2414
|
const removeWork = () => {
|
|
@@ -1387,7 +2429,7 @@ var BackupCreate = class BackupCreate {
|
|
|
1387
2429
|
try {
|
|
1388
2430
|
staging = mkdtempSync(join(tmpdir(), "inferative-backup-"));
|
|
1389
2431
|
writer = TarWriter.create(partial, options.recipients);
|
|
1390
|
-
const manifest = await BackupCreate.write(options, session, writer, staging, store);
|
|
2432
|
+
const manifest = await BackupCreate.write(options, session, writer, staging, store, scopeWork);
|
|
1391
2433
|
await fence?.requireLive();
|
|
1392
2434
|
await writer.close();
|
|
1393
2435
|
BackupCreate.publish(partial, options.archive);
|
|
@@ -1404,6 +2446,21 @@ var BackupCreate = class BackupCreate {
|
|
|
1404
2446
|
});
|
|
1405
2447
|
}
|
|
1406
2448
|
}
|
|
2449
|
+
/**
|
|
2450
|
+
* Reads an object that the history key sealed, whole, and seals it for the target.
|
|
2451
|
+
*
|
|
2452
|
+
* @returns The bytes to archive and the moved object; the bytes as they are when no key of this host opens it.
|
|
2453
|
+
*/
|
|
2454
|
+
static async moveObject(exporter, key, stream, custom) {
|
|
2455
|
+
const pieces = [];
|
|
2456
|
+
for await (const chunk of stream) pieces.push(chunk);
|
|
2457
|
+
const bytes = Buffer.concat(pieces);
|
|
2458
|
+
const object = await exporter.objectOf(key, bytes, custom ?? {});
|
|
2459
|
+
return {
|
|
2460
|
+
chunks: [object?.bytes ?? bytes],
|
|
2461
|
+
object
|
|
2462
|
+
};
|
|
2463
|
+
}
|
|
1407
2464
|
/** Deletes the fence row of the run, and says whether the store deletes again. */
|
|
1408
2465
|
static async releaseFence(options, fence) {
|
|
1409
2466
|
options.print(await fence.release() ? "Deletion fence: released; the file store deletes again." : `Deletion fence: the row could not be deleted, so the file store refuses deletes until ${fence.leaseEndsAt}.`);
|
|
@@ -1424,11 +2481,14 @@ var BackupCreate = class BackupCreate {
|
|
|
1424
2481
|
}
|
|
1425
2482
|
rmSync(partial, { force: true });
|
|
1426
2483
|
}
|
|
1427
|
-
static async write(options, session, writer, staging, store) {
|
|
2484
|
+
static async write(options, session, writer, staging, store, scopeWork) {
|
|
1428
2485
|
const entries = [];
|
|
1429
2486
|
const serverVersion = await session.serverVersion();
|
|
1430
2487
|
const required = new RequiredObjects(session.defaultSchema);
|
|
1431
2488
|
await session.beginSnapshot();
|
|
2489
|
+
const listed = await session.tables();
|
|
2490
|
+
const scope = options.organization === void 0 ? void 0 : new OrganizationScope(session, listed, options.organization);
|
|
2491
|
+
await scope?.requireOrganization(session);
|
|
1432
2492
|
const schemaLines = await session.schemaLines();
|
|
1433
2493
|
const schemaBytes = Buffer.from(JSON.stringify(schemaLines), "utf8");
|
|
1434
2494
|
await writer.addBytes(BackupManifest.schemaEntry, schemaBytes);
|
|
@@ -1438,22 +2498,25 @@ var BackupCreate = class BackupCreate {
|
|
|
1438
2498
|
sha256: ContentDigest.sha256(schemaBytes)
|
|
1439
2499
|
});
|
|
1440
2500
|
const tables = [];
|
|
1441
|
-
for (const [position, table] of
|
|
2501
|
+
for (const [position, table] of listed.entries()) {
|
|
1442
2502
|
const entry = BackupManifest.tableEntry(position + 1);
|
|
1443
|
-
const backupTable = await BackupCreate.writeTable(session, writer, staging, table, entry, store === void 0 ? void 0 : required.collectorOf(table));
|
|
2503
|
+
const backupTable = await BackupCreate.writeTable(session, writer, staging, table, entry, store === void 0 ? void 0 : required.collectorOf(table), scope, scopeWork);
|
|
1444
2504
|
tables.push(backupTable.table);
|
|
1445
2505
|
entries.push(backupTable.entry);
|
|
1446
2506
|
}
|
|
1447
2507
|
const sequences = await session.sequences();
|
|
1448
2508
|
const migrations = await session.migrations();
|
|
1449
|
-
const secrets = await SecretStoreCheck.content(session);
|
|
2509
|
+
const secrets = await SecretStoreCheck.content(session, scope);
|
|
1450
2510
|
await session.endSnapshot();
|
|
1451
|
-
const files = store === void 0 ? null : await BackupCreate.writeObjects(store, writer, staging, entries, required);
|
|
2511
|
+
const files = store === void 0 ? null : await BackupCreate.writeObjects(store, writer, staging, entries, required, scope, scopeWork);
|
|
2512
|
+
const exporter = scopeWork?.exporter;
|
|
1452
2513
|
const manifest = {
|
|
1453
2514
|
format: BackupManifest.format,
|
|
1454
|
-
formatVersion: BackupManifest.formatVersion,
|
|
2515
|
+
formatVersion: exporter === void 0 ? BackupManifest.formatVersion : BackupManifest.transferFormatVersion,
|
|
1455
2516
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1456
2517
|
host: options.host,
|
|
2518
|
+
...scope === void 0 ? {} : { organization: scope.organizationId },
|
|
2519
|
+
...exporter === void 0 ? {} : { transfer: exporter.section() },
|
|
1457
2520
|
versions: {
|
|
1458
2521
|
...options.versions,
|
|
1459
2522
|
[session.versionName]: serverVersion
|
|
@@ -1474,22 +2537,29 @@ var BackupCreate = class BackupCreate {
|
|
|
1474
2537
|
};
|
|
1475
2538
|
await writer.addBytes(BackupManifest.entry, Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`, "utf8"));
|
|
1476
2539
|
const report = new BackupReport(options.print);
|
|
2540
|
+
if (scope !== void 0) report.organization(scope.organizationId, scope.countOf(ScopeRuleKind.LeftOut), scope.countOf(ScopeRuleKind.Credential));
|
|
1477
2541
|
report.database(BackupManifest.databaseContent(manifest));
|
|
1478
2542
|
report.files(files);
|
|
1479
2543
|
report.missingObjects(files?.missing ?? []);
|
|
1480
2544
|
report.secrets(secrets);
|
|
1481
|
-
if (
|
|
2545
|
+
if (scope !== void 0) report.transfer(manifest.transfer, exporter?.fingerprint());
|
|
2546
|
+
if (options.secretKeys !== void 0 && secrets !== null && exporter === void 0) report.readability(await SecretStoreCheck.readability(session, options.secretKeys, scope));
|
|
1482
2547
|
return manifest;
|
|
1483
2548
|
}
|
|
1484
|
-
static async writeTable(session, writer, staging, table, entry, collect) {
|
|
2549
|
+
static async writeTable(session, writer, staging, table, entry, collect, scope, scopeWork) {
|
|
1485
2550
|
const path = join(staging, "table.ndjson");
|
|
1486
2551
|
const digest = new ContentDigest();
|
|
2552
|
+
const collectHistory = scopeWork?.history.collectorOf(table, session.defaultSchema);
|
|
2553
|
+
const rewrite = scopeWork?.exporter?.rewriterOf(table, session.defaultSchema);
|
|
2554
|
+
const exporter = scopeWork?.exporter;
|
|
2555
|
+
const mask = exporter === void 0 ? void 0 : SealedTables.maskerOf(table, session.defaultSchema, (kind, id) => exporter.isUnreadable(kind, id));
|
|
1487
2556
|
const staged = await StagedFile.write(path, (async function* lines() {
|
|
1488
|
-
for await (const row of BackupRows.of(session, table)) {
|
|
1489
|
-
const line = DatabaseContentReader.lineOf(row);
|
|
2557
|
+
for await (const row of BackupRows.of(session, table, scope)) {
|
|
1490
2558
|
collect?.(row);
|
|
1491
|
-
|
|
1492
|
-
|
|
2559
|
+
collectHistory?.(row);
|
|
2560
|
+
const archived = rewrite === void 0 ? row : await rewrite(row);
|
|
2561
|
+
digest.add(DatabaseContentReader.lineOf(mask === void 0 ? archived : mask(archived)));
|
|
2562
|
+
yield `${DatabaseContentReader.lineOf(archived)}\n`;
|
|
1493
2563
|
}
|
|
1494
2564
|
})());
|
|
1495
2565
|
await writer.addFile(entry, path, staged.size);
|
|
@@ -1513,9 +2583,12 @@ var BackupCreate = class BackupCreate {
|
|
|
1513
2583
|
/**
|
|
1514
2584
|
* Stages each object in a file, one at a time, because a tar header holds the size before the bytes. A required
|
|
1515
2585
|
* object that the copy lacks is missing. An object that no committed row needs and that is gone is left out: a
|
|
1516
|
-
* restored install reads it as an unfinished upload or a cleanup that already ran.
|
|
2586
|
+
* restored install reads it as an unfinished upload or a cleanup that already ran. With an organization, an object
|
|
2587
|
+
* is copied when a kept row needs it, when its key names the organization, or when it is a large tool result of a
|
|
2588
|
+
* kept session or a page of a kept conversation ({@link HistoryObjects}). With a move, each object that the history
|
|
2589
|
+
* key sealed is read whole, opened and sealed for the target.
|
|
1517
2590
|
*/
|
|
1518
|
-
static async writeObjects(store, writer, staging, entries, required) {
|
|
2591
|
+
static async writeObjects(store, writer, staging, entries, required, scope, scopeWork) {
|
|
1519
2592
|
const digest = new ContentDigest();
|
|
1520
2593
|
const lines = [];
|
|
1521
2594
|
const missing = [];
|
|
@@ -1523,6 +2596,7 @@ var BackupCreate = class BackupCreate {
|
|
|
1523
2596
|
const path = join(staging, "object.bin");
|
|
1524
2597
|
let bytes = 0;
|
|
1525
2598
|
for (const key of await store.list()) {
|
|
2599
|
+
if (scope !== void 0 && !required.isRequired(key) && !scope.hasObjectKey(key) && scopeWork?.history.isKept(key) !== true) continue;
|
|
1526
2600
|
const metadata = await store.stat(key);
|
|
1527
2601
|
const stream = await store.getStream(key);
|
|
1528
2602
|
if (metadata === null || stream === null) {
|
|
@@ -1533,7 +2607,8 @@ var BackupCreate = class BackupCreate {
|
|
|
1533
2607
|
continue;
|
|
1534
2608
|
}
|
|
1535
2609
|
const entry = BackupManifest.objectEntry(digest.count + 1);
|
|
1536
|
-
const
|
|
2610
|
+
const moved = scopeWork?.exporter === void 0 || scopeWork.history.bindingOf(key) === void 0 ? void 0 : await BackupCreate.moveObject(scopeWork.exporter, key, stream, metadata.custom);
|
|
2611
|
+
const staged = await StagedFile.write(path, moved?.chunks ?? stream);
|
|
1537
2612
|
await writer.addFile(entry, path, staged.size);
|
|
1538
2613
|
rmSync(path, { force: true });
|
|
1539
2614
|
const object = {
|
|
@@ -1542,7 +2617,8 @@ var BackupCreate = class BackupCreate {
|
|
|
1542
2617
|
size: staged.size,
|
|
1543
2618
|
sha256: staged.sha256,
|
|
1544
2619
|
contentType: metadata.contentType ?? null,
|
|
1545
|
-
custom: FileStoreContent.customOf(metadata.custom)
|
|
2620
|
+
custom: FileStoreContent.customOf(moved?.object?.custom ?? metadata.custom),
|
|
2621
|
+
...moved?.object === void 0 ? {} : { transfer: { binding: moved.object.binding } }
|
|
1546
2622
|
};
|
|
1547
2623
|
digest.add(FileStoreContent.lineOf(object));
|
|
1548
2624
|
lines.push(JSON.stringify(object));
|
|
@@ -1631,11 +2707,285 @@ var ArchiveScan = class ArchiveScan {
|
|
|
1631
2707
|
}
|
|
1632
2708
|
};
|
|
1633
2709
|
//#endregion
|
|
2710
|
+
//#region src/backup/sealed-value-import.ts
|
|
2711
|
+
/**
|
|
2712
|
+
* The side of the target of a move: it opens each moved value with the transfer key of this host's root and seals it
|
|
2713
|
+
* again under the current keys of this host, in the rows and objects that the restore writes. The verifier of each
|
|
2714
|
+
* session token is derived again under this host's history key. It sends no statement of its own.
|
|
2715
|
+
*/
|
|
2716
|
+
var SealedValueImport = class SealedValueImport {
|
|
2717
|
+
keys;
|
|
2718
|
+
schema;
|
|
2719
|
+
constructor(keys, schema) {
|
|
2720
|
+
this.keys = keys;
|
|
2721
|
+
this.schema = schema;
|
|
2722
|
+
}
|
|
2723
|
+
/**
|
|
2724
|
+
* @param transfer - The move that the manifest records.
|
|
2725
|
+
* @param hostKeys - The keys of this host.
|
|
2726
|
+
* @returns The keys of this host for the move.
|
|
2727
|
+
* @throws When this host sets no root, or no root of this host gives the transfer key of the move. The message names
|
|
2728
|
+
* the fingerprints only.
|
|
2729
|
+
*/
|
|
2730
|
+
static async keysOf(transfer, hostKeys) {
|
|
2731
|
+
const root = await SecretStoreCheck.rootOf(hostKeys);
|
|
2732
|
+
const fingerprint = await SecretTransferKey.fingerprintOf(await SecretTransferKey.parse(transfer.recipient));
|
|
2733
|
+
if (!root.isSet()) throw new Error(`The sealed values of the archive moved to the transfer key ${fingerprint}. Set ${RootSecret.variable} to the root secret of the deployment that printed it. No row was written.`);
|
|
2734
|
+
const opened = await SecretTransfer.forRoot(root, transfer.recipient, transfer.movePublicKey);
|
|
2735
|
+
if (opened === void 0) {
|
|
2736
|
+
const own = await SecretTransferKey.of(root);
|
|
2737
|
+
const ownFingerprint = own === void 0 ? "none" : await SecretTransferKey.fingerprintOf(await SecretTransferKey.parse(own));
|
|
2738
|
+
throw new Error(`The sealed values of the archive moved to the transfer key ${fingerprint}, and the root secret of this host gives the transfer key ${ownFingerprint}. Restore it on the deployment that printed the key. No row was written.`);
|
|
2739
|
+
}
|
|
2740
|
+
return SealedValueImport.atRest(opened, hostKeys);
|
|
2741
|
+
}
|
|
2742
|
+
/**
|
|
2743
|
+
* The keys of this host for a check: `undefined` only when no root of this host gives the transfer key, as on the
|
|
2744
|
+
* source. A key setting that does not parse is an error, so a check never skips the moved values for it.
|
|
2745
|
+
*
|
|
2746
|
+
* @param transfer - The move that the manifest records.
|
|
2747
|
+
* @param hostKeys - The keys of this host.
|
|
2748
|
+
* @returns The keys of this host for the move, or `undefined` when they are not of the target.
|
|
2749
|
+
* @throws When a key setting of this host does not parse. The message names the setting, never a value.
|
|
2750
|
+
*/
|
|
2751
|
+
static async keysIfTarget(transfer, hostKeys) {
|
|
2752
|
+
const root = await SecretStoreCheck.rootOf(hostKeys);
|
|
2753
|
+
const opened = root.isSet() ? await SecretTransfer.forRoot(root, transfer.recipient, transfer.movePublicKey) : void 0;
|
|
2754
|
+
return opened === void 0 ? void 0 : SealedValueImport.atRest(opened, hostKeys);
|
|
2755
|
+
}
|
|
2756
|
+
/**
|
|
2757
|
+
* @returns The keys at rest of this host beside the opened transfer.
|
|
2758
|
+
* @throws When a key setting does not parse, or the root gives no key at rest. The message holds no value.
|
|
2759
|
+
*/
|
|
2760
|
+
static async atRest(transfer, hostKeys) {
|
|
2761
|
+
const ring = await SealedTables.ringOf(hostKeys);
|
|
2762
|
+
const history = await SealedTables.historyCipherOf(hostKeys);
|
|
2763
|
+
if (ring === void 0 || history === void 0) throw new Error("The root secret of this host gives no key at rest. No row was written.");
|
|
2764
|
+
return {
|
|
2765
|
+
transfer,
|
|
2766
|
+
ring,
|
|
2767
|
+
history
|
|
2768
|
+
};
|
|
2769
|
+
}
|
|
2770
|
+
/**
|
|
2771
|
+
* @param keys - The keys of this host ({@link keysOf}).
|
|
2772
|
+
* @param schema - The schema of the libraries' tables.
|
|
2773
|
+
* @returns The import.
|
|
2774
|
+
*/
|
|
2775
|
+
static of(keys, schema) {
|
|
2776
|
+
return new SealedValueImport(keys, schema);
|
|
2777
|
+
}
|
|
2778
|
+
/**
|
|
2779
|
+
* @param table - A table of the restored database.
|
|
2780
|
+
* @returns What gives the row that the restore writes, or `undefined` for a table with no sealed value.
|
|
2781
|
+
* @throws When the table lacks a column that the move reads.
|
|
2782
|
+
*/
|
|
2783
|
+
rewriterOf(table) {
|
|
2784
|
+
if (table.schema !== this.schema) return;
|
|
2785
|
+
if (table.name === SealedTables.secretTable) {
|
|
2786
|
+
const positions = SealedTables.positionsOf(table, [
|
|
2787
|
+
"reference",
|
|
2788
|
+
"key_id",
|
|
2789
|
+
"envelope"
|
|
2790
|
+
]);
|
|
2791
|
+
return (row) => this.secretRow(row, positions);
|
|
2792
|
+
}
|
|
2793
|
+
if (table.name === SealedTables.historyTable) {
|
|
2794
|
+
const positions = SealedTables.positionsOf(table, [
|
|
2795
|
+
"session_id",
|
|
2796
|
+
"position",
|
|
2797
|
+
"payload",
|
|
2798
|
+
"outcome",
|
|
2799
|
+
"offload_reference",
|
|
2800
|
+
"key_id"
|
|
2801
|
+
]);
|
|
2802
|
+
return (row) => this.historyRow(row, positions);
|
|
2803
|
+
}
|
|
2804
|
+
if (table.name === SealedTables.tokenTable) {
|
|
2805
|
+
const positions = SealedTables.positionsOf(table, ["token_id", "verifier_hash"]);
|
|
2806
|
+
return async (row) => {
|
|
2807
|
+
const verifier = await ModelHistorySeals.tokenVerifierOf(this.keys.history, SealedTables.valueAt(row, positions["token_id"]) ?? "");
|
|
2808
|
+
return SealedValueImport.replaced(row, { [positions["verifier_hash"] ?? -1]: await ModelHistorySeals.tokenVerifierHashOf(verifier) });
|
|
2809
|
+
};
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
/**
|
|
2813
|
+
* @param object - An object of the archive that the move sealed.
|
|
2814
|
+
* @param bytes - Its bytes.
|
|
2815
|
+
* @returns The bytes and the custom metadata that the store of this host keeps.
|
|
2816
|
+
* @throws When the object does not open with the transfer key of this host.
|
|
2817
|
+
*/
|
|
2818
|
+
async objectOf(object, bytes) {
|
|
2819
|
+
const binding = object.transfer?.binding ?? "";
|
|
2820
|
+
const plain = await this.open(SealedValueKind.HistoryObject, binding, bytes, object.key);
|
|
2821
|
+
return {
|
|
2822
|
+
bytes: new TextEncoder().encode(await this.keys.history.encrypt(plain, binding)),
|
|
2823
|
+
custom: {
|
|
2824
|
+
...object.custom,
|
|
2825
|
+
[ModelHistorySeals.keyIdField]: await this.keys.history.keyId()
|
|
2826
|
+
}
|
|
2827
|
+
};
|
|
2828
|
+
}
|
|
2829
|
+
async secretRow(row, positions) {
|
|
2830
|
+
if (SealedTables.valueAt(row, positions["key_id"]) !== SealedTables.marker) return row;
|
|
2831
|
+
const reference = SealedTables.valueAt(row, positions["reference"]) ?? "";
|
|
2832
|
+
const plain = await this.open(SealedValueKind.SecretStore, reference, SealedTables.valueAt(row, positions["envelope"]) ?? "", reference);
|
|
2833
|
+
const sealed = await SecretEnvelope.seal(this.keys.ring, reference, plain);
|
|
2834
|
+
return SealedValueImport.replaced(row, {
|
|
2835
|
+
[positions["key_id"] ?? -1]: sealed.keyId,
|
|
2836
|
+
[positions["envelope"] ?? -1]: sealed.envelope
|
|
2837
|
+
});
|
|
2838
|
+
}
|
|
2839
|
+
/**
|
|
2840
|
+
* An inline row opens its columns. A large row stays as it is: its object moves, and a read takes the key that the
|
|
2841
|
+
* object names.
|
|
2842
|
+
*/
|
|
2843
|
+
async historyRow(row, positions) {
|
|
2844
|
+
if (SealedTables.valueAt(row, positions["offload_reference"]) !== null || SealedTables.valueAt(row, positions["key_id"]) !== SealedTables.marker) return row;
|
|
2845
|
+
const sessionId = SealedTables.valueAt(row, positions["session_id"]) ?? "";
|
|
2846
|
+
const position = Number(SealedTables.valueAt(row, positions["position"]));
|
|
2847
|
+
const changes = { [positions["key_id"] ?? -1]: await this.keys.history.keyId() };
|
|
2848
|
+
for (const column of ["payload", "outcome"]) {
|
|
2849
|
+
const moved = SealedTables.valueAt(row, positions[column]);
|
|
2850
|
+
if (moved !== null) {
|
|
2851
|
+
const binding = ModelHistorySeals.rowColumnBinding(sessionId, position, column);
|
|
2852
|
+
const plain = await this.open(SealedValueKind.HistoryColumn, binding, moved, SealedTables.historyPlaceOf(sessionId, position));
|
|
2853
|
+
changes[positions[column] ?? -1] = await this.keys.history.encrypt(plain, binding);
|
|
2854
|
+
}
|
|
2855
|
+
}
|
|
2856
|
+
return SealedValueImport.replaced(row, changes);
|
|
2857
|
+
}
|
|
2858
|
+
/** @returns The plain value; it throws with the place of the value, never the value. */
|
|
2859
|
+
async open(kind, binding, sealed, place) {
|
|
2860
|
+
try {
|
|
2861
|
+
return await this.keys.transfer.open(kind, binding, typeof sealed === "string" ? sealed : new TextDecoder().decode(sealed));
|
|
2862
|
+
} catch {
|
|
2863
|
+
throw new Error(`A sealed value of the archive (${kind} ${place}) does not open with the transfer key of this host: the archive changed after the backup.`);
|
|
2864
|
+
}
|
|
2865
|
+
}
|
|
2866
|
+
static replaced(row, changes) {
|
|
2867
|
+
return row.map((value, position) => changes[position] ?? value);
|
|
2868
|
+
}
|
|
2869
|
+
};
|
|
2870
|
+
//#endregion
|
|
2871
|
+
//#region src/backup/sealed-value-check.ts
|
|
2872
|
+
/**
|
|
2873
|
+
* Checks on the target that the values of a move are there: it opens each sealed value of the organization with the
|
|
2874
|
+
* keys of this host, makes the keyed digest of the move, and compares the counts and the digests with the manifest.
|
|
2875
|
+
* A value that the source could not open is left out, as the manifest names it. It reads the three tables of sealed
|
|
2876
|
+
* values once and each moved object once, and prints no value.
|
|
2877
|
+
*/
|
|
2878
|
+
var SealedValueCheck = class SealedValueCheck {
|
|
2879
|
+
transfer;
|
|
2880
|
+
keys;
|
|
2881
|
+
isUnreadable;
|
|
2882
|
+
tally = new SealedValueTally();
|
|
2883
|
+
constructor(transfer, keys, isUnreadable) {
|
|
2884
|
+
this.transfer = transfer;
|
|
2885
|
+
this.keys = keys;
|
|
2886
|
+
this.isUnreadable = isUnreadable;
|
|
2887
|
+
}
|
|
2888
|
+
/**
|
|
2889
|
+
* @param transfer - The move that the manifest records.
|
|
2890
|
+
* @param hostKeys - The keys of this host.
|
|
2891
|
+
* @returns The check, or `undefined` when no root of this host gives the transfer key (as on the source).
|
|
2892
|
+
* @throws When a key setting of this host does not parse. The message names the setting, never a value.
|
|
2893
|
+
*/
|
|
2894
|
+
static async of(transfer, hostKeys) {
|
|
2895
|
+
const keys = await SealedValueImport.keysIfTarget(transfer, hostKeys);
|
|
2896
|
+
if (keys === void 0) return;
|
|
2897
|
+
return new SealedValueCheck(transfer, keys, SealedValueTally.lookupOf(transfer.unreadable));
|
|
2898
|
+
}
|
|
2899
|
+
/**
|
|
2900
|
+
* @param session - The database, with no open transaction.
|
|
2901
|
+
* @param scope - The organization of the archive.
|
|
2902
|
+
*/
|
|
2903
|
+
async readRows(session, scope) {
|
|
2904
|
+
await session.beginSnapshot();
|
|
2905
|
+
try {
|
|
2906
|
+
for (const table of await session.tables()) if (table.schema === session.defaultSchema) await this.readTable(session, table, scope);
|
|
2907
|
+
} finally {
|
|
2908
|
+
await session.abortSnapshot();
|
|
2909
|
+
}
|
|
2910
|
+
}
|
|
2911
|
+
/**
|
|
2912
|
+
* @param store - The file store.
|
|
2913
|
+
* @param objects - The objects of the archive.
|
|
2914
|
+
*/
|
|
2915
|
+
async readObjects(store, objects) {
|
|
2916
|
+
for (const object of objects) {
|
|
2917
|
+
const binding = object.transfer?.binding;
|
|
2918
|
+
if (binding === void 0) continue;
|
|
2919
|
+
const stored = await store.get(object.key);
|
|
2920
|
+
const plain = stored === null ? void 0 : await this.keys.history.decrypt(new TextDecoder().decode(stored.bytes), binding, stored.metadata.custom?.[ModelHistorySeals.keyIdField]).catch(() => void 0);
|
|
2921
|
+
if (plain !== void 0) await this.count(SealedValueKind.HistoryObject, binding, plain);
|
|
2922
|
+
}
|
|
2923
|
+
}
|
|
2924
|
+
/**
|
|
2925
|
+
* @param hasObjects - Whether the check read the objects of a store.
|
|
2926
|
+
* @returns One line for each difference; none when every moved value opens and is the same.
|
|
2927
|
+
*/
|
|
2928
|
+
differences(hasObjects) {
|
|
2929
|
+
return this.tally.differencesFrom(hasObjects ? this.transfer.kinds : this.transfer.kinds.filter((kind) => kind.kind !== SealedValueKind.HistoryObject));
|
|
2930
|
+
}
|
|
2931
|
+
async readTable(session, table, scope) {
|
|
2932
|
+
const reader = this.readerOf(table);
|
|
2933
|
+
if (reader === void 0) return;
|
|
2934
|
+
for await (const row of BackupRows.of(session, table, scope)) await reader(row);
|
|
2935
|
+
}
|
|
2936
|
+
readerOf(table) {
|
|
2937
|
+
const at = SealedTables.valueAt;
|
|
2938
|
+
if (table.name === SealedTables.secretTable) {
|
|
2939
|
+
const positions = SealedTables.positionsOf(table, ["reference", "envelope"]);
|
|
2940
|
+
return async (row) => {
|
|
2941
|
+
const reference = at(row, positions["reference"]) ?? "";
|
|
2942
|
+
if (this.isUnreadable(SealedValueKind.SecretStore, reference)) return;
|
|
2943
|
+
const lookup = await SecretEnvelope.open(this.keys.ring, reference, at(row, positions["envelope"]) ?? "");
|
|
2944
|
+
if (lookup.status === SecretLookupStatus.Found) await this.count(SealedValueKind.SecretStore, reference, lookup.value);
|
|
2945
|
+
};
|
|
2946
|
+
}
|
|
2947
|
+
if (table.name === SealedTables.historyTable) {
|
|
2948
|
+
const positions = SealedTables.positionsOf(table, [
|
|
2949
|
+
"session_id",
|
|
2950
|
+
"position",
|
|
2951
|
+
"payload",
|
|
2952
|
+
"outcome",
|
|
2953
|
+
"offload_reference",
|
|
2954
|
+
"key_id"
|
|
2955
|
+
]);
|
|
2956
|
+
return async (row) => {
|
|
2957
|
+
const sessionId = at(row, positions["session_id"]) ?? "";
|
|
2958
|
+
const position = Number(at(row, positions["position"]));
|
|
2959
|
+
if (at(row, positions["offload_reference"]) !== null || this.isUnreadable(SealedValueKind.HistoryColumn, SealedTables.historyPlaceOf(sessionId, position))) return;
|
|
2960
|
+
for (const column of ["payload", "outcome"]) {
|
|
2961
|
+
const sealed = at(row, positions[column]);
|
|
2962
|
+
const binding = ModelHistorySeals.rowColumnBinding(sessionId, position, column);
|
|
2963
|
+
const plain = sealed === null ? void 0 : await this.keys.history.decrypt(sealed, binding, at(row, positions["key_id"]) ?? void 0).catch(() => void 0);
|
|
2964
|
+
if (plain !== void 0) await this.count(SealedValueKind.HistoryColumn, binding, plain);
|
|
2965
|
+
}
|
|
2966
|
+
};
|
|
2967
|
+
}
|
|
2968
|
+
if (table.name === SealedTables.tokenTable) {
|
|
2969
|
+
const positions = SealedTables.positionsOf(table, ["token_id", "verifier_hash"]);
|
|
2970
|
+
return async (row) => {
|
|
2971
|
+
const tokenId = at(row, positions["token_id"]) ?? "";
|
|
2972
|
+
if (await ModelHistorySeals.storedTokenVerifierOf(this.keys.history, tokenId, at(row, positions["verifier_hash"]) ?? "") !== void 0) await this.count(SealedValueKind.SessionToken, tokenId, "");
|
|
2973
|
+
};
|
|
2974
|
+
}
|
|
2975
|
+
}
|
|
2976
|
+
async count(kind, binding, plain) {
|
|
2977
|
+
this.tally.add(kind, await this.keys.transfer.digestOf(kind, binding, plain));
|
|
2978
|
+
}
|
|
2979
|
+
};
|
|
2980
|
+
//#endregion
|
|
1634
2981
|
//#region src/backup/backup-verify.ts
|
|
1635
2982
|
/**
|
|
1636
2983
|
* Compares a database and a store with an archive: the schema, the row count and the digest of each table, the
|
|
1637
2984
|
* sequences, the migrations journal, and the key, bytes and metadata of each object. It also checks that the host's
|
|
1638
|
-
* keys read the values of the secret store. It reads and writes nothing else.
|
|
2985
|
+
* keys read the values of the secret store. It reads and writes nothing else. The check of an organization backup
|
|
2986
|
+
* compares the rows that belong to the organization, and the objects of the archive and those whose key names it.
|
|
2987
|
+
* When the sealed values of the archive moved to a transfer key, the comparison masks them, and a host whose root
|
|
2988
|
+
* gives that key opens each of them and compares them with the move ({@link SealedValueCheck}).
|
|
1639
2989
|
*/
|
|
1640
2990
|
var BackupVerify = class {
|
|
1641
2991
|
/**
|
|
@@ -1646,18 +2996,25 @@ var BackupVerify = class {
|
|
|
1646
2996
|
const report = new BackupReport(options.print);
|
|
1647
2997
|
const checked = options.checked ?? await ArchiveScan.check(options.archive, options.identities);
|
|
1648
2998
|
const { manifest } = checked;
|
|
2999
|
+
const transfer = manifest.transfer;
|
|
3000
|
+
const sealedCheck = transfer === void 0 ? void 0 : await SealedValueCheck.of(transfer, options.secretKeys);
|
|
1649
3001
|
let isSame = true;
|
|
1650
3002
|
if (options.checked === void 0) options.print(`Archive: ${manifest.entries.length + 1} entries, each with the size and the SHA-256 that its manifest records.`);
|
|
1651
3003
|
if (options.databaseAddress !== void 0) {
|
|
1652
3004
|
const session = await DatabaseSessions.open(options.databaseAddress);
|
|
1653
3005
|
try {
|
|
1654
3006
|
BackupManifest.requireDialect(manifest, session.dialect);
|
|
1655
|
-
const content = await DatabaseContentReader.read(session);
|
|
3007
|
+
const content = await DatabaseContentReader.read(session, manifest.organization, transfer);
|
|
1656
3008
|
const expected = BackupManifest.databaseContent(manifest);
|
|
1657
3009
|
isSame = report.comparison("Database", BackupComparison.database(expected, content)) && isSame;
|
|
1658
|
-
if (
|
|
3010
|
+
if (sealedCheck !== void 0 && manifest.organization !== void 0) await sealedCheck.readRows(session, new OrganizationScope(session, await session.tables(), manifest.organization));
|
|
3011
|
+
else if (transfer !== void 0) options.print("Sealed values: they moved to the transfer key of another deployment, and no root of this host gives it, so their content is compared on that deployment only.");
|
|
3012
|
+
else if (expected.secrets !== null && expected.secrets.keys.length > 0) {
|
|
1659
3013
|
if (options.secretKeys === void 0) options.print(`Secret store: neither ${RootSecret.variable} nor ${SecretStoreCheck.keysVariable} is set, so the check of the keys did not run.`);
|
|
1660
|
-
else
|
|
3014
|
+
else {
|
|
3015
|
+
const scope = manifest.organization === void 0 ? void 0 : new OrganizationScope(session, await session.tables(), manifest.organization);
|
|
3016
|
+
isSame = report.readability(await SecretStoreCheck.readability(session, options.secretKeys, scope)) && isSame;
|
|
3017
|
+
}
|
|
1661
3018
|
}
|
|
1662
3019
|
} finally {
|
|
1663
3020
|
await session.close();
|
|
@@ -1668,8 +3025,18 @@ var BackupVerify = class {
|
|
|
1668
3025
|
else if (options.files === void 0) options.print("Files: not compared.");
|
|
1669
3026
|
else {
|
|
1670
3027
|
const files = await FileStoreLocations.open(options.files);
|
|
1671
|
-
const
|
|
1672
|
-
|
|
3028
|
+
const { organization } = manifest;
|
|
3029
|
+
try {
|
|
3030
|
+
const actual = await FileStoreContent.read(files.store, organization === void 0 ? void 0 : (key) => checked.objects.has(key) || OrganizationScope.isObjectKeyOf(organization, key));
|
|
3031
|
+
isSame = report.comparison("Files", BackupComparison.files(checked.objects, actual.objects)) && isSame;
|
|
3032
|
+
if (sealedCheck !== void 0 && options.databaseAddress !== void 0) await sealedCheck.readObjects(files.store, checked.objects.values());
|
|
3033
|
+
} finally {
|
|
3034
|
+
await files.close();
|
|
3035
|
+
}
|
|
3036
|
+
}
|
|
3037
|
+
if (sealedCheck !== void 0 && options.databaseAddress !== void 0) {
|
|
3038
|
+
isSame = report.comparison("Sealed values", sealedCheck.differences(manifest.files !== null && options.files !== void 0)) && isSame;
|
|
3039
|
+
report.unreadable(transfer?.unreadable ?? []);
|
|
1673
3040
|
}
|
|
1674
3041
|
return isSame;
|
|
1675
3042
|
}
|
|
@@ -1709,6 +3076,20 @@ var MigrationReplay = class MigrationReplay {
|
|
|
1709
3076
|
}
|
|
1710
3077
|
}
|
|
1711
3078
|
/**
|
|
3079
|
+
* Refuses a folder that holds a migration the backup did not apply. An organization backup holds the rows of one
|
|
3080
|
+
* organization and no step of a later migration runs on them, so its restore needs the same migrations as its
|
|
3081
|
+
* source.
|
|
3082
|
+
*
|
|
3083
|
+
* @param folder - The host's migrations folder, which {@link check} found to hold every migration of the journal.
|
|
3084
|
+
* @param applied - The journal of the backup.
|
|
3085
|
+
* @throws When the folder holds a later migration.
|
|
3086
|
+
*/
|
|
3087
|
+
static requireSameHead(folder, applied) {
|
|
3088
|
+
const names = new Set(applied.map((migration) => migration.name));
|
|
3089
|
+
const later = readdirSync(folder).filter((name) => !names.has(name) && existsSync(join(folder, name, MigrationReplay.migrationFile))).sort();
|
|
3090
|
+
if (later.length > 0) throw new Error(`The migrations folder ${folder} holds ${later.length === 1 ? "the migration" : "the migrations"} ${later.join(", ")}, which the source of the organization backup did not apply (its head is ${applied.at(-1)?.name ?? "none"}). An organization restore needs the same migrations as its source: restore with the release of the source, or back up the organization again after the source is on this release.`);
|
|
3091
|
+
}
|
|
3092
|
+
/**
|
|
1712
3093
|
* @param address - The connection string of the empty database.
|
|
1713
3094
|
* @param folder - The host's migrations folder.
|
|
1714
3095
|
* @param applied - The journal of the backup.
|
|
@@ -1828,7 +3209,10 @@ var MultipartWrite = class MultipartWrite {
|
|
|
1828
3209
|
* (`PgLoad`: one transaction with the foreign keys dropped and the triggers off; `MysqlLoad`: in the order of the
|
|
1829
3210
|
* foreign keys, each statement on its own), holds all agent work until a person releases it ({@link RestoreHold})
|
|
1830
3211
|
* before the rows commit, sets the counters, streams the objects into the store, and then runs {@link BackupVerify}
|
|
1831
|
-
* on the result.
|
|
3212
|
+
* on the result. An organization backup restores only when it is complete and only with the migrations of its source
|
|
3213
|
+
* ({@link MigrationReplay.requireSameHead}), so a refused one leaves the target empty. When its sealed values moved
|
|
3214
|
+
* to a transfer key, the root of this host must give that key, and each moved value is sealed again under the keys of
|
|
3215
|
+
* this host as it is written ({@link SealedValueImport}). A failure after the migrations leaves the schema, a failure of a MySQL load
|
|
1832
3216
|
* leaves rows, and a failure during the objects also leaves the committed rows and some objects: before the next
|
|
1833
3217
|
* run, drop and create the database and empty the file store.
|
|
1834
3218
|
*/
|
|
@@ -1845,9 +3229,15 @@ var BackupRestore = class BackupRestore {
|
|
|
1845
3229
|
const { manifest } = checked;
|
|
1846
3230
|
options.print(`Archive: ${manifest.entries.length + 1} entries, each with the size and the SHA-256 that its manifest records.`);
|
|
1847
3231
|
MigrationReplay.check(options.migrationsFolder, manifest.database.migrations);
|
|
3232
|
+
if (manifest.organization !== void 0) {
|
|
3233
|
+
BackupRestore.requireComplete(manifest);
|
|
3234
|
+
MigrationReplay.requireSameHead(options.migrationsFolder, manifest.database.migrations);
|
|
3235
|
+
options.print(`Organization: ${manifest.organization}. The archive holds the rows and the objects of this organization only.`);
|
|
3236
|
+
}
|
|
3237
|
+
const targetKeys = manifest.transfer === void 0 ? void 0 : await SealedValueImport.keysOf(manifest.transfer, options.secretKeys);
|
|
1848
3238
|
const files = manifest.files === null || options.files === void 0 ? void 0 : await FileStoreLocations.open(options.files);
|
|
1849
3239
|
try {
|
|
1850
|
-
await BackupRestore.restore(options, checked, files);
|
|
3240
|
+
await BackupRestore.restore(options, checked, files, targetKeys);
|
|
1851
3241
|
} finally {
|
|
1852
3242
|
await files?.close();
|
|
1853
3243
|
}
|
|
@@ -1862,7 +3252,7 @@ var BackupRestore = class BackupRestore {
|
|
|
1862
3252
|
print: options.print
|
|
1863
3253
|
});
|
|
1864
3254
|
}
|
|
1865
|
-
static async restore(options, checked, files) {
|
|
3255
|
+
static async restore(options, checked, files, targetKeys) {
|
|
1866
3256
|
const { manifest } = checked;
|
|
1867
3257
|
const session = await DatabaseSessions.open(options.databaseAddress);
|
|
1868
3258
|
try {
|
|
@@ -1872,14 +3262,27 @@ var BackupRestore = class BackupRestore {
|
|
|
1872
3262
|
await MigrationReplay.apply(options.databaseAddress, options.migrationsFolder, manifest.database.migrations);
|
|
1873
3263
|
options.print(`Migrations: applied ${manifest.database.migrations.length} (head ${BackupComparison.headOf(BackupManifest.databaseContent(manifest))}).`);
|
|
1874
3264
|
await BackupRestore.checkSchema(session, checked);
|
|
1875
|
-
const
|
|
3265
|
+
const importer = targetKeys === void 0 ? void 0 : SealedValueImport.of(targetKeys, session.defaultSchema);
|
|
3266
|
+
const tables = await BackupRestore.checkTables(session, checked, importer);
|
|
1876
3267
|
options.print(`Schema: the same as the backup (${manifest.database.schemaLines} lines).`);
|
|
1877
|
-
await BackupRestore.load(options, session, files, checked, tables);
|
|
3268
|
+
await BackupRestore.load(options, session, files, checked, tables, importer);
|
|
3269
|
+
if (targetKeys !== void 0) options.print(`Sealed values: sealed again under the keys of this host, from the transfer key ${targetKeys.transfer.fingerprint}.`);
|
|
1878
3270
|
} finally {
|
|
1879
3271
|
await session.close();
|
|
1880
3272
|
}
|
|
1881
3273
|
}
|
|
1882
3274
|
/**
|
|
3275
|
+
* Refuses an organization archive whose manifest names objects with no bytes, before the migrations run: a
|
|
3276
|
+
* customer's install starts from the whole organization or not at all.
|
|
3277
|
+
*
|
|
3278
|
+
* @throws With every missing object.
|
|
3279
|
+
*/
|
|
3280
|
+
static requireComplete(manifest) {
|
|
3281
|
+
const missing = manifest.files?.missing ?? [];
|
|
3282
|
+
if (missing.length === 0) return;
|
|
3283
|
+
throw new Error([`The organization archive is incomplete: it lacks the bytes of ${String(missing.length)} objects that a committed row names. No row was written. Back up the organization again when nobody deletes files.`, ...missing.map((object) => ` The object ${object.key}: ${object.reason}`)].join("\n"));
|
|
3284
|
+
}
|
|
3285
|
+
/**
|
|
1883
3286
|
* Refuses a store that holds objects, an object larger than one multipart upload can hold, and metadata that the
|
|
1884
3287
|
* store cannot keep, before the migrations run.
|
|
1885
3288
|
*/
|
|
@@ -1917,7 +3320,7 @@ var BackupRestore = class BackupRestore {
|
|
|
1917
3320
|
*
|
|
1918
3321
|
* @returns The table of the database for each table entry of the archive.
|
|
1919
3322
|
*/
|
|
1920
|
-
static async checkTables(session, checked) {
|
|
3323
|
+
static async checkTables(session, checked, importer) {
|
|
1921
3324
|
const { database } = checked.manifest;
|
|
1922
3325
|
const made = new Map((await session.tables()).map((table) => [DatabaseSession.displayName(table.schema, table.name), table]));
|
|
1923
3326
|
const differences = [];
|
|
@@ -1928,11 +3331,15 @@ var BackupRestore = class BackupRestore {
|
|
|
1928
3331
|
made.delete(name);
|
|
1929
3332
|
if (table === void 0) differences.push(`The table ${name} of the backup is not in the database.`);
|
|
1930
3333
|
else if (JSON.stringify(backedUp.columns) !== JSON.stringify(table.columns)) differences.push(`The columns of the table ${name} differ from the database.`);
|
|
1931
|
-
else
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
3334
|
+
else {
|
|
3335
|
+
const rewrite = importer?.rewriterOf(table);
|
|
3336
|
+
byEntry.set(backedUp.entry, {
|
|
3337
|
+
entry: backedUp.entry,
|
|
3338
|
+
table,
|
|
3339
|
+
rows: backedUp.rows,
|
|
3340
|
+
...rewrite === void 0 ? {} : { rewrite }
|
|
3341
|
+
});
|
|
3342
|
+
}
|
|
1936
3343
|
}
|
|
1937
3344
|
for (const name of made.keys()) differences.push(`The table ${name} of the database is not in the backup.`);
|
|
1938
3345
|
const sequences = new Set((await session.sequences()).map((state) => DatabaseSession.displayName(state.schema, state.name)));
|
|
@@ -1943,7 +3350,7 @@ var BackupRestore = class BackupRestore {
|
|
|
1943
3350
|
if (differences.length > 0) throw new Error(["The manifest of the archive does not match the database the migrations made. No row was written.", ...differences.slice(0, BackupRestore.shownSchemaLines).map((line) => ` ${line}`)].join("\n"));
|
|
1944
3351
|
return byEntry;
|
|
1945
3352
|
}
|
|
1946
|
-
static async load(options, session, files, checked, tables) {
|
|
3353
|
+
static async load(options, session, files, checked, tables, importer) {
|
|
1947
3354
|
const { print } = options;
|
|
1948
3355
|
const objects = new Map([...checked.objects.values()].map((object) => [object.entry, object]));
|
|
1949
3356
|
const load = await session.startLoad([...tables.values()], checked.manifest.database.sequences);
|
|
@@ -1963,6 +3370,16 @@ var BackupRestore = class BackupRestore {
|
|
|
1963
3370
|
await BackupRestore.finishDatabase(session, load, print);
|
|
1964
3371
|
isDatabaseOpen = false;
|
|
1965
3372
|
}
|
|
3373
|
+
if (importer !== void 0 && object.transfer !== void 0) {
|
|
3374
|
+
const resealed = await importer.objectOf(object, await BackupRestore.bytesOf(entry));
|
|
3375
|
+
await files.store.put(object.key, resealed.bytes, {
|
|
3376
|
+
...object.contentType === null ? {} : { contentType: object.contentType },
|
|
3377
|
+
custom: resealed.custom
|
|
3378
|
+
});
|
|
3379
|
+
objectCount += 1;
|
|
3380
|
+
objectBytes += resealed.bytes.length;
|
|
3381
|
+
continue;
|
|
3382
|
+
}
|
|
1966
3383
|
const metadata = {
|
|
1967
3384
|
...object.contentType === null ? {} : { contentType: object.contentType },
|
|
1968
3385
|
...Object.keys(object.custom).length === 0 ? {} : { custom: object.custom }
|
|
@@ -1992,6 +3409,12 @@ var BackupRestore = class BackupRestore {
|
|
|
1992
3409
|
print(await load.finish());
|
|
1993
3410
|
held.forEach(print);
|
|
1994
3411
|
}
|
|
3412
|
+
/** @returns The whole bytes of an archive entry. */
|
|
3413
|
+
static async bytesOf(entry) {
|
|
3414
|
+
const pieces = [];
|
|
3415
|
+
for await (const chunk of entry.chunks()) pieces.push(chunk);
|
|
3416
|
+
return Buffer.concat(pieces);
|
|
3417
|
+
}
|
|
1995
3418
|
/** @returns A stream over the bytes of an archive entry, as a store takes a body. */
|
|
1996
3419
|
static streamOf(entry) {
|
|
1997
3420
|
const chunks = entry.chunks();
|
|
@@ -2093,6 +3516,8 @@ var BackupCli = class BackupCli {
|
|
|
2093
3516
|
};
|
|
2094
3517
|
/** The exit status of a wrong option. */
|
|
2095
3518
|
static usageStatus = 2;
|
|
3519
|
+
/** The variable that holds the transfer key of `create`, when `--transfer-key` names none. */
|
|
3520
|
+
static transferKeyVariable = "INFERATIVE_BACKUP_TRANSFER_KEY";
|
|
2096
3521
|
/**
|
|
2097
3522
|
* @param values - The options.
|
|
2098
3523
|
* @param io - Where to read and write.
|
|
@@ -2104,13 +3529,22 @@ var BackupCli = class BackupCli {
|
|
|
2104
3529
|
const requestedOut = BackupCli.required(values.out, "--out");
|
|
2105
3530
|
const recipients = BackupCli.recipients(values, io);
|
|
2106
3531
|
const out = BackupCli.archiveName(requestedOut, recipients);
|
|
3532
|
+
if (values.organization !== void 0 && !OrganizationScope.idPattern.test(values.organization)) throw new BackupUsageError("--organization takes an organization id of letters, digits and hyphens.");
|
|
3533
|
+
const transferKey = values.transferKey ?? BackupCli.valueOf(io.env[BackupCli.transferKeyVariable]);
|
|
3534
|
+
if (transferKey !== void 0 && values.organization === void 0) throw new BackupUsageError("--transfer-key moves the sealed values of one organization: name --organization.");
|
|
3535
|
+
if (transferKey !== void 0) {
|
|
3536
|
+
await BackupCli.requireTransferKey(transferKey);
|
|
3537
|
+
BackupCli.requireSourceKeys(io);
|
|
3538
|
+
}
|
|
2107
3539
|
const manifest = await BackupCreate.run({
|
|
2108
3540
|
archive: BackupCli.path(io, out),
|
|
2109
3541
|
recipients,
|
|
2110
3542
|
databaseAddress: BackupCli.databaseAddress(values, io),
|
|
2111
3543
|
files: BackupCli.files(values, io),
|
|
2112
3544
|
host: values.host ?? BackupCli.projectName(io.project),
|
|
3545
|
+
...values.organization === void 0 ? {} : { organization: values.organization },
|
|
2113
3546
|
secretKeys: SecretStoreCheck.hostKeysOf(io.env),
|
|
3547
|
+
...transferKey === void 0 ? {} : { transferKey },
|
|
2114
3548
|
versions: BackupCli.versions(io.project),
|
|
2115
3549
|
fenceLeaseMinutes: BackupCli.fenceLeaseMinutes(values),
|
|
2116
3550
|
print: io.print
|
|
@@ -2163,6 +3597,25 @@ var BackupCli = class BackupCli {
|
|
|
2163
3597
|
});
|
|
2164
3598
|
}
|
|
2165
3599
|
/**
|
|
3600
|
+
* Prints the transfer key of this host: the public key that its root secret gives, which an organization backup on
|
|
3601
|
+
* another deployment seals the organization's sealed values to. The root never leaves the host.
|
|
3602
|
+
*
|
|
3603
|
+
* @param values - The options.
|
|
3604
|
+
* @param io - Where to read and write.
|
|
3605
|
+
* @returns The exit status.
|
|
3606
|
+
*/
|
|
3607
|
+
static async transferKey(values, given) {
|
|
3608
|
+
return BackupCli.guard(given, async () => {
|
|
3609
|
+
const io = BackupCli.withEnvFile(values, given);
|
|
3610
|
+
const root = await SecretStoreCheck.rootOf(SecretStoreCheck.hostKeysOf(io.env));
|
|
3611
|
+
const key = await SecretTransferKey.of(root);
|
|
3612
|
+
if (key === void 0) throw new BackupUsageError(`Set ${RootSecret.variable} to the root secret of this host, in the environment or in the --env-file.`);
|
|
3613
|
+
io.print(`Transfer key of this host, for backup create --organization <id> --transfer-key on the source: ${key}`);
|
|
3614
|
+
io.print("Only the root secret of this host opens what a backup seals to it. Restore the archive on this host.");
|
|
3615
|
+
return 0;
|
|
3616
|
+
});
|
|
3617
|
+
}
|
|
3618
|
+
/**
|
|
2166
3619
|
* Writes a new age private key to a file that only its owner reads, and prints its public key.
|
|
2167
3620
|
*
|
|
2168
3621
|
* @param values - The options.
|
|
@@ -2216,6 +3669,23 @@ var BackupCli = class BackupCli {
|
|
|
2216
3669
|
return 1;
|
|
2217
3670
|
}
|
|
2218
3671
|
}
|
|
3672
|
+
/** Refuses a text that is not a transfer key, before the backup reads anything. */
|
|
3673
|
+
static async requireTransferKey(text) {
|
|
3674
|
+
try {
|
|
3675
|
+
await SecretTransferKey.parse(text);
|
|
3676
|
+
} catch (failure) {
|
|
3677
|
+
throw new BackupUsageError(failure.message);
|
|
3678
|
+
}
|
|
3679
|
+
}
|
|
3680
|
+
/** Refuses a move on a host that sets no key to open its sealed values. */
|
|
3681
|
+
static requireSourceKeys(io) {
|
|
3682
|
+
const keys = SecretStoreCheck.hostKeysOf(io.env);
|
|
3683
|
+
if (keys?.root === void 0 && keys?.listed === void 0 && keys?.historyKey === void 0) throw new BackupUsageError(`--transfer-key opens each sealed value with the keys of this host: set ${RootSecret.variable}, and ${SecretStoreCheck.keysVariable} or ${SecretStoreCheck.historyKeyVariable} when the host sets them.`);
|
|
3684
|
+
}
|
|
3685
|
+
/** @returns The value, or `undefined` when it is empty or unset. */
|
|
3686
|
+
static valueOf(value) {
|
|
3687
|
+
return value === void 0 || value.trim() === "" ? void 0 : value.trim();
|
|
3688
|
+
}
|
|
2219
3689
|
/** @returns The io with the variables of `--env-file` over the environment; the file wins. */
|
|
2220
3690
|
static withEnvFile(values, io) {
|
|
2221
3691
|
if (values.envFile === void 0) return io;
|