@vrtmrz/livesync-commonlib 0.1.42 → 0.1.44

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 CHANGED
@@ -26,6 +26,7 @@ The package is ESM-only and declares Node 20 or later. Browser entry points are
26
26
  | -------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
27
27
  | `@vrtmrz/livesync-commonlib` | `DirectFileManipulator` for integrations which access CouchDB directly | Deliberately small, but its high-level lifecycle and file-operation semantics are not final |
28
28
  | `@vrtmrz/livesync-commonlib/context` | Instance-owned events, translation injection, and host-neutral standard-I/O types | Focused, package-tested pre-1.0 contract |
29
+ | `@vrtmrz/livesync-commonlib/diagnostics` | Read-only Usage and integrity inspection, name projection, and reports | Focused pre-1.0 diagnostic contract |
29
30
  | `@vrtmrz/livesync-commonlib/hashing` | Chunk ID calculation and exact file-content hashing | Focused, package-tested pre-1.0 contract |
30
31
  | `@vrtmrz/livesync-commonlib/browser` | Rooted File System Access API storage | Focused, package-tested pre-1.0 contract |
31
32
  | `@vrtmrz/livesync-commonlib/node` | Rooted Node storage, Node standard I/O, and selected Node capabilities | Supported platform façade; keeps Node-only dependencies behind an explicit boundary |
@@ -119,6 +120,45 @@ See [the settings lifecycle guide](docs/settings-lifecycle.md) before initialisi
119
120
 
120
121
  The focused Setup URI entry offers an Ephemeral mode bound to the current fixed seven-day window and a Persistent mode compatible with existing readers. Both use the same URI structure. See [the Setup URI sharing guide](docs/setup-uri.md) for the availability boundary, import behaviour, and compatibility limits.
121
122
 
123
+ ## Database diagnostics
124
+
125
+ The focused `/diagnostics` entry provides read-only Usage and integrity reports, with original names or temporary pseudonyms selected by the host for each run. Integrity inspection covers normal-file Metadata, current conflict branches, and content comparisons for suspect groups in the local database and, by default, CouchDB; the host can exclude the remote source for one run. See [Database diagnostics](docs/database-diagnostics.md) for coverage, progress, cancellation, pseudonym lookup, and privacy boundaries.
126
+
127
+ Integrity Markdown places a compact state summary and review index before all findings, while retaining each observation and its follow-up references. This formatting does not change the projected JSON data or schema; see [the Markdown field guide](docs/database-diagnostics.md#compact-integrity-markdown-report) for the meaning and limits of its review index.
128
+
129
+ ```typescript
130
+ import {
131
+ analyseDatabaseUsage,
132
+ createDiagnosticNameMapper,
133
+ createLocalDiagnosticSource,
134
+ formatUsageTSV,
135
+ parseDiagnosticPathToken,
136
+ projectUsageReport,
137
+ } from '@vrtmrz/livesync-commonlib/diagnostics';
138
+
139
+ const result = await analyseDatabaseUsage({ source: createLocalDiagnosticSource(localPouchDB) });
140
+ const mapper = createDiagnosticNameMapper('pseudonym');
141
+ const report = projectUsageReport(result, mapper);
142
+ if (report.status === 'complete') {
143
+ const tsv = formatUsageTSV(report);
144
+ // Present the report through the host's own UI or output stream.
145
+ }
146
+ ```
147
+
148
+ Path pseudonyms include the report salt. A consumer can parse that token and supply its salt to a new mapper for a targeted follow-up against exact local Metadata paths:
149
+
150
+ ```typescript
151
+ const pathToken = report.rows[0]?.path;
152
+ const parsed = pathToken === undefined ? undefined : parseDiagnosticPathToken(pathToken);
153
+ if (parsed) {
154
+ const followUpMapper = createDiagnosticNameMapper('pseudonym', parsed.salt);
155
+ const candidateToken = followUpMapper.path(storedVaultRelativePath);
156
+ // Compare this token with the path pseudonym on this device.
157
+ }
158
+ ```
159
+
160
+ The parser accepts only complete path tokens; it does not reverse them to recover a path. The salt is public, so a guessed path can be checked. Older ordinal pseudonyms have no corresponding lookup.
161
+
122
162
  ## Chunk ID calculation
123
163
 
124
164
  The `/hashing` entry exports `HashManager` and its `HashManagerCoreOptions` type. It uses the same implementation as database writes, including legacy algorithms and independent ID keys. Hosts supply their settings service and await `initialise()` before calling `computeHash(piece)`.
@@ -2,9 +2,18 @@ import type { EntryHasPath, FilePathWithPrefix } from "./types.js";
2
2
  import type { IPathService } from "../services/base/IService.js";
3
3
  /** Check the complete source listing before an operation can discard either database. */
4
4
  export declare function assertUniqueStoragePathIdentities(paths: Iterable<FilePathWithPrefix>, pathService: Pick<IPathService, "path2id">): Promise<void>;
5
- /** Distinct Metadata documents must not be merged by a change of path identity. */
5
+ /**
6
+ * Distinct Metadata documents must not be merged by a change of path identity.
7
+ * Callers must enumerate entries with `conflicts: true` so unresolved revisions remain visible.
8
+ * `requireMatchingIds: false` is reserved for preflight checks before replacing the local database;
9
+ * only that mode excludes conflict-free logical deletions from collision checks.
10
+ */
6
11
  export declare function assertMetadataPathIdentities(entries: AsyncIterable<EntryHasPath & {
7
12
  _id: string;
13
+ deleted?: boolean;
14
+ _conflicts?: string[];
8
15
  }> | Iterable<EntryHasPath & {
9
16
  _id: string;
17
+ deleted?: boolean;
18
+ _conflicts?: string[];
10
19
  }>, pathService: Pick<IPathService, "path2id">, requireMatchingIds: boolean): Promise<void>;
@@ -16,6 +16,7 @@ async function assertUniqueStoragePathIdentities(paths, pathService) {
16
16
  async function assertMetadataPathIdentities(entries, pathService, requireMatchingIds) {
17
17
  const identities = /* @__PURE__ */ new Map();
18
18
  for await (const entry of entries) {
19
+ if (!requireMatchingIds && entry.deleted === true && !entry._conflicts?.length) continue;
19
20
  const path = id2path_base(entry._id, entry);
20
21
  const id = await pathService.path2id(path);
21
22
  const previous = identities.get(id);
@@ -0,0 +1,15 @@
1
+ import { type RemoteDBSettings } from "../common/types.js";
2
+ import { type DiagnosticDatabaseSource } from "./types.js";
3
+ export interface CouchDBDiagnosticSourceOptions {
4
+ settings: RemoteDBSettings;
5
+ fetch(request: string, options: RequestInit): Promise<Response>;
6
+ signal?: AbortSignal;
7
+ }
8
+ /**
9
+ * Open an operation-owned HTTP reader. All requests are GETs, including the
10
+ * Security Seed lookup; the replication connection and its setup paths are
11
+ * deliberately absent from this boundary.
12
+ */
13
+ export declare function createCouchDBDiagnosticSource({ settings: originalSettings, fetch, signal, }: CouchDBDiagnosticSourceOptions): DiagnosticDatabaseSource & {
14
+ close(): Promise<void>;
15
+ };
@@ -0,0 +1,202 @@
1
+ import { DOCID_SYNC_PARAMETERS } from "../common/types.js";
2
+ import { isObfuscatedEntry, parseHeaderValues } from "../common/utils.js";
3
+ import { getConfiguredFunctionsForEncryption, isEncryptedMeta } from "../pouchdb/encryption.js";
4
+ import { isPathProbablyObfuscated } from "octagonal-wheels/encryption/encryption";
5
+ import { decompressDoc } from "../pouchdb/compress.js";
6
+ import { AuthorizationHeaderGenerator, generateCredentialObject } from "../replication/httplib.js";
7
+ import { base64ToArrayBuffer } from "../string_and_binary/convert.js";
8
+ import { DiagnosticReadError } from "./types.js";
9
+ const MAX_BULK_DOCUMENTS = 64;
10
+ const MAX_BULK_URL_LENGTH = 6e3;
11
+ function createCouchDBDiagnosticSource({
12
+ settings: originalSettings,
13
+ fetch,
14
+ signal
15
+ }) {
16
+ const settings = { ...originalSettings };
17
+ const root = `${settings.couchDB_URI.replace(/\/+$/, "")}/${encodeURIComponent(settings.couchDB_DBNAME)}`;
18
+ const url = new URL(root);
19
+ if (!settings.couchDB_DBNAME || !["https:", "http:"].includes(url.protocol) || url.search || url.hash) {
20
+ throw new DiagnosticReadError("source-unavailable");
21
+ }
22
+ if (settings.encrypt && !settings.passphrase && !settings.permitEmptyPassphrase) {
23
+ throw new DiagnosticReadError("source-unavailable");
24
+ }
25
+ const controller = new AbortController();
26
+ const abort = () => controller.abort();
27
+ if (signal?.aborted) abort();
28
+ else signal?.addEventListener("abort", abort, { once: true });
29
+ const auth = new AuthorizationHeaderGenerator();
30
+ const credentials = generateCredentialObject(settings);
31
+ const headers = new Headers(parseHeaderValues(settings.couchDB_CustomHeaders));
32
+ const checkCancelled = () => {
33
+ if (controller.signal.aborted) throw new DOMException("Diagnostic cancelled", "AbortError");
34
+ };
35
+ const requestURL = (path, parameters = {}) => {
36
+ const requestURL2 = new URL(`${root}${path}`);
37
+ for (const [key, value] of Object.entries(parameters)) requestURL2.searchParams.set(key, value);
38
+ return requestURL2.toString();
39
+ };
40
+ const readJSON = async (path, parameters = {}) => {
41
+ checkCancelled();
42
+ headers.set("authorization", await auth.getAuthorizationHeader(credentials));
43
+ checkCancelled();
44
+ const response = await fetch(requestURL(path, parameters), {
45
+ method: "GET",
46
+ headers,
47
+ cache: "no-store",
48
+ signal: controller.signal
49
+ });
50
+ checkCancelled();
51
+ if (!response.ok) throw new DiagnosticReadError("document-unreadable", response.status === 404);
52
+ const result = await response.json();
53
+ checkCancelled();
54
+ return result;
55
+ };
56
+ let salt;
57
+ const readSalt = () => salt ??= (async () => {
58
+ try {
59
+ const parameters = await readJSON(`/${DOCID_SYNC_PARAMETERS}`);
60
+ if (typeof parameters.pbkdf2salt !== "string" || !parameters.pbkdf2salt) {
61
+ throw new DiagnosticReadError("security-seed-unavailable");
62
+ }
63
+ const bytes = new Uint8Array(base64ToArrayBuffer(parameters.pbkdf2salt));
64
+ if (!bytes.length) throw new DiagnosticReadError("security-seed-unavailable");
65
+ return bytes;
66
+ } catch {
67
+ checkCancelled();
68
+ throw new DiagnosticReadError("security-seed-unavailable");
69
+ }
70
+ })();
71
+ const decrypt = settings.encrypt ? getConfiguredFunctionsForEncryption(
72
+ settings.passphrase,
73
+ settings.useDynamicIterationCount,
74
+ false,
75
+ readSalt,
76
+ settings.E2EEAlgorithm,
77
+ false,
78
+ () => {
79
+ }
80
+ ).outgoing : async (doc) => doc;
81
+ const decode = async (id, value) => {
82
+ if (!value || typeof value !== "object" || !("_id" in value) || value._id !== id || !("_rev" in value) || typeof value._rev !== "string") {
83
+ throw new DiagnosticReadError("document-unreadable");
84
+ }
85
+ const decoded = await decompressDoc(await decrypt(value));
86
+ if ("e_" in decoded && decoded.e_ === true || "path" in decoded && typeof decoded.path === "string" && (isEncryptedMeta(decoded) || isObfuscatedEntry(decoded) && isPathProbablyObfuscated(decoded.path)))
87
+ throw new DiagnosticReadError("document-unreadable");
88
+ checkCancelled();
89
+ return decoded;
90
+ };
91
+ const source = {
92
+ async info() {
93
+ const info = await readJSON("");
94
+ return { update_seq: info.update_seq, doc_count: info.doc_count };
95
+ },
96
+ async *enumerateIds() {
97
+ let previous;
98
+ while (true) {
99
+ const parameters = { limit: "256" };
100
+ if (previous !== void 0) {
101
+ parameters.startkey = JSON.stringify(previous);
102
+ parameters.skip = "1";
103
+ }
104
+ const page = await readJSON("/_all_docs", parameters);
105
+ if (!Array.isArray(page.rows)) throw new DiagnosticReadError("source-unavailable");
106
+ if (page.rows.length === 0) return;
107
+ for (const row of page.rows) {
108
+ checkCancelled();
109
+ if (typeof row.id !== "string") throw new DiagnosticReadError("source-unavailable");
110
+ if (!row.value?.deleted) yield row.id;
111
+ }
112
+ const last = page.rows.at(-1).id;
113
+ if (last === previous) throw new DiagnosticReadError("source-unavailable");
114
+ previous = last;
115
+ if (page.rows.length < 256) return;
116
+ }
117
+ },
118
+ async get(id, options = {}) {
119
+ const parameters = {};
120
+ if (options.rev !== void 0) parameters.rev = options.rev;
121
+ if (options.conflicts) parameters.conflicts = "true";
122
+ if (options.revs) parameters.revs = "true";
123
+ if (options.revs_info) parameters.revs_info = "true";
124
+ return await decode(id, await readJSON(`/${encodeURIComponent(id)}`, parameters));
125
+ },
126
+ async getMany(ids, options = {}) {
127
+ const result = [];
128
+ const parameters = (keys) => ({
129
+ keys: JSON.stringify(keys),
130
+ include_docs: "true",
131
+ ...options.conflicts ? { conflicts: "true" } : {}
132
+ });
133
+ const readBatch = async (keys) => {
134
+ if (!keys.length) return;
135
+ let rows;
136
+ try {
137
+ const page = await readJSON("/_all_docs", parameters(keys));
138
+ if (!Array.isArray(page.rows)) throw new DiagnosticReadError("document-unreadable");
139
+ rows = page.rows;
140
+ } catch {
141
+ checkCancelled();
142
+ result.push(...keys.map((id) => ({ id, error: new DiagnosticReadError("document-unreadable") })));
143
+ return;
144
+ }
145
+ for (let offset = 0; offset < keys.length; offset += 4) {
146
+ checkCancelled();
147
+ const decoded = await Promise.allSettled(
148
+ keys.slice(offset, offset + 4).map(async (id, index) => {
149
+ try {
150
+ const row = rows[offset + index];
151
+ if (!row || row.key !== id) throw new DiagnosticReadError("document-unreadable");
152
+ if (row.error === "not_found" || row.value?.deleted)
153
+ throw new DiagnosticReadError("document-unreadable", true);
154
+ if (row.error || row.id !== id) throw new DiagnosticReadError("document-unreadable");
155
+ return { id, document: await decode(id, row.doc) };
156
+ } catch (error) {
157
+ checkCancelled();
158
+ return {
159
+ id,
160
+ error: error instanceof DiagnosticReadError ? error : new DiagnosticReadError("document-unreadable")
161
+ };
162
+ }
163
+ })
164
+ );
165
+ checkCancelled();
166
+ for (const outcome of decoded) {
167
+ if (outcome.status === "rejected") throw outcome.reason;
168
+ result.push(outcome.value);
169
+ }
170
+ }
171
+ };
172
+ let pending = [];
173
+ for (const id of ids) {
174
+ checkCancelled();
175
+ if (pending.length >= MAX_BULK_DOCUMENTS || requestURL("/_all_docs", parameters([...pending, id])).length > MAX_BULK_URL_LENGTH) {
176
+ await readBatch(pending);
177
+ pending = [];
178
+ }
179
+ if (requestURL("/_all_docs", parameters([id])).length > MAX_BULK_URL_LENGTH) {
180
+ try {
181
+ result.push({ id, document: await source.get(id, options) });
182
+ } catch (error) {
183
+ checkCancelled();
184
+ result.push({ id, error });
185
+ }
186
+ } else pending.push(id);
187
+ }
188
+ await readBatch(pending);
189
+ checkCancelled();
190
+ return result;
191
+ },
192
+ close() {
193
+ signal?.removeEventListener("abort", abort);
194
+ controller.abort();
195
+ return Promise.resolve();
196
+ }
197
+ };
198
+ return source;
199
+ }
200
+ export {
201
+ createCouchDBDiagnosticSource
202
+ };
@@ -0,0 +1,10 @@
1
+ export { analyseDatabaseUsage } from "./usage.js";
2
+ export type { DatabaseUsageSource, DatabaseUsageResult, DatabaseUsageRow, DatabaseUsageProgress, DatabaseUsageError, } from "./usage.js";
3
+ export { analyseDatabaseIntegrity } from "./integrity.js";
4
+ export { createLocalDiagnosticSource } from "./local.js";
5
+ export { createCouchDBDiagnosticSource } from "./couchdb.js";
6
+ export type { CouchDBDiagnosticSourceOptions } from "./couchdb.js";
7
+ export { createDiagnosticNameMapper, parseDiagnosticPathToken, projectIntegrityReport, projectUsageReport, formatDiagnosticJSON, formatIntegrityMarkdown, formatUsageTSV, } from "./reports.js";
8
+ export type { DiagnosticNameMapper, DiagnosticReportVersions, ProjectedDiagnosticReport, ProjectedDatabaseIntegrityReport, ProjectedDatabaseUsageReport, } from "./reports.js";
9
+ export { DiagnosticReadError } from "./types.js";
10
+ export type { DiagnosticStatus, DiagnosticNameMode, DiagnosticSourceName, DiagnosticReason, DiagnosticReadOptions, DiagnosticDocumentReadResult, DiagnosticDatabaseSource, DiagnosticError, DiagnosticContent, DiagnosticCoverage, DiagnosticObservation, DiagnosticPathEquivalenceGroup, DiagnosticIdentitySettings, DatabaseIntegrityResult, DatabaseIntegrityOptions, DatabaseIntegrityProgress, DatabaseIntegrityLog, } from "./types.js";
@@ -0,0 +1,28 @@
1
+ import { analyseDatabaseUsage } from "./usage.js";
2
+ import { analyseDatabaseIntegrity } from "./integrity.js";
3
+ import { createLocalDiagnosticSource } from "./local.js";
4
+ import { createCouchDBDiagnosticSource } from "./couchdb.js";
5
+ import {
6
+ createDiagnosticNameMapper,
7
+ parseDiagnosticPathToken,
8
+ projectIntegrityReport,
9
+ projectUsageReport,
10
+ formatDiagnosticJSON,
11
+ formatIntegrityMarkdown,
12
+ formatUsageTSV
13
+ } from "./reports.js";
14
+ import { DiagnosticReadError } from "./types.js";
15
+ export {
16
+ DiagnosticReadError,
17
+ analyseDatabaseIntegrity,
18
+ analyseDatabaseUsage,
19
+ createCouchDBDiagnosticSource,
20
+ createDiagnosticNameMapper,
21
+ createLocalDiagnosticSource,
22
+ formatDiagnosticJSON,
23
+ formatIntegrityMarkdown,
24
+ formatUsageTSV,
25
+ parseDiagnosticPathToken,
26
+ projectIntegrityReport,
27
+ projectUsageReport
28
+ };
@@ -0,0 +1,5 @@
1
+ import type { DatabaseIntegrityOptions, DatabaseIntegrityResult } from "./types.js";
2
+ /**
3
+ * Inspect current normal-file Metadata and content evidence without changing a source.
4
+ */
5
+ export declare function analyseDatabaseIntegrity(options: DatabaseIntegrityOptions): Promise<DatabaseIntegrityResult>;