@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
@@ -1,22 +1,35 @@
1
1
  import type { PouchDBShim, SomeDocument } from "../../pouchdb/ReplicatorShim.js";
2
- import type { TrysteroReplicatorP2PServer } from "./TrysteroReplicatorP2PServer.js";
2
+ import type { RpcSessionProvider } from "./rpcSessionProvider.js";
3
3
  import { type BindableObject, type NonPrivateMethodKeys, type Response } from "./types.js";
4
4
  import type { JsonLike } from "../../rpc/index.js";
5
- export declare class TrysteroReplicatorP2PClient {
6
- _server: TrysteroReplicatorP2PServer;
5
+ export declare class TrysteroReplicatorP2PClient<TProvider extends RpcSessionProvider = RpcSessionProvider> {
6
+ _server: TProvider | undefined;
7
7
  _connectedPeerId: string;
8
- _remoteDB: PouchDBShim<SomeDocument<object>>;
8
+ _remoteDB: PouchDBShim<SomeDocument<object>> | undefined;
9
+ /** The cached remote database facade, or undefined after this client closes. */
9
10
  get remoteDB(): PouchDBShim<SomeDocument<object>>;
10
- /** Bind the reverse database RPC calls to one finite-operation signal. */
11
+ /**
12
+ * Return the cached database facade or bind its calls to a finite-operation signal.
13
+ * Each facade resolves the provider's current room when an operation runs.
14
+ *
15
+ * @throws {Error} when this client has closed.
16
+ */
11
17
  getRemoteDB(signal?: AbortSignal): PouchDBShim<SomeDocument<object>>;
12
- constructor(server: TrysteroReplicatorP2PServer, connectedPeerId: string);
18
+ constructor(server: TProvider, connectedPeerId: string);
13
19
  _bindRemoteDB(signal?: AbortSignal): PouchDBShim<SomeDocument<object>>;
14
20
  private getCallOptions;
21
+ private getRpcRoom;
15
22
  _sendRPC(type: string, args: JsonLike[], timeout?: number): Promise<JsonLike>;
16
23
  __onResponse(_data: Response): void;
17
24
  bindRemoteFunction<T extends unknown[], U>(type: string, timeout?: number, signal?: AbortSignal): (...args: T) => Promise<U>;
18
25
  invokeRemoteFunction<T extends unknown[], U>(type: string, args: T, timeout?: number, signal?: AbortSignal): Promise<U>;
26
+ /**
27
+ * Send a notification without requesting an RPC response.
28
+ * Resolves when the transport send completes.
29
+ */
30
+ notifyRemoteFunction(type: string, args: JsonLike[]): Promise<void>;
19
31
  bindRemoteObjectFunctions<T extends BindableObject<any>, U extends keyof T>(key: U, timeout?: number): (...args: Parameters<T[U]>) => Promise<Awaited<ReturnType<T[U]>>>;
20
32
  invokeRemoteObjectFunction<T extends BindableObject<any>, U extends NonPrivateMethodKeys<T>>(key: U, args: Parameters<T[U]>, timeout?: number, signal?: AbortSignal): Promise<Awaited<ReturnType<T[U]>>>;
33
+ /** Release the cached facade and provider reference; captured operations then reject without sending. */
21
34
  close(): void;
22
35
  }
@@ -7,12 +7,22 @@ class TrysteroReplicatorP2PClient {
7
7
  _server;
8
8
  _connectedPeerId;
9
9
  _remoteDB;
10
+ /** The cached remote database facade, or undefined after this client closes. */
10
11
  get remoteDB() {
11
12
  return this._remoteDB;
12
13
  }
13
- /** Bind the reverse database RPC calls to one finite-operation signal. */
14
+ /**
15
+ * Return the cached database facade or bind its calls to a finite-operation signal.
16
+ * Each facade resolves the provider's current room when an operation runs.
17
+ *
18
+ * @throws {Error} when this client has closed.
19
+ */
14
20
  getRemoteDB(signal) {
15
- return signal ? this._bindRemoteDB(signal) : this._remoteDB;
21
+ const remoteDB = this._remoteDB;
22
+ if (remoteDB === void 0) {
23
+ throw new Error("Not connected to any room");
24
+ }
25
+ return signal ? this._bindRemoteDB(signal) : remoteDB;
16
26
  }
17
27
  constructor(server, connectedPeerId) {
18
28
  this._server = server;
@@ -33,50 +43,44 @@ class TrysteroReplicatorP2PClient {
33
43
  getCallOptions(timeout, signal) {
34
44
  return { timeoutMs: timeout, signal };
35
45
  }
36
- _sendRPC(type, args, timeout = DEFAULT_RPC_TIMEOUT) {
46
+ getRpcRoom() {
37
47
  const room = this._server?.rpcRoom;
38
48
  if (!room) {
39
49
  throw new Error("Not connected to any room");
40
50
  }
41
- const session = room.session(this._connectedPeerId);
42
- return session.call(toRpcMethodName(type), args, timeout);
51
+ return room;
52
+ }
53
+ _sendRPC(type, args, timeout = DEFAULT_RPC_TIMEOUT) {
54
+ return this.getRpcRoom().session(this._connectedPeerId).call(toRpcMethodName(type), args, timeout);
43
55
  }
44
56
  __onResponse(_data) {
45
57
  }
46
58
  bindRemoteFunction(type, timeout = DEFAULT_RPC_TIMEOUT, signal) {
47
59
  return async (...args) => {
48
- const room = this._server?.rpcRoom;
49
- if (!room) {
50
- throw new Error("Not connected to any room");
51
- }
52
- return await room.session(this._connectedPeerId).call(toRpcMethodName(type), args, this.getCallOptions(timeout, signal));
60
+ return await this.getRpcRoom().session(this._connectedPeerId).call(toRpcMethodName(type), args, this.getCallOptions(timeout, signal));
53
61
  };
54
62
  }
55
63
  async invokeRemoteFunction(type, args, timeout = DEFAULT_RPC_TIMEOUT, signal) {
56
- const room = this._server?.rpcRoom;
57
- if (!room) {
58
- throw new Error("Not connected to any room");
59
- }
60
- return await room.session(this._connectedPeerId).call(toRpcMethodName(type), args, this.getCallOptions(timeout, signal));
64
+ return await this.getRpcRoom().session(this._connectedPeerId).call(toRpcMethodName(type), args, this.getCallOptions(timeout, signal));
65
+ }
66
+ /**
67
+ * Send a notification without requesting an RPC response.
68
+ * Resolves when the transport send completes.
69
+ */
70
+ async notifyRemoteFunction(type, args) {
71
+ await this.getRpcRoom().session(this._connectedPeerId).notify(toRpcMethodName(type), args);
61
72
  }
62
73
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- This is a generic function binder, so we can't be more specific about the types here.
63
74
  bindRemoteObjectFunctions(key, timeout = DEFAULT_RPC_TIMEOUT) {
64
75
  return async (...args) => {
65
- const room = this._server?.rpcRoom;
66
- if (!room) {
67
- throw new Error("Not connected to any room");
68
- }
69
- return await room.session(this._connectedPeerId).call(toRpcMethodName(key.toString()), args, timeout);
76
+ return await this.getRpcRoom().session(this._connectedPeerId).call(toRpcMethodName(key.toString()), args, timeout);
70
77
  };
71
78
  }
72
79
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- This is a generic function binder, so we can't be more specific about the types here.
73
80
  async invokeRemoteObjectFunction(key, args, timeout = DEFAULT_RPC_TIMEOUT, signal) {
74
- const room = this._server?.rpcRoom;
75
- if (!room) {
76
- throw new Error("Not connected to any room");
77
- }
78
- return await room.session(this._connectedPeerId).call(toRpcMethodName(key.toString()), args, this.getCallOptions(timeout, signal));
81
+ return await this.getRpcRoom().session(this._connectedPeerId).call(toRpcMethodName(key.toString()), args, this.getCallOptions(timeout, signal));
79
82
  }
83
+ /** Release the cached facade and provider reference; captured operations then reject without sending. */
80
84
  close() {
81
85
  this._remoteDB = void 0;
82
86
  this._server = void 0;
@@ -0,0 +1,66 @@
1
+ import { type P2PSyncSetting } from "../../../common/types.js";
2
+ import type { StoredMapLike } from "../../../dataobject/StoredMap.js";
3
+ import type { Confirm } from "../../../interfaces/Confirm.js";
4
+ import type { Computed } from "octagonal-wheels/dataobject/Computed";
5
+ import { type Advertisement } from "../types.js";
6
+ import type { P2PPeerAcceptance } from "../replicationTypes.js";
7
+ export type AcceptanceDecision = {
8
+ peerId: string;
9
+ name: string;
10
+ decision: boolean;
11
+ isTemporary: boolean;
12
+ };
13
+ export type RevokeAcceptanceDecision = {
14
+ peerId: string;
15
+ name: string;
16
+ };
17
+ /** Host capabilities and dynamic method overrides used for peer admission. */
18
+ export interface PeerAdmissionDependencies {
19
+ isEnabled(): boolean;
20
+ advertisement(peerId: string): Advertisement | undefined;
21
+ currentSettings(): P2PSyncSetting;
22
+ acceptedPeers(): Pick<StoredMapLike<boolean>, "get" | "set" | "delete">;
23
+ temporaryAcceptedPeers(): Map<string, boolean>;
24
+ confirm(): Pick<Confirm, "askSelectStringDialogue">;
25
+ dispatchConnectionStatus(): Promise<void>;
26
+ acceptablePatterns(): Pick<Computed<[P2PSyncSetting], RegExp[]>, "update">;
27
+ deniedPatterns(): Pick<Computed<[P2PSyncSetting], RegExp[]>, "update">;
28
+ /** Forward to the host's overridable `_confirmUserToAccept` method. */
29
+ promptPeerAcceptance(peerId: string): Promise<boolean>;
30
+ /** Forward to the host's overridable `evaluatePeerAcceptance` method. */
31
+ evaluatePeerAcceptance(peerId: string): Promise<P2PPeerAcceptance>;
32
+ /** Forward to the host's overridable `confirmUserToAccept` method. */
33
+ confirmUserToAccept(peerId: string): Promise<boolean>;
34
+ }
35
+ type PeerAdmissionContext<Keys extends keyof PeerAdmissionDependencies> = {
36
+ deps: Pick<PeerAdmissionDependencies, Keys>;
37
+ };
38
+ type MakeDecisionContext = PeerAdmissionContext<"acceptedPeers" | "temporaryAcceptedPeers" | "dispatchConnectionStatus">;
39
+ type RevokeDecisionContext = MakeDecisionContext;
40
+ type PromptPeerAcceptanceContext = PeerAdmissionContext<"advertisement" | "confirm" | "temporaryAcceptedPeers" | "acceptedPeers" | "dispatchConnectionStatus">;
41
+ type ConfirmUserToAcceptContext = PeerAdmissionContext<"promptPeerAcceptance">;
42
+ type EvaluatePeerAcceptanceContext = PeerAdmissionContext<"isEnabled" | "advertisement" | "temporaryAcceptedPeers" | "acceptedPeers" | "currentSettings" | "acceptablePatterns" | "deniedPatterns">;
43
+ type IsAcceptablePeerContext = PeerAdmissionContext<"advertisement" | "temporaryAcceptedPeers" | "acceptedPeers" | "currentSettings" | "dispatchConnectionStatus" | "evaluatePeerAcceptance" | "confirmUserToAccept">;
44
+ export interface PeerAdmission {
45
+ makeDecision(decision: AcceptanceDecision): Promise<void>;
46
+ revokeDecision(decision: RevokeAcceptanceDecision): Promise<void>;
47
+ confirmUserToAccept(peerId: string): Promise<boolean>;
48
+ promptPeerAcceptance(peerId: string): Promise<boolean>;
49
+ evaluatePeerAcceptance(peerId: string): Promise<P2PPeerAcceptance>;
50
+ isAcceptablePeer(peerId: string): Promise<boolean>;
51
+ }
52
+ /** Persist a manual peer decision, then publish its updated connection status. */
53
+ export declare function makeDecision({ deps }: MakeDecisionContext, decision: AcceptanceDecision): Promise<void>;
54
+ /** Remove the temporary and persisted decisions, then publish the updated status. */
55
+ export declare function revokeDecision({ deps }: RevokeDecisionContext, decision: RevokeAcceptanceDecision): Promise<void>;
56
+ /** Ask the user for a peer decision and apply the selected scope immediately. */
57
+ export declare function promptPeerAcceptance({ deps }: PromptPeerAcceptanceContext, peerId: string): Promise<boolean>;
58
+ /** Deduplicate simultaneous prompts for the same peer while preserving host overrides. */
59
+ export declare function confirmUserToAccept({ deps }: ConfirmUserToAcceptContext, peerId: string): Promise<boolean>;
60
+ /** Evaluate stored and automatic policy without prompting or changing decisions. */
61
+ export declare function evaluatePeerAcceptance({ deps }: EvaluatePeerAcceptanceContext, peerId: string): Promise<P2PPeerAcceptance>;
62
+ /** Enforce automatic admission first, then headless policy and the host prompt override. */
63
+ export declare function isAcceptablePeer({ deps }: IsAcceptablePeerContext, peerId: string): Promise<boolean>;
64
+ /** Compose peer-admission operations from live host capabilities without owning state. */
65
+ export declare function createPeerAdmission(deps: PeerAdmissionDependencies): PeerAdmission;
66
+ export {};
@@ -0,0 +1,142 @@
1
+ import { AutoAccepting } from "../../../common/types.js";
2
+ import { shareRunningResult } from "octagonal-wheels/concurrency/lock_v2";
3
+ import { bindContext } from "octagonal-wheels/context";
4
+ import { ResponsePreventedError } from "../types.js";
5
+ async function makeDecision({ deps }, decision) {
6
+ if (decision.decision) {
7
+ if (decision.isTemporary) {
8
+ deps.temporaryAcceptedPeers().set(decision.peerId, true);
9
+ } else {
10
+ await deps.acceptedPeers().set(decision.name, true);
11
+ }
12
+ } else if (decision.isTemporary) {
13
+ deps.temporaryAcceptedPeers().set(decision.peerId, false);
14
+ } else {
15
+ await deps.acceptedPeers().set(decision.name, false);
16
+ }
17
+ await deps.dispatchConnectionStatus();
18
+ }
19
+ async function revokeDecision({ deps }, decision) {
20
+ deps.temporaryAcceptedPeers().delete(decision.peerId);
21
+ await deps.acceptedPeers().delete(decision.name);
22
+ await deps.dispatchConnectionStatus();
23
+ }
24
+ function promptPeerAcceptance({ deps }, peerId) {
25
+ const peerInfo = deps.advertisement(peerId);
26
+ if (!peerInfo) {
27
+ throw new Error("Unknown Peer");
28
+ }
29
+ const peerName = peerInfo.name;
30
+ const message = `Are you sure to establish connection to ${peerName} (${peerId})?
31
+ You can chose as follows:
32
+ - Accept: Accept all connections from this peer.
33
+ - Ignore: Reject all connections from this peer.
34
+ - Accept Temporarily: Accept the connection for this session only.
35
+ - Ignore Temporarily: Reject the connection for this session only.
36
+
37
+ >[!INFO] You can revoke your decision from the Peer-to-Peer Replicator Pane.`;
38
+ const OPTION_ACCEPT = "Accept";
39
+ const OPTION_IGNORE = "Ignore";
40
+ const OPTION_ACCEPT_TEMPORARILY = "Accept Temporarily";
41
+ const OPTION_IGNORE_TEMPORARILY = "Ignore Temporarily";
42
+ const OPTIONS = [OPTION_ACCEPT, OPTION_IGNORE, OPTION_ACCEPT_TEMPORARILY, OPTION_IGNORE_TEMPORARILY];
43
+ return deps.confirm().askSelectStringDialogue(message, OPTIONS, {
44
+ title: "P2P Connection Request",
45
+ defaultAction: "Ignore Temporarily",
46
+ timeout: 30
47
+ }).then((decision) => {
48
+ if (decision === OPTION_ACCEPT_TEMPORARILY) {
49
+ deps.temporaryAcceptedPeers().set(peerId, true);
50
+ void deps.dispatchConnectionStatus();
51
+ return true;
52
+ } else if (decision === OPTION_IGNORE_TEMPORARILY) {
53
+ deps.temporaryAcceptedPeers().set(peerId, false);
54
+ void deps.dispatchConnectionStatus();
55
+ return false;
56
+ } else if (decision === OPTION_ACCEPT) {
57
+ deps.temporaryAcceptedPeers().delete(peerId);
58
+ void deps.acceptedPeers().set(peerName, true);
59
+ void deps.dispatchConnectionStatus();
60
+ return true;
61
+ } else if (decision === OPTION_IGNORE) {
62
+ deps.temporaryAcceptedPeers().delete(peerId);
63
+ void deps.acceptedPeers().set(peerName, false);
64
+ void deps.dispatchConnectionStatus();
65
+ return false;
66
+ } else {
67
+ throw new ResponsePreventedError("User Accepting failed");
68
+ }
69
+ });
70
+ }
71
+ function confirmUserToAccept({ deps }, peerId) {
72
+ return shareRunningResult(`confirmUserToAccept-${peerId}`, () => deps.promptPeerAcceptance(peerId));
73
+ }
74
+ async function evaluatePeerAcceptance({ deps }, peerId) {
75
+ if (!deps.isEnabled()) {
76
+ return "unknown";
77
+ }
78
+ const peerInfo = deps.advertisement(peerId);
79
+ if (!peerInfo) {
80
+ return "unknown";
81
+ }
82
+ const peerName = peerInfo.name;
83
+ if (deps.temporaryAcceptedPeers().has(peerId)) {
84
+ return deps.temporaryAcceptedPeers().get(peerId) ? "accepted" : "rejected";
85
+ }
86
+ const accepted = await deps.acceptedPeers().get(peerName);
87
+ if (accepted !== void 0 && accepted !== null) {
88
+ return accepted ? "accepted" : "rejected";
89
+ }
90
+ const currentSettings = { ...deps.currentSettings() };
91
+ const isAcceptable = (await deps.acceptablePatterns().update(currentSettings)).value.some(
92
+ (pattern) => pattern.test(peerName)
93
+ );
94
+ const isDeny = (await deps.deniedPatterns().update(currentSettings)).value.some(
95
+ (pattern) => pattern.test(peerName)
96
+ );
97
+ if (isDeny) {
98
+ return "rejected";
99
+ }
100
+ if (isAcceptable || currentSettings.P2P_AutoAccepting === AutoAccepting.ALL) {
101
+ return "accepted";
102
+ }
103
+ return "undecided";
104
+ }
105
+ async function isAcceptablePeer({ deps }, peerId) {
106
+ const acceptance = await deps.evaluatePeerAcceptance(peerId);
107
+ if (acceptance === "accepted") {
108
+ const peerName = deps.advertisement(peerId)?.name;
109
+ const persisted = peerName ? await deps.acceptedPeers().get(peerName) : void 0;
110
+ if (!deps.temporaryAcceptedPeers().has(peerId) && persisted == null) {
111
+ deps.temporaryAcceptedPeers().set(peerId, true);
112
+ void deps.dispatchConnectionStatus();
113
+ }
114
+ return true;
115
+ }
116
+ if (acceptance === "rejected" || acceptance === "unknown") {
117
+ return false;
118
+ }
119
+ if (deps.currentSettings().P2P_IsHeadless) {
120
+ return false;
121
+ }
122
+ return await deps.confirmUserToAccept(peerId);
123
+ }
124
+ function createPeerAdmission(deps) {
125
+ return {
126
+ makeDecision: bindContext({ deps }, makeDecision),
127
+ revokeDecision: bindContext({ deps }, revokeDecision),
128
+ confirmUserToAccept: bindContext({ deps }, confirmUserToAccept),
129
+ promptPeerAcceptance: bindContext({ deps }, promptPeerAcceptance),
130
+ evaluatePeerAcceptance: bindContext({ deps }, evaluatePeerAcceptance),
131
+ isAcceptablePeer: bindContext({ deps }, isAcceptablePeer)
132
+ };
133
+ }
134
+ export {
135
+ confirmUserToAccept,
136
+ createPeerAdmission,
137
+ evaluatePeerAcceptance,
138
+ isAcceptablePeer,
139
+ makeDecision,
140
+ promptPeerAcceptance,
141
+ revokeDecision
142
+ };
@@ -1,4 +1,4 @@
1
- import { type Room } from "@trystero-p2p/nostr";
1
+ import { type Room, joinRoom } from "@trystero-p2p/nostr";
2
2
  import { type P2PSyncSetting } from "../../common/types.js";
3
3
  import { type ReplicatorHostEnv, type FullFilledDeviceInfo, type Request, type Response, type Payload, type Advertisement, type BindableObject, type BindableFunction } from "./types.js";
4
4
  import { StoredMapLike } from "../../dataobject/StoredMap.js";
@@ -6,22 +6,18 @@ import { TrysteroReplicatorP2PClient } from "./TrysteroReplicatorP2PClient.js";
6
6
  import { Computed } from "octagonal-wheels/dataobject/Computed";
7
7
  import { RpcRoom, type JsonLike, type RpcRequestContext } from "../../rpc/index.js";
8
8
  import { type DiagRTCStats } from "../../rpc/transports/DiagRTCPeerConnections.types.js";
9
+ import type { P2PPeerAcceptance } from "./replicationTypes.js";
10
+ export type { P2PPeerAcceptance } from "./replicationTypes.js";
11
+ import { type AcceptanceDecision, type RevokeAcceptanceDecision } from "./TrysteroReplicatorP2PServer/peerAdmission.js";
12
+ export type { AcceptanceDecision, RevokeAcceptanceDecision } from "./TrysteroReplicatorP2PServer/peerAdmission.js";
13
+ /** Room creation is borrowed; the Server still owns each joined room and its RPC bindings. */
14
+ export interface P2PServerOptions {
15
+ createRoom?: typeof joinRoom;
16
+ }
9
17
  export type PeerInfo = Advertisement & {
10
18
  isAccepted: boolean | undefined;
11
19
  isTemporaryAccepted: boolean | undefined;
12
20
  };
13
- export type AcceptanceDecision = {
14
- peerId: string;
15
- name: string;
16
- decision: boolean;
17
- isTemporary: boolean;
18
- };
19
- export type RevokeAcceptanceDecision = {
20
- peerId: string;
21
- name: string;
22
- };
23
- /** Non-interactive result of evaluating the persisted and automatic peer policy. */
24
- export type P2PPeerAcceptance = "accepted" | "rejected" | "undecided" | "unknown";
25
21
  export type P2PServerInfo = {
26
22
  isConnected: boolean;
27
23
  knownAdvertisements: PeerInfo[];
@@ -65,7 +61,7 @@ export declare class TrysteroReplicatorP2PServer {
65
61
  _activeRoomId: string;
66
62
  ___send?: (data: Payload, peerId?: string) => Promise<void>;
67
63
  assignedFunctions: Map<string, BindableFunction>;
68
- clients: Map<string, TrysteroReplicatorP2PClient>;
64
+ clients: Map<string, TrysteroReplicatorP2PClient<this>>;
69
65
  _bindingObjects: BindableObject[];
70
66
  _rpcRoom?: RpcRoom;
71
67
  protected _peerStatusEventCleanup: (() => void) | undefined;
@@ -73,6 +69,8 @@ export declare class TrysteroReplicatorP2PServer {
73
69
  private _platformUnloadCleanup;
74
70
  private _sessionPeerHandlers;
75
71
  private _hostLifetimeEnded;
72
+ private readonly createRoom;
73
+ private readonly peerAdmission;
76
74
  protected _peerConnectionEventCleanup(): void;
77
75
  _diagStats: DiagRTCStats;
78
76
  get isDisposed(): boolean;
@@ -83,10 +81,12 @@ export declare class TrysteroReplicatorP2PServer {
83
81
  /** Release subscriptions whose lifetime is the host object rather than one transport join. */
84
82
  dispose(): void;
85
83
  dispatchConnectionStatus(): Promise<void>;
86
- constructor(env: ReplicatorHostEnv, _serverPeerId?: string);
84
+ constructor(env: ReplicatorHostEnv, _serverPeerId?: string, options?: P2PServerOptions);
87
85
  /** Attach callbacks owned by the current room session and return their disposer. */
88
86
  setSessionPeerHandlers(handlers: P2PSessionPeerHandlers): () => void;
87
+ /** Persist or retain a session decision, then await the existing status notification. */
89
88
  makeDecision(decision: AcceptanceDecision): Promise<void>;
89
+ /** Revoke both decision scopes before awaiting the existing status notification. */
90
90
  revokeDecision(decision: RevokeAcceptanceDecision): Promise<void>;
91
91
  get room(): Room;
92
92
  get serverPeerId(): string;
@@ -104,7 +104,9 @@ export declare class TrysteroReplicatorP2PServer {
104
104
  onAdvertisement(data: Advertisement, peerId: string): void;
105
105
  acceptedPeers: StoredMapLike<boolean>;
106
106
  temporaryAcceptedPeers: Map<string, boolean>;
107
+ /** Share a peer's in-flight prompt while preserving the overridable prompt entry point. */
107
108
  confirmUserToAccept(peerId: string): Promise<boolean>;
109
+ /** Apply one dialogue result without awaiting the original background writes or status work. */
108
110
  _confirmUserToAccept(peerId: string): Promise<boolean>;
109
111
  _acceptablePeers: Computed<[settings: P2PSyncSetting], RegExp[]>;
110
112
  _shouldDenyPeers: Computed<[settings: P2PSyncSetting], RegExp[]>;
@@ -113,6 +115,7 @@ export declare class TrysteroReplicatorP2PServer {
113
115
  * decision. Unattended automation uses this boundary before starting RPC.
114
116
  */
115
117
  evaluatePeerAcceptance(peerId: string): Promise<P2PPeerAcceptance>;
118
+ /** Keep automatic-decision caching and interactive admission at their existing public boundary. */
116
119
  isAcceptablePeer(peerId: string): Promise<boolean>;
117
120
  __send(data: Payload, peerId: string): Promise<void>;
118
121
  processArrivedRPC(data: Payload, peerId: string): Promise<void>;
@@ -134,7 +137,7 @@ export declare class TrysteroReplicatorP2PServer {
134
137
  __onResponse(data: Response, peerId: string): void;
135
138
  __onRequest(data: Request, peerId: string): Promise<void>;
136
139
  close(): Promise<void>;
137
- getConnection(peerId: string): TrysteroReplicatorP2PClient;
140
+ getConnection(peerId: string): TrysteroReplicatorP2PClient<this>;
138
141
  get rpcRoom(): RpcRoom;
139
142
  }
140
143
  export { TrysteroReplicatorP2PServer as P2PHost };
@@ -1,7 +1,7 @@
1
1
  import { reportP2PDiagnostic } from "../../p2p/p2pDiagnostics.js";
2
2
  import { parsePeerPatterns } from "./peerPatterns.js";
3
3
  import { selfId, joinRoom } from "@trystero-p2p/nostr";
4
- import { AutoAccepting, LOG_LEVEL_INFO, LOG_LEVEL_NOTICE } from "../../common/types.js";
4
+ import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE } from "../../common/types.js";
5
5
  import { LOG_LEVEL_VERBOSE, Logger } from "../../common/logger.js";
6
6
  import {
7
7
  DIRECTION_RESPONSE,
@@ -13,7 +13,6 @@ import { StoredMapLike } from "../../dataobject/StoredMap.js";
13
13
  import { TrysteroReplicatorP2PClient } from "./TrysteroReplicatorP2PClient.js";
14
14
  import { createHostingDB } from "./ProxiedDB.js";
15
15
  import { EVENT_PLATFORM_UNLOADED } from "../../events/coreEvents.js";
16
- import { shareRunningResult } from "octagonal-wheels/concurrency/lock_v2";
17
16
  import { Computed } from "octagonal-wheels/dataobject/Computed";
18
17
  import { RpcRoom } from "../../rpc/index.js";
19
18
  import { resolveTrysteroRpcOptions } from "../../rpc/transports/TrysteroTransport.js";
@@ -23,6 +22,9 @@ import { generateJoinRoomOptions } from "../../rpc/transports/trysteroUtils.js";
23
22
  import { subscribeConnectionStatus, subscribeFailureDiagnosis } from "../../rpc/transports/DiagRTCPeerConnections.js";
24
23
  import {} from "../../rpc/transports/DiagRTCPeerConnections.types.js";
25
24
  import { asRpcErrorShape } from "../../rpc/errors.js";
25
+ import {
26
+ createPeerAdmission
27
+ } from "./TrysteroReplicatorP2PServer/peerAdmission.js";
26
28
  const EVENT_SERVER_STATUS = "p2p-server-status";
27
29
  const EVENT_MAKE_DECISION = "make-decision-p2p-peer";
28
30
  const EVENT_REVOKE_DECISION = "revoke-decision-p2p-peer";
@@ -49,6 +51,21 @@ class TrysteroReplicatorP2PServer {
49
51
  _platformUnloadCleanup;
50
52
  _sessionPeerHandlers;
51
53
  _hostLifetimeEnded = false;
54
+ createRoom;
55
+ peerAdmission = createPeerAdmission({
56
+ isEnabled: () => this.isEnabled,
57
+ advertisement: (peerId) => this._knownAdvertisements.get(peerId),
58
+ currentSettings: () => this.currentSettings,
59
+ acceptedPeers: () => this.acceptedPeers,
60
+ temporaryAcceptedPeers: () => this.temporaryAcceptedPeers,
61
+ confirm: () => this.confirm,
62
+ dispatchConnectionStatus: () => this.dispatchConnectionStatus(),
63
+ acceptablePatterns: () => this._acceptablePeers,
64
+ deniedPatterns: () => this._shouldDenyPeers,
65
+ promptPeerAcceptance: (peerId) => this._confirmUserToAccept(peerId),
66
+ evaluatePeerAcceptance: (peerId) => this.evaluatePeerAcceptance(peerId),
67
+ confirmUserToAccept: (peerId) => this.confirmUserToAccept(peerId)
68
+ });
52
69
  _peerConnectionEventCleanup() {
53
70
  if (this._peerStatusEventCleanup) {
54
71
  this._peerStatusEventCleanup();
@@ -130,9 +147,10 @@ class TrysteroReplicatorP2PServer {
130
147
  diag: this._diagStats
131
148
  });
132
149
  }
133
- constructor(env, _serverPeerId = selfId) {
150
+ constructor(env, _serverPeerId = selfId, options = {}) {
134
151
  this._env = env;
135
152
  this._serverPeerId = _serverPeerId;
153
+ this.createRoom = options.createRoom ?? joinRoom;
136
154
  this._platformUnloadCleanup = this._env.events.onEvent(EVENT_PLATFORM_UNLOADED, () => {
137
155
  void this.shutdown();
138
156
  });
@@ -150,26 +168,13 @@ class TrysteroReplicatorP2PServer {
150
168
  }
151
169
  };
152
170
  }
171
+ /** Persist or retain a session decision, then await the existing status notification. */
153
172
  async makeDecision(decision) {
154
- if (decision.decision) {
155
- if (decision.isTemporary) {
156
- this.temporaryAcceptedPeers.set(decision.peerId, true);
157
- } else {
158
- await this.acceptedPeers.set(decision.name, true);
159
- }
160
- } else {
161
- if (decision.isTemporary) {
162
- this.temporaryAcceptedPeers.set(decision.peerId, false);
163
- } else {
164
- await this.acceptedPeers.set(decision.name, false);
165
- }
166
- }
167
- await this.dispatchConnectionStatus();
173
+ await this.peerAdmission.makeDecision(decision);
168
174
  }
175
+ /** Revoke both decision scopes before awaiting the existing status notification. */
169
176
  async revokeDecision(decision) {
170
- this.temporaryAcceptedPeers.delete(decision.peerId);
171
- await this.acceptedPeers.delete(decision.name);
172
- await this.dispatchConnectionStatus();
177
+ await this.peerAdmission.revokeDecision(decision);
173
178
  }
174
179
  get room() {
175
180
  return this._room;
@@ -236,53 +241,13 @@ class TrysteroReplicatorP2PServer {
236
241
  }
237
242
  acceptedPeers;
238
243
  temporaryAcceptedPeers = /* @__PURE__ */ new Map();
244
+ /** Share a peer's in-flight prompt while preserving the overridable prompt entry point. */
239
245
  confirmUserToAccept(peerId) {
240
- return shareRunningResult(`confirmUserToAccept-${peerId}`, () => this._confirmUserToAccept(peerId));
246
+ return this.peerAdmission.confirmUserToAccept(peerId);
241
247
  }
248
+ /** Apply one dialogue result without awaiting the original background writes or status work. */
242
249
  _confirmUserToAccept(peerId) {
243
- const peerInfo = this._knownAdvertisements.get(peerId);
244
- if (!peerInfo) throw new Error("Unknown Peer");
245
- const peerName = peerInfo.name;
246
- const message = `Are you sure to establish connection to ${peerName} (${peerId})?
247
- You can chose as follows:
248
- - Accept: Accept all connections from this peer.
249
- - Ignore: Reject all connections from this peer.
250
- - Accept Temporarily: Accept the connection for this session only.
251
- - Ignore Temporarily: Reject the connection for this session only.
252
-
253
- >[!INFO] You can revoke your decision from the Peer-to-Peer Replicator Pane.`;
254
- const OPTION_ACCEPT = "Accept";
255
- const OPTION_IGNORE = "Ignore";
256
- const OPTION_ACCEPT_TEMPORARILY = "Accept Temporarily";
257
- const OPTION_IGNORE_TEMPORARILY = "Ignore Temporarily";
258
- const OPTIONS = [OPTION_ACCEPT, OPTION_IGNORE, OPTION_ACCEPT_TEMPORARILY, OPTION_IGNORE_TEMPORARILY];
259
- return this.confirm.askSelectStringDialogue(message, OPTIONS, {
260
- title: "P2P Connection Request",
261
- defaultAction: "Ignore Temporarily",
262
- timeout: 30
263
- }).then((decision) => {
264
- if (decision === OPTION_ACCEPT_TEMPORARILY) {
265
- this.temporaryAcceptedPeers.set(peerId, true);
266
- void this.dispatchConnectionStatus();
267
- return true;
268
- } else if (decision === OPTION_IGNORE_TEMPORARILY) {
269
- this.temporaryAcceptedPeers.set(peerId, false);
270
- void this.dispatchConnectionStatus();
271
- return false;
272
- } else if (decision === OPTION_ACCEPT) {
273
- this.temporaryAcceptedPeers.delete(peerId);
274
- void this.acceptedPeers.set(peerName, true);
275
- void this.dispatchConnectionStatus();
276
- return true;
277
- } else if (decision === OPTION_IGNORE) {
278
- this.temporaryAcceptedPeers.delete(peerId);
279
- void this.acceptedPeers.set(peerName, false);
280
- void this.dispatchConnectionStatus();
281
- return false;
282
- } else {
283
- throw new ResponsePreventedError("User Accepting failed");
284
- }
285
- });
250
+ return this.peerAdmission.promptPeerAcceptance(peerId);
286
251
  }
287
252
  _acceptablePeers = new Computed({
288
253
  evaluation: (settings) => {
@@ -299,36 +264,11 @@ You can chose as follows:
299
264
  * decision. Unattended automation uses this boundary before starting RPC.
300
265
  */
301
266
  async evaluatePeerAcceptance(peerId) {
302
- if (!this.isEnabled) return "unknown";
303
- const peerInfo = this._knownAdvertisements.get(peerId);
304
- if (!peerInfo) return "unknown";
305
- const peerName = peerInfo.name;
306
- if (this.temporaryAcceptedPeers.has(peerId)) {
307
- return this.temporaryAcceptedPeers.get(peerId) ? "accepted" : "rejected";
308
- }
309
- const accepted = await this.acceptedPeers.get(peerName);
310
- if (accepted !== void 0 && accepted !== null) return accepted ? "accepted" : "rejected";
311
- const currentSettings = { ...this.currentSettings };
312
- const isAcceptable = (await this._acceptablePeers.update(currentSettings)).value.some((e) => e.test(peerName));
313
- const isDeny = (await this._shouldDenyPeers.update(currentSettings)).value.some((e) => e.test(peerName));
314
- if (isDeny) return "rejected";
315
- if (isAcceptable || currentSettings.P2P_AutoAccepting === AutoAccepting.ALL) return "accepted";
316
- return "undecided";
267
+ return await this.peerAdmission.evaluatePeerAcceptance(peerId);
317
268
  }
269
+ /** Keep automatic-decision caching and interactive admission at their existing public boundary. */
318
270
  async isAcceptablePeer(peerId) {
319
- const acceptance = await this.evaluatePeerAcceptance(peerId);
320
- if (acceptance === "accepted") {
321
- const peerName = this._knownAdvertisements.get(peerId)?.name;
322
- const persisted = peerName ? await this.acceptedPeers.get(peerName) : void 0;
323
- if (!this.temporaryAcceptedPeers.has(peerId) && persisted == null) {
324
- this.temporaryAcceptedPeers.set(peerId, true);
325
- void this.dispatchConnectionStatus();
326
- }
327
- return true;
328
- }
329
- if (acceptance === "rejected" || acceptance === "unknown") return false;
330
- if (this.currentSettings.P2P_IsHeadless) return false;
331
- return await this.confirmUserToAccept(peerId);
271
+ return await this.peerAdmission.isAcceptablePeer(peerId);
332
272
  }
333
273
  async __send(data, peerId) {
334
274
  if (!this.isEnabled) return;
@@ -461,7 +401,7 @@ You can chose as follows:
461
401
  this._peerFailureAnalysisCleanup = subscribeFailureDiagnosis((status) => {
462
402
  Logger(`[P2P] Connection failure detected: ${status.userMessage}`, LOG_LEVEL_NOTICE);
463
403
  });
464
- const room = joinRoom(options, roomId, {
404
+ const room = this.createRoom(options, roomId, {
465
405
  handshakeTimeoutMs: 3e4,
466
406
  onJoinError: (error) => {
467
407
  if (!this._hostLifetimeEnded)
@@ -1,5 +1,5 @@
1
1
  import { type P2PDiagnosticInput } from "../../p2p/p2pDiagnostics.js";
2
- import type { P2PReplicationResult } from "./TrysteroReplicator.js";
2
+ import type { P2PReplicationResult } from "./replicationTypes.js";
3
3
  /** Describe an observed response without coercing an unavailable response to refusal. */
4
4
  export declare function authenticationResultDiagnostic(peerId: string, response: unknown): P2PDiagnosticInput;
5
5
  export declare function authenticationFailureDiagnostic(peerId: string, error: unknown, signal?: AbortSignal): P2PDiagnosticInput;
@@ -1,15 +1,6 @@
1
1
  import type { ProgressInfo } from "../../pouchdb/ReplicatorShim.js";
2
- import type { P2PReplicationDirectionProgress } from "./TrysteroReplicator.js";
3
- /** Transient attempt correlation; no replication checkpoint is stored here. */
4
- export type ProgressAcknowledgement = {
5
- attempt: number;
6
- finalProgress?: ProgressInfo;
7
- };
8
- export type AcknowledgedProgressAttempt = {
9
- attempt: number;
10
- isActive: boolean;
11
- checkedChanges: number;
12
- };
2
+ import type { P2PReplicationDirectionProgress, ProgressAcknowledgement, AcknowledgedProgressAttempt } from "./replicationTypes.js";
3
+ export type { ProgressAcknowledgement, AcknowledgedProgressAttempt } from "./replicationTypes.js";
13
4
  export declare function projectDirectionProgress(info?: ProgressInfo | null): P2PReplicationDirectionProgress;
14
5
  /** Return the next attempt snapshot, or reject stale, reordered, or already-ended progress. */
15
6
  export declare function projectAcknowledgedAttempt(previous: AcknowledgedProgressAttempt | undefined, info: ProgressInfo | null | undefined, acknowledgement: ProgressAcknowledgement): AcknowledgedProgressAttempt | undefined;