mindoodb 0.2.0 → 0.2.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/dist/browser/index.mjs +16 -0
- package/dist/cloudflare/MindooDatabaseObject.d.ts +7 -0
- package/dist/cloudflare/MindooDatabaseObject.d.ts.map +1 -1
- package/dist/cloudflare/MindooDatabaseObject.js +52 -3
- package/dist/cloudflare/MindooDatabaseObject.js.map +1 -1
- package/dist/cloudflare/MindooServerObject.d.ts +2 -0
- package/dist/cloudflare/MindooServerObject.d.ts.map +1 -1
- package/dist/cloudflare/MindooServerObject.js +22 -1
- package/dist/cloudflare/MindooServerObject.js.map +1 -1
- package/dist/cloudflare/http.d.ts +10 -0
- package/dist/cloudflare/http.d.ts.map +1 -1
- package/dist/cloudflare/http.js +21 -2
- package/dist/cloudflare/http.js.map +1 -1
- package/dist/cloudflare/types.d.ts +6 -0
- package/dist/cloudflare/types.d.ts.map +1 -1
- package/dist/cloudflare/worker.d.ts.map +1 -1
- package/dist/cloudflare/worker.js +21 -0
- package/dist/cloudflare/worker.js.map +1 -1
- package/dist/core/BaseMindooDB.d.ts +56 -2
- package/dist/core/BaseMindooDB.d.ts.map +1 -1
- package/dist/core/BaseMindooDB.js +341 -20
- package/dist/core/BaseMindooDB.js.map +1 -1
- package/dist/core/BaseMindooTenant.d.ts +23 -5
- package/dist/core/BaseMindooTenant.d.ts.map +1 -1
- package/dist/core/BaseMindooTenant.js +115 -16
- package/dist/core/BaseMindooTenant.js.map +1 -1
- package/dist/core/BaseMindooTenantDirectory.d.ts +18 -0
- package/dist/core/BaseMindooTenantDirectory.d.ts.map +1 -1
- package/dist/core/BaseMindooTenantDirectory.js +154 -0
- package/dist/core/BaseMindooTenantDirectory.js.map +1 -1
- package/dist/core/ChangeDocDraft.d.ts.map +1 -1
- package/dist/core/ChangeDocDraft.js +2 -0
- package/dist/core/ChangeDocDraft.js.map +1 -1
- package/dist/core/applyChangesInSlices.d.ts +18 -5
- package/dist/core/applyChangesInSlices.d.ts.map +1 -1
- package/dist/core/applyChangesInSlices.js +31 -18
- package/dist/core/applyChangesInSlices.js.map +1 -1
- package/dist/core/builtinDbInvariants.d.ts +13 -1
- package/dist/core/builtinDbInvariants.d.ts.map +1 -1
- package/dist/core/builtinDbInvariants.js +21 -4
- package/dist/core/builtinDbInvariants.js.map +1 -1
- package/dist/core/documentLoadGuard.d.ts +114 -0
- package/dist/core/documentLoadGuard.d.ts.map +1 -0
- package/dist/core/documentLoadGuard.js +341 -0
- package/dist/core/documentLoadGuard.js.map +1 -0
- package/dist/core/errors.d.ts +5 -0
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +9 -0
- package/dist/core/errors.js.map +1 -1
- package/dist/core/index.d.ts +5 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +25 -7
- package/dist/core/index.js.map +1 -1
- package/dist/core/live/LiveChannel.d.ts +5 -0
- package/dist/core/live/LiveChannel.d.ts.map +1 -1
- package/dist/core/live/LiveChannel.js +4 -2
- package/dist/core/live/LiveChannel.js.map +1 -1
- package/dist/core/teamShares.d.ts +37 -0
- package/dist/core/teamShares.d.ts.map +1 -0
- package/dist/core/teamShares.js +57 -0
- package/dist/core/teamShares.js.map +1 -0
- package/dist/core/types.d.ts +76 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js.map +1 -1
- package/dist/core/userkeys/index.d.ts +1 -1
- package/dist/core/userkeys/index.d.ts.map +1 -1
- package/dist/core/userkeys/index.js.map +1 -1
- package/dist/core/userkeys/recipients.d.ts +5 -0
- package/dist/core/userkeys/recipients.d.ts.map +1 -1
- package/dist/core/userkeys/recipients.js +3 -0
- package/dist/core/userkeys/recipients.js.map +1 -1
- package/dist/core/userkeys/scopedSealedKeys.d.ts +12 -0
- package/dist/core/userkeys/scopedSealedKeys.d.ts.map +1 -0
- package/dist/core/userkeys/scopedSealedKeys.js +65 -0
- package/dist/core/userkeys/scopedSealedKeys.js.map +1 -0
- package/dist/core/userkeys/sealedCrypto.d.ts +44 -0
- package/dist/core/userkeys/sealedCrypto.d.ts.map +1 -1
- package/dist/core/userkeys/sealedCrypto.js +50 -4
- package/dist/core/userkeys/sealedCrypto.js.map +1 -1
- package/dist/core/userkeys/sealedTypes.d.ts +18 -0
- package/dist/core/userkeys/sealedTypes.d.ts.map +1 -1
- package/dist/core/userkeys/sealedTypes.js.map +1 -1
- package/dist/core/values.d.ts +38 -2
- package/dist/core/values.d.ts.map +1 -1
- package/dist/core/values.js +40 -3
- package/dist/core/values.js.map +1 -1
- package/dist/server/DeviceDiscoveryService.d.ts +19 -0
- package/dist/server/DeviceDiscoveryService.d.ts.map +1 -1
- package/dist/server/DeviceDiscoveryService.js +24 -19
- package/dist/server/DeviceDiscoveryService.js.map +1 -1
- package/package.json +1 -1
|
@@ -7,6 +7,7 @@ exports.BaseMindooDB = exports.CUSTOM_DOC_ID_INITIAL_CHANGE_BYTES = void 0;
|
|
|
7
7
|
const MindooFilingStore_1 = require("./filing/MindooFilingStore");
|
|
8
8
|
const automerge_adapter_1 = require("./automerge-adapter");
|
|
9
9
|
const applyChangesInSlices_1 = require("./applyChangesInSlices");
|
|
10
|
+
const documentLoadGuard_1 = require("./documentLoadGuard");
|
|
10
11
|
const ChangeDocDraft_1 = require("./ChangeDocDraft");
|
|
11
12
|
const values_1 = require("./values");
|
|
12
13
|
const storeEntryTime_1 = require("./storeEntryTime");
|
|
@@ -26,6 +27,7 @@ const purgeDocumentHistory_1 = require("./appendonlystores/purgeDocumentHistory"
|
|
|
26
27
|
const idGeneration_1 = require("./utils/idGeneration");
|
|
27
28
|
const timeSource_1 = require("./utils/timeSource");
|
|
28
29
|
const errors_1 = require("./errors");
|
|
30
|
+
const scopedSealedKeys_1 = require("./userkeys/scopedSealedKeys");
|
|
29
31
|
const EntrySignature_1 = require("./crypto/EntrySignature");
|
|
30
32
|
const copyDocument_1 = require("./copy/copyDocument");
|
|
31
33
|
const copyDocuments_1 = require("./copy/copyDocuments");
|
|
@@ -670,7 +672,10 @@ class BaseMindooDB {
|
|
|
670
672
|
if (attachmentStore.getStoreKind() !== types_4.StoreKind.attachments) {
|
|
671
673
|
throw new Error(`[BaseMindooDB] Expected attachment store kind ${types_4.StoreKind.attachments} but received ${attachmentStore.getStoreKind()}`);
|
|
672
674
|
}
|
|
673
|
-
|
|
675
|
+
// Sealed key series are named after a document id, which is unique per
|
|
676
|
+
// database only: keep this database's series apart in the session cache.
|
|
677
|
+
this.ownerTenant = tenant;
|
|
678
|
+
this.tenant = (0, scopedSealedKeys_1.withScopedSealedKeys)(tenant, store.getId());
|
|
674
679
|
this.store = store;
|
|
675
680
|
this.attachmentStore = attachmentStore;
|
|
676
681
|
this.chunkSizeBytes =
|
|
@@ -4458,7 +4463,7 @@ class BaseMindooDB {
|
|
|
4458
4463
|
return result;
|
|
4459
4464
|
}
|
|
4460
4465
|
getTenant() {
|
|
4461
|
-
return this.
|
|
4466
|
+
return this.ownerTenant;
|
|
4462
4467
|
}
|
|
4463
4468
|
async createDocument(options) {
|
|
4464
4469
|
return this.createDocumentInternal(options ?? {});
|
|
@@ -6580,7 +6585,7 @@ class BaseMindooDB {
|
|
|
6580
6585
|
}
|
|
6581
6586
|
return;
|
|
6582
6587
|
}
|
|
6583
|
-
this.assignHydrated(container, key, this.hydrateTypedValues(sourceValue));
|
|
6588
|
+
this.assignHydrated(container, key, this.hydrateTypedValues(sourceValue, 0, { largeStringsAtomic: false }));
|
|
6584
6589
|
if (Array.isArray(sourceValue)) {
|
|
6585
6590
|
// The copied list holds plain strings; bring their marks along.
|
|
6586
6591
|
this.forEachTextPath(sourceValue, path, (textPath) => this.restoreTextAt(targetDoc, sourceDoc, textPath));
|
|
@@ -7988,6 +7993,147 @@ class BaseMindooDB {
|
|
|
7988
7993
|
async deleteDocument(docId, options = {}) {
|
|
7989
7994
|
return this.deleteDocInternal(docId, options.signingKeyPair, options.signingKeyPassword, options.bypassAccessControlPrecheck, options.attribution);
|
|
7990
7995
|
}
|
|
7996
|
+
/**
|
|
7997
|
+
* The signed and decrypted Automerge changes of a document, without loading
|
|
7998
|
+
* it: every `doc_create`, `doc_change`, `doc_delete` and `doc_undelete` entry
|
|
7999
|
+
* whose signature verifies, decrypted, in store order. Snapshots are left
|
|
8000
|
+
* out, so nothing here has to be trusted beyond the signed entries.
|
|
8001
|
+
*
|
|
8002
|
+
* For documents this process refuses to load (`DocumentTooLargeError`):
|
|
8003
|
+
* hand the changes to an Automerge instance that may fail on its own, such
|
|
8004
|
+
* as one in a worker, to read the document there.
|
|
8005
|
+
*
|
|
8006
|
+
* Not available while the tenant enforces access control, where each change
|
|
8007
|
+
* is judged against the document state it produces. Returns `null` for an
|
|
8008
|
+
* unknown document.
|
|
8009
|
+
*/
|
|
8010
|
+
async getDocumentPayloads(docId) {
|
|
8011
|
+
const allEntryMetadata = await this.scanAllMetadata(this.store, { docId });
|
|
8012
|
+
if (allEntryMetadata.length === 0)
|
|
8013
|
+
return null;
|
|
8014
|
+
await this.ingestSealedKeyFromEntries(allEntryMetadata);
|
|
8015
|
+
if (await this.isAclEnforced()) {
|
|
8016
|
+
throw new Error(`Document ${docId} cannot be read without loading it while access control is enforced`);
|
|
8017
|
+
}
|
|
8018
|
+
const replay = allEntryMetadata
|
|
8019
|
+
.filter((meta) => this.isDocumentReplayEntry(meta))
|
|
8020
|
+
.sort((a, b) => (a.receivedAt ?? a.createdAt) === (b.receivedAt ?? b.createdAt)
|
|
8021
|
+
? a.id.localeCompare(b.id)
|
|
8022
|
+
: (a.receivedAt ?? a.createdAt) - (b.receivedAt ?? b.createdAt));
|
|
8023
|
+
const fetched = await this.fetchEntries(replay.map((meta) => meta.id));
|
|
8024
|
+
const byId = new Map(fetched.map((entry) => [entry.id, entry]));
|
|
8025
|
+
const changes = [];
|
|
8026
|
+
let decryptionKeyId = null;
|
|
8027
|
+
for (const meta of replay) {
|
|
8028
|
+
const entry = byId.get(meta.id);
|
|
8029
|
+
if (!entry)
|
|
8030
|
+
continue;
|
|
8031
|
+
if (await this.shouldSkipLoadedEntryForBuiltin(entry))
|
|
8032
|
+
continue;
|
|
8033
|
+
if (!(await this.verifyEntrySignatureForDb(entry, entry.encryptedData))) {
|
|
8034
|
+
this.logger.warn(`Invalid signature for entry ${entry.id}, skipping`);
|
|
8035
|
+
continue;
|
|
8036
|
+
}
|
|
8037
|
+
changes.push(await this.tenant.decryptPayload(entry.encryptedData, entry.decryptionKeyId));
|
|
8038
|
+
if (meta.entryType === "doc_create" || decryptionKeyId === null) {
|
|
8039
|
+
decryptionKeyId = entry.decryptionKeyId;
|
|
8040
|
+
}
|
|
8041
|
+
}
|
|
8042
|
+
if (changes.length === 0)
|
|
8043
|
+
return null;
|
|
8044
|
+
return {
|
|
8045
|
+
docId,
|
|
8046
|
+
changes,
|
|
8047
|
+
decryptionKeyId: decryptionKeyId ?? replay[0].decryptionKeyId,
|
|
8048
|
+
heads: this.replayHeads(replay),
|
|
8049
|
+
estimate: (0, documentLoadGuard_1.estimateDocumentLoad)(null, changes),
|
|
8050
|
+
};
|
|
8051
|
+
}
|
|
8052
|
+
/**
|
|
8053
|
+
* Deletes a document this process cannot load, from a lifecycle change built
|
|
8054
|
+
* elsewhere (see {@link getDocumentPayloads}): an Automerge change on top of
|
|
8055
|
+
* the document's current heads that touches nothing but `_lastModified` and
|
|
8056
|
+
* `_attachments` at the root, as `deleteDocument()` would write it. The
|
|
8057
|
+
* change is checked for exactly that before it is signed, encrypted and
|
|
8058
|
+
* stored as a `doc_delete` entry; the body stays in the history, as with
|
|
8059
|
+
* every delete.
|
|
8060
|
+
*
|
|
8061
|
+
* `documentUsernameHash` is the document's `username_hash` field, if any
|
|
8062
|
+
* (the built-in user databases decide who may delete by it).
|
|
8063
|
+
*/
|
|
8064
|
+
async deleteDocumentWithChange(docId, lifecycleChange, options = {}) {
|
|
8065
|
+
this.assertWritable("deleteDocumentWithChange");
|
|
8066
|
+
const allEntryMetadata = await this.scanAllMetadata(this.store, { docId });
|
|
8067
|
+
const replay = allEntryMetadata.filter((meta) => this.isDocumentReplayEntry(meta));
|
|
8068
|
+
if (replay.length === 0)
|
|
8069
|
+
throw new errors_1.DocumentNotFoundError(docId);
|
|
8070
|
+
if (await this.isAclEnforced()) {
|
|
8071
|
+
throw new Error(`Document ${docId} cannot be deleted without loading it while access control is enforced`);
|
|
8072
|
+
}
|
|
8073
|
+
const latest = [...replay].sort((a, b) => a.createdAt - b.createdAt).at(-1);
|
|
8074
|
+
if (latest.entryType === "doc_delete")
|
|
8075
|
+
return; // already deleted
|
|
8076
|
+
const decoded = automerge_adapter_1.Automerge.decodeChange(lifecycleChange);
|
|
8077
|
+
const heads = this.replayHeads(replay);
|
|
8078
|
+
const deps = [...(decoded.deps ?? [])].sort();
|
|
8079
|
+
if (deps.length !== heads.length || deps.some((dep, index) => dep !== [...heads].sort()[index])) {
|
|
8080
|
+
throw new Error(`The delete change for ${docId} does not build on the document's current heads`);
|
|
8081
|
+
}
|
|
8082
|
+
const allowedKeys = new Set(["_lastModified", "_attachments"]);
|
|
8083
|
+
for (const op of decoded.ops ?? []) {
|
|
8084
|
+
if (op.obj !== "_root" || typeof op.key !== "string" || !allowedKeys.has(op.key)) {
|
|
8085
|
+
throw new Error(`The delete change for ${docId} touches more than _lastModified and _attachments`);
|
|
8086
|
+
}
|
|
8087
|
+
}
|
|
8088
|
+
await this.assertLifecycleMutationAllowed("doc_delete", undefined, undefined, options.documentUsernameHash ?? null, docId);
|
|
8089
|
+
const createMeta = replay.find((meta) => meta.entryType === "doc_create") ?? replay[0];
|
|
8090
|
+
const decryptionKeyId = createMeta.decryptionKeyId;
|
|
8091
|
+
const now = (0, timeSource_1.semanticNow)();
|
|
8092
|
+
const automergeHash = decoded.hash;
|
|
8093
|
+
const encryptedPayload = await this.tenant.encryptPayload(lifecycleChange, decryptionKeyId);
|
|
8094
|
+
const contentHash = await (0, idGeneration_1.computeContentHash)(encryptedPayload, this.getSubtle());
|
|
8095
|
+
const entryId = await (0, idGeneration_1.generateDocEntryId)(docId, automergeHash, decoded.deps ?? [], this.getSubtle());
|
|
8096
|
+
const dependencyIds = await this.ensureAutomergeDepsResolved(docId, decoded.deps ?? []);
|
|
8097
|
+
const currentUser = await this.tenant.getCurrentUserId();
|
|
8098
|
+
const signature = await this.tenant.signPayload(encryptedPayload);
|
|
8099
|
+
const entryMetadata = {
|
|
8100
|
+
entryType: "doc_delete",
|
|
8101
|
+
id: entryId,
|
|
8102
|
+
contentHash,
|
|
8103
|
+
docId,
|
|
8104
|
+
dependencyIds,
|
|
8105
|
+
createdAt: now,
|
|
8106
|
+
createdByPublicKey: currentUser.userSigningPublicKey,
|
|
8107
|
+
decryptionKeyId,
|
|
8108
|
+
signature,
|
|
8109
|
+
originalSize: lifecycleChange.length,
|
|
8110
|
+
encryptedSize: encryptedPayload.length,
|
|
8111
|
+
entryVersion: types_1.CURRENT_STORE_ENTRY_VERSION,
|
|
8112
|
+
};
|
|
8113
|
+
entryMetadata.metadataSignature = await this.computeEntryMetadataSignature(entryMetadata);
|
|
8114
|
+
await this.putLocalEntries([{ ...entryMetadata, encryptedData: encryptedPayload }]);
|
|
8115
|
+
this.registerAutomergeHashMapping(docId, automergeHash, entryId);
|
|
8116
|
+
this.docCache.delete(docId);
|
|
8117
|
+
this.dirtyDocIds.delete(docId);
|
|
8118
|
+
const awaitingWitness = (0, storeEntryTime_1.isProvisional)(entryMetadata);
|
|
8119
|
+
this.updateIndex(docId, now, true, decryptionKeyId, "visible", awaitingWitness, (0, storeEntryTime_1.isVersioned)(entryMetadata) && !awaitingWitness, true);
|
|
8120
|
+
this.cacheMetaDirty = true;
|
|
8121
|
+
this.cacheManager?.markDirty();
|
|
8122
|
+
this.logger.info(`Document ${docId} deleted from a prepared change`);
|
|
8123
|
+
}
|
|
8124
|
+
/** Automerge hashes of the replay entries nothing else depends on: the document's heads. */
|
|
8125
|
+
replayHeads(replay) {
|
|
8126
|
+
const dependedOn = new Set(replay.flatMap((meta) => meta.dependencyIds));
|
|
8127
|
+
const heads = [];
|
|
8128
|
+
for (const meta of replay) {
|
|
8129
|
+
if (dependedOn.has(meta.id))
|
|
8130
|
+
continue;
|
|
8131
|
+
const parsed = (0, idGeneration_1.parseDocEntryId)(meta.id);
|
|
8132
|
+
if (parsed)
|
|
8133
|
+
heads.push(parsed.automergeHash);
|
|
8134
|
+
}
|
|
8135
|
+
return heads;
|
|
8136
|
+
}
|
|
7991
8137
|
/**
|
|
7992
8138
|
* Bulk-delete documents in a single append-only store write.
|
|
7993
8139
|
*
|
|
@@ -8449,7 +8595,7 @@ class BaseMindooDB {
|
|
|
8449
8595
|
const applyAll = (automergeDoc) => {
|
|
8450
8596
|
for (const [key, value] of Object.entries(update.set ?? {})) {
|
|
8451
8597
|
if (value !== undefined) {
|
|
8452
|
-
this.
|
|
8598
|
+
this.assignValue(automergeDoc, automergeDoc, key, [key], value);
|
|
8453
8599
|
}
|
|
8454
8600
|
}
|
|
8455
8601
|
for (const key of update.unset ?? []) {
|
|
@@ -9330,7 +9476,7 @@ class BaseMindooDB {
|
|
|
9330
9476
|
}
|
|
9331
9477
|
continue;
|
|
9332
9478
|
}
|
|
9333
|
-
this.
|
|
9479
|
+
this.assignValue(automergeDoc, parent, key, op.path, op.value);
|
|
9334
9480
|
}
|
|
9335
9481
|
}
|
|
9336
9482
|
validateTextPatch(patch) {
|
|
@@ -9483,6 +9629,36 @@ class BaseMindooDB {
|
|
|
9483
9629
|
* (integers beyond the safe range, see hydrateTypedValues) are assigned
|
|
9484
9630
|
* once more on their own.
|
|
9485
9631
|
*/
|
|
9632
|
+
/**
|
|
9633
|
+
* Writes `raw` (a plain or `MindooValue`-tagged value) at `key` of `parent`.
|
|
9634
|
+
* A long string (see TEXT_ASSIGN_SPLICE_THRESHOLD) written over existing
|
|
9635
|
+
* collaborative text edits that text: only the changed part is stored as a
|
|
9636
|
+
* splice, so the field stays text, merges with concurrent typing, and is not
|
|
9637
|
+
* rewritten character by character. Any other value (a short string, an
|
|
9638
|
+
* atomic string, a number, an object, rich text) is assigned as before.
|
|
9639
|
+
*/
|
|
9640
|
+
assignValue(automergeDoc, parent, key, path, raw) {
|
|
9641
|
+
const current = parent?.[key];
|
|
9642
|
+
const textValue = typeof raw === "string"
|
|
9643
|
+
? raw
|
|
9644
|
+
: raw !== null &&
|
|
9645
|
+
typeof raw === "object" &&
|
|
9646
|
+
!Array.isArray(raw) &&
|
|
9647
|
+
raw[values_1.MINDOO_VALUE_TAG] === "text"
|
|
9648
|
+
? (0, values_1.parseTypedValue)(raw).value
|
|
9649
|
+
: null;
|
|
9650
|
+
if (textValue !== null &&
|
|
9651
|
+
typeof current === "string" &&
|
|
9652
|
+
Math.max(current.length, textValue.length) >= values_1.TEXT_ASSIGN_SPLICE_THRESHOLD &&
|
|
9653
|
+
!this.isRichTextAt(automergeDoc, path)) {
|
|
9654
|
+
const splice = (0, ChangeDocDraft_1.diffTextSplice)(current, textValue);
|
|
9655
|
+
if (splice) {
|
|
9656
|
+
automerge_adapter_1.Automerge.splice(automergeDoc, path, splice.index, splice.deleteCount, splice.insert);
|
|
9657
|
+
}
|
|
9658
|
+
return;
|
|
9659
|
+
}
|
|
9660
|
+
this.assignHydrated(parent, key, this.hydrateTypedValues(raw));
|
|
9661
|
+
}
|
|
9486
9662
|
assignHydrated(container, key, hydrated) {
|
|
9487
9663
|
container[key] = this.withoutNestedFloats(hydrated);
|
|
9488
9664
|
this.restoreNestedFloats(container[key], hydrated);
|
|
@@ -9520,7 +9696,15 @@ class BaseMindooDB {
|
|
|
9520
9696
|
this.restoreNestedFloats(target[key], entry, depth + 1);
|
|
9521
9697
|
}
|
|
9522
9698
|
}
|
|
9523
|
-
hydrateTypedValues(value, depth = 0) {
|
|
9699
|
+
hydrateTypedValues(value, depth = 0, options = {}) {
|
|
9700
|
+
// Large plain strings are atomic: collaborative text costs one Automerge
|
|
9701
|
+
// operation per character (see LARGE_STRING_ATOMIC_THRESHOLD). Restores copy
|
|
9702
|
+
// values back with their original types and pass largeStringsAtomic: false.
|
|
9703
|
+
if (typeof value === "string" &&
|
|
9704
|
+
value.length >= values_1.LARGE_STRING_ATOMIC_THRESHOLD &&
|
|
9705
|
+
options.largeStringsAtomic !== false) {
|
|
9706
|
+
return new automerge_adapter_1.Automerge.ImmutableString(value);
|
|
9707
|
+
}
|
|
9524
9708
|
// Automerge stores a JS integer as int64, clamps larger ones (1e20 became
|
|
9525
9709
|
// 9223372036854775807, which no reader can decode as a number) and reads
|
|
9526
9710
|
// 2^53 − 1 and beyond back as BigInt: a 64-bit float holds what was written.
|
|
@@ -9542,7 +9726,7 @@ class BaseMindooDB {
|
|
|
9542
9726
|
// Array.from, not map: map keeps the realm of an array that came from
|
|
9543
9727
|
// another realm (structuredClone in a VM context, another frame), and
|
|
9544
9728
|
// Automerge only assigns arrays that pass `instanceof Array`.
|
|
9545
|
-
return Array.from(value, (entry) => this.hydrateTypedValues(entry, depth + 1));
|
|
9729
|
+
return Array.from(value, (entry) => this.hydrateTypedValues(entry, depth + 1, options));
|
|
9546
9730
|
}
|
|
9547
9731
|
const record = value;
|
|
9548
9732
|
if (Object.prototype.hasOwnProperty.call(record, values_1.MINDOO_VALUE_TAG)) {
|
|
@@ -9554,12 +9738,15 @@ class BaseMindooDB {
|
|
|
9554
9738
|
return new automerge_adapter_1.Automerge.Counter(typed.value);
|
|
9555
9739
|
case "timestamp":
|
|
9556
9740
|
return (0, values_1.toTimestampDate)(typed.value, 'Typed value "timestamp"');
|
|
9741
|
+
case "text":
|
|
9742
|
+
// Collaborative text whatever its length.
|
|
9743
|
+
return typed.value;
|
|
9557
9744
|
}
|
|
9558
9745
|
}
|
|
9559
9746
|
const result = {};
|
|
9560
9747
|
for (const [key, entry] of Object.entries(record)) {
|
|
9561
9748
|
if (entry !== undefined) {
|
|
9562
|
-
result[key] = this.hydrateTypedValues(entry, depth + 1);
|
|
9749
|
+
result[key] = this.hydrateTypedValues(entry, depth + 1, options);
|
|
9563
9750
|
}
|
|
9564
9751
|
}
|
|
9565
9752
|
return result;
|
|
@@ -9781,7 +9968,8 @@ class BaseMindooDB {
|
|
|
9781
9968
|
}
|
|
9782
9969
|
applyJsonPatchOperations(automergeDoc, patch) {
|
|
9783
9970
|
for (const operation of patch.set ?? []) {
|
|
9784
|
-
this.
|
|
9971
|
+
const parent = this.ensureJsonParentAtPath(automergeDoc, operation.path);
|
|
9972
|
+
this.assignValue(automergeDoc, parent, operation.path[operation.path.length - 1], operation.path, structuredClone(operation.value));
|
|
9785
9973
|
}
|
|
9786
9974
|
for (const operation of patch.unset ?? []) {
|
|
9787
9975
|
this.unsetJsonValueAtPath(automergeDoc, operation.path);
|
|
@@ -11115,6 +11303,49 @@ class BaseMindooDB {
|
|
|
11115
11303
|
await prefetchFrom(i + 1);
|
|
11116
11304
|
}
|
|
11117
11305
|
catch (error) {
|
|
11306
|
+
if ((0, documentLoadGuard_1.isDocumentTooLargeError)(error)) {
|
|
11307
|
+
// Too large to load in this process (setDocumentLoadBudget): emit
|
|
11308
|
+
// it like an inaccessible document, so consumers (the summary
|
|
11309
|
+
// update behind every query) drop it and go on instead of failing
|
|
11310
|
+
// for every other document of the database.
|
|
11311
|
+
this.logger.warn(`Skipping document ${entry.docId}: ${error.message}`);
|
|
11312
|
+
yieldedDocuments++;
|
|
11313
|
+
yield {
|
|
11314
|
+
doc: this.buildInaccessibleDoc(entry),
|
|
11315
|
+
cursor: {
|
|
11316
|
+
changeSeq: entry.changeSeq,
|
|
11317
|
+
lastModified: entry.lastModified,
|
|
11318
|
+
docId: entry.docId,
|
|
11319
|
+
feedEpoch: this.changeFeedEpoch,
|
|
11320
|
+
},
|
|
11321
|
+
};
|
|
11322
|
+
await prefetchFrom(i + 1);
|
|
11323
|
+
continue;
|
|
11324
|
+
}
|
|
11325
|
+
if ((0, errors_1.isSymmetricKeyNotFound)(error)) {
|
|
11326
|
+
// The index holds the document as readable, but a key it needs is
|
|
11327
|
+
// not here (delegation per account: one group of the database is
|
|
11328
|
+
// shared with this user, another is not; a key series that arrives
|
|
11329
|
+
// only partly). Treat it like the missing-key case of the sync:
|
|
11330
|
+
// drop any plaintext, mark the entry inaccessible, so a key that
|
|
11331
|
+
// arrives later reveals it again, and emit an inaccessible
|
|
11332
|
+
// tombstone, so the summary, full-text and view updates go on with
|
|
11333
|
+
// the other documents instead of failing every query.
|
|
11334
|
+
this.logger.warn(`Skipping document ${entry.docId}: ${error.message}`);
|
|
11335
|
+
await this.markUndecryptableDocument(entry);
|
|
11336
|
+
yieldedDocuments++;
|
|
11337
|
+
yield {
|
|
11338
|
+
doc: this.buildInaccessibleDoc(entry),
|
|
11339
|
+
cursor: {
|
|
11340
|
+
changeSeq: entry.changeSeq,
|
|
11341
|
+
lastModified: entry.lastModified,
|
|
11342
|
+
docId: entry.docId,
|
|
11343
|
+
feedEpoch: this.changeFeedEpoch,
|
|
11344
|
+
},
|
|
11345
|
+
};
|
|
11346
|
+
await prefetchFrom(i + 1);
|
|
11347
|
+
continue;
|
|
11348
|
+
}
|
|
11118
11349
|
this.logger.error(`Error processing document ${entry.docId}:`, error);
|
|
11119
11350
|
// Stop processing on error
|
|
11120
11351
|
throw error;
|
|
@@ -12091,6 +12322,64 @@ class BaseMindooDB {
|
|
|
12091
12322
|
async revealHistory(doc, recipients, options) {
|
|
12092
12323
|
return this.mutateRecipients(doc, "reveal", recipients, options);
|
|
12093
12324
|
}
|
|
12325
|
+
async recipientsNeedRepair(doc) {
|
|
12326
|
+
const keyId = doc.getDecryptionKeyId();
|
|
12327
|
+
if (!(0, sealedTypes_1.isSealedKeyId)(keyId) || (0, sealedTypes_1.groupKeyDocIdOf)(keyId, doc.getId()) !== undefined)
|
|
12328
|
+
return null;
|
|
12329
|
+
const tenant = this.tenant;
|
|
12330
|
+
if (tenant.getSealedGenerations(keyId).length === 0)
|
|
12331
|
+
return null;
|
|
12332
|
+
const internalDoc = this.getCachedDocument(doc.getId()) ?? (await this.loadDocumentInternal(doc.getId()));
|
|
12333
|
+
if (!internalDoc || internalDoc.isDeleted)
|
|
12334
|
+
return null;
|
|
12335
|
+
const blocks = (await this.scanAllMetadata(this.store, { docId: doc.getId() }))
|
|
12336
|
+
.map((entry) => entry.recipients)
|
|
12337
|
+
.filter((block) => !!block && (0, sealedTypes_1.hasRecipientWraps)(block));
|
|
12338
|
+
const newest = (0, recipients_1.newestRecipientBlock)(await this.scanAllMetadata(this.store, { docId: doc.getId() }));
|
|
12339
|
+
if (!newest)
|
|
12340
|
+
return null;
|
|
12341
|
+
const topBundles = new Set(blocks.filter((block) => block.epoch === newest.epoch).map((block) => block.bundle));
|
|
12342
|
+
const wrapped = new Set((0, sealedTypes_1.allRecipientWraps)(newest).map((wrap) => wrap.keyFingerprint));
|
|
12343
|
+
const map = (0, recipients_1.readEncryptFor)(internalDoc.doc);
|
|
12344
|
+
const missing = [];
|
|
12345
|
+
const stale = [];
|
|
12346
|
+
const activeSpecs = [];
|
|
12347
|
+
const activeLabels = [];
|
|
12348
|
+
for (const [id, entry] of Object.entries(map)) {
|
|
12349
|
+
const label = entry.label ?? id;
|
|
12350
|
+
if (entry.removedAt) {
|
|
12351
|
+
if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint))
|
|
12352
|
+
stale.push(label);
|
|
12353
|
+
continue;
|
|
12354
|
+
}
|
|
12355
|
+
if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint))
|
|
12356
|
+
continue;
|
|
12357
|
+
activeSpecs.push(entry.kind === "device" ? { device: entry.keyFingerprint ?? id, label: entry.label } : label);
|
|
12358
|
+
activeLabels.push(label);
|
|
12359
|
+
}
|
|
12360
|
+
if (activeSpecs.length) {
|
|
12361
|
+
// The stored fingerprint may be an older User-Key generation: count the
|
|
12362
|
+
// reader as wrapped when the newest block wraps their current key.
|
|
12363
|
+
const resolved = await (0, recipients_1.resolveRecipientSpecs)({
|
|
12364
|
+
tenant,
|
|
12365
|
+
specs: activeSpecs,
|
|
12366
|
+
options: { includeSelf: false, strict: false },
|
|
12367
|
+
addedBy: "",
|
|
12368
|
+
now: (0, timeSource_1.semanticNow)(),
|
|
12369
|
+
});
|
|
12370
|
+
const current = new Set(resolved.targets.filter((target) => wrapped.has(target.keyFingerprint)).map((target) => target.id));
|
|
12371
|
+
for (const [index, label] of activeLabels.entries()) {
|
|
12372
|
+
const target = resolved.targets.find((candidate) => candidate.id === label || candidate.label === label || candidate.stableId === label);
|
|
12373
|
+
if (!target || !current.has(target.id))
|
|
12374
|
+
missing.push(activeLabels[index]);
|
|
12375
|
+
}
|
|
12376
|
+
}
|
|
12377
|
+
const need = { forked: topBundles.size > 1, missing, stale };
|
|
12378
|
+
return need.forked || missing.length || stale.length ? need : null;
|
|
12379
|
+
}
|
|
12380
|
+
async repairRecipients(doc, options) {
|
|
12381
|
+
return this.mutateRecipients(doc, "repair", [], options);
|
|
12382
|
+
}
|
|
12094
12383
|
async canChangeRecipients(doc, next) {
|
|
12095
12384
|
const after = { ...doc.getData() };
|
|
12096
12385
|
after[sealedTypes_1.ENCRYPT_FOR_FIELD] = {
|
|
@@ -12117,16 +12406,19 @@ class BaseMindooDB {
|
|
|
12117
12406
|
const now = (0, timeSource_1.semanticNow)();
|
|
12118
12407
|
const signer = options?.signingKeyPair?.publicKey ??
|
|
12119
12408
|
(await this.tenant.getCurrentUserId()).userSigningPublicKey;
|
|
12120
|
-
|
|
12121
|
-
|
|
12122
|
-
|
|
12123
|
-
|
|
12124
|
-
|
|
12125
|
-
|
|
12126
|
-
|
|
12127
|
-
|
|
12128
|
-
|
|
12129
|
-
|
|
12409
|
+
// A repair names nobody: it re-seals for the readers already on the list.
|
|
12410
|
+
const resolved = mode === "repair"
|
|
12411
|
+
? { targets: [], skipped: [] }
|
|
12412
|
+
: await (0, recipients_1.resolveRecipientSpecs)({
|
|
12413
|
+
tenant,
|
|
12414
|
+
specs,
|
|
12415
|
+
options: {
|
|
12416
|
+
includeSelf: mode === "set" ? options?.includeSelf !== false : false,
|
|
12417
|
+
strict: options?.strict,
|
|
12418
|
+
},
|
|
12419
|
+
addedBy: signer,
|
|
12420
|
+
now,
|
|
12421
|
+
});
|
|
12130
12422
|
const currentMap = (0, recipients_1.readEncryptFor)(internalDoc.doc);
|
|
12131
12423
|
const activeIds = new Set(Object.entries(currentMap)
|
|
12132
12424
|
.filter(([, e]) => !e.removedAt)
|
|
@@ -12180,7 +12472,9 @@ class BaseMindooDB {
|
|
|
12180
12472
|
const withoutHistory = (mode === "add" || mode === "set") &&
|
|
12181
12473
|
addedTargets.length > 0 &&
|
|
12182
12474
|
(options?.history ?? sealedTypes_1.DEFAULT_RECIPIENT_HISTORY) === "none";
|
|
12183
|
-
|
|
12475
|
+
// A repair (after concurrent recipient changes) always seals a new
|
|
12476
|
+
// generation for exactly the current readers.
|
|
12477
|
+
const rotate = removedStableIds.length > 0 || withoutHistory || mode === "repair";
|
|
12184
12478
|
const heldSeries = tenant.getSealedSeries
|
|
12185
12479
|
? tenant.getSealedSeries(internalDoc.decryptionKeyId)
|
|
12186
12480
|
: tenant
|
|
@@ -12285,6 +12579,8 @@ class BaseMindooDB {
|
|
|
12285
12579
|
generations,
|
|
12286
12580
|
targets: remaining,
|
|
12287
12581
|
epoch,
|
|
12582
|
+
// Keys of concurrent branches travel along, for readers added later.
|
|
12583
|
+
extra: tenant.getSealedForkKeys(internalDoc.decryptionKeyId),
|
|
12288
12584
|
});
|
|
12289
12585
|
tenant.rememberSealedGenerations(internalDoc.decryptionKeyId, series.map((entry) => entry.key), recipientsBlock, series.map((entry) => entry.epoch));
|
|
12290
12586
|
const headsBeforeChange = automerge_adapter_1.Automerge.getHeads(internalDoc.doc);
|
|
@@ -13020,6 +13316,8 @@ class BaseMindooDB {
|
|
|
13020
13316
|
this.logger.debug(`Planner returned ${entriesToLoad.length} replay entries for ${docId}; diagnostics=${JSON.stringify(materializationPlan.diagnostics || {})}`);
|
|
13021
13317
|
// Load the snapshot first if we have one
|
|
13022
13318
|
let doc = undefined;
|
|
13319
|
+
// The snapshot bytes the document was loaded from, for the load budget.
|
|
13320
|
+
let loadedSnapshotBytes = null;
|
|
13023
13321
|
if (startFromSnapshot && snapshotMeta) {
|
|
13024
13322
|
this.logger.debug(`Loading snapshot for document ${docId}`);
|
|
13025
13323
|
const snapshotLoadStartedAt = Date.now();
|
|
@@ -13056,9 +13354,13 @@ class BaseMindooDB {
|
|
|
13056
13354
|
// This deserializes a full document snapshot from binary data
|
|
13057
13355
|
// According to Automerge docs: load() is equivalent to init() followed by loadIncremental()
|
|
13058
13356
|
this.logger.debug(`Loading snapshot into Automerge document`);
|
|
13357
|
+
// A document too large for this process must not reach Automerge:
|
|
13358
|
+
// a panicking load ends the wasm instance for every document.
|
|
13359
|
+
(0, documentLoadGuard_1.assertDocumentLoadWithinBudget)(docId, decryptedSnapshot, []);
|
|
13059
13360
|
const automergeStartedAt = Date.now();
|
|
13060
13361
|
doc = automerge_adapter_1.Automerge.load(decryptedSnapshot);
|
|
13061
13362
|
automergeTime += Date.now() - automergeStartedAt;
|
|
13363
|
+
loadedSnapshotBytes = decryptedSnapshot;
|
|
13062
13364
|
if (this.isDebugEnabled())
|
|
13063
13365
|
this.logger.debug(`Successfully loaded snapshot, document heads: ${JSON.stringify(automerge_adapter_1.Automerge.getHeads(doc))}`);
|
|
13064
13366
|
// Mandatory snapshot-head verification (docs/accesscontrol.md §10): the
|
|
@@ -13068,6 +13370,7 @@ class BaseMindooDB {
|
|
|
13068
13370
|
if (!(0, materializationGuard_1.snapshotHeadsMatch)(automerge_adapter_1.Automerge.getHeads(doc), snapshotData.snapshotHeadHashes)) {
|
|
13069
13371
|
this.logger.warn(`Snapshot ${snapshotData.id} heads do not match declared snapshotHeadHashes, loading from scratch`);
|
|
13070
13372
|
doc = undefined;
|
|
13373
|
+
loadedSnapshotBytes = null;
|
|
13071
13374
|
startFromSnapshot = false;
|
|
13072
13375
|
}
|
|
13073
13376
|
else {
|
|
@@ -13191,6 +13494,7 @@ class BaseMindooDB {
|
|
|
13191
13494
|
// Batch apply all changes at once - Automerge handles dependency ordering
|
|
13192
13495
|
if (changeBytes.length > 0) {
|
|
13193
13496
|
this.logger.debug(`Applying ${changeBytes.length} changes to document ${docId} using applyChangesInSlices`);
|
|
13497
|
+
(0, documentLoadGuard_1.assertDocumentLoadWithinBudget)(docId, loadedSnapshotBytes, changeBytes);
|
|
13194
13498
|
try {
|
|
13195
13499
|
const automergeStartedAt = Date.now();
|
|
13196
13500
|
// In slices: one huge batch can exhaust Automerge's memory
|
|
@@ -13477,6 +13781,23 @@ class BaseMindooDB {
|
|
|
13477
13781
|
* never materialized) and `getHeads() === []` — backed by an empty Automerge
|
|
13478
13782
|
* document so it never touches the underlying ciphertext or the document cache.
|
|
13479
13783
|
*/
|
|
13784
|
+
/**
|
|
13785
|
+
* A document whose key is missing although the index holds it as readable:
|
|
13786
|
+
* forget its plaintext and flip the index entry to `"inaccessible"` (as the
|
|
13787
|
+
* missing-key branch of the sync does), so listings drop it and a key that
|
|
13788
|
+
* arrives later reveals it through `reconcileKeyVisibility`.
|
|
13789
|
+
*/
|
|
13790
|
+
async markUndecryptableDocument(entry) {
|
|
13791
|
+
this.noteInaccessibleDocument(entry.docId);
|
|
13792
|
+
const position = this.getDocIndexPosition(entry.docId);
|
|
13793
|
+
const current = position === undefined ? undefined : this.index[position];
|
|
13794
|
+
if (current?.accessState !== "visible")
|
|
13795
|
+
return;
|
|
13796
|
+
await this.purgeMaterializedDocument(entry.docId);
|
|
13797
|
+
this.updateIndex(entry.docId, current.lastModified, true, current.decryptionKeyId, "inaccessible");
|
|
13798
|
+
this.cacheMetaDirty = true;
|
|
13799
|
+
this.cacheManager?.markDirty();
|
|
13800
|
+
}
|
|
13480
13801
|
buildInaccessibleDoc(entry) {
|
|
13481
13802
|
const internalDoc = {
|
|
13482
13803
|
id: entry.docId,
|