@vrtmrz/livesync-commonlib 0.4.2 → 0.5.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 (100) hide show
  1. package/README.md +7 -5
  2. package/dist/API/DirectFileManipulatorV2.d.ts +1 -0
  3. package/dist/API/DirectFileManipulatorV2.js +3 -1
  4. package/dist/API/processSetting.d.ts +1 -0
  5. package/dist/API/processSetting.js +3 -0
  6. package/dist/common/models/setting.const.defaults.js +1 -0
  7. package/dist/common/models/setting.const.qr.js +2 -1
  8. package/dist/common/models/setting.encryption.d.ts +2 -0
  9. package/dist/common/models/setting.encryption.js +6 -0
  10. package/dist/common/models/setting.lifecycle.js +7 -2
  11. package/dist/common/models/setting.policy.d.ts +4 -0
  12. package/dist/common/models/setting.policy.js +9 -0
  13. package/dist/common/models/setting.type.d.ts +2 -0
  14. package/dist/common/models/shared.definition.configNames.js +5 -0
  15. package/dist/common/models/tweak.definition.d.ts +1 -0
  16. package/dist/common/settingConstants.d.ts +1 -0
  17. package/dist/common/utils.js +5 -4
  18. package/dist/diagnostics/couchdb.js +4 -2
  19. package/dist/interfaces/StorageAccess.d.ts +8 -2
  20. package/dist/managers/ChunkFetcher.js +27 -4
  21. package/dist/managers/chunkFetcher.helper.js +1 -1
  22. package/dist/platform/FilePathIndex.d.ts +110 -0
  23. package/dist/platform/FilePathIndex.js +146 -0
  24. package/dist/pouchdb/StreamingFetch.d.ts +1 -2
  25. package/dist/pouchdb/encryption.d.ts +5 -10
  26. package/dist/pouchdb/encryption.eden.d.ts +11 -0
  27. package/dist/pouchdb/encryption.eden.js +37 -0
  28. package/dist/pouchdb/encryption.js +67 -63
  29. package/dist/pouchdb/encryption.policy.d.ts +9 -0
  30. package/dist/pouchdb/encryption.policy.js +125 -0
  31. package/dist/replication/UnencryptedContentRejectedError.d.ts +16 -0
  32. package/dist/replication/UnencryptedContentRejectedError.js +44 -0
  33. package/dist/replication/couchdb/LiveSyncReplicator.js +41 -4
  34. package/dist/replication/index.d.ts +2 -0
  35. package/dist/replication/index.js +3 -0
  36. package/dist/replication/trystero/LiveSyncTrysteroReplicator.d.ts +3 -3
  37. package/dist/replication/trystero/P2PAutomationCoordinator.d.ts +1 -1
  38. package/dist/replication/trystero/P2PReplicationWire.d.ts +1 -1
  39. package/dist/replication/trystero/TrysteroReplicator/changeRelay.d.ts +133 -0
  40. package/dist/replication/trystero/TrysteroReplicator/changeRelay.js +176 -0
  41. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.d.ts +55 -0
  42. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.js +99 -0
  43. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.d.ts +83 -0
  44. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.js +121 -0
  45. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.d.ts +75 -0
  46. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.js +131 -0
  47. package/dist/replication/trystero/TrysteroReplicator/progress.d.ts +57 -0
  48. package/dist/replication/trystero/TrysteroReplicator/progress.js +84 -0
  49. package/dist/replication/trystero/TrysteroReplicator/relayControl.d.ts +20 -0
  50. package/dist/replication/trystero/TrysteroReplicator/relayControl.js +25 -0
  51. package/dist/replication/trystero/TrysteroReplicator/transfers.d.ts +125 -0
  52. package/dist/replication/trystero/TrysteroReplicator/transfers.js +278 -0
  53. package/dist/replication/trystero/TrysteroReplicator.d.ts +65 -481
  54. package/dist/replication/trystero/TrysteroReplicator.js +240 -673
  55. package/dist/replication/trystero/TrysteroReplicatorP2PClient.d.ts +19 -6
  56. package/dist/replication/trystero/TrysteroReplicatorP2PClient.js +29 -25
  57. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.d.ts +66 -0
  58. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.js +142 -0
  59. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +19 -16
  60. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +33 -93
  61. package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +1 -1
  62. package/dist/replication/trystero/p2pReplicationProgress.d.ts +2 -11
  63. package/dist/replication/trystero/replicationTypes.d.ts +88 -0
  64. package/dist/replication/trystero/replicationTypes.js +0 -0
  65. package/dist/replication/trystero/rpcSessionProvider.d.ts +13 -0
  66. package/dist/replication/trystero/rpcSessionProvider.js +0 -0
  67. package/dist/replication/unencryptedContentMessages.d.ts +8 -0
  68. package/dist/replication/unencryptedContentMessages.js +12 -0
  69. package/dist/rpc/RpcRoom/pendingInvocations.d.ts +141 -0
  70. package/dist/rpc/RpcRoom/pendingInvocations.js +225 -0
  71. package/dist/rpc/RpcRoom.d.ts +9 -4
  72. package/dist/rpc/RpcRoom.js +73 -118
  73. package/dist/rpc/RpcSession.d.ts +6 -0
  74. package/dist/rpc/RpcSession.js +11 -0
  75. package/dist/rpc/types.d.ts +2 -0
  76. package/dist/serviceFeatures/targetFilter.d.ts +1 -1
  77. package/dist/serviceFeatures/targetFilter.js +8 -38
  78. package/dist/serviceModules/FileAccessBase.d.ts +4 -0
  79. package/dist/serviceModules/FileAccessBase.js +10 -0
  80. package/dist/serviceModules/Rebuilder.js +29 -5
  81. package/dist/serviceModules/ServiceFileAccessBase/fileNames.d.ts +54 -0
  82. package/dist/serviceModules/ServiceFileAccessBase/fileNames.js +57 -0
  83. package/dist/serviceModules/ServiceFileAccessBase.d.ts +5 -1
  84. package/dist/serviceModules/ServiceFileAccessBase.js +18 -3
  85. package/dist/serviceModules/adapters/IFileSystemAdapter.d.ts +3 -0
  86. package/dist/services/base/RemoteConnection.d.ts +2 -0
  87. package/dist/services/base/RemoteService.js +2 -1
  88. package/dist/services/base/SettingService.js +2 -0
  89. package/dist/settings.d.ts +2 -1
  90. package/dist/settings.js +2 -0
  91. package/dist/storage.d.ts +2 -0
  92. package/dist/storage.js +2 -0
  93. package/dist/worker/bgWorker.js +1 -1
  94. package/docs/development.md +103 -0
  95. package/docs/offline-scanner.md +2 -1
  96. package/docs/p2p-transport-lifecycle.md +24 -0
  97. package/docs/platform-storage.md +22 -0
  98. package/docs/releasing.md +6 -0
  99. package/docs/settings-lifecycle.md +6 -0
  100. package/package.json +1 -1
@@ -1,3 +1,8 @@
1
+ import { getUnencryptedContentRejectionMessage } from "../unencryptedContentMessages.js";
2
+ import {
3
+ getUnencryptedContentRejection,
4
+ isUnencryptedContentRejectedError
5
+ } from "../UnencryptedContentRejectedError.js";
1
6
  import { observeReplicationProgress } from "./replicationProgress.js";
2
7
  import {
3
8
  VER,
@@ -93,6 +98,14 @@ async function* genReplication(s, signal) {
93
98
  void s.on("denied", (err) => push(["denied", err]));
94
99
  void s.on("error", (err) => push(["error", err]));
95
100
  void s.on("paused", (err) => push(["paused", err]));
101
+ const requestSource = s.pull ?? s;
102
+ let policyFailureReported = false;
103
+ const onRequestError = (error) => {
104
+ if (policyFailureReported || !isUnencryptedContentRejectedError(error)) return;
105
+ policyFailureReported = true;
106
+ push(["error", error]);
107
+ };
108
+ requestSource.addListener("requestError", onRequestError);
96
109
  void s.then(() => push(["finally"])).catch(() => push(["finally"]));
97
110
  const onAbort = () => inbox.close();
98
111
  signal.addEventListener("abort", onAbort, { once: true });
@@ -111,6 +124,7 @@ async function* genReplication(s, signal) {
111
124
  }
112
125
  } finally {
113
126
  signal.removeEventListener("abort", onAbort);
127
+ requestSource.removeListener("requestError", onRequestError);
114
128
  s.cancel();
115
129
  inbox.close();
116
130
  }
@@ -166,6 +180,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
166
180
  value.encrypt,
167
181
  value.passphrase,
168
182
  value.E2EEAlgorithm,
183
+ value.encrypt === true && value.acceptUnencryptedContent === true,
169
184
  value.enableCompression,
170
185
  value.pathNormalizationVersion,
171
186
  value.readChunksOnline,
@@ -190,10 +205,15 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
190
205
  return void 0;
191
206
  }
192
207
  connection = openedConnection;
193
- return await prepareInitialFetchFastForward(local, connection.db, {
194
- push: {},
195
- ...snapshot.readChunksOnline ? { pull: { ...selectorOnDemandPull } } : {}
196
- }, isCurrent);
208
+ return await prepareInitialFetchFastForward(
209
+ local,
210
+ connection.db,
211
+ {
212
+ push: {},
213
+ ...snapshot.readChunksOnline ? { pull: { ...selectorOnDemandPull } } : {}
214
+ },
215
+ isCurrent
216
+ );
197
217
  },
198
218
  dispose: async () => {
199
219
  if (disposed) return;
@@ -359,6 +379,17 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
359
379
  this.syncStatus = "ERRORED";
360
380
  this.abortController();
361
381
  this.updateInfo();
382
+ if (isUnencryptedContentRejectedError(e)) {
383
+ Logger(getUnencryptedContentRejectionMessage("replication"), LOG_LEVEL_NOTICE, "sync");
384
+ const rejection = getUnencryptedContentRejection(e);
385
+ if (rejection) {
386
+ Logger(
387
+ `CouchDB replication rejected ${rejection.contentKind}: ${rejection.documentId}`,
388
+ LOG_LEVEL_VERBOSE
389
+ );
390
+ }
391
+ return;
392
+ }
362
393
  Logger("Replication error", LOG_LEVEL_NOTICE, "sync");
363
394
  Logger(e, LOG_LEVEL_VERBOSE);
364
395
  }
@@ -440,6 +471,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
440
471
  return "FAILED";
441
472
  case "error":
442
473
  this.replicationErrored(e);
474
+ if (isUnencryptedContentRejectedError(e)) return "FAILED";
443
475
  Logger("Replication stopped.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
444
476
  if (this.env.services.remote.hadLastPostFailedBySize) {
445
477
  if (e && e.status == 413) {
@@ -469,6 +501,10 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
469
501
  }
470
502
  return "CANCELLED";
471
503
  } catch (ex) {
504
+ if (isUnencryptedContentRejectedError(ex)) {
505
+ this.replicationErrored(ex);
506
+ return "FAILED";
507
+ }
472
508
  Logger(`Unexpected synchronization exception`);
473
509
  Logger(ex, LOG_LEVEL_VERBOSE);
474
510
  return "FAILED";
@@ -1444,6 +1480,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1444
1480
  ...connectionOptions,
1445
1481
  encryptionAlgorithm: settings.E2EEAlgorithm,
1446
1482
  encryptInternalMetadata: usesEncryptedInternalMetadata(settings),
1483
+ acceptUnencryptedContent: settings.acceptUnencryptedContent === true,
1447
1484
  useCouchDBCacheControlHeadersOnly: settings.useCouchDBCacheControlHeadersOnly === true
1448
1485
  }
1449
1486
  );
@@ -1,5 +1,7 @@
1
1
  export { CAPABILITY_NOT_APPLICABLE, CAPABILITY_NOT_IMPLEMENTED, CENTRAL_REMOTE_REPLICATION_READINESS, NO_INTERACTION, PEER_REPLICATION_READINESS, PROVIDER_OWNED_CENTRAL_REMOTE_REPLICATION_READINESS, REPLICATION_CANCELLED, REPLICATION_COMPLETED, REPLICATION_PROGRESS_PRESENTATIONS, USER_INITIATED_REPLICATION_AUTHORITY, defineReplicatorProviderDefinitions, isReplicationCompleted, outcomeFromContinuousOpenReplication, outcomeFromFiniteOpenReplication, replicationBlocked, replicationFailed, supportedOpenReplicationContinuous, supportedOpenReplicationOneShot, supportedOpenReplicationUnattended, supportedStopActiveTransfer, supportedCapability, } from "./ReplicatorProvider.js";
2
2
  export type { ReplicatorInstance } from "./ReplicatorInstance.js";
3
+ export { isUnencryptedContentRejectedError, UnencryptedContentRejectedError } from "./UnencryptedContentRejectedError.js";
4
+ export type { UnencryptedContentKind } from "./UnencryptedContentRejectedError.js";
3
5
  export type { ActiveReplicatorContext, CapabilitySupport, ContinuousReplicationRequest, ContinuousReplicationTrigger, ContinuousRunner, InteractionAuthority, InteractionPermissions, NotApplicableCapability, NotImplementedCapability, NoInteraction, PermittedInteractionPermissions, ReplicationBlockReason, ReplicationAttemptFailure, ReplicationCancelled, ReplicationCompleted, ReplicationFailed, ReplicationInteraction, ReplicationOutcome, ReplicationProgressPresentation, ReplicationReadinessRequirements, ReplicationPartial, ReplicationFailureRequest, ReplicatorConfigurationIdentity, ReplicatorProviderDefinition, ReplicatorProviderDefinitionMap, StopActiveTransferRunner, SupportedCapability, UnattendedOneShotRequest, UnattendedReplicationTrigger, UnattendedOneShotRunner, UserInitiatedOneShotRequest, UserInitiatedReplicationAuthority, UserInitiatedOneShotRunner, } from "./ReplicatorProvider.js";
4
6
  export { CAPABILITY_SUPPORT_KINDS, CAPABILITY_UNAVAILABLE_REASONS } from "./ProviderCapability.js";
5
7
  export { NO_REMOTE_RESOURCE_CAPABILITIES, REMOTE_RESOURCE_KINDS } from "./RemoteResource.js";
@@ -21,6 +21,7 @@ import {
21
21
  supportedStopActiveTransfer,
22
22
  supportedCapability
23
23
  } from "./ReplicatorProvider.js";
24
+ import { isUnencryptedContentRejectedError, UnencryptedContentRejectedError } from "./UnencryptedContentRejectedError.js";
24
25
  import { CAPABILITY_SUPPORT_KINDS, CAPABILITY_UNAVAILABLE_REASONS } from "./ProviderCapability.js";
25
26
  import { NO_REMOTE_RESOURCE_CAPABILITIES, REMOTE_RESOURCE_KINDS } from "./RemoteResource.js";
26
27
  import {
@@ -67,6 +68,7 @@ export {
67
68
  REPLICATION_COMPLETED,
68
69
  REPLICATION_PROGRESS_PRESENTATIONS,
69
70
  USER_INITIATED_REPLICATION_AUTHORITY,
71
+ UnencryptedContentRejectedError,
70
72
  applyCentralRemoteAdministrationMutation,
71
73
  assessRemoteFeatureDocument,
72
74
  centralRemoteAdministrationVerificationFailed,
@@ -76,6 +78,7 @@ export {
76
78
  inspectDatabasePathIdentity,
77
79
  isCentralRemoteAdministrationVerified,
78
80
  isReplicationCompleted,
81
+ isUnencryptedContentRejectedError,
79
82
  milestoneSatisfiesCentralRemoteAdministration,
80
83
  outcomeFromContinuousOpenReplication,
81
84
  outcomeFromFiniteOpenReplication,
@@ -36,12 +36,12 @@ export declare class LiveSyncTrysteroReplicator extends LiveSyncAbstractReplicat
36
36
  onNewPeer(peer: Advertisement): Promise<void>;
37
37
  onPeerLeaved(peerId: string): void;
38
38
  replicateFromCommand(showResult?: boolean): Promise<boolean>;
39
- replicateFrom(peerId: string, showNotice?: boolean, skipOrdinaryReplicationPolicy?: boolean): Promise<import("./TrysteroReplicator.js").P2PReplicationResult>;
40
- requestSynchroniseToPeer(peerId: string): Promise<import("./TrysteroReplicator.js").P2PReplicationResult>;
39
+ replicateFrom(peerId: string, showNotice?: boolean, skipOrdinaryReplicationPolicy?: boolean): Promise<import("./replicationTypes.js").P2PReplicationResult>;
40
+ requestSynchroniseToPeer(peerId: string): Promise<import("./replicationTypes.js").P2PReplicationResult>;
41
41
  getRemoteConfig(peerId: string): Promise<false | import("../../common/types.js").ObsidianLiveSyncSettings>;
42
42
  watchPeer(peerId: string): void;
43
43
  unwatchPeer(peerId: string): void;
44
- sync(peerId: string, showNotice?: boolean): Promise<import("./TrysteroReplicator.js").P2PReplicationResult>;
44
+ sync(peerId: string, showNotice?: boolean): Promise<import("./replicationTypes.js").P2PReplicationResult>;
45
45
  setOnSetup(): void;
46
46
  clearOnSetup(): void;
47
47
  makeDecision(decision: AcceptanceDecision): Promise<void>;
@@ -1,4 +1,4 @@
1
- import type { P2PReplicationResult } from "./TrysteroReplicator.js";
1
+ import type { P2PReplicationResult } from "./replicationTypes.js";
2
2
  /**
3
3
  * Stable de-duplication state for automatic baseline transfers.
4
4
  *
@@ -1,5 +1,5 @@
1
1
  import { type RpcErrorShape } from "../../rpc/index.js";
2
- import type { P2PReplicationResult } from "./TrysteroReplicator.js";
2
+ import type { P2PReplicationResult } from "./replicationTypes.js";
3
3
  /** JSON-safe representation used only while a replication result crosses RPC. */
4
4
  export type P2PReplicationWireResult = {
5
5
  readonly status: "completed";
@@ -0,0 +1,133 @@
1
+ import type { EntryDoc } from "../../../common/types.js";
2
+ import type { P2PDiagnosticInput } from "../../../p2p/p2pDiagnostics.js";
3
+ /**
4
+ * One host/room binding captured before admission is awaited.
5
+ * isCurrent must still identify that binding when admission settles; a
6
+ * replacement room must not receive work authorised for the previous room.
7
+ */
8
+ export interface PeerNotificationTarget {
9
+ isAccepted(): Promise<boolean>;
10
+ isCurrent(): boolean;
11
+ send(): Promise<void>;
12
+ }
13
+ /**
14
+ * Capabilities supplied by the replicator. The relay owns notification policy
15
+ * and feed state; the host retains the database, transport, and transfer lifetime.
16
+ */
17
+ export interface ChangeRelayDependencies<TPullResult> {
18
+ /** Open the database feed using the relay's existing selection policy. */
19
+ createChangesFeed(options: PouchDB.Core.ChangesOptions): PouchDB.Core.Changes<EntryDoc>;
20
+ hasHost(): boolean;
21
+ peerIds(): readonly string[];
22
+ /** Capture identity and operations together, before asynchronous admission. */
23
+ captureNotificationTarget(peerId: string): PeerNotificationTarget | undefined;
24
+ isDisposed(): boolean;
25
+ /** Retain the host notification entry point, including overrides and observers. */
26
+ announceChanges(): void | Promise<void>;
27
+ /** Run a pull through the host's existing finite-operation owner. */
28
+ pullPeer(peerId: string): Promise<TPullResult>;
29
+ dispatchStatus(): void;
30
+ reportDiagnostic(input: P2PDiagnosticInput): void;
31
+ }
32
+ interface ChangeRelayState {
33
+ /** The feed handle remains here until its terminal cleanup clears it. */
34
+ changes: PouchDB.Core.Changes<EntryDoc> | undefined;
35
+ /** Local announcement policy, rather than evidence of peer delivery. */
36
+ isBroadcasting: boolean;
37
+ /** Sources whose progress notifications may start a pull. */
38
+ watchingPeers: Set<string>;
39
+ /** Opaque database sequence; the relay records it without ordering it. */
40
+ lastSeq: string | number;
41
+ }
42
+ /** Change-relay state exposed through the existing replicator facade. */
43
+ export interface ChangeRelay<TPullResult> extends ChangeRelayState {
44
+ enableBroadcastChanges(): void;
45
+ disableBroadcastChanges(): void;
46
+ notifyProgress(excludePeerId?: string): Promise<void> | undefined;
47
+ watchPeer(peerId: string): void;
48
+ unwatchPeer(peerId: string): void;
49
+ onUpdateDatabase(peerId: string): Promise<TPullResult | false>;
50
+ }
51
+ type OnChangeContext = {
52
+ deps: Pick<ChangeRelayDependencies<unknown>, "announceChanges">;
53
+ relay: Pick<ChangeRelayState, "lastSeq">;
54
+ };
55
+ type CloseChangesContext = {
56
+ deps: Pick<ChangeRelayDependencies<unknown>, "dispatchStatus" | "reportDiagnostic">;
57
+ relay: Pick<ChangeRelayState, "changes" | "isBroadcasting">;
58
+ };
59
+ type DisableBroadcastChangesContext = CloseChangesContext;
60
+ type EnableBroadcastChangesContext = {
61
+ deps: Pick<ChangeRelayDependencies<unknown>, "createChangesFeed" | "dispatchStatus" | "reportDiagnostic" | "announceChanges">;
62
+ relay: Pick<ChangeRelayState, "changes" | "isBroadcasting">;
63
+ onChange(change: PouchDB.Core.ChangesResponseChange<EntryDoc>): Promise<void>;
64
+ closeChanges(reason?: unknown): void;
65
+ };
66
+ type NotifyProgressContext = {
67
+ deps: Pick<ChangeRelayDependencies<unknown>, "hasHost" | "peerIds">;
68
+ relay: Pick<ChangeRelayState, "isBroadcasting">;
69
+ notifyPeerProgress(peerId: string): Promise<void>;
70
+ };
71
+ type NotifyPeerProgressContext = {
72
+ deps: Pick<ChangeRelayDependencies<unknown>, "captureNotificationTarget" | "isDisposed" | "reportDiagnostic">;
73
+ relay: Pick<ChangeRelayState, "isBroadcasting">;
74
+ };
75
+ type WatchPeerContext = {
76
+ deps: Pick<ChangeRelayDependencies<unknown>, "dispatchStatus" | "reportDiagnostic">;
77
+ relay: Pick<ChangeRelayState, "watchingPeers">;
78
+ };
79
+ type UnwatchPeerContext = WatchPeerContext;
80
+ type OnUpdateDatabaseContext<TPullResult> = {
81
+ deps: Pick<ChangeRelayDependencies<TPullResult>, "pullPeer" | "reportDiagnostic">;
82
+ relay: Pick<ChangeRelayState, "watchingPeers">;
83
+ };
84
+ /**
85
+ * Record a feed sequence before forwarding the host's existing notification
86
+ * entry point. The sequence is opaque and is not compared or normalised.
87
+ */
88
+ export declare function onChange({ deps, relay }: OnChangeContext, change: Pick<PouchDB.Core.ChangesResponseChange<EntryDoc>, "seq">): Promise<void>;
89
+ /**
90
+ * Close a completed or failed changes feed and report its terminal transition.
91
+ * Feed errors retain their existing diagnostic and log classification.
92
+ */
93
+ export declare function closeChanges({ deps, relay }: CloseChangesContext, reason?: unknown): void;
94
+ /**
95
+ * Stop announcements immediately and request cancellation of the live feed.
96
+ * A synchronous completion callback may already have reported the transition.
97
+ */
98
+ export declare function disableBroadcastChanges({ deps, relay }: DisableBroadcastChangesContext): void;
99
+ /**
100
+ * Enable one live feed and announce its start through the host entry point.
101
+ * Repeated enable calls retain the current feed. Feed callbacks are composed
102
+ * from the separately testable change and close operations.
103
+ */
104
+ export declare function enableBroadcastChanges({ deps, relay, onChange: handleChange, closeChanges: handleClose, }: EnableBroadcastChangesContext): void;
105
+ /**
106
+ * Schedule notifications using the existing per-peer serialisation keys.
107
+ * The returned promise means scheduling finished; it does not await peer sends
108
+ * or remote acquisition. Disabled broadcasting or a missing host returns early.
109
+ */
110
+ export declare function notifyProgress({ deps, relay, notifyPeerProgress: notifyPeer }: NotifyProgressContext, excludePeerId?: string): Promise<void> | undefined;
111
+ /** Send only while the captured host/room remains usable after admission. */
112
+ export declare function notifyPeerProgress({ deps, relay }: NotifyPeerProgressContext, peerId: string): Promise<void>;
113
+ /** Enable pulls from this source; repeated calls still refresh host status. */
114
+ export declare function watchPeer({ deps, relay }: WatchPeerContext, peerId: string): void;
115
+ /** Refuse new progress-triggered pulls without changing an active transfer. */
116
+ export declare function unwatchPeer({ deps, relay }: UnwatchPeerContext, peerId: string): void;
117
+ /**
118
+ * Admit a watched source to the existing serial pull path and retain its result.
119
+ * Follow policy is checked before queueing, as in the replicator facade. The
120
+ * host owns transfer cancellation; removing Follow does not cancel queued work.
121
+ * An unwatched source returns false without starting a pull.
122
+ */
123
+ export declare function onUpdateDatabase<TPullResult>({ deps, relay }: OnUpdateDatabaseContext<TPullResult>, peerId: string): Promise<TPullResult | false>;
124
+ /**
125
+ * Construct one relay without opening a feed or starting transport work.
126
+ *
127
+ * The returned facade and the bound operations share one state object. Existing
128
+ * replicator accessors may replace its fields without creating a second owner.
129
+ * The feed outlives each synchronous operation and closes at an explicit stop
130
+ * or terminal feed event; it does not belong to a short asynchronous scope.
131
+ */
132
+ export declare function createChangeRelay<TPullResult>(deps: ChangeRelayDependencies<TPullResult>): ChangeRelay<TPullResult>;
133
+ export {};
@@ -0,0 +1,176 @@
1
+ import { bindContext } from "octagonal-wheels/context";
2
+ import { serialized } from "octagonal-wheels/concurrency/lock_v2";
3
+ import { fireAndForget } from "octagonal-wheels/promises";
4
+ import { LOG_LEVEL_INFO, LOG_LEVEL_VERBOSE, Logger } from "octagonal-wheels/common/logger";
5
+ import { notificationFailureDiagnostic } from "../p2pReplicationDiagnostics.js";
6
+ async function onChange({ deps, relay }, change) {
7
+ relay.lastSeq = change.seq;
8
+ await deps.announceChanges();
9
+ }
10
+ function closeChanges({ deps, relay }, reason) {
11
+ const wasBroadcasting = relay.isBroadcasting;
12
+ if (reason) {
13
+ if (reason instanceof Error) {
14
+ Logger("Error while broadcasting the changes", LOG_LEVEL_INFO);
15
+ Logger(reason, LOG_LEVEL_VERBOSE);
16
+ } else {
17
+ Logger("Broadcasting the changes has been finished", LOG_LEVEL_INFO);
18
+ Logger(reason, LOG_LEVEL_VERBOSE);
19
+ }
20
+ }
21
+ void relay.changes?.cancel();
22
+ void relay.changes?.removeAllListeners();
23
+ relay.changes = void 0;
24
+ relay.isBroadcasting = false;
25
+ deps.dispatchStatus();
26
+ if (wasBroadcasting) {
27
+ deps.reportDiagnostic({
28
+ category: "sync",
29
+ code: "broadcast-disabled",
30
+ ...reason instanceof Error ? { reason: "replication-error" } : {}
31
+ });
32
+ }
33
+ }
34
+ function disableBroadcastChanges({ deps, relay }) {
35
+ const wasBroadcasting = relay.isBroadcasting;
36
+ relay.changes?.cancel();
37
+ const needsDiagnostic = wasBroadcasting && relay.isBroadcasting;
38
+ relay.isBroadcasting = false;
39
+ deps.dispatchStatus();
40
+ if (needsDiagnostic) {
41
+ deps.reportDiagnostic({ category: "sync", code: "broadcast-disabled" });
42
+ }
43
+ }
44
+ function enableBroadcastChanges({
45
+ deps,
46
+ relay,
47
+ onChange: handleChange,
48
+ closeChanges: handleClose
49
+ }) {
50
+ if (relay.isBroadcasting) {
51
+ return;
52
+ }
53
+ relay.isBroadcasting = true;
54
+ deps.dispatchStatus();
55
+ if (relay.changes) {
56
+ void relay.changes.cancel();
57
+ void relay.changes.removeAllListeners();
58
+ }
59
+ relay.changes = deps.createChangesFeed({
60
+ since: "now",
61
+ live: true,
62
+ include_docs: false,
63
+ selector: { _id: { $gt: "_local/" } }
64
+ });
65
+ void relay.changes.on("change", handleChange);
66
+ void relay.changes.on("error", handleClose);
67
+ void relay.changes.on("complete", handleClose);
68
+ deps.reportDiagnostic({ category: "sync", code: "broadcast-enabled" });
69
+ fireAndForget(async () => await deps.announceChanges());
70
+ }
71
+ function notifyProgress({ deps, relay, notifyPeerProgress: notifyPeer }, excludePeerId) {
72
+ if (!relay.isBroadcasting || !deps.hasHost()) {
73
+ return;
74
+ }
75
+ for (const peerId of deps.peerIds()) {
76
+ if (peerId === excludePeerId) {
77
+ continue;
78
+ }
79
+ void serialized("notifyProgress-" + peerId, () => notifyPeer(peerId));
80
+ }
81
+ return Promise.resolve();
82
+ }
83
+ async function notifyPeerProgress({ deps, relay }, peerId) {
84
+ const target = deps.captureNotificationTarget(peerId);
85
+ if (!target || deps.isDisposed() || !relay.isBroadcasting) {
86
+ return;
87
+ }
88
+ const isAcceptable = await target.isAccepted();
89
+ if (!isAcceptable) {
90
+ deps.reportDiagnostic({
91
+ category: "sync",
92
+ code: "change-notification-ignored",
93
+ peerId,
94
+ reason: "not-accepted"
95
+ });
96
+ Logger("Peer " + peerId + " is not acceptable to notify progress", LOG_LEVEL_VERBOSE);
97
+ return;
98
+ }
99
+ try {
100
+ if (deps.isDisposed() || !relay.isBroadcasting || !target.isCurrent()) {
101
+ return;
102
+ }
103
+ await target.send();
104
+ deps.reportDiagnostic({ category: "sync", code: "change-notification-sent", peerId });
105
+ } catch (error) {
106
+ deps.reportDiagnostic(notificationFailureDiagnostic(peerId, error));
107
+ Logger("Error while notifying progress to " + peerId, LOG_LEVEL_VERBOSE);
108
+ Logger(error, LOG_LEVEL_VERBOSE);
109
+ }
110
+ }
111
+ function watchPeer({ deps, relay }, peerId) {
112
+ const watchingPeers = relay.watchingPeers;
113
+ if (!watchingPeers.has(peerId)) {
114
+ deps.reportDiagnostic({ category: "sync", code: "watch-enabled", peerId });
115
+ }
116
+ watchingPeers.add(peerId);
117
+ deps.dispatchStatus();
118
+ }
119
+ function unwatchPeer({ deps, relay }, peerId) {
120
+ const watchingPeers = relay.watchingPeers;
121
+ if (watchingPeers.has(peerId)) {
122
+ deps.reportDiagnostic({ category: "sync", code: "watch-disabled", peerId });
123
+ }
124
+ watchingPeers.delete(peerId);
125
+ deps.dispatchStatus();
126
+ }
127
+ async function onUpdateDatabase({ deps, relay }, peerId) {
128
+ const watchingPeers = relay.watchingPeers;
129
+ if (watchingPeers.has(peerId)) {
130
+ deps.reportDiagnostic({ category: "sync", code: "change-notification-received", peerId });
131
+ Logger("Progress notification from " + peerId, LOG_LEVEL_VERBOSE);
132
+ return await serialized("onProgress-" + peerId, async () => await deps.pullPeer(peerId));
133
+ }
134
+ deps.reportDiagnostic({
135
+ category: "sync",
136
+ code: "change-notification-ignored",
137
+ peerId,
138
+ reason: "not-watching"
139
+ });
140
+ return false;
141
+ }
142
+ function createChangeRelay(deps) {
143
+ const relay = {
144
+ changes: void 0,
145
+ isBroadcasting: false,
146
+ watchingPeers: /* @__PURE__ */ new Set(),
147
+ lastSeq: ""
148
+ };
149
+ const onChangeForRelay = bindContext({ deps, relay }, onChange);
150
+ const closeChangesForRelay = bindContext({ deps, relay }, closeChanges);
151
+ const enableBroadcastChangesForRelay = bindContext(
152
+ { deps, relay, onChange: onChangeForRelay, closeChanges: closeChangesForRelay },
153
+ enableBroadcastChanges
154
+ );
155
+ const notifyPeerProgressForRelay = bindContext({ deps, relay }, notifyPeerProgress);
156
+ return Object.assign(relay, {
157
+ enableBroadcastChanges: enableBroadcastChangesForRelay,
158
+ disableBroadcastChanges: bindContext({ deps, relay }, disableBroadcastChanges),
159
+ notifyProgress: bindContext({ deps, relay, notifyPeerProgress: notifyPeerProgressForRelay }, notifyProgress),
160
+ watchPeer: bindContext({ deps, relay }, watchPeer),
161
+ unwatchPeer: bindContext({ deps, relay }, unwatchPeer),
162
+ onUpdateDatabase: bindContext({ deps, relay }, onUpdateDatabase)
163
+ });
164
+ }
165
+ export {
166
+ closeChanges,
167
+ createChangeRelay,
168
+ disableBroadcastChanges,
169
+ enableBroadcastChanges,
170
+ notifyPeerProgress,
171
+ notifyProgress,
172
+ onChange,
173
+ onUpdateDatabase,
174
+ unwatchPeer,
175
+ watchPeer
176
+ };
@@ -0,0 +1,55 @@
1
+ import { type ObsidianLiveSyncSettings, type P2PSyncSetting } from "../../../common/types.js";
2
+ import type { Confirm } from "../../../interfaces/Confirm.js";
3
+ import { toP2PWireError } from "../P2PReplicationWire.js";
4
+ declare const SHARE_PASSPHRASE_KEY: "P2P.AskPassphraseForShare";
5
+ declare const DECRYPT_PASSPHRASE_KEY: "P2P.AskPassphraseForDecrypt";
6
+ type ConfigurationExchangeHost = {
7
+ requestConfiguration(peerId: string, timeoutMs: number): Promise<unknown>;
8
+ };
9
+ type ConfigurationExchangeDependencies = {
10
+ isSetup(): boolean;
11
+ /** Return the immutable settings snapshot associated with this room. */
12
+ settings(): P2PSyncSetting;
13
+ askString: Confirm["askString"];
14
+ translate(key: typeof SHARE_PASSPHRASE_KEY | typeof DECRYPT_PASSPHRASE_KEY): string;
15
+ host(): ConfigurationExchangeHost | undefined;
16
+ };
17
+ /** Dependencies needed to share one room's configuration with a peer. */
18
+ export type ShareConfigurationDependencies = Pick<ConfigurationExchangeDependencies, "isSetup" | "settings" | "askString" | "translate">;
19
+ /** Dependencies needed to request and validate a peer's configuration. */
20
+ export type GetRemoteConfigDependencies = Pick<ConfigurationExchangeDependencies, "host" | "askString" | "translate">;
21
+ type ShareConfigurationResult = string | {
22
+ error: ReturnType<typeof toP2PWireError>;
23
+ };
24
+ /**
25
+ * Create the room-scoped settings transfer operations without prompting or contacting a peer.
26
+ *
27
+ * The sharing boundary omits P2P runtime credentials and clears the established local secret fields.
28
+ * Saved remote profile URIs remain part of the exported settings. The supplied settings getter must
29
+ * return the immutable snapshot for the room, rather than settings from a later room or editor state.
30
+ */
31
+ export declare function createConfigurationExchange(dependencies: ConfigurationExchangeDependencies): {
32
+ shareConfiguration: (fromPeerId: string) => Promise<ShareConfigurationResult>;
33
+ getRemoteConfig: (peerId: string) => Promise<false | ObsidianLiveSyncSettings>;
34
+ };
35
+ /**
36
+ * Ask a peer-scoped sharing prompt, then encrypt the room snapshot after the prompt settles.
37
+ *
38
+ * Blank, cancelled, and duplicate prompts deliberately produce an encrypted masked decoy. The
39
+ * returned string is only the RPC payload; it does not apply settings on the receiving device.
40
+ * Settings and prompt callbacks are invoked through the supplied dependency object, preserving
41
+ * host-defined method receivers.
42
+ */
43
+ export declare function shareConfiguration(dependencies: ShareConfigurationDependencies, fromPeerId: string): Promise<ShareConfigurationResult>;
44
+ /**
45
+ * Request and validate a peer's settings without applying them to the local device.
46
+ *
47
+ * The remote request and password prompt remain outside the decrypt/parse/validation catch so
48
+ * transport and prompt rejections propagate. A missing host or empty passphrase returns false;
49
+ * decryption, parsing, and ID-validation failures also return false. Success means
50
+ * a parsed configuration with validated ID-key fields and runtime ICE data omitted.
51
+ * The host remains responsible for persisting or activating those settings. Host and prompt
52
+ * callbacks are invoked through the supplied dependency object, preserving host-defined receivers.
53
+ */
54
+ export declare function getRemoteConfig(dependencies: GetRemoteConfigDependencies, peerId: string): Promise<ObsidianLiveSyncSettings | false>;
55
+ export {};
@@ -0,0 +1,99 @@
1
+ import { configuredIdKey } from "../../../common/idDerivation.js";
2
+ import { omitP2PRuntimeSettings } from "../../../common/types.js";
3
+ import { skipIfDuplicated } from "octagonal-wheels/concurrency/lock_v2";
4
+ import { bindContext } from "octagonal-wheels/context";
5
+ import { decryptWithEphemeralSalt, encryptWithEphemeralSalt } from "octagonal-wheels/encryption/hkdf";
6
+ import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE, Logger } from "octagonal-wheels/common/logger";
7
+ import { toP2PWireError } from "../P2PReplicationWire.js";
8
+ const SHARE_PASSPHRASE_KEY = "P2P.AskPassphraseForShare";
9
+ const DECRYPT_PASSPHRASE_KEY = "P2P.AskPassphraseForDecrypt";
10
+ async function encrypt(data, passphrase) {
11
+ return await encryptWithEphemeralSalt(data, passphrase, true);
12
+ }
13
+ async function decrypt(encryptedData, passphrase) {
14
+ return await decryptWithEphemeralSalt(encryptedData, passphrase);
15
+ }
16
+ function createConfigurationExchange(dependencies) {
17
+ return {
18
+ shareConfiguration: bindContext(dependencies, shareConfiguration),
19
+ getRemoteConfig: bindContext(dependencies, getRemoteConfig)
20
+ };
21
+ }
22
+ async function shareConfiguration(dependencies, fromPeerId) {
23
+ if (dependencies.isSetup()) {
24
+ return { error: toP2PWireError(new Error("The setup is in progress")) };
25
+ }
26
+ const passphrase = await skipIfDuplicated(`getAllConfig-${fromPeerId}`, async () => {
27
+ return await dependencies.askString(
28
+ "Passphrase required",
29
+ dependencies.translate(SHARE_PASSPHRASE_KEY),
30
+ "something you only know",
31
+ true
32
+ );
33
+ });
34
+ const setting = {
35
+ ...omitP2PRuntimeSettings(dependencies.settings()),
36
+ configPassphraseStore: "",
37
+ encryptedCouchDBConnection: "",
38
+ encryptedPassphrase: "",
39
+ pluginSyncExtendedSetting: {}
40
+ };
41
+ delete setting.P2P_managedType;
42
+ delete setting.P2P_managedId;
43
+ delete setting.P2P_managedToken;
44
+ if (!passphrase || passphrase.trim() == "") {
45
+ Logger(
46
+ "Passphrase is required to transfer the configuration. The peer cannot be decrypt the config\nIf you repeatedly receive unintended configuration-sharing requests, change the RPC channel immediately. It allows you to leave the connection and disappear, while they are trying brute force attack for the decoy on their local.",
47
+ LOG_LEVEL_NOTICE
48
+ );
49
+ const decoy = JSON.stringify(
50
+ Object.fromEntries(
51
+ Object.entries(setting).map(([key]) => {
52
+ return [key, "******".repeat(Math.ceil(Math.random() * 10) + 2)];
53
+ })
54
+ )
55
+ );
56
+ const randomPassphrase = Math.random().toString(36).substring(7);
57
+ return encrypt(decoy, randomPassphrase);
58
+ }
59
+ return encrypt(JSON.stringify(setting), passphrase.trim());
60
+ }
61
+ async function getRemoteConfig(dependencies, peerId) {
62
+ const host = dependencies.host();
63
+ if (!host) {
64
+ Logger("Server is not available", LOG_LEVEL_NOTICE);
65
+ return false;
66
+ }
67
+ const encryptedConfig = await host.requestConfiguration(peerId, 0);
68
+ const passphrase = await dependencies.askString(
69
+ "Passphrase required",
70
+ dependencies.translate(DECRYPT_PASSPHRASE_KEY),
71
+ "something you only know",
72
+ true
73
+ );
74
+ if (!passphrase || passphrase.trim() == "") {
75
+ Logger("Passphrase is required to decrypt the configuration. The config cannot be decrypted", LOG_LEVEL_NOTICE);
76
+ return false;
77
+ }
78
+ try {
79
+ const decryptedConfig = JSON.parse(
80
+ await decrypt(encryptedConfig, passphrase)
81
+ );
82
+ const settings = {
83
+ ...decryptedConfig,
84
+ idDerivationVersion: decryptedConfig.idDerivationVersion ?? 0,
85
+ idDerivationKey: decryptedConfig.idDerivationKey ?? ""
86
+ };
87
+ configuredIdKey(settings);
88
+ return omitP2PRuntimeSettings(settings);
89
+ } catch (e) {
90
+ Logger("Error while decrypting the configuration", LOG_LEVEL_NOTICE);
91
+ Logger(e, LOG_LEVEL_VERBOSE);
92
+ return false;
93
+ }
94
+ }
95
+ export {
96
+ createConfigurationExchange,
97
+ getRemoteConfig,
98
+ shareConfiguration
99
+ };