@vrtmrz/livesync-commonlib 0.4.3 → 0.6.0

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.
Files changed (130) hide show
  1. package/README.md +2 -2
  2. package/dist/common/LSError.d.ts +13 -0
  3. package/dist/common/LSError.js +19 -1
  4. package/dist/diagnostics/local.d.ts +7 -2
  5. package/dist/interfaces/DatabaseFileAccess.d.ts +20 -4
  6. package/dist/interfaces/FileHandler.d.ts +67 -1
  7. package/dist/interfaces/FileHandler.js +16 -0
  8. package/dist/interfaces/StorageAccess.d.ts +8 -2
  9. package/dist/interfaces/StorageEventManager.d.ts +7 -0
  10. package/dist/managers/ChunkFetcher.d.ts +16 -0
  11. package/dist/managers/ChunkFetcher.js +190 -112
  12. package/dist/managers/EntryManager/EntryManager.d.ts +7 -0
  13. package/dist/managers/EntryManager/EntryManager.js +6 -0
  14. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +9 -5
  15. package/dist/managers/EntryManager/EntryManagerImpls.js +103 -76
  16. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.d.ts +7 -3
  17. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.js +83 -16
  18. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.d.ts +3 -2
  19. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.js +38 -36
  20. package/dist/managers/LayeredChunkManager/types.d.ts +15 -1
  21. package/dist/managers/LayeredChunkManager.d.ts +4 -0
  22. package/dist/managers/LayeredChunkManager.js +19 -6
  23. package/dist/managers/LiveSyncManagers.d.ts +2 -0
  24. package/dist/managers/LiveSyncManagers.js +6 -0
  25. package/dist/managers/StorageEventManager.d.ts +22 -0
  26. package/dist/managers/StorageEventManager.js +48 -1
  27. package/dist/platform/FilePathIndex.d.ts +110 -0
  28. package/dist/platform/FilePathIndex.js +146 -0
  29. package/dist/pouchdb/LiveSyncLocalDB.d.ts +32 -0
  30. package/dist/pouchdb/LiveSyncLocalDB.js +72 -18
  31. package/dist/pouchdb/LocalDatabaseReadScope.d.ts +24 -0
  32. package/dist/pouchdb/LocalDatabaseReadScope.js +62 -0
  33. package/dist/pouchdb/pathIdentityCompatibility.d.ts +6 -2
  34. package/dist/pouchdb/pathIdentityCompatibility.js +15 -10
  35. package/dist/replication/contentRead.d.ts +3 -0
  36. package/dist/replication/contentRead.js +4 -0
  37. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +8 -1
  38. package/dist/replication/couchdb/LiveSyncReplicator.js +187 -119
  39. package/dist/replication/index.d.ts +5 -1
  40. package/dist/replication/index.js +18 -1
  41. package/dist/replication/trystero/LiveSyncTrysteroReplicator.d.ts +3 -3
  42. package/dist/replication/trystero/P2PAutomationCoordinator.d.ts +1 -1
  43. package/dist/replication/trystero/P2PReplicationWire.d.ts +1 -1
  44. package/dist/replication/trystero/TrysteroReplicator/changeRelay.d.ts +133 -0
  45. package/dist/replication/trystero/TrysteroReplicator/changeRelay.js +176 -0
  46. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.d.ts +55 -0
  47. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.js +99 -0
  48. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.d.ts +83 -0
  49. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.js +121 -0
  50. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.d.ts +75 -0
  51. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.js +131 -0
  52. package/dist/replication/trystero/TrysteroReplicator/progress.d.ts +57 -0
  53. package/dist/replication/trystero/TrysteroReplicator/progress.js +84 -0
  54. package/dist/replication/trystero/TrysteroReplicator/relayControl.d.ts +20 -0
  55. package/dist/replication/trystero/TrysteroReplicator/relayControl.js +25 -0
  56. package/dist/replication/trystero/TrysteroReplicator/transfers.d.ts +125 -0
  57. package/dist/replication/trystero/TrysteroReplicator/transfers.js +278 -0
  58. package/dist/replication/trystero/TrysteroReplicator.d.ts +65 -483
  59. package/dist/replication/trystero/TrysteroReplicator.js +240 -673
  60. package/dist/replication/trystero/TrysteroReplicatorP2PClient.d.ts +19 -6
  61. package/dist/replication/trystero/TrysteroReplicatorP2PClient.js +29 -25
  62. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.d.ts +66 -0
  63. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.js +142 -0
  64. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +19 -16
  65. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +33 -93
  66. package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +1 -1
  67. package/dist/replication/trystero/p2pReplicationProgress.d.ts +2 -11
  68. package/dist/replication/trystero/replicationTypes.d.ts +88 -0
  69. package/dist/replication/trystero/replicationTypes.js +0 -0
  70. package/dist/replication/trystero/rpcSessionProvider.d.ts +13 -0
  71. package/dist/replication/trystero/rpcSessionProvider.js +0 -0
  72. package/dist/rpc/RpcRoom/pendingInvocations.d.ts +141 -0
  73. package/dist/rpc/RpcRoom/pendingInvocations.js +225 -0
  74. package/dist/rpc/RpcRoom.d.ts +9 -4
  75. package/dist/rpc/RpcRoom.js +73 -118
  76. package/dist/rpc/RpcSession.d.ts +6 -0
  77. package/dist/rpc/RpcSession.js +11 -0
  78. package/dist/rpc/types.d.ts +2 -0
  79. package/dist/serviceFeatures/offlineScanner/files.d.ts +1 -1
  80. package/dist/serviceFeatures/offlineScanner/files.js +27 -7
  81. package/dist/serviceFeatures/offlineScanner/scan.d.ts +5 -1
  82. package/dist/serviceFeatures/offlineScanner/scan.js +2 -1
  83. package/dist/serviceFeatures/offlineScanner.d.ts +1 -1
  84. package/dist/serviceFeatures/offlineScanner.js +10 -2
  85. package/dist/serviceFeatures/targetFilter.d.ts +1 -1
  86. package/dist/serviceFeatures/targetFilter.js +8 -38
  87. package/dist/serviceModules/FileAccessBase.d.ts +4 -0
  88. package/dist/serviceModules/FileAccessBase.js +10 -0
  89. package/dist/serviceModules/Rebuilder.js +1 -1
  90. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +13 -0
  91. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +190 -123
  92. package/dist/serviceModules/ServiceFileAccessBase/fileNames.d.ts +54 -0
  93. package/dist/serviceModules/ServiceFileAccessBase/fileNames.js +57 -0
  94. package/dist/serviceModules/ServiceFileAccessBase.d.ts +5 -1
  95. package/dist/serviceModules/ServiceFileAccessBase.js +18 -3
  96. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +17 -7
  97. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +3 -2
  98. package/dist/serviceModules/ServiceFileHandlerBase/events.js +9 -9
  99. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -9
  100. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +10 -0
  101. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +28 -4
  102. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +11 -5
  103. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +144 -58
  104. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +16 -2
  105. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +1 -0
  106. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +7 -2
  107. package/dist/serviceModules/ServiceFileHandlerBase.js +13 -4
  108. package/dist/serviceModules/adapters/IFileSystemAdapter.d.ts +3 -0
  109. package/dist/services/base/ControlService.js +1 -5
  110. package/dist/services/base/DatabaseEventService.d.ts +3 -0
  111. package/dist/services/base/DatabaseEventService.js +3 -0
  112. package/dist/services/base/DatabaseService.d.ts +15 -0
  113. package/dist/services/base/DatabaseService.js +85 -4
  114. package/dist/services/base/IService.d.ts +18 -1
  115. package/dist/services/base/KeyValueDBService.d.ts +5 -4
  116. package/dist/services/base/KeyValueDBService.js +46 -48
  117. package/dist/services/base/ReplicationService.d.ts +3 -1
  118. package/dist/services/base/ReplicationService.js +3 -1
  119. package/dist/services/base/VaultScanResult.d.ts +5 -0
  120. package/dist/services/lib/HandlerUtils.d.ts +40 -5
  121. package/dist/services/lib/HandlerUtils.js +52 -4
  122. package/dist/storage.d.ts +2 -0
  123. package/dist/storage.js +2 -0
  124. package/docs/development.md +111 -0
  125. package/docs/offline-scanner.md +46 -0
  126. package/docs/p2p-transport-lifecycle.md +24 -0
  127. package/docs/platform-storage.md +22 -0
  128. package/docs/releasing.md +48 -0
  129. package/docs/settings-lifecycle.md +4 -2
  130. package/package.json +1 -1
@@ -0,0 +1,121 @@
1
+ import { bindContext } from "octagonal-wheels/context";
2
+ import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, Logger } from "octagonal-wheels/common/logger";
3
+ function createConfiguredTargets(deps) {
4
+ const wait = bindContext({ deps }, waitForConfiguredAdvertisements);
5
+ return {
6
+ replicateFromCommand: bindContext({ deps, waitForConfiguredAdvertisements: wait }, replicateFromCommand)
7
+ };
8
+ }
9
+ function configuredPeerNames(names) {
10
+ return [...new Set(names.split(",").map((name) => name.trim()))].filter(Boolean);
11
+ }
12
+ function findAdvertisement(advertisements, peerName) {
13
+ return advertisements.find((advertisement) => advertisement.name === peerName);
14
+ }
15
+ function areConfiguredPeersPresent(deps, peerNames) {
16
+ return peerNames.every((name) => findAdvertisement(deps.advertisements(), name) !== void 0);
17
+ }
18
+ function finishAdvertisementWait(state, abortListener) {
19
+ const { detachAdvertisement, signal, cancelTimeout, resolve } = state;
20
+ detachAdvertisement();
21
+ signal?.removeEventListener("abort", abortListener);
22
+ cancelTimeout?.();
23
+ resolve();
24
+ }
25
+ function finishIfConfiguredPeersPresent(deps, peerNames, finish) {
26
+ if (areConfiguredPeersPresent(deps, peerNames)) {
27
+ finish();
28
+ }
29
+ }
30
+ function registerAdvertisementWait({ deps }, peerNames, timeoutMs, signal, resolve) {
31
+ if (areConfiguredPeersPresent(deps, peerNames) || timeoutMs <= 0 || signal?.aborted) {
32
+ resolve();
33
+ return;
34
+ }
35
+ const state = {
36
+ signal,
37
+ resolve,
38
+ detachAdvertisement: () => void 0,
39
+ cancelTimeout: void 0
40
+ };
41
+ const finish = () => finishAdvertisementWait(state, finish);
42
+ state.detachAdvertisement = deps.onAdvertisement(() => finishIfConfiguredPeersPresent(deps, peerNames, finish));
43
+ signal?.addEventListener("abort", finish, { once: true });
44
+ state.cancelTimeout = deps.scheduleTimeout(finish, timeoutMs);
45
+ if (areConfiguredPeersPresent(deps, peerNames) || signal?.aborted) {
46
+ finish();
47
+ }
48
+ }
49
+ function waitForConfiguredAdvertisements(context, peerNames, timeoutMs, signal) {
50
+ return new Promise((resolve) => registerAdvertisementWait(context, peerNames, timeoutMs, signal, resolve));
51
+ }
52
+ function configuredTargetResult(name, peerId, result) {
53
+ if (result.status === "completed") {
54
+ return { name, peerId, status: "completed" };
55
+ }
56
+ if (result.status === "cancelled") {
57
+ return { name, peerId, status: "cancelled" };
58
+ }
59
+ return { name, peerId, status: "failed", error: result.error };
60
+ }
61
+ async function replicateFromCommand({ deps, waitForConfiguredAdvertisements: waitForConfiguredAdvertisements2 }, showResult = false, discoveryTimeoutMs = 5e3, callerSignal) {
62
+ const logLevel = showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO;
63
+ if (!deps.currentSettings().P2P_Enabled) {
64
+ Logger(deps.translate("P2P.NotEnabled"), logLevel);
65
+ return { status: "blocked", reason: "no-targets", targets: [] };
66
+ }
67
+ const peerNames = configuredPeerNames(deps.currentSettings().P2P_SyncOnReplication);
68
+ if (peerNames.length === 0) {
69
+ Logger(deps.translate("P2P.NoAutoSyncPeers"), logLevel);
70
+ return { status: "blocked", reason: "no-targets", targets: [] };
71
+ }
72
+ await waitForConfiguredAdvertisements2(peerNames, discoveryTimeoutMs, callerSignal);
73
+ const targets = [];
74
+ for (const peerName of peerNames) {
75
+ if (callerSignal?.aborted) {
76
+ targets.push({ name: peerName, status: "cancelled" });
77
+ continue;
78
+ }
79
+ const advertisement = findAdvertisement(deps.advertisements(), peerName);
80
+ if (!advertisement) {
81
+ Logger(deps.translate("P2P.SeemsOffline", { name: peerName }), logLevel);
82
+ targets.push({ name: peerName, status: "missing" });
83
+ continue;
84
+ }
85
+ const acceptance = await deps.evaluatePeerAcceptance(advertisement.peerId) ?? "unknown";
86
+ if (acceptance !== "accepted") {
87
+ targets.push({
88
+ name: peerName,
89
+ peerId: advertisement.peerId,
90
+ status: acceptance === "rejected" ? "rejected" : acceptance === "undecided" ? "undecided" : "missing"
91
+ });
92
+ continue;
93
+ }
94
+ Logger(deps.translate("P2P.SyncStartedWith", { name: peerName }), logLevel);
95
+ const result = await deps.runBaseline(
96
+ peerName,
97
+ () => deps.sync(advertisement.peerId, showResult, callerSignal)
98
+ );
99
+ targets.push(configuredTargetResult(peerName, advertisement.peerId, result));
100
+ }
101
+ if (targets.every((target) => target.status === "completed")) {
102
+ Logger(deps.translate("P2P.SyncCompleted"), logLevel);
103
+ return { status: "completed", targets };
104
+ }
105
+ if (targets.every((target) => target.status === "cancelled")) {
106
+ return { status: "cancelled", targets };
107
+ }
108
+ return { status: "partial", targets };
109
+ }
110
+ export {
111
+ areConfiguredPeersPresent,
112
+ configuredPeerNames,
113
+ configuredTargetResult,
114
+ createConfiguredTargets,
115
+ findAdvertisement,
116
+ finishAdvertisementWait,
117
+ finishIfConfiguredPeersPresent,
118
+ registerAdvertisementWait,
119
+ replicateFromCommand,
120
+ waitForConfiguredAdvertisements
121
+ };
@@ -0,0 +1,75 @@
1
+ import { type EncryptionSettings, type ObsidianLiveSyncSettings, type P2PSyncSetting } from "../../../common/types.js";
2
+ import { getPathNormalizationVersion } from "../../../common/pathNormalization.js";
3
+ import type { P2PDiagnosticInput } from "../../../p2p/p2pDiagnostics.js";
4
+ import { type LOG_LEVEL } from "octagonal-wheels/common/logger";
5
+ /** Agreement data contains a passphrase digest and challenge proof, never the ID key. */
6
+ export type PeerTweakSettings = Partial<ObsidianLiveSyncSettings> & {
7
+ pathNormalizationVersion: ReturnType<typeof getPathNormalizationVersion>;
8
+ idDerivationVersion: NonNullable<EncryptionSettings["idDerivationVersion"]>;
9
+ idDerivationProof: string;
10
+ };
11
+ /** Narrow RPC operations on a connection captured before asynchronous validation. */
12
+ export interface PeerAgreementConnection {
13
+ requestAuthentication(timeoutMs: number, signal?: AbortSignal): Promise<boolean | undefined>;
14
+ requestTweakSettings(challenge: string, timeoutMs: number, signal?: AbortSignal): Promise<PeerTweakSettings>;
15
+ }
16
+ export interface PeerAgreementHost {
17
+ peerPlatform(peerId: string): string | undefined;
18
+ connection(peerId: string): PeerAgreementConnection;
19
+ }
20
+ /** The authentication operation uses only the authentication method on a captured connection. */
21
+ interface PeerAuthenticationHost {
22
+ connection(peerId: string): Pick<PeerAgreementConnection, "requestAuthentication">;
23
+ }
24
+ /**
25
+ * The host owns room binding, database validation, and presentation authority.
26
+ * Snapshot settings describe the room; current settings supply policy and identity
27
+ * metadata at the same stages as the original replicator implementation.
28
+ */
29
+ export interface PeerAgreementDependencies {
30
+ host(): PeerAgreementHost | undefined;
31
+ settings(): P2PSyncSetting;
32
+ currentSettings(): P2PSyncSetting;
33
+ platform(): string;
34
+ assertPathIdentity(settings: P2PSyncSetting): Promise<void>;
35
+ /** Resolve through the facade so host overrides and observers remain effective. */
36
+ localTweakSettings(challenge: string): Promise<PeerTweakSettings>;
37
+ reportDiagnostic(input: P2PDiagnosticInput): void;
38
+ }
39
+ /** Settings and path-identity capabilities used to produce a peer's tweak response. */
40
+ export type GetTweakSettingsDependencies = Pick<PeerAgreementDependencies, "settings" | "currentSettings" | "assertPathIdentity">;
41
+ /** Host and diagnostic capabilities used to request peer authentication. */
42
+ export type RequestAuthenticateDependencies = Pick<PeerAgreementDependencies, "reportDiagnostic"> & {
43
+ host(): PeerAuthenticationHost | undefined;
44
+ };
45
+ /** Host and local-policy capabilities used to compare peer tweak settings. */
46
+ export type CheckTweakValuesDependencies = Pick<PeerAgreementDependencies, "host" | "platform" | "localTweakSettings">;
47
+ export interface PeerAgreement {
48
+ getTweakSettings(challenge: string): Promise<PeerTweakSettings>;
49
+ requestAuthenticate(peerId: string, signal?: AbortSignal): Promise<boolean | undefined>;
50
+ checkTweakValues(peerId: string, signal?: AbortSignal, logLevel?: LOG_LEVEL): Promise<boolean>;
51
+ }
52
+ /** Construct stateless agreement operations without reading the host or starting RPC. */
53
+ export declare function createPeerAgreement(deps: PeerAgreementDependencies): PeerAgreement;
54
+ /**
55
+ * Build the settings response for an opaque challenge (historically named peer ID).
56
+ * Validate current path identity first, then project the room snapshot's matched
57
+ * tweak fields. Read current ID settings separately, preserving that policy stage.
58
+ * The passphrase is hashed and the ID key becomes a challenge-bound proof.
59
+ */
60
+ export declare function getTweakSettings(deps: GetTweakSettingsDependencies, challenge: string): Promise<PeerTweakSettings>;
61
+ /**
62
+ * Ask the captured host for admission using the existing 20-second RPC deadline.
63
+ * Preserve its result for the caller's strict acceptance check. Missing hosts and
64
+ * RPC failures return false; failures retain the existing redacted diagnostics.
65
+ */
66
+ export declare function requestAuthenticate(deps: RequestAuthenticateDependencies, peerId: string, signal?: AbortSignal): Promise<boolean | undefined>;
67
+ /**
68
+ * Compare peer compatibility within the initiating call's logging authority.
69
+ * Capture the connection before generating the challenge. Path identity is checked
70
+ * before the pseudo-replicator exception; ordinary peers then require matching
71
+ * content and ID settings. Representation-only differences warn and still pass.
72
+ * RPC/local-validation errors propagate; an observed abort after RPC returns false.
73
+ */
74
+ export declare function checkTweakValues(deps: CheckTweakValuesDependencies, peerId: string, signal?: AbortSignal, logLevel?: LOG_LEVEL): Promise<boolean>;
75
+ export {};
@@ -0,0 +1,131 @@
1
+ import {
2
+ TweakValuesShouldMatchedTemplate
3
+ } from "../../../common/types.js";
4
+ import { configuredIdKey, computeKeyedId } from "../../../common/idDerivation.js";
5
+ import { assessTweakCompatibility } from "../../../common/models/tweak.compatibility.js";
6
+ import { getPathNormalizationVersion } from "../../../common/pathNormalization.js";
7
+ import { getWebCrypto } from "../../../mods.js";
8
+ import { uint8ArrayToHexString } from "../../../string_and_binary/convert.js";
9
+ import { Logger, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
10
+ import { bindContext } from "octagonal-wheels/context";
11
+ import { cloneViaJSON } from "octagonal-wheels/encoding/json";
12
+ import { sha1 } from "octagonal-wheels/hash/purejs";
13
+ import { authenticationFailureDiagnostic, authenticationResultDiagnostic } from "../p2pReplicationDiagnostics.js";
14
+ function createPeerAgreement(deps) {
15
+ return {
16
+ getTweakSettings: bindContext(deps, getTweakSettings),
17
+ requestAuthenticate: bindContext(deps, requestAuthenticate),
18
+ checkTweakValues: bindContext(deps, checkTweakValues)
19
+ };
20
+ }
21
+ async function hashPassphrase(source) {
22
+ const salt = (~~((/* @__PURE__ */ new Date()).getTime() / 1e3 / 180)).toString(36);
23
+ const salt2 = await sha1(salt);
24
+ return await sha1(salt2 + source);
25
+ }
26
+ async function getTweakSettings(deps, challenge) {
27
+ const currentSettings = deps.currentSettings();
28
+ const pathNormalizationVersion = getPathNormalizationVersion(currentSettings);
29
+ if (pathNormalizationVersion === 1) {
30
+ await deps.assertPathIdentity(currentSettings);
31
+ }
32
+ const allSettings = cloneViaJSON(deps.settings());
33
+ for (const key in allSettings) {
34
+ if (key == "encrypt") {
35
+ continue;
36
+ }
37
+ if (key == "passphrase") {
38
+ allSettings[key] = await hashPassphrase(allSettings[key] ?? "");
39
+ continue;
40
+ }
41
+ if (!(key in TweakValuesShouldMatchedTemplate)) {
42
+ delete allSettings[key];
43
+ }
44
+ }
45
+ const idSettings = deps.currentSettings();
46
+ const idDerivationVersion = idSettings.idDerivationVersion ?? 0;
47
+ const idKey = configuredIdKey({ idDerivationVersion, idDerivationKey: idSettings.idDerivationKey ?? "" });
48
+ return {
49
+ ...allSettings,
50
+ pathNormalizationVersion,
51
+ idDerivationVersion,
52
+ idDerivationProof: idKey && idSettings.encrypt && idSettings.usePathObfuscation ? await computeKeyedId(idKey, "peer-agreement", challenge) : ""
53
+ };
54
+ }
55
+ async function requestAuthenticate(deps, peerId, signal) {
56
+ const host = deps.host();
57
+ if (!host) {
58
+ return false;
59
+ }
60
+ try {
61
+ const connection = host.connection(peerId);
62
+ const result = await connection.requestAuthentication(2e4, signal);
63
+ deps.reportDiagnostic(authenticationResultDiagnostic(peerId, result));
64
+ return result;
65
+ } catch (error) {
66
+ deps.reportDiagnostic(authenticationFailureDiagnostic(peerId, error, signal));
67
+ Logger("Error while requesting authentication", LOG_LEVEL_VERBOSE);
68
+ Logger(error, LOG_LEVEL_VERBOSE);
69
+ return false;
70
+ }
71
+ }
72
+ async function checkTweakValues(deps, peerId, signal, logLevel = LOG_LEVEL_NOTICE) {
73
+ const host = deps.host();
74
+ if (!host) {
75
+ Logger("Server is not available", logLevel);
76
+ return false;
77
+ }
78
+ const peerPlatform = host.peerPlatform(peerId);
79
+ if (peerPlatform == null) {
80
+ Logger("Peer is not found", logLevel);
81
+ return false;
82
+ }
83
+ const connection = host.connection(peerId);
84
+ const challengeBytes = new Uint8Array(16);
85
+ (await getWebCrypto()).getRandomValues(challengeBytes);
86
+ const challenge = uint8ArrayToHexString(challengeBytes);
87
+ const tweakValues = await connection.requestTweakSettings(challenge, 5e3, signal);
88
+ if (signal?.aborted) {
89
+ return false;
90
+ }
91
+ const thisTweakValues = await deps.localTweakSettings(challenge);
92
+ const localPathNormalizationVersion = getPathNormalizationVersion(thisTweakValues);
93
+ const peerPathNormalizationVersion = getPathNormalizationVersion(tweakValues);
94
+ if (localPathNormalizationVersion !== peerPathNormalizationVersion) {
95
+ Logger("Replication cancelled: The path identity mode does not match this peer.", logLevel);
96
+ return false;
97
+ }
98
+ if (deps.platform() === "pseudo-replicator" || peerPlatform === "pseudo-replicator") {
99
+ return true;
100
+ }
101
+ if (thisTweakValues.passphrase !== tweakValues.passphrase) {
102
+ Logger(
103
+ "Replication cancelled: Passphrase is not matched\nCannot replicate to a remote database until the problem is resolved.",
104
+ logLevel
105
+ );
106
+ return false;
107
+ }
108
+ if (thisTweakValues.encrypt !== tweakValues.encrypt || thisTweakValues.usePathObfuscation !== tweakValues.usePathObfuscation) {
109
+ Logger("Replication cancelled: The encryption or path obfuscation settings do not match this peer.", logLevel);
110
+ return false;
111
+ }
112
+ if (thisTweakValues.encrypt && thisTweakValues.usePathObfuscation && ((thisTweakValues.idDerivationVersion ?? 0) !== (tweakValues.idDerivationVersion ?? 0) || (thisTweakValues.idDerivationProof ?? "") !== (tweakValues.idDerivationProof ?? ""))) {
113
+ Logger("Replication cancelled: The ID derivation settings do not match this peer.", logLevel);
114
+ return false;
115
+ }
116
+ const tweakAssessment = assessTweakCompatibility(thisTweakValues, tweakValues);
117
+ if (!tweakAssessment.representationDiffers) {
118
+ return true;
119
+ }
120
+ Logger(
121
+ "Some mismatched configuration have been detected... Please check settings for efficient replication.",
122
+ logLevel
123
+ );
124
+ return true;
125
+ }
126
+ export {
127
+ checkTweakValues,
128
+ createPeerAgreement,
129
+ getTweakSettings,
130
+ requestAuthenticate
131
+ };
@@ -0,0 +1,57 @@
1
+ import type { ProgressInfo } from "../../../pouchdb/ReplicatorShim.js";
2
+ import type { P2PReplicationReport, AcknowledgedProgressAttempt, ProgressAcknowledgement } from "../replicationTypes.js";
3
+ export type { P2PReplicationDirectionProgress, P2PReplicationProgress, P2PReplicationReport, } from "../replicationTypes.js";
4
+ /** A target captured from the current room and used for one progress acknowledgement. */
5
+ export type ProgressAcknowledgementTarget = {
6
+ send(info?: ProgressInfo, acknowledgement?: ProgressAcknowledgement): Promise<unknown>;
7
+ };
8
+ /** Host capabilities needed to report and acknowledge replication progress. */
9
+ export type ReplicationProgressDependencies = {
10
+ isDisposed: () => boolean;
11
+ peerName: (peerId: string) => string | undefined;
12
+ emitProgress: (report: P2PReplicationReport) => void;
13
+ captureAcknowledgementTarget: (peerId: string) => ProgressAcknowledgementTarget | undefined;
14
+ };
15
+ type AcknowledgedAttempts = Map<string, AcknowledgedProgressAttempt>;
16
+ type OnReplicationProgressDeps = Pick<ReplicationProgressDependencies, "isDisposed" | "peerName" | "emitProgress">;
17
+ type OnProgressAcknowledgedContext = {
18
+ dependencies: Pick<ReplicationProgressDependencies, "isDisposed" | "peerName" | "emitProgress">;
19
+ acknowledgedAttempts: AcknowledgedAttempts;
20
+ };
21
+ type AcknowledgeProgressDeps = Pick<ReplicationProgressDependencies, "isDisposed" | "captureAcknowledgementTarget">;
22
+ /**
23
+ * Emit the local side of replication progress without creating or waiting for a
24
+ * transport acknowledgement. The fetching report carries the current PouchDB
25
+ * progress snapshot and preserves its statistics as an independent copy.
26
+ */
27
+ export declare function onReplicationProgress(dependencies: OnReplicationProgressDeps, peerId: string, info?: ProgressInfo): boolean;
28
+ /**
29
+ * Accept a remote progress acknowledgement only when its attempt and checked
30
+ * change count are not stale. Final progress supplies the last statistics after
31
+ * transfer completion, while the emitted sending direction remains inactive.
32
+ */
33
+ export declare function onProgressAcknowledged({ dependencies, acknowledgedAttempts }: OnProgressAcknowledgedContext, peerId: string, info?: ProgressInfo | null, acknowledgement?: ProgressAcknowledgement): boolean;
34
+ /**
35
+ * Report progress without awaiting the reporting RPC's response. Capture the
36
+ * current room after checking disposal and observe send failures in the background.
37
+ * This reporting RPC is separate from the response-free change notification.
38
+ */
39
+ export declare function acknowledgeProgress(dependencies: AcknowledgeProgressDeps, remotePeerId: string, info?: ProgressInfo, acknowledgement?: ProgressAcknowledgement): void;
40
+ /** Start a new room-independent attempt number in this module realm. */
41
+ export declare function beginAttempt(): ProgressAcknowledgement;
42
+ /** Forget only the departed peer's ordering state. */
43
+ export declare function peerLeft(acknowledgedAttempts: AcknowledgedAttempts, peerId: string): void;
44
+ /** Forget all room-local acknowledgement state without resetting attempt order. */
45
+ export declare function clear(acknowledgedAttempts: AcknowledgedAttempts): void;
46
+ /**
47
+ * Create the room-local coordinator for progress projection and acknowledgement
48
+ * ordering. Construction is inert: it allocates only the bounded peer-state map.
49
+ */
50
+ export declare function createReplicationProgress(dependencies: ReplicationProgressDependencies): {
51
+ onReplicationProgress: (peerId: string, info?: ProgressInfo) => boolean;
52
+ onProgressAcknowledged: (peerId: string, info?: ProgressInfo, acknowledgement?: ProgressAcknowledgement) => boolean;
53
+ acknowledgeProgress: (remotePeerId: string, info?: ProgressInfo, acknowledgement?: ProgressAcknowledgement) => void;
54
+ beginAttempt: typeof beginAttempt;
55
+ peerLeft: (peerId: string) => void;
56
+ clear: () => void;
57
+ };
@@ -0,0 +1,84 @@
1
+ import { Logger, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
2
+ import { bindContext } from "octagonal-wheels/context";
3
+ import { projectAcknowledgedAttempt, projectDirectionProgress } from "../p2pReplicationProgress.js";
4
+ let nextProgressAttempt = 0;
5
+ function onReplicationProgress(dependencies, peerId, info) {
6
+ if (dependencies.isDisposed()) {
7
+ return false;
8
+ }
9
+ const peerName = dependencies.peerName(peerId) || peerId;
10
+ dependencies.emitProgress({
11
+ peerId,
12
+ peerName,
13
+ fetching: projectDirectionProgress(info)
14
+ });
15
+ return true;
16
+ }
17
+ function onProgressAcknowledged({ dependencies, acknowledgedAttempts }, peerId, info, acknowledgement) {
18
+ if (dependencies.isDisposed()) {
19
+ return false;
20
+ }
21
+ if (acknowledgement) {
22
+ const next = projectAcknowledgedAttempt(acknowledgedAttempts.get(peerId), info, acknowledgement);
23
+ if (!next) {
24
+ return false;
25
+ }
26
+ acknowledgedAttempts.set(peerId, next);
27
+ }
28
+ const peerName = dependencies.peerName(peerId) || peerId;
29
+ const sending = projectDirectionProgress(info ?? acknowledgement?.finalProgress);
30
+ sending.isActive = info != null;
31
+ dependencies.emitProgress({
32
+ peerId,
33
+ peerName,
34
+ sending
35
+ });
36
+ return true;
37
+ }
38
+ function acknowledgeProgress(dependencies, remotePeerId, info, acknowledgement) {
39
+ if (dependencies.isDisposed()) {
40
+ return;
41
+ }
42
+ try {
43
+ const target = dependencies.captureAcknowledgementTarget(remotePeerId);
44
+ if (!target) {
45
+ return;
46
+ }
47
+ void target.send(info, acknowledgement).catch((error) => {
48
+ Logger("Error while acknowledging the progress", LOG_LEVEL_VERBOSE);
49
+ Logger(error, LOG_LEVEL_VERBOSE);
50
+ });
51
+ } catch (error) {
52
+ Logger("Error while acknowledging the progress", LOG_LEVEL_VERBOSE);
53
+ Logger(error, LOG_LEVEL_VERBOSE);
54
+ }
55
+ }
56
+ function beginAttempt() {
57
+ return { attempt: ++nextProgressAttempt };
58
+ }
59
+ function peerLeft(acknowledgedAttempts, peerId) {
60
+ acknowledgedAttempts.delete(peerId);
61
+ }
62
+ function clear(acknowledgedAttempts) {
63
+ acknowledgedAttempts.clear();
64
+ }
65
+ function createReplicationProgress(dependencies) {
66
+ const acknowledgedAttempts = /* @__PURE__ */ new Map();
67
+ return {
68
+ onReplicationProgress: bindContext(dependencies, onReplicationProgress),
69
+ onProgressAcknowledged: bindContext({ dependencies, acknowledgedAttempts }, onProgressAcknowledged),
70
+ acknowledgeProgress: bindContext(dependencies, acknowledgeProgress),
71
+ beginAttempt,
72
+ peerLeft: bindContext(acknowledgedAttempts, peerLeft),
73
+ clear: bindContext(acknowledgedAttempts, clear)
74
+ };
75
+ }
76
+ export {
77
+ acknowledgeProgress,
78
+ beginAttempt,
79
+ clear,
80
+ createReplicationProgress,
81
+ onProgressAcknowledged,
82
+ onReplicationProgress,
83
+ peerLeft
84
+ };
@@ -0,0 +1,20 @@
1
+ /** The facade borrows relay controls; it does not own another socket registry. */
2
+ export interface RelayControl {
3
+ getSockets(): Record<string, {
4
+ close(): void;
5
+ }>;
6
+ pauseReconnection(): void;
7
+ resumeReconnection(): void;
8
+ }
9
+ /** Default operations retain Trystero's existing shared relay ownership. */
10
+ export declare const defaultRelayControl: RelayControl;
11
+ export type RelayDisconnectionContext = {
12
+ relay: Pick<RelayControl, "getSockets" | "pauseReconnection">;
13
+ pauseServe(): Promise<void>;
14
+ };
15
+ /**
16
+ * Capture sockets before pausing reconnection, close that snapshot, and start
17
+ * the host's existing asynchronous stop operation without awaiting it. A read,
18
+ * pause, or close failure retains its original synchronous propagation order.
19
+ */
20
+ export declare function disconnectRelay({ relay, pauseServe }: RelayDisconnectionContext): void;
@@ -0,0 +1,25 @@
1
+ import { getRelaySockets, pauseRelayReconnection, resumeRelayReconnection } from "@trystero-p2p/nostr";
2
+ function readRelaySockets() {
3
+ return getRelaySockets();
4
+ }
5
+ const defaultRelayControl = {
6
+ getSockets: readRelaySockets,
7
+ pauseReconnection: () => {
8
+ pauseRelayReconnection();
9
+ },
10
+ resumeReconnection: () => {
11
+ resumeRelayReconnection();
12
+ }
13
+ };
14
+ function disconnectRelay({ relay, pauseServe }) {
15
+ const sockets = Object.entries(relay.getSockets());
16
+ relay.pauseReconnection();
17
+ for (const [, socket] of sockets) {
18
+ socket.close();
19
+ }
20
+ void pauseServe();
21
+ }
22
+ export {
23
+ defaultRelayControl,
24
+ disconnectRelay
25
+ };
@@ -0,0 +1,125 @@
1
+ import type { EntryDoc, P2PSyncSetting } from "../../../common/types.js";
2
+ import type { P2PDiagnosticInput } from "../../../p2p/p2pDiagnostics.js";
3
+ import type { replicateShim, ProgressInfo, PouchDBShim, SomeDocument } from "../../../pouchdb/ReplicatorShim.js";
4
+ import { type LOG_LEVEL } from "octagonal-wheels/common/logger";
5
+ import { type P2PReplicationWireResult } from "../P2PReplicationWire.js";
6
+ import type { P2PReplicationResult, ProgressAcknowledgement } from "../replicationTypes.js";
7
+ export type { P2PReplicationResult } from "../replicationTypes.js";
8
+ export declare const P2P_REPLICATION_COMPLETED: Readonly<{
9
+ readonly status: "completed";
10
+ readonly ok: true;
11
+ }>;
12
+ export declare const P2P_REPLICATION_CANCELLED: Readonly<{
13
+ readonly status: "cancelled";
14
+ }>;
15
+ export declare function p2pReplicationFailed(error: unknown): P2PReplicationResult;
16
+ export declare function isP2PReplicationCancelled(result: P2PReplicationResult): boolean;
17
+ export interface TransferConnection {
18
+ requestSynchronisation(timeoutMs: number, signal?: AbortSignal): Promise<P2PReplicationWireResult>;
19
+ /** Reuse the RPC database contract rather than requiring a complete PouchDB implementation. */
20
+ getRemoteDB(signal?: AbortSignal): PouchDBShim<SomeDocument<object>>;
21
+ }
22
+ export interface TransferHost {
23
+ connection(peerId: string): TransferConnection;
24
+ }
25
+ /** Borrowed capabilities: session lifetime and public method dispatch remain with the facade. */
26
+ export interface TransferDependencies {
27
+ host(): TransferHost | undefined;
28
+ database(): PouchDB.Database<EntryDoc>;
29
+ currentSettings(): P2PSyncSetting;
30
+ replicate: typeof replicateShim;
31
+ processReplicatedDocs(docs: Array<PouchDB.Core.ExistingDocument<EntryDoc>>): void | Promise<void>;
32
+ canStartOrdinaryReplication(showMessage?: boolean): Promise<boolean>;
33
+ requestAuthenticate(peerId: string, signal?: AbortSignal): Promise<boolean | undefined>;
34
+ checkTweakValues(peerId: string, signal?: AbortSignal, logLevel?: LOG_LEVEL): Promise<boolean>;
35
+ replicateFrom(peerId: string, showNotice: boolean, fromStart: boolean, skipPolicy: boolean, signal?: AbortSignal): Promise<P2PReplicationResult>;
36
+ requestSynchroniseToPeer(peerId: string, signal?: AbortSignal): Promise<P2PReplicationResult>;
37
+ dispatchStatus(): void;
38
+ dispatchReplicationProgress(peerId: string, info?: ProgressInfo): void;
39
+ acknowledgeProgress(peerId: string, info?: ProgressInfo, acknowledgement?: ProgressAcknowledgement): void;
40
+ beginProgressAttempt(): ProgressAcknowledgement;
41
+ reportDiagnostic(input: P2PDiagnosticInput): void;
42
+ notifyProgress(excludePeerId?: string): Promise<void> | undefined;
43
+ }
44
+ interface TransferState {
45
+ availableReplicationPairs: Set<string>;
46
+ replicateToPeers: Set<string>;
47
+ replicateFromPeers: Set<string>;
48
+ }
49
+ export interface Transfers extends TransferState {
50
+ requestSynchroniseToPeer(peerId: string, signal?: AbortSignal): Promise<P2PReplicationResult>;
51
+ requestSynchroniseToAllAvailablePeers(): Promise<void>;
52
+ sync(peerId: string, showNotice: boolean, signal?: AbortSignal): Promise<P2PReplicationResult>;
53
+ replicateFrom(peerId: string, showNotice: boolean, fromStart: boolean, skipPolicy: boolean, signal?: AbortSignal): Promise<P2PReplicationResult>;
54
+ clearActivePeers(): void;
55
+ }
56
+ /** Only policy admission and connection lookup are needed for a reverse request. */
57
+ export type RequestSynchronisationContext = {
58
+ deps: Pick<TransferDependencies, "canStartOrdinaryReplication" | "host">;
59
+ };
60
+ export type AvailableTargetsContext = {
61
+ deps: Pick<TransferDependencies, "requestSynchroniseToPeer">;
62
+ state: Pick<TransferState, "availableReplicationPairs">;
63
+ };
64
+ export type BidirectionalSyncContext = {
65
+ deps: Pick<TransferDependencies, "replicateFrom" | "requestSynchroniseToPeer">;
66
+ };
67
+ /** The observer forwards a composed pull result and only owns diagnostic reporting. */
68
+ export type ReplicationObservationContext = {
69
+ deps: Pick<TransferDependencies, "reportDiagnostic">;
70
+ pullFromWithinSession: Transfers["replicateFrom"];
71
+ };
72
+ export type PeerAgreementGateContext = {
73
+ deps: Pick<TransferDependencies, "requestAuthenticate" | "checkTweakValues">;
74
+ };
75
+ export type DatabaseTransferContext = {
76
+ deps: Pick<TransferDependencies, "host" | "database" | "currentSettings" | "replicate" | "processReplicatedDocs" | "notifyProgress">;
77
+ };
78
+ /** Admission and database transfer are operations composed by the factory. */
79
+ export type PullContext = {
80
+ deps: Pick<TransferDependencies, "canStartOrdinaryReplication" | "dispatchStatus" | "beginProgressAttempt" | "dispatchReplicationProgress" | "acknowledgeProgress">;
81
+ state: Pick<TransferState, "replicateFromPeers">;
82
+ checkPeerForReplication(peerId: string, logLevel: LOG_LEVEL, signal?: AbortSignal): Promise<P2PReplicationResult | undefined>;
83
+ transferFromPeer(peerId: string, fromStart: boolean, logLevel: LOG_LEVEL, signal?: AbortSignal, onStatistics?: (info: ProgressInfo) => void): Promise<P2PReplicationResult>;
84
+ };
85
+ export type ActiveTransferStateContext = {
86
+ state: Pick<TransferState, "replicateFromPeers" | "replicateToPeers">;
87
+ };
88
+ /** Clear activity indicators without discarding the available-target set or closing borrowed resources. */
89
+ export declare function clearActivePeers({ state }: ActiveTransferStateContext): void;
90
+ /**
91
+ * Construct the transfer state owner without opening a database or starting RPC.
92
+ * Public facade accessors and these operations share the same peer sets. The
93
+ * containing session lends its cancellation signal; no new session owner exists.
94
+ */
95
+ export declare function createTransfers(deps: TransferDependencies): Transfers;
96
+ /**
97
+ * Request the reverse transfer after ordinary-policy admission and the existing
98
+ * 25 ms scheduling delay. Cancellation is checked on both sides of that delay;
99
+ * the RPC itself retains its zero deadline and the caller's signal.
100
+ */
101
+ export declare function requestSynchroniseToPeer(context: RequestSynchronisationContext, peerId: string, signal?: AbortSignal): Promise<P2PReplicationResult>;
102
+ /** Retain the existing shared scheduling key and fan-out to available peer IDs. */
103
+ export declare function requestSynchroniseToAllAvailablePeers(context: AvailableTargetsContext): Promise<void>;
104
+ /** Apply the existing pull-result and cancellation gates before requesting the reverse transfer. */
105
+ export declare function sync(context: BidirectionalSyncContext, remotePeer: string, showNotice: boolean, signal?: AbortSignal): Promise<P2PReplicationResult>;
106
+ /** Report the pull outcome without changing which failures propagate to the caller. */
107
+ export declare function replicateFrom(context: ReplicationObservationContext, remotePeer: string, showNotice: boolean, fromStart: boolean, skipOrdinaryReplicationPolicy: boolean, signal?: AbortSignal): Promise<P2PReplicationResult>;
108
+ /**
109
+ * Apply policy and agreement before registering an active pull. Preserve the
110
+ * existing progress-start boundary and finalisation order; the session remains
111
+ * responsible for cancellation, and these operations do not close borrowed DBs.
112
+ */
113
+ export declare function pullFromWithinSession(context: PullContext, remotePeer: string, showNotice: boolean, fromStart: boolean, skipOrdinaryReplicationPolicy: boolean, signal?: AbortSignal): Promise<P2PReplicationResult>;
114
+ /**
115
+ * Keep authentication and compatibility gates ahead of transfer state entry.
116
+ * Facade dispatch preserves caller overrides; this layer alone translates
117
+ * failed gates into the replication result and cancellation vocabulary.
118
+ */
119
+ export declare function checkPeerForReplication(context: PeerAgreementGateContext, remotePeer: string, logLevel: LOG_LEVEL, signal?: AbortSignal): Promise<P2PReplicationResult | undefined>;
120
+ /**
121
+ * Validate both database identities before invoking the shared replication engine.
122
+ * Notify other peers only after the host has processed a committed batch. The
123
+ * engine owns checkpoint and document handling; this adapter retains its options.
124
+ */
125
+ export declare function transferFromPeer(context: DatabaseTransferContext, remotePeer: string, fromStart: boolean, logLevel: LOG_LEVEL, signal?: AbortSignal, onStatistics?: (info: ProgressInfo) => void): Promise<P2PReplicationResult>;