@vrtmrz/livesync-commonlib 0.4.3 → 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 (60) hide show
  1. package/README.md +2 -2
  2. package/dist/interfaces/StorageAccess.d.ts +8 -2
  3. package/dist/platform/FilePathIndex.d.ts +110 -0
  4. package/dist/platform/FilePathIndex.js +146 -0
  5. package/dist/replication/trystero/LiveSyncTrysteroReplicator.d.ts +3 -3
  6. package/dist/replication/trystero/P2PAutomationCoordinator.d.ts +1 -1
  7. package/dist/replication/trystero/P2PReplicationWire.d.ts +1 -1
  8. package/dist/replication/trystero/TrysteroReplicator/changeRelay.d.ts +133 -0
  9. package/dist/replication/trystero/TrysteroReplicator/changeRelay.js +176 -0
  10. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.d.ts +55 -0
  11. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.js +99 -0
  12. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.d.ts +83 -0
  13. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.js +121 -0
  14. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.d.ts +75 -0
  15. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.js +131 -0
  16. package/dist/replication/trystero/TrysteroReplicator/progress.d.ts +57 -0
  17. package/dist/replication/trystero/TrysteroReplicator/progress.js +84 -0
  18. package/dist/replication/trystero/TrysteroReplicator/relayControl.d.ts +20 -0
  19. package/dist/replication/trystero/TrysteroReplicator/relayControl.js +25 -0
  20. package/dist/replication/trystero/TrysteroReplicator/transfers.d.ts +125 -0
  21. package/dist/replication/trystero/TrysteroReplicator/transfers.js +278 -0
  22. package/dist/replication/trystero/TrysteroReplicator.d.ts +65 -483
  23. package/dist/replication/trystero/TrysteroReplicator.js +240 -673
  24. package/dist/replication/trystero/TrysteroReplicatorP2PClient.d.ts +19 -6
  25. package/dist/replication/trystero/TrysteroReplicatorP2PClient.js +29 -25
  26. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.d.ts +66 -0
  27. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.js +142 -0
  28. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +19 -16
  29. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +33 -93
  30. package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +1 -1
  31. package/dist/replication/trystero/p2pReplicationProgress.d.ts +2 -11
  32. package/dist/replication/trystero/replicationTypes.d.ts +88 -0
  33. package/dist/replication/trystero/replicationTypes.js +0 -0
  34. package/dist/replication/trystero/rpcSessionProvider.d.ts +13 -0
  35. package/dist/replication/trystero/rpcSessionProvider.js +0 -0
  36. package/dist/rpc/RpcRoom/pendingInvocations.d.ts +141 -0
  37. package/dist/rpc/RpcRoom/pendingInvocations.js +225 -0
  38. package/dist/rpc/RpcRoom.d.ts +9 -4
  39. package/dist/rpc/RpcRoom.js +73 -118
  40. package/dist/rpc/RpcSession.d.ts +6 -0
  41. package/dist/rpc/RpcSession.js +11 -0
  42. package/dist/rpc/types.d.ts +2 -0
  43. package/dist/serviceFeatures/targetFilter.d.ts +1 -1
  44. package/dist/serviceFeatures/targetFilter.js +8 -38
  45. package/dist/serviceModules/FileAccessBase.d.ts +4 -0
  46. package/dist/serviceModules/FileAccessBase.js +10 -0
  47. package/dist/serviceModules/Rebuilder.js +1 -1
  48. package/dist/serviceModules/ServiceFileAccessBase/fileNames.d.ts +54 -0
  49. package/dist/serviceModules/ServiceFileAccessBase/fileNames.js +57 -0
  50. package/dist/serviceModules/ServiceFileAccessBase.d.ts +5 -1
  51. package/dist/serviceModules/ServiceFileAccessBase.js +18 -3
  52. package/dist/serviceModules/adapters/IFileSystemAdapter.d.ts +3 -0
  53. package/dist/storage.d.ts +2 -0
  54. package/dist/storage.js +2 -0
  55. package/docs/development.md +103 -0
  56. package/docs/p2p-transport-lifecycle.md +24 -0
  57. package/docs/platform-storage.md +22 -0
  58. package/docs/releasing.md +6 -0
  59. package/docs/settings-lifecycle.md +4 -2
  60. package/package.json +1 -1
@@ -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
+ };
@@ -0,0 +1,83 @@
1
+ import type { TimeoutScheduler } from "octagonal-wheels/concurrency/deferredAction";
2
+ import type { P2PSyncSetting } from "../../../common/types.js";
3
+ import type { MessageTranslator } from "../../../services/base/MessageTranslator.js";
4
+ import type { Advertisement } from "../types.js";
5
+ import type { P2PPeerAcceptance, P2PReplicationResult, P2PConfiguredTargetResult, P2PConfiguredReplicationResult } from "../replicationTypes.js";
6
+ export type { P2PConfiguredTargetResult, P2PConfiguredReplicationResult } from "../replicationTypes.js";
7
+ /** Narrow host capabilities used to synchronise the configured peer list. */
8
+ export interface ConfiguredTargetsDependencies {
9
+ /** Read current settings; enablement and configured names are read separately. */
10
+ currentSettings(): P2PSyncSetting;
11
+ /** Return the advertisements currently known to the room. */
12
+ advertisements(): readonly Advertisement[];
13
+ /** Evaluate current admission policy without opening any user interface. */
14
+ evaluatePeerAcceptance(peerId: string): Promise<P2PPeerAcceptance | undefined>;
15
+ /** Preserve the host's existing baseline-work deduplication and ordering. */
16
+ runBaseline(peerName: string, task: () => Promise<P2PReplicationResult>): Promise<P2PReplicationResult>;
17
+ /** Preserve dynamic host sync dispatch, result presentation, and cancellation. */
18
+ sync(peerId: string, showResult: boolean, signal?: AbortSignal): Promise<P2PReplicationResult>;
19
+ /** Subscribe to advertisement changes and return the synchronous detacher. */
20
+ onAdvertisement(listener: () => void): () => void;
21
+ /** Schedule a timeout and return its matching cancellation function. */
22
+ scheduleTimeout: TimeoutScheduler;
23
+ /** Translate the existing configured-sync log messages. */
24
+ translate: MessageTranslator;
25
+ }
26
+ /** Configured-target operation exposed by the existing replicator facade. */
27
+ export interface ConfiguredTargets {
28
+ replicateFromCommand(showResult?: boolean, discoveryTimeoutMs?: number, callerSignal?: AbortSignal): Promise<P2PConfiguredReplicationResult>;
29
+ }
30
+ /** Only discovery capabilities are needed while waiting for advertisements. */
31
+ export type AdvertisementWaitContext = {
32
+ deps: Pick<ConfiguredTargetsDependencies, "advertisements" | "onAdvertisement" | "scheduleTimeout">;
33
+ };
34
+ /** The workflow consumes a composed wait operation, not its timer or subscription dependencies. */
35
+ export type ConfiguredSyncContext = {
36
+ deps: Pick<ConfiguredTargetsDependencies, "currentSettings" | "advertisements" | "evaluatePeerAcceptance" | "runBaseline" | "sync" | "translate">;
37
+ waitForConfiguredAdvertisements(peerNames: readonly string[], timeoutMs: number, signal?: AbortSignal): Promise<void>;
38
+ };
39
+ /** Resources acquired for one discovery wait; no state is shared between waits. */
40
+ export type AdvertisementWaitState = {
41
+ signal: AbortSignal | undefined;
42
+ resolve(): void;
43
+ detachAdvertisement(): void;
44
+ cancelTimeout: (() => void) | undefined;
45
+ };
46
+ /** Construct bindings without reading settings, subscribing, scheduling, or starting replication. */
47
+ export declare function createConfiguredTargets(deps: ConfiguredTargetsDependencies): ConfiguredTargets;
48
+ /** Read, trim, and de-duplicate the already selected policy string. */
49
+ export declare function configuredPeerNames(names: string): string[];
50
+ /** Find a peer in the advertisement snapshot supplied by the caller. */
51
+ export declare function findAdvertisement(advertisements: readonly Advertisement[], peerName: string): Advertisement | undefined;
52
+ /** Re-read advertisements for each configured name, preserving the existing discovery predicate. */
53
+ export declare function areConfiguredPeersPresent(deps: Pick<ConfiguredTargetsDependencies, "advertisements">, peerNames: readonly string[]): boolean;
54
+ /** Release event, abort, and timeout hooks synchronously before completing the wait. */
55
+ export declare function finishAdvertisementWait(state: AdvertisementWaitState, abortListener: () => void): void;
56
+ /** Finish discovery only after its captured set of names is currently present. */
57
+ export declare function finishIfConfiguredPeersPresent(deps: Pick<ConfiguredTargetsDependencies, "advertisements">, peerNames: readonly string[], finish: () => void): void;
58
+ /**
59
+ * Register one event-driven discovery wait. The Promise adapter supplies resolve;
60
+ * this function needs only advertisements, subscription, and timing capabilities.
61
+ * Registration order and the final recheck preserve the existing handling of
62
+ * advertisements and aborts delivered during setup. Setup errors propagate to
63
+ * the adapter's executor, which turns them into promise rejection.
64
+ */
65
+ export declare function registerAdvertisementWait({ deps }: AdvertisementWaitContext, peerNames: readonly string[], timeoutMs: number, signal: AbortSignal | undefined, resolve: () => void): void;
66
+ /**
67
+ * Adapt advertisement events, timeout, and abort to one promise without an outer
68
+ * async/await wrapper. Initial checks also run inside the executor, so their
69
+ * exceptions remain rejections. Timeout and cancellation end discovery waiting;
70
+ * target processing still classifies each target separately.
71
+ */
72
+ export declare function waitForConfiguredAdvertisements(context: AdvertisementWaitContext, peerNames: readonly string[], timeoutMs: number, signal?: AbortSignal): Promise<void>;
73
+ /** Keep the target-level outcome mapping used by the facade. */
74
+ export declare function configuredTargetResult(name: string, peerId: string, result: P2PReplicationResult): P2PConfiguredTargetResult;
75
+ /**
76
+ * Synchronise configured peers sequentially without opening peer-selection UI.
77
+ *
78
+ * The configured-name list is fixed for this invocation, while advertisement
79
+ * identity and admission are re-read for each target. A returned failed sync
80
+ * becomes a failed target; thrown settings, admission, baseline, timer, or sync
81
+ * errors propagate to the caller unchanged.
82
+ */
83
+ export declare function replicateFromCommand({ deps, waitForConfiguredAdvertisements }: ConfiguredSyncContext, showResult?: boolean, discoveryTimeoutMs?: number, callerSignal?: AbortSignal): Promise<P2PConfiguredReplicationResult>;
@@ -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
+ };