@jr2804/livesync-cli 1.0.28-cli.1 → 1.0.29-cli.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +674 -76
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -66,6 +66,329 @@ let buffer = require("buffer");
|
|
|
66
66
|
let node_zlib = require("node:zlib");
|
|
67
67
|
node_zlib = require_stream_collector.__toESM(node_zlib);
|
|
68
68
|
let chokidar = require("chokidar");
|
|
69
|
+
//#region ../../integrations/cloudflare/settings.ts
|
|
70
|
+
/** The lifetime requested from Cloudflare for each issued credential set. */
|
|
71
|
+
var CLOUDFLARE_TURN_CREDENTIAL_TTL_SECONDS = 86400;
|
|
72
|
+
/** The Cloudflare TURN credential-generation endpoint. */
|
|
73
|
+
var CLOUDFLARE_TURN_CREDENTIAL_ENDPOINT = "https://rtc.live.cloudflare.com/v1/turn/keys";
|
|
74
|
+
var TURN_KEY_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,255}$/;
|
|
75
|
+
var BEARER_TOKEN_PATTERN = /^[A-Za-z0-9._~+/-]+={0,2}$/;
|
|
76
|
+
var MAX_BEARER_TOKEN_LENGTH = 4096;
|
|
77
|
+
/**
|
|
78
|
+
* Returns a safe validation message for a Cloudflare TURN configuration.
|
|
79
|
+
* The result never includes the supplied Key ID or API token.
|
|
80
|
+
*/
|
|
81
|
+
function validateCloudflareTurnConfiguration(value) {
|
|
82
|
+
const turnKeyId = value.turnKeyId;
|
|
83
|
+
if (typeof turnKeyId !== "string" || turnKeyId.length === 0) return "Enter a TURN Key ID.";
|
|
84
|
+
if (!TURN_KEY_ID_PATTERN.test(turnKeyId)) return "TURN Key ID contains unsupported characters.";
|
|
85
|
+
const apiToken = value.apiToken;
|
|
86
|
+
if (typeof apiToken !== "string" || apiToken.length === 0) return "Enter a TURN Key API Token.";
|
|
87
|
+
if (apiToken.length > MAX_BEARER_TOKEN_LENGTH || !BEARER_TOKEN_PATTERN.test(apiToken)) return "TURN Key API Token must use Bearer token syntax.";
|
|
88
|
+
}
|
|
89
|
+
var FAILURE_MESSAGES = {
|
|
90
|
+
configuration: "The Cloudflare TURN configuration is invalid.",
|
|
91
|
+
authentication: "The Cloudflare TURN credential request was not authorised.",
|
|
92
|
+
unavailable: "The Cloudflare TURN service is unavailable.",
|
|
93
|
+
"invalid-response": "The Cloudflare TURN service returned an invalid response."
|
|
94
|
+
};
|
|
95
|
+
function credentialFailure(code, retryable) {
|
|
96
|
+
return Object.assign(new Error(FAILURE_MESSAGES[code]), {
|
|
97
|
+
code,
|
|
98
|
+
retryable
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
function isRecord$2(value) {
|
|
102
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
103
|
+
}
|
|
104
|
+
function abortError() {
|
|
105
|
+
try {
|
|
106
|
+
return new DOMException("The operation was aborted.", "AbortError");
|
|
107
|
+
} catch {
|
|
108
|
+
const error = /* @__PURE__ */ new Error("The operation was aborted.");
|
|
109
|
+
error.name = "AbortError";
|
|
110
|
+
return error;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function throwIfAborted$1(signal) {
|
|
114
|
+
if (signal.aborted) throw abortError();
|
|
115
|
+
}
|
|
116
|
+
function isControlCharacter(value) {
|
|
117
|
+
return Array.from(value).some((character) => {
|
|
118
|
+
const code = character.charCodeAt(0);
|
|
119
|
+
return code <= 31 || code === 127;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
function isPort(value) {
|
|
123
|
+
if (!/^\d{1,5}$/.test(value)) return false;
|
|
124
|
+
const port = Number(value);
|
|
125
|
+
return port >= 1 && port <= 65535;
|
|
126
|
+
}
|
|
127
|
+
function isHost(value) {
|
|
128
|
+
return value.length > 0 && /^[A-Za-z0-9._-]+$/.test(value);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Validates the URL forms accepted by WebRTC's ICE server configuration.
|
|
132
|
+
* TURN URLs may carry only the standard transport query parameter; userinfo,
|
|
133
|
+
* paths, fragments, and arbitrary query values are not accepted.
|
|
134
|
+
*/
|
|
135
|
+
function isSupportedIceServerUrl(value) {
|
|
136
|
+
if (value.length === 0 || value.length > 2048 || isControlCharacter(value)) return false;
|
|
137
|
+
const schemeMatch = /^(stun|stuns|turn|turns):(.+)$/i.exec(value);
|
|
138
|
+
if (!schemeMatch) return false;
|
|
139
|
+
const remainder = schemeMatch[2];
|
|
140
|
+
const queryIndex = remainder.indexOf("?");
|
|
141
|
+
const authority = queryIndex >= 0 ? remainder.slice(0, queryIndex) : remainder;
|
|
142
|
+
const query = queryIndex >= 0 ? remainder.slice(queryIndex + 1) : "";
|
|
143
|
+
if (authority.length === 0 || authority.includes("/") || authority.includes("#") || authority.includes("@")) return false;
|
|
144
|
+
if (authority.includes("%")) return false;
|
|
145
|
+
if (authority.startsWith("[")) {
|
|
146
|
+
const closingBracket = authority.indexOf("]");
|
|
147
|
+
if (closingBracket < 0) return false;
|
|
148
|
+
const host = authority.slice(1, closingBracket);
|
|
149
|
+
if (!/^[0-9A-Fa-f:.]+$/.test(host) || !host.includes(":")) return false;
|
|
150
|
+
const suffix = authority.slice(closingBracket + 1);
|
|
151
|
+
if (suffix !== "" && (!suffix.startsWith(":") || !isPort(suffix.slice(1)))) return false;
|
|
152
|
+
} else {
|
|
153
|
+
const colonIndex = authority.lastIndexOf(":");
|
|
154
|
+
const host = colonIndex >= 0 ? authority.slice(0, colonIndex) : authority;
|
|
155
|
+
if (!isHost(host) || colonIndex >= 0 && !isPort(authority.slice(colonIndex + 1))) return false;
|
|
156
|
+
if (colonIndex >= 0 && host.includes(":")) return false;
|
|
157
|
+
}
|
|
158
|
+
if (query.length === 0) return true;
|
|
159
|
+
const queryParts = query.split("&");
|
|
160
|
+
return queryParts.length === 1 && /^transport=(udp|tcp)$/i.test(queryParts[0]);
|
|
161
|
+
}
|
|
162
|
+
function isTurnUrl(value) {
|
|
163
|
+
return /^(turn|turns):/i.test(value);
|
|
164
|
+
}
|
|
165
|
+
function isCredential(value) {
|
|
166
|
+
return typeof value === "string" && value.length > 0 && value.length <= 4096 && !isControlCharacter(value);
|
|
167
|
+
}
|
|
168
|
+
function normaliseIceServers(value) {
|
|
169
|
+
if (!isRecord$2(value) || !Array.isArray(value.iceServers)) throw credentialFailure("invalid-response", false);
|
|
170
|
+
if (value.iceServers.length === 0 || value.iceServers.length > 16) throw credentialFailure("invalid-response", false);
|
|
171
|
+
const servers = [];
|
|
172
|
+
let urlCount = 0;
|
|
173
|
+
let hasTurnServer = false;
|
|
174
|
+
for (const candidate of value.iceServers) {
|
|
175
|
+
if (!isRecord$2(candidate)) throw credentialFailure("invalid-response", false);
|
|
176
|
+
const rawUrls = candidate.urls;
|
|
177
|
+
const urls = typeof rawUrls === "string" ? [rawUrls] : Array.isArray(rawUrls) && rawUrls.every((url) => typeof url === "string") ? [...rawUrls] : void 0;
|
|
178
|
+
if (!urls || urls.length === 0) throw credentialFailure("invalid-response", false);
|
|
179
|
+
urlCount += urls.length;
|
|
180
|
+
if (urlCount > 32 || urls.some((url) => !isSupportedIceServerUrl(url))) throw credentialFailure("invalid-response", false);
|
|
181
|
+
const turnEntry = urls.some(isTurnUrl);
|
|
182
|
+
hasTurnServer ||= turnEntry;
|
|
183
|
+
const normalised = { urls };
|
|
184
|
+
if (turnEntry) {
|
|
185
|
+
if (!isCredential(candidate.username) || !isCredential(candidate.credential)) throw credentialFailure("invalid-response", false);
|
|
186
|
+
normalised.username = candidate.username;
|
|
187
|
+
normalised.credential = candidate.credential;
|
|
188
|
+
}
|
|
189
|
+
servers.push(normalised);
|
|
190
|
+
}
|
|
191
|
+
if (!hasTurnServer) throw credentialFailure("invalid-response", false);
|
|
192
|
+
return Object.freeze(servers);
|
|
193
|
+
}
|
|
194
|
+
var BoundedResponseError = class extends Error {
|
|
195
|
+
constructor(kind) {
|
|
196
|
+
super(kind);
|
|
197
|
+
this.kind = kind;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
async function readResponseBody(response) {
|
|
201
|
+
const contentLength = response.headers.get("content-length");
|
|
202
|
+
if (contentLength !== null) {
|
|
203
|
+
const declaredLength = Number(contentLength);
|
|
204
|
+
if (!Number.isFinite(declaredLength) || declaredLength < 0) throw new BoundedResponseError("invalid-length");
|
|
205
|
+
if (declaredLength > 32768) throw new BoundedResponseError("too-large");
|
|
206
|
+
}
|
|
207
|
+
if (!response.body) try {
|
|
208
|
+
const text = await response.text();
|
|
209
|
+
if (new TextEncoder().encode(text).byteLength > 32768) throw new BoundedResponseError("too-large");
|
|
210
|
+
return text;
|
|
211
|
+
} catch (error) {
|
|
212
|
+
if (error instanceof BoundedResponseError) throw error;
|
|
213
|
+
throw new BoundedResponseError("read-failed");
|
|
214
|
+
}
|
|
215
|
+
const reader = response.body.getReader();
|
|
216
|
+
const chunks = [];
|
|
217
|
+
let totalBytes = 0;
|
|
218
|
+
try {
|
|
219
|
+
while (true) {
|
|
220
|
+
const result = await reader.read();
|
|
221
|
+
if (result.done) break;
|
|
222
|
+
totalBytes += result.value.byteLength;
|
|
223
|
+
if (totalBytes > 32768) {
|
|
224
|
+
try {
|
|
225
|
+
await reader.cancel();
|
|
226
|
+
} catch {}
|
|
227
|
+
throw new BoundedResponseError("too-large");
|
|
228
|
+
}
|
|
229
|
+
chunks.push(result.value);
|
|
230
|
+
}
|
|
231
|
+
} catch (error) {
|
|
232
|
+
if (error instanceof BoundedResponseError) throw error;
|
|
233
|
+
throw new BoundedResponseError("read-failed");
|
|
234
|
+
} finally {
|
|
235
|
+
reader.releaseLock();
|
|
236
|
+
}
|
|
237
|
+
const bytes = new Uint8Array(totalBytes);
|
|
238
|
+
let offset = 0;
|
|
239
|
+
for (const chunk of chunks) {
|
|
240
|
+
bytes.set(chunk, offset);
|
|
241
|
+
offset += chunk.byteLength;
|
|
242
|
+
}
|
|
243
|
+
return new TextDecoder().decode(bytes);
|
|
244
|
+
}
|
|
245
|
+
function classifyHttpFailure(status) {
|
|
246
|
+
if (status === 401 || status === 403) return credentialFailure("authentication", false);
|
|
247
|
+
if (status === 408 || status === 429 || status >= 500) return credentialFailure("unavailable", true);
|
|
248
|
+
return credentialFailure("unavailable", false);
|
|
249
|
+
}
|
|
250
|
+
function parseResponseBody(body) {
|
|
251
|
+
let value;
|
|
252
|
+
try {
|
|
253
|
+
value = JSON.parse(body);
|
|
254
|
+
} catch {
|
|
255
|
+
throw credentialFailure("invalid-response", false);
|
|
256
|
+
}
|
|
257
|
+
return normaliseIceServers(value);
|
|
258
|
+
}
|
|
259
|
+
/** Acquire one temporary ICE configuration for a new room connection. */
|
|
260
|
+
async function acquireCloudflareTurnCredentials(configuration, dependencies, signal) {
|
|
261
|
+
if (validateCloudflareTurnConfiguration(configuration)) throw credentialFailure("configuration", false);
|
|
262
|
+
const now = dependencies.now ?? Date.now;
|
|
263
|
+
const requestDeadlineMs = dependencies.requestDeadlineMs ?? 15e3;
|
|
264
|
+
throwIfAborted$1(signal);
|
|
265
|
+
const requestStartedAt = now();
|
|
266
|
+
if (!Number.isFinite(requestStartedAt)) throw credentialFailure("unavailable", true);
|
|
267
|
+
const requestController = new AbortController();
|
|
268
|
+
let cancelledByCaller = false;
|
|
269
|
+
let rejectCaller;
|
|
270
|
+
const callerAbort = new Promise((_resolve, reject) => {
|
|
271
|
+
rejectCaller = reject;
|
|
272
|
+
});
|
|
273
|
+
let timedOut = false;
|
|
274
|
+
const onAbort = () => {
|
|
275
|
+
cancelledByCaller = true;
|
|
276
|
+
requestController.abort();
|
|
277
|
+
rejectCaller?.(abortError());
|
|
278
|
+
};
|
|
279
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
280
|
+
if (signal.aborted) {
|
|
281
|
+
signal.removeEventListener("abort", onAbort);
|
|
282
|
+
requestController.abort();
|
|
283
|
+
throw abortError();
|
|
284
|
+
}
|
|
285
|
+
let timeoutId;
|
|
286
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
287
|
+
timeoutId = globalThis.setTimeout(() => {
|
|
288
|
+
timedOut = true;
|
|
289
|
+
requestController.abort();
|
|
290
|
+
reject(credentialFailure("unavailable", true));
|
|
291
|
+
}, requestDeadlineMs);
|
|
292
|
+
});
|
|
293
|
+
const cleanup = () => {
|
|
294
|
+
if (timeoutId !== void 0) globalThis.clearTimeout(timeoutId);
|
|
295
|
+
signal.removeEventListener("abort", onAbort);
|
|
296
|
+
};
|
|
297
|
+
const endpoint = `${CLOUDFLARE_TURN_CREDENTIAL_ENDPOINT}/${configuration.turnKeyId}/credentials/generate-ice-servers`;
|
|
298
|
+
let response;
|
|
299
|
+
try {
|
|
300
|
+
response = await Promise.race([
|
|
301
|
+
dependencies.fetch(endpoint, {
|
|
302
|
+
method: "POST",
|
|
303
|
+
headers: {
|
|
304
|
+
Authorization: `Bearer ${configuration.apiToken}`,
|
|
305
|
+
"Content-Type": "application/json"
|
|
306
|
+
},
|
|
307
|
+
body: JSON.stringify({ ttl: CLOUDFLARE_TURN_CREDENTIAL_TTL_SECONDS }),
|
|
308
|
+
signal: requestController.signal,
|
|
309
|
+
redirect: "error",
|
|
310
|
+
credentials: "omit",
|
|
311
|
+
cache: "no-store"
|
|
312
|
+
}),
|
|
313
|
+
callerAbort,
|
|
314
|
+
deadline
|
|
315
|
+
]);
|
|
316
|
+
} catch {
|
|
317
|
+
cleanup();
|
|
318
|
+
if (cancelledByCaller || signal.aborted) throw abortError();
|
|
319
|
+
if (timedOut) throw credentialFailure("unavailable", true);
|
|
320
|
+
throw credentialFailure("unavailable", true);
|
|
321
|
+
}
|
|
322
|
+
if (cancelledByCaller || signal.aborted) {
|
|
323
|
+
cleanup();
|
|
324
|
+
throw abortError();
|
|
325
|
+
}
|
|
326
|
+
if (timedOut || requestController.signal.aborted) {
|
|
327
|
+
cleanup();
|
|
328
|
+
throw credentialFailure("unavailable", true);
|
|
329
|
+
}
|
|
330
|
+
if (response.status !== 201) {
|
|
331
|
+
cleanup();
|
|
332
|
+
throw classifyHttpFailure(response.status);
|
|
333
|
+
}
|
|
334
|
+
let body;
|
|
335
|
+
try {
|
|
336
|
+
body = await Promise.race([
|
|
337
|
+
readResponseBody(response),
|
|
338
|
+
callerAbort,
|
|
339
|
+
deadline
|
|
340
|
+
]);
|
|
341
|
+
} catch (error) {
|
|
342
|
+
cleanup();
|
|
343
|
+
if (cancelledByCaller || signal.aborted) throw abortError();
|
|
344
|
+
if (timedOut) throw credentialFailure("unavailable", true);
|
|
345
|
+
if (error instanceof BoundedResponseError && error.kind === "read-failed") throw credentialFailure("unavailable", true);
|
|
346
|
+
throw credentialFailure("invalid-response", false);
|
|
347
|
+
}
|
|
348
|
+
try {
|
|
349
|
+
throwIfAborted$1(signal);
|
|
350
|
+
const iceServers = parseResponseBody(body);
|
|
351
|
+
const expiresAt = requestStartedAt + CLOUDFLARE_TURN_CREDENTIAL_TTL_SECONDS * 1e3;
|
|
352
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= now() + 3e4) throw credentialFailure("invalid-response", false);
|
|
353
|
+
return {
|
|
354
|
+
iceServers,
|
|
355
|
+
expiresAt
|
|
356
|
+
};
|
|
357
|
+
} finally {
|
|
358
|
+
cleanup();
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
//#endregion
|
|
362
|
+
//#region ../../integrations/turnSettings.ts
|
|
363
|
+
/** Validate provider inputs without requesting credentials. */
|
|
364
|
+
function validateManagedTurnSettings(settings) {
|
|
365
|
+
if (settings.P2P_managedType === void 0 || settings.P2P_managedType === "") return void 0;
|
|
366
|
+
if (settings.P2P_managedType !== "CF") return "The selected TURN configuration is not supported.";
|
|
367
|
+
return validateCloudflareTurnConfiguration({
|
|
368
|
+
turnKeyId: settings.P2P_managedId ?? "",
|
|
369
|
+
apiToken: settings.P2P_managedToken ?? ""
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
//#endregion
|
|
373
|
+
//#region ../../serviceFeatures/useP2PSettingsPreparation.ts
|
|
374
|
+
/** Prepare a connection copy using the host's HTTP adapter. */
|
|
375
|
+
function useP2PSettingsPreparation(fetch) {
|
|
376
|
+
return async (settings, signal) => {
|
|
377
|
+
const error = validateManagedTurnSettings(settings);
|
|
378
|
+
if (error) throw new Error(error);
|
|
379
|
+
if (!settings.P2P_managedType) return { ...settings };
|
|
380
|
+
const { iceServers, expiresAt } = await acquireCloudflareTurnCredentials({
|
|
381
|
+
turnKeyId: settings.P2P_managedId ?? "",
|
|
382
|
+
apiToken: settings.P2P_managedToken ?? ""
|
|
383
|
+
}, { fetch }, signal);
|
|
384
|
+
return {
|
|
385
|
+
...settings,
|
|
386
|
+
P2P_iceServers: iceServers,
|
|
387
|
+
P2P_iceServersExpiresAt: expiresAt
|
|
388
|
+
};
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
//#endregion
|
|
69
392
|
//#region ../../../node_modules/octagonal-wheels/dist/common/polyfill.js
|
|
70
393
|
var _a$1;
|
|
71
394
|
var FallbackWeakRef = "WeakRef" in globalThis ? globalThis.WeakRef : (_a$1 = class WeakRef {
|
|
@@ -4078,6 +4401,13 @@ var ChunkAlgorithms = {
|
|
|
4078
4401
|
};
|
|
4079
4402
|
//#endregion
|
|
4080
4403
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/models/setting.p2p.js
|
|
4404
|
+
function hasManagedP2PTurnConfiguration(settings) {
|
|
4405
|
+
return typeof settings.P2P_managedType === "string" && settings.P2P_managedType.trim().length > 0;
|
|
4406
|
+
}
|
|
4407
|
+
function omitP2PRuntimeSettings(settings) {
|
|
4408
|
+
const { P2P_iceServers: _iceServers, P2P_iceServersExpiresAt: _expiresAt, ...persistable } = settings;
|
|
4409
|
+
return persistable;
|
|
4410
|
+
}
|
|
4081
4411
|
function normaliseP2PMaxWirePayloadBytes(value) {
|
|
4082
4412
|
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < P2PMessageSizePresets.MaximumCompatibility || value > P2PMessageSizePresets.Standard) return P2PMessageSizePresets.Standard;
|
|
4083
4413
|
return value;
|
|
@@ -4337,13 +4667,14 @@ var SETTINGS_MIGRATIONS = [{
|
|
|
4337
4667
|
} : void 0
|
|
4338
4668
|
}];
|
|
4339
4669
|
function cloneSettings$1(source, fallbacks) {
|
|
4670
|
+
const persistableSource = omitP2PRuntimeSettings(source);
|
|
4340
4671
|
return {
|
|
4341
4672
|
...fallbacks,
|
|
4342
|
-
...
|
|
4343
|
-
remoteConfigurations: Object.fromEntries(Object.entries(
|
|
4673
|
+
...persistableSource,
|
|
4674
|
+
remoteConfigurations: Object.fromEntries(Object.entries(persistableSource.remoteConfigurations ?? fallbacks.remoteConfigurations).map(([id, config]) => [id, { ...config }])),
|
|
4344
4675
|
pluginSyncExtendedSetting: {
|
|
4345
4676
|
...fallbacks.pluginSyncExtendedSetting,
|
|
4346
|
-
...
|
|
4677
|
+
...persistableSource.pluginSyncExtendedSetting
|
|
4347
4678
|
}
|
|
4348
4679
|
};
|
|
4349
4680
|
}
|
|
@@ -11559,10 +11890,10 @@ var HeadlessAPIService = class extends InjectableAPIService {
|
|
|
11559
11890
|
return "headless-app";
|
|
11560
11891
|
}
|
|
11561
11892
|
getAppVersion() {
|
|
11562
|
-
return `1.0.
|
|
11893
|
+
return `1.0.29`;
|
|
11563
11894
|
}
|
|
11564
11895
|
getPluginVersion() {
|
|
11565
|
-
return `1.0.
|
|
11896
|
+
return `1.0.29`;
|
|
11566
11897
|
}
|
|
11567
11898
|
getPlatform() {
|
|
11568
11899
|
return "server";
|
|
@@ -12048,7 +12379,7 @@ async function decryptString(encrypted, passphrase) {
|
|
|
12048
12379
|
var PROXY_SCHEME = "https";
|
|
12049
12380
|
function parseSlsUri(uriString) {
|
|
12050
12381
|
const match = uriString.match(/^sls\+([^:]+):(.*)$/);
|
|
12051
|
-
if (!match) throw new Error(
|
|
12382
|
+
if (!match) throw new Error("Unsupported URI");
|
|
12052
12383
|
const subscheme = match[1];
|
|
12053
12384
|
const rest = match[2];
|
|
12054
12385
|
return {
|
|
@@ -12065,7 +12396,7 @@ var ConnectionStringParser = class {
|
|
|
12065
12396
|
*/
|
|
12066
12397
|
static parse(uriString) {
|
|
12067
12398
|
const match = uriString.match(/^sls\+([^:]+):/);
|
|
12068
|
-
if (!match) throw new Error(
|
|
12399
|
+
if (!match) throw new Error("Unsupported URI");
|
|
12069
12400
|
const subscheme = match[1];
|
|
12070
12401
|
if (subscheme === "p2p") return {
|
|
12071
12402
|
type: "p2p",
|
|
@@ -12082,7 +12413,7 @@ var ConnectionStringParser = class {
|
|
|
12082
12413
|
type: "s3",
|
|
12083
12414
|
settings: this.parseS3(url)
|
|
12084
12415
|
};
|
|
12085
|
-
default: throw new Error(
|
|
12416
|
+
default: throw new Error("Unsupported protocol");
|
|
12086
12417
|
}
|
|
12087
12418
|
}
|
|
12088
12419
|
/**
|
|
@@ -12161,7 +12492,7 @@ var ConnectionStringParser = class {
|
|
|
12161
12492
|
}
|
|
12162
12493
|
static parseP2P(uriString) {
|
|
12163
12494
|
const match = uriString.match(/^sls\+p2p:\/\/([^?#]+)(?:\?([^#]*))?(?:#(.*))?$/);
|
|
12164
|
-
if (!match) throw new Error(
|
|
12495
|
+
if (!match) throw new Error("Invalid P2P URI");
|
|
12165
12496
|
const authority = match[1];
|
|
12166
12497
|
const queryString = match[2] || "";
|
|
12167
12498
|
let userinfo = "";
|
|
@@ -12189,7 +12520,10 @@ var ConnectionStringParser = class {
|
|
|
12189
12520
|
P2P_turnUsername: searchParams.get("turnUser") || "",
|
|
12190
12521
|
P2P_turnCredential: searchParams.get("turnPass") || "",
|
|
12191
12522
|
P2P_maxWirePayloadBytes: normaliseP2PMaxWirePayloadBytes(Number(searchParams.get("maxWirePayloadBytes"))),
|
|
12192
|
-
P2P_connectionPath: normaliseP2PConnectionPath(searchParams.get("connectionPath"))
|
|
12523
|
+
P2P_connectionPath: normaliseP2PConnectionPath(searchParams.get("connectionPath")),
|
|
12524
|
+
P2P_managedType: searchParams.get("managedType") || void 0,
|
|
12525
|
+
P2P_managedId: searchParams.get("managedId") || void 0,
|
|
12526
|
+
P2P_managedToken: searchParams.get("token") || void 0
|
|
12193
12527
|
};
|
|
12194
12528
|
}
|
|
12195
12529
|
static serializeP2P(settings) {
|
|
@@ -12204,6 +12538,9 @@ var ConnectionStringParser = class {
|
|
|
12204
12538
|
if (settings.P2P_turnCredential) searchParams.set("turnPass", settings.P2P_turnCredential);
|
|
12205
12539
|
searchParams.set("maxWirePayloadBytes", String(normaliseP2PMaxWirePayloadBytes(settings.P2P_maxWirePayloadBytes)));
|
|
12206
12540
|
searchParams.set("connectionPath", normaliseP2PConnectionPath(settings.P2P_connectionPath));
|
|
12541
|
+
if (settings.P2P_managedType) searchParams.set("managedType", settings.P2P_managedType);
|
|
12542
|
+
if (settings.P2P_managedId) searchParams.set("managedId", settings.P2P_managedId);
|
|
12543
|
+
if (settings.P2P_managedToken) searchParams.set("token", settings.P2P_managedToken);
|
|
12207
12544
|
return `sls+p2p://${settings.P2P_passphrase ? `:${encodeURIComponent(settings.P2P_passphrase)}@` : ""}${encodeURIComponent(settings.P2P_roomID)}${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
|
|
12208
12545
|
}
|
|
12209
12546
|
};
|
|
@@ -12260,6 +12597,7 @@ function migrateLegacyRemoteConfigurationsInPlace(settings, log) {
|
|
|
12260
12597
|
if (createdIds.length === 0) return false;
|
|
12261
12598
|
const preferredId = settings.remoteType === REMOTE_MINIO ? "legacy-s3" : settings.remoteType === REMOTE_P2P ? "legacy-p2p" : "legacy-couchdb";
|
|
12262
12599
|
settings.activeConfigurationId = settings.remoteConfigurations[preferredId] ? preferredId : createdIds[0];
|
|
12600
|
+
if (settings.remoteConfigurations["legacy-p2p"]) settings.P2P_ActiveRemoteConfigurationId = "legacy-p2p";
|
|
12263
12601
|
return true;
|
|
12264
12602
|
}
|
|
12265
12603
|
function createRemoteConfigurationId() {
|
|
@@ -12447,10 +12785,7 @@ var SettingService = class extends ServiceBase {
|
|
|
12447
12785
|
async saveSettingData() {
|
|
12448
12786
|
this.saveDeviceAndVaultName();
|
|
12449
12787
|
const previousSettings = this._lastPersistedSettings ?? this.cloneSettings(this.settings);
|
|
12450
|
-
const settings =
|
|
12451
|
-
...this.settings,
|
|
12452
|
-
remoteConfigurations: Object.fromEntries(Object.entries(this.settings.remoteConfigurations || {}).map(([id, config]) => [id, { ...config }]))
|
|
12453
|
-
};
|
|
12788
|
+
const settings = this.cloneSettings(this.settings);
|
|
12454
12789
|
const hookResults = await this.onBeforeSaveSettingData(settings, previousSettings);
|
|
12455
12790
|
for (const patch of hookResults) {
|
|
12456
12791
|
if (patch instanceof Error || !patch) continue;
|
|
@@ -12463,8 +12798,17 @@ var SettingService = class extends ServiceBase {
|
|
|
12463
12798
|
this.setSmallConfig(SETTING_KEY_P2P_DEVICE_NAME, settings.P2P_DevicePeerName.trim());
|
|
12464
12799
|
settings.P2P_DevicePeerName = "";
|
|
12465
12800
|
}
|
|
12466
|
-
|
|
12467
|
-
|
|
12801
|
+
delete settings.P2P_managedType;
|
|
12802
|
+
delete settings.P2P_managedId;
|
|
12803
|
+
delete settings.P2P_managedToken;
|
|
12804
|
+
if (this.usedPassphrase == "" && !await this.getPassphrase(settings)) {
|
|
12805
|
+
if (Object.values(settings.remoteConfigurations).some((config) => this.hasManagedP2PProfileURI(config.uri))) {
|
|
12806
|
+
const message = "Failed to retrieve a passphrase for managed P2P source data. Settings were not saved.";
|
|
12807
|
+
this._log(message, 128);
|
|
12808
|
+
throw new Error(message);
|
|
12809
|
+
}
|
|
12810
|
+
this._log("Failed to retrieve passphrase. data.json contains unencrypted items!", 64);
|
|
12811
|
+
} else {
|
|
12468
12812
|
if (settings.couchDB_PASSWORD != "" || settings.couchDB_URI != "" || settings.couchDB_USER != "" || settings.couchDB_DBNAME) {
|
|
12469
12813
|
const connectionSetting = {
|
|
12470
12814
|
couchDB_DBNAME: settings.couchDB_DBNAME,
|
|
@@ -12514,8 +12858,24 @@ var SettingService = class extends ServiceBase {
|
|
|
12514
12858
|
const configs = settings.remoteConfigurations || {};
|
|
12515
12859
|
for (const [id, config] of Object.entries(configs)) {
|
|
12516
12860
|
if (config.isEncrypted || config.uri.trim() === "") continue;
|
|
12517
|
-
const
|
|
12861
|
+
const managedP2PProfile = this.hasManagedP2PProfileURI(config.uri);
|
|
12862
|
+
let encryptedURI;
|
|
12863
|
+
try {
|
|
12864
|
+
encryptedURI = await this.encryptConfigurationItem(config.uri, settings);
|
|
12865
|
+
} catch (error) {
|
|
12866
|
+
if (managedP2PProfile) {
|
|
12867
|
+
const message = `Failed to encrypt managed P2P remote configuration '${id}'. Settings were not saved.`;
|
|
12868
|
+
this._log(message, 128);
|
|
12869
|
+
throw new Error(message);
|
|
12870
|
+
}
|
|
12871
|
+
throw error;
|
|
12872
|
+
}
|
|
12518
12873
|
if (encryptedURI === "") {
|
|
12874
|
+
if (managedP2PProfile) {
|
|
12875
|
+
const message = `Failed to encrypt managed P2P remote configuration '${id}'. Settings were not saved.`;
|
|
12876
|
+
this._log(message, 128);
|
|
12877
|
+
throw new Error(message);
|
|
12878
|
+
}
|
|
12519
12879
|
this._log(`Failed to encrypt remote configuration '${id}'. This entry will be saved in plain text.`, 128);
|
|
12520
12880
|
continue;
|
|
12521
12881
|
}
|
|
@@ -12526,6 +12886,14 @@ var SettingService = class extends ServiceBase {
|
|
|
12526
12886
|
};
|
|
12527
12887
|
}
|
|
12528
12888
|
}
|
|
12889
|
+
hasManagedP2PProfileURI(uri) {
|
|
12890
|
+
const trimmed = uri.trim();
|
|
12891
|
+
if (!trimmed.startsWith("sls+p2p://")) return false;
|
|
12892
|
+
const queryStart = trimmed.indexOf("?");
|
|
12893
|
+
if (queryStart < 0) return false;
|
|
12894
|
+
const query = trimmed.slice(queryStart + 1).split("#", 1)[0];
|
|
12895
|
+
return (new URLSearchParams(query).get("managedType") ?? "").trim().length > 0;
|
|
12896
|
+
}
|
|
12529
12897
|
async decryptRemoteConfigurationUris(settings, passphrase) {
|
|
12530
12898
|
const configs = settings.remoteConfigurations || {};
|
|
12531
12899
|
for (const [id, config] of Object.entries(configs)) {
|
|
@@ -12603,7 +12971,7 @@ var SettingService = class extends ServiceBase {
|
|
|
12603
12971
|
try {
|
|
12604
12972
|
this.settings = await this.adjustSettings({
|
|
12605
12973
|
...this.settings,
|
|
12606
|
-
...partial
|
|
12974
|
+
...omitP2PRuntimeSettings(partial)
|
|
12607
12975
|
});
|
|
12608
12976
|
} catch (ex) {
|
|
12609
12977
|
this._log("Error in applying external settings: ", 128);
|
|
@@ -12769,7 +13137,7 @@ var SettingService = class extends ServiceBase {
|
|
|
12769
13137
|
}
|
|
12770
13138
|
cloneSettings(settings) {
|
|
12771
13139
|
return {
|
|
12772
|
-
...settings,
|
|
13140
|
+
...omitP2PRuntimeSettings(settings),
|
|
12773
13141
|
remoteConfigurations: Object.fromEntries(Object.entries(settings.remoteConfigurations || {}).map(([id, config]) => [id, { ...config }]))
|
|
12774
13142
|
};
|
|
12775
13143
|
}
|
|
@@ -33317,6 +33685,21 @@ var allMessages = {
|
|
|
33317
33685
|
* remove it from this map in the same change.
|
|
33318
33686
|
*/
|
|
33319
33687
|
var liveSyncProvisionalEnglishMessages = {
|
|
33688
|
+
"Configure TURN when a direct connection cannot be established or when you select TURN relay only.": "Configure TURN when a direct connection cannot be established or when you select TURN relay only.",
|
|
33689
|
+
"TURN configuration": "TURN configuration",
|
|
33690
|
+
Manual: "Manual",
|
|
33691
|
+
"Managed (Cloudflare)": "Managed (Cloudflare)",
|
|
33692
|
+
"TURN Key ID": "TURN Key ID",
|
|
33693
|
+
"TURN Key API Token": "TURN Key API Token",
|
|
33694
|
+
"Unsupported TURN configuration": "Unsupported TURN configuration",
|
|
33695
|
+
"The API token is saved with this profile and included in Setup URI and QR code sharing. Temporary TURN credentials are kept in memory only.": "The API token is saved with this profile and included in Setup URI and QR code sharing. Temporary TURN credentials are kept in memory only.",
|
|
33696
|
+
"TURN relay only requires a TURN server or a configured credential source under Advanced Settings.": "TURN relay only requires a TURN server or a configured credential source under Advanced Settings.",
|
|
33697
|
+
"TURN relay only requires TURN configuration. Connection path has been restored to Automatic.": "TURN relay only requires TURN configuration. Connection path has been restored to Automatic.",
|
|
33698
|
+
"Enter a TURN Key ID.": "Enter a TURN Key ID.",
|
|
33699
|
+
"TURN Key ID contains unsupported characters.": "TURN Key ID contains unsupported characters.",
|
|
33700
|
+
"Enter a TURN Key API Token.": "Enter a TURN Key API Token.",
|
|
33701
|
+
"TURN Key API Token must use Bearer token syntax.": "TURN Key API Token must use Bearer token syntax.",
|
|
33702
|
+
"The selected TURN configuration is not supported.": "The selected TURN configuration is not supported.",
|
|
33320
33703
|
"Setup Complete: Preparing to Fetch from Another Device": "Setup Complete: Preparing to Fetch from Another Device",
|
|
33321
33704
|
"The P2P connection has been configured successfully. The initial synchronisation data must now be fetched from an online source device.": "The P2P connection has been configured successfully. The initial synchronisation data must now be fetched from an online source device.",
|
|
33322
33705
|
"After restarting, select an online source device for the initial Fetch. The local LiveSync database on this device will be rebuilt from that source. Unsynchronised files in this Vault may conflict with the fetched data.": "After restarting, select an online source device for the initial Fetch. The local LiveSync database on this device will be rebuilt from that source. Unsynchronised files in this Vault may conflict with the fetched data.",
|
|
@@ -33331,7 +33714,7 @@ var liveSyncProvisionalEnglishMessages = {
|
|
|
33331
33714
|
"The project's public signalling relay is a best-effort convenience operated by the project author. It does not store Vault contents, but signalling metadata may be visible to the relay. Availability and log retention are not guaranteed. You can replace it with your own Nostr-compatible relay.": "The project's public signalling relay is a best-effort convenience operated by the project author. It does not store Vault contents, but signalling metadata may be visible to the relay. Availability and log retention are not guaranteed. You can replace it with your own Nostr-compatible relay.",
|
|
33332
33715
|
"Learn more about P2P connections": "Learn more about P2P connections",
|
|
33333
33716
|
"Learn more about signalling and TURN": "Learn more about signalling and TURN",
|
|
33334
|
-
"
|
|
33717
|
+
"WebRTC encrypts data between your devices, including when it passes through TURN. The TURN provider cannot read the transferred data. It can see network addresses and traffic volume.": "WebRTC encrypts data between your devices, including when it passes through TURN. The TURN provider cannot read the transferred data. It can see network addresses and traffic volume.",
|
|
33335
33718
|
"Connection compatibility": "Connection compatibility",
|
|
33336
33719
|
"P2P message size": "P2P message size",
|
|
33337
33720
|
Standard: "Standard",
|
|
@@ -34352,8 +34735,8 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
|
|
|
34352
34735
|
};
|
|
34353
34736
|
//#endregion
|
|
34354
34737
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/coreEnvVars.js
|
|
34355
|
-
var manifestVersion = "1.0.
|
|
34356
|
-
var packageVersion = "1.0.
|
|
34738
|
+
var manifestVersion = "1.0.29";
|
|
34739
|
+
var packageVersion = "1.0.29";
|
|
34357
34740
|
//#endregion
|
|
34358
34741
|
//#region ../../../node_modules/octagonal-wheels/dist/iterable/map.js
|
|
34359
34742
|
/**
|
|
@@ -34936,6 +35319,18 @@ async function performFullScan(host, log, errorManager, showingNoticeOrOptions =
|
|
|
34936
35319
|
if (showingNotice) log("Initialize done!", 64, "syncAll");
|
|
34937
35320
|
return scanResult;
|
|
34938
35321
|
}
|
|
35322
|
+
function useOfflineScanner(host) {
|
|
35323
|
+
const log = createInstanceLogFunction("SF:OfflineScanner", host.services.API);
|
|
35324
|
+
const errorManager = new UnresolvedErrorManager(host.services.appLifecycle, host.services.context.events);
|
|
35325
|
+
const handleScanVault = async (showingNotice, ignoreSuspending = false, continueOnFileFailure = false) => {
|
|
35326
|
+
return await performFullScan(host, log, errorManager, {
|
|
35327
|
+
showingNotice,
|
|
35328
|
+
ignoreSuspending,
|
|
35329
|
+
continueOnFileFailure
|
|
35330
|
+
});
|
|
35331
|
+
};
|
|
35332
|
+
host.services.vault.scanVault.addHandler(handleScanVault);
|
|
35333
|
+
}
|
|
34939
35334
|
//#endregion
|
|
34940
35335
|
//#region ../../modules/main/ModuleLiveSyncMain.ts
|
|
34941
35336
|
var ModuleLiveSyncMain = class extends AbstractModule {
|
|
@@ -34960,7 +35355,8 @@ var ModuleLiveSyncMain = class extends AbstractModule {
|
|
|
34960
35355
|
return false;
|
|
34961
35356
|
}
|
|
34962
35357
|
}
|
|
34963
|
-
const
|
|
35358
|
+
const { ignoreSuspending = false, continueOnFileFailure = true } = this.core.startupDatabaseOptions;
|
|
35359
|
+
const initialisationResult = await this.services.databaseEvents.initialiseDatabase(false, false, ignoreSuspending, continueOnFileFailure);
|
|
34964
35360
|
if (initialisationResult === VaultScanResults.FAILED) {
|
|
34965
35361
|
this._log($msg("Ui.Common.LocalDatabaseInitialisationFailed"), 64);
|
|
34966
35362
|
return false;
|
|
@@ -58291,7 +58687,8 @@ var LiveSyncBaseCore = class {
|
|
|
58291
58687
|
getAddOn(cls) {
|
|
58292
58688
|
for (const addon of this.addOns) if (addon.constructor.name == cls) return addon;
|
|
58293
58689
|
}
|
|
58294
|
-
constructor(serviceHub, serviceModuleInitialiser, extraModuleInitialiser, addOnsInitialiser, featuresInitialiser) {
|
|
58690
|
+
constructor(serviceHub, serviceModuleInitialiser, extraModuleInitialiser, addOnsInitialiser, featuresInitialiser, startupDatabaseOptions = {}) {
|
|
58691
|
+
this.startupDatabaseOptions = startupDatabaseOptions;
|
|
58295
58692
|
this.addOns = [];
|
|
58296
58693
|
this._services = void 0;
|
|
58297
58694
|
this.modules = [];
|
|
@@ -60399,8 +60796,9 @@ var NodeFileSystemAdapter = class {
|
|
|
60399
60796
|
return null;
|
|
60400
60797
|
}
|
|
60401
60798
|
async getFiles() {
|
|
60402
|
-
|
|
60403
|
-
|
|
60799
|
+
const files = /* @__PURE__ */ new Map();
|
|
60800
|
+
await this.scanDirectoryInto("", files);
|
|
60801
|
+
return Array.from(files.values());
|
|
60404
60802
|
}
|
|
60405
60803
|
async renameFile(file, newPath) {
|
|
60406
60804
|
const oldPath = file.path;
|
|
@@ -60442,6 +60840,9 @@ var NodeFileSystemAdapter = class {
|
|
|
60442
60840
|
* Helper method to recursively scan directory and populate file cache
|
|
60443
60841
|
*/
|
|
60444
60842
|
async scanDirectory(relativePath = "") {
|
|
60843
|
+
await this.scanDirectoryInto(relativePath, this.fileCache);
|
|
60844
|
+
}
|
|
60845
|
+
async scanDirectoryInto(relativePath, files) {
|
|
60445
60846
|
const fullPath = this.resolvePath(relativePath);
|
|
60446
60847
|
try {
|
|
60447
60848
|
if ((await this.storage.stat(relativePath))?.type !== "folder") throw new Error(`Directory does not exist: ${fullPath}`);
|
|
@@ -60453,9 +60854,9 @@ var NodeFileSystemAdapter = class {
|
|
|
60453
60854
|
path: entryPath,
|
|
60454
60855
|
stat
|
|
60455
60856
|
};
|
|
60456
|
-
|
|
60857
|
+
files.set(entryPath, file);
|
|
60457
60858
|
}
|
|
60458
|
-
for (const entryPath of entries.folders) await this.
|
|
60859
|
+
for (const entryPath of entries.folders) await this.scanDirectoryInto(entryPath, files);
|
|
60459
60860
|
} catch (error) {
|
|
60460
60861
|
this.reportDiagnostic(`Error scanning directory ${fullPath}:`, error);
|
|
60461
60862
|
}
|
|
@@ -64463,10 +64864,9 @@ async function decodeSettingsFromSetupURI(uri, passphrase) {
|
|
|
64463
64864
|
const encryptedSetting = uri.substring(configURIBase.length);
|
|
64464
64865
|
const decrypted = await decryptString(decodeURIComponent(encryptedSetting), passphrase);
|
|
64465
64866
|
try {
|
|
64466
|
-
return JSON.parse(decrypted);
|
|
64467
|
-
} catch
|
|
64867
|
+
return omitP2PRuntimeSettings(JSON.parse(decrypted));
|
|
64868
|
+
} catch {
|
|
64468
64869
|
Logger(`Failed to parse settings from decrypted data`, 64);
|
|
64469
|
-
Logger(e, 16);
|
|
64470
64870
|
return false;
|
|
64471
64871
|
}
|
|
64472
64872
|
}
|
|
@@ -64724,7 +65124,7 @@ async function runCommand(options, context) {
|
|
|
64724
65124
|
const log = (msg) => writeStderrLine(standardIo, `[Daemon] ${String(msg)}`);
|
|
64725
65125
|
replicationScheduling.setExternalPollingMode(!!options.interval);
|
|
64726
65126
|
await core.services.setting.applyPartial({ disableCheckingConfigMismatch: true }, true);
|
|
64727
|
-
log("Replicating
|
|
65127
|
+
log("Replicating with remote...");
|
|
64728
65128
|
if (!isReplicationCompleted(await core.services.replication.replicateUnattended({
|
|
64729
65129
|
trigger: "daemon",
|
|
64730
65130
|
interaction: NO_INTERACTION
|
|
@@ -64734,13 +65134,6 @@ async function runCommand(options, context) {
|
|
|
64734
65134
|
}
|
|
64735
65135
|
replicationScheduling.markInitialOneShotSatisfied();
|
|
64736
65136
|
log("Initial replication complete");
|
|
64737
|
-
const errorManager = new UnresolvedErrorManager(core.services.appLifecycle, core.services.context.events);
|
|
64738
|
-
log("Running mirror scan...");
|
|
64739
|
-
if (!await performFullScan(core, log, errorManager, false, true)) {
|
|
64740
|
-
writeStderrLine(standardIo, "[Daemon] Mirror scan failed, cannot continue");
|
|
64741
|
-
return false;
|
|
64742
|
-
}
|
|
64743
|
-
log("Mirror scan complete");
|
|
64744
65137
|
const restoreSyncSettings = async () => {
|
|
64745
65138
|
await core.services.setting.applyPartial({
|
|
64746
65139
|
...context.originalSyncSettings,
|
|
@@ -65022,8 +65415,7 @@ async function runCommand(options, context) {
|
|
|
65022
65415
|
}
|
|
65023
65416
|
if (options.command === "mirror") {
|
|
65024
65417
|
writeStderrLine(standardIo, "[Command] mirror");
|
|
65025
|
-
|
|
65026
|
-
return await performFullScan(core, log, new UnresolvedErrorManager(core.services.appLifecycle, core.services.context.events), false, true) === VaultScanResults.COMPLETED;
|
|
65418
|
+
return true;
|
|
65027
65419
|
}
|
|
65028
65420
|
if (options.command === "remote-add") {
|
|
65029
65421
|
if (options.commandArgs.length < 2) throw new Error("remote-add requires two arguments: <name> <connstr>");
|
|
@@ -70075,11 +70467,29 @@ function createDiagRTCPeerConnectionConstructor() {
|
|
|
70075
70467
|
}
|
|
70076
70468
|
//#endregion
|
|
70077
70469
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/rpc/transports/trysteroUtils.js
|
|
70470
|
+
function containsTurnUrl(iceServers) {
|
|
70471
|
+
return iceServers.some((server) => {
|
|
70472
|
+
return (typeof server.urls === "string" ? [server.urls] : server.urls).some((url) => /^turns?:/iu.test(url));
|
|
70473
|
+
});
|
|
70474
|
+
}
|
|
70475
|
+
function copyIceServers(iceServers) {
|
|
70476
|
+
return iceServers.map((server) => ({
|
|
70477
|
+
urls: typeof server.urls === "string" ? server.urls : [...server.urls],
|
|
70478
|
+
...server.username === void 0 ? {} : { username: server.username },
|
|
70479
|
+
...server.credential === void 0 ? {} : { credential: server.credential }
|
|
70480
|
+
}));
|
|
70481
|
+
}
|
|
70078
70482
|
function generateJoinRoomOptions(settings) {
|
|
70079
70483
|
const passphraseNumbers = mixedHash(settings.P2P_passphrase, 0);
|
|
70080
70484
|
const passphrase = passphraseNumbers[0].toString(36) + passphraseNumbers[1].toString(36);
|
|
70081
70485
|
const relays = splitP2PRelayUrls(settings.P2P_relays);
|
|
70082
70486
|
const turnServers = splitP2PTurnServerUrls(settings.P2P_turnServers);
|
|
70487
|
+
const managedTurnSelected = hasManagedP2PTurnConfiguration(settings);
|
|
70488
|
+
const preparedIceServers = settings.P2P_iceServers;
|
|
70489
|
+
if (preparedIceServers !== void 0 && preparedIceServers.length === 0) throw new Error("Prepared ICE servers must not be empty.");
|
|
70490
|
+
if (managedTurnSelected && preparedIceServers === void 0) throw new Error("The selected managed TURN configuration requires prepared ICE servers.");
|
|
70491
|
+
if (managedTurnSelected && preparedIceServers && !containsTurnUrl(preparedIceServers)) throw new Error("The prepared ICE servers do not contain a TURN route.");
|
|
70492
|
+
if (preparedIceServers !== void 0 && normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && !containsTurnUrl(preparedIceServers)) throw new Error("Relay-only P2P requires a prepared TURN route.");
|
|
70083
70493
|
const relayConfig = {
|
|
70084
70494
|
manualReconnection: true,
|
|
70085
70495
|
urls: relays
|
|
@@ -70091,12 +70501,13 @@ function generateJoinRoomOptions(settings) {
|
|
|
70091
70501
|
};
|
|
70092
70502
|
if (settings.P2P_useDiagRTC) options.rtcPolyfill = createDiagRTCPeerConnectionConstructor();
|
|
70093
70503
|
else if (typeof compatGlobal.RTCPeerConnection !== "undefined") options.rtcPolyfill = compatGlobal.RTCPeerConnection;
|
|
70094
|
-
if (
|
|
70504
|
+
if (preparedIceServers !== void 0) options.turnConfig = copyIceServers(preparedIceServers);
|
|
70505
|
+
else if (!managedTurnSelected && turnServers.length > 0) options.turnConfig = [{
|
|
70095
70506
|
urls: turnServers,
|
|
70096
70507
|
username: settings.P2P_turnUsername,
|
|
70097
70508
|
credential: settings.P2P_turnCredential
|
|
70098
70509
|
}];
|
|
70099
|
-
if (normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && hasValidP2PTurnServerUrl(settings.P2P_turnServers)) options.rtcConfig = { iceTransportPolicy: "relay" };
|
|
70510
|
+
if (normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && (preparedIceServers !== void 0 ? containsTurnUrl(preparedIceServers) : !managedTurnSelected && hasValidP2PTurnServerUrl(settings.P2P_turnServers))) options.rtcConfig = { iceTransportPolicy: "relay" };
|
|
70100
70511
|
return options;
|
|
70101
70512
|
}
|
|
70102
70513
|
//#endregion
|
|
@@ -70200,7 +70611,7 @@ var TrysteroReplicatorP2PServer = class {
|
|
|
70200
70611
|
await this._room?.leave();
|
|
70201
70612
|
} catch (ex) {
|
|
70202
70613
|
Logger(`Some error has been occurred while leaving the room, but possibly can be ignored`, 16);
|
|
70203
|
-
|
|
70614
|
+
this.logTransportError(ex);
|
|
70204
70615
|
}
|
|
70205
70616
|
this._room = void 0;
|
|
70206
70617
|
this._env.events.emitEvent(EVENT_P2P_DISCONNECTED);
|
|
@@ -70218,7 +70629,7 @@ var TrysteroReplicatorP2PServer = class {
|
|
|
70218
70629
|
this._rpcRoom = void 0;
|
|
70219
70630
|
} catch (ex) {
|
|
70220
70631
|
Logger(`Some error has been occurred while shutting down the server`, 32);
|
|
70221
|
-
|
|
70632
|
+
this.logTransportError(ex);
|
|
70222
70633
|
}
|
|
70223
70634
|
}
|
|
70224
70635
|
/** Release subscriptions whose lifetime is the host object rather than one transport join. */
|
|
@@ -70547,7 +70958,7 @@ You can chose as follows:
|
|
|
70547
70958
|
handshakeTimeoutMs: 3e4,
|
|
70548
70959
|
onJoinError: (error) => {
|
|
70549
70960
|
Logger("Some peer Failed to join Trystero room");
|
|
70550
|
-
|
|
70961
|
+
this.logTransportError(error);
|
|
70551
70962
|
}
|
|
70552
70963
|
});
|
|
70553
70964
|
await this.setRoom(room);
|
|
@@ -70556,6 +70967,13 @@ You can chose as follows:
|
|
|
70556
70967
|
this.dispatchConnectionStatus();
|
|
70557
70968
|
await this.startService(bindings, beforeAdvertisement);
|
|
70558
70969
|
}
|
|
70970
|
+
logTransportError(error) {
|
|
70971
|
+
if (this.settings.P2P_iceServers !== void 0) {
|
|
70972
|
+
Logger("Managed P2P transport error details were omitted.", 16);
|
|
70973
|
+
return;
|
|
70974
|
+
}
|
|
70975
|
+
Logger(error, 16);
|
|
70976
|
+
}
|
|
70559
70977
|
/**
|
|
70560
70978
|
* @deprecated Use serveFunction or serveObject instead. This is only for backward compatibility and may be removed in the future.
|
|
70561
70979
|
* @param type
|
|
@@ -70904,12 +71322,15 @@ var TrysteroReplicator = class {
|
|
|
70904
71322
|
return await this.confirm.askString("Passphrase required", this.translate("P2P.AskPassphraseForShare"), "something you only know", true);
|
|
70905
71323
|
});
|
|
70906
71324
|
const setting = {
|
|
70907
|
-
...this.settings,
|
|
71325
|
+
...omitP2PRuntimeSettings(this.settings),
|
|
70908
71326
|
configPassphraseStore: "",
|
|
70909
71327
|
encryptedCouchDBConnection: "",
|
|
70910
71328
|
encryptedPassphrase: "",
|
|
70911
71329
|
pluginSyncExtendedSetting: {}
|
|
70912
71330
|
};
|
|
71331
|
+
delete setting.P2P_managedType;
|
|
71332
|
+
delete setting.P2P_managedId;
|
|
71333
|
+
delete setting.P2P_managedToken;
|
|
70913
71334
|
if (!passphrase || passphrase.trim() == "") {
|
|
70914
71335
|
Logger("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.", 64);
|
|
70915
71336
|
return encrypt(JSON.stringify(Object.fromEntries(Object.entries(setting).map(([key, value]) => {
|
|
@@ -71241,7 +71662,7 @@ ${info.lastSeq} / ${info.maxSeqInBatch})`, logLevel, "p2p-replicator");
|
|
|
71241
71662
|
return false;
|
|
71242
71663
|
}
|
|
71243
71664
|
try {
|
|
71244
|
-
return JSON.parse(await decrypt(encryptedConfig, passphrase));
|
|
71665
|
+
return omitP2PRuntimeSettings(JSON.parse(await decrypt(encryptedConfig, passphrase)));
|
|
71245
71666
|
} catch (e) {
|
|
71246
71667
|
Logger("Error while decrypting the configuration", 64);
|
|
71247
71668
|
Logger(e, 16);
|
|
@@ -71489,18 +71910,24 @@ var P2PRoomSession = class {
|
|
|
71489
71910
|
//#endregion
|
|
71490
71911
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/replication/trystero/p2pReplicatorConfigurationIdentity.js
|
|
71491
71912
|
function getP2PReplicatorConfigurationIdentity(settings) {
|
|
71913
|
+
const managedTurnSelected = hasManagedP2PTurnConfiguration(settings);
|
|
71492
71914
|
const turnServerValue = settings.P2P_turnServers ?? "";
|
|
71493
71915
|
const turnServers = splitP2PTurnServerUrls(turnServerValue);
|
|
71494
|
-
const effectivePath = normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && hasValidP2PTurnServerUrl(turnServerValue) ? P2PConnectionPaths.Relay : P2PConnectionPaths.Automatic;
|
|
71495
|
-
const turnAuthentication = turnServers.length > 0 ? [settings.P2P_turnUsername, settings.P2P_turnCredential] : void 0;
|
|
71916
|
+
const effectivePath = normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && (managedTurnSelected || hasValidP2PTurnServerUrl(turnServerValue)) ? P2PConnectionPaths.Relay : P2PConnectionPaths.Automatic;
|
|
71917
|
+
const turnAuthentication = !managedTurnSelected && turnServers.length > 0 ? [settings.P2P_turnUsername, settings.P2P_turnCredential] : void 0;
|
|
71496
71918
|
return JSON.stringify([
|
|
71497
71919
|
"p2p",
|
|
71498
71920
|
settings.P2P_AppID || "self-hosted-livesync",
|
|
71499
71921
|
settings.P2P_roomID,
|
|
71500
71922
|
settings.P2P_passphrase,
|
|
71501
71923
|
splitP2PRelayUrls(settings.P2P_relays),
|
|
71502
|
-
turnServers,
|
|
71924
|
+
managedTurnSelected ? void 0 : turnServers,
|
|
71503
71925
|
turnAuthentication,
|
|
71926
|
+
managedTurnSelected ? [
|
|
71927
|
+
settings.P2P_managedType,
|
|
71928
|
+
settings.P2P_managedId,
|
|
71929
|
+
settings.P2P_managedToken
|
|
71930
|
+
] : void 0,
|
|
71504
71931
|
normaliseP2PMaxWirePayloadBytes(settings.P2P_maxWirePayloadBytes),
|
|
71505
71932
|
effectivePath,
|
|
71506
71933
|
settings.P2P_useDiagRTC ?? false
|
|
@@ -71515,19 +71942,26 @@ function activeP2PRelayBindingCovers(activeSettings, trialSettings) {
|
|
|
71515
71942
|
}
|
|
71516
71943
|
//#endregion
|
|
71517
71944
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/replication/trystero/P2PRoomSessionOwner.js
|
|
71945
|
+
var StaleRoomReconciliationError = class extends Error {};
|
|
71946
|
+
var P2P_ROOM_OPEN_TIMEOUT_MS = 3e4;
|
|
71947
|
+
var P2P_SETTINGS_PREPARATION_TIMEOUT_MS = 3e4;
|
|
71518
71948
|
var P2PRoomSessionOwner = class {
|
|
71519
|
-
constructor(env, createSession = (sessionEnv) => new P2PRoomSession(sessionEnv)) {
|
|
71949
|
+
constructor(env, createSession = (sessionEnv) => new P2PRoomSession(sessionEnv), options = {}) {
|
|
71520
71950
|
this.env = env;
|
|
71521
71951
|
this.createSession = createSession;
|
|
71952
|
+
this.options = options;
|
|
71522
71953
|
}
|
|
71523
71954
|
env;
|
|
71524
71955
|
createSession;
|
|
71956
|
+
options;
|
|
71525
71957
|
current;
|
|
71526
71958
|
lifecycleOperation = Promise.resolve();
|
|
71527
71959
|
persistentDemands = /* @__PURE__ */ new Set();
|
|
71528
71960
|
finiteDemands = /* @__PURE__ */ new Set();
|
|
71529
71961
|
automationCoordinator = new P2PAutomationCoordinator();
|
|
71530
71962
|
activeBinding;
|
|
71963
|
+
pendingPreparation;
|
|
71964
|
+
runtimeGeneration = 0;
|
|
71531
71965
|
get currentSession() {
|
|
71532
71966
|
return this.current;
|
|
71533
71967
|
}
|
|
@@ -71550,6 +71984,7 @@ var P2PRoomSessionOwner = class {
|
|
|
71550
71984
|
if (active && enabled) this.persistentDemands.add(demand);
|
|
71551
71985
|
else this.persistentDemands.delete(demand);
|
|
71552
71986
|
if (active && !enabled) Logger(this.env.services.context.translate("P2P.NotEnabled"), 64);
|
|
71987
|
+
this.fencePreparationForCurrentSettings(enabled);
|
|
71553
71988
|
await this.reconcileTransport();
|
|
71554
71989
|
}
|
|
71555
71990
|
/**
|
|
@@ -71562,6 +71997,7 @@ var P2PRoomSessionOwner = class {
|
|
|
71562
71997
|
if (!this.env.services.setting.currentSettings().P2P_Enabled) throw new Error("P2P is not enabled.");
|
|
71563
71998
|
const demand = /* @__PURE__ */ Symbol("p2p-finite-room-demand");
|
|
71564
71999
|
this.finiteDemands.add(demand);
|
|
72000
|
+
this.fencePreparationForCurrentSettings(true);
|
|
71565
72001
|
try {
|
|
71566
72002
|
await this.reconcileTransport();
|
|
71567
72003
|
if (!this.finiteDemands.has(demand)) throw new Error("The P2P room demand was retired before the operation started.");
|
|
@@ -71602,39 +72038,55 @@ var P2PRoomSessionOwner = class {
|
|
|
71602
72038
|
return;
|
|
71603
72039
|
}
|
|
71604
72040
|
const binding = this.getEffectiveBinding();
|
|
71605
|
-
if (this.current?.host.isServing && this.bindingsMatch(this.activeBinding, binding)) {
|
|
72041
|
+
if (this.current?.host.isServing && this.bindingsMatch(this.activeBinding, binding) && this.connectionSettingsRemainUsable(this.activeBinding?.settings)) {
|
|
71606
72042
|
this.reconcileCurrentSessionPolicy(this.current);
|
|
71607
72043
|
Logger("P2P replicator is already open.");
|
|
71608
72044
|
return;
|
|
71609
72045
|
}
|
|
71610
72046
|
if (this.current) await this.closeTransport();
|
|
71611
72047
|
let candidate;
|
|
72048
|
+
const operationGeneration = this.runtimeGeneration;
|
|
71612
72049
|
try {
|
|
71613
|
-
|
|
71614
|
-
|
|
72050
|
+
const connectionSettings = await this.prepareConnectionSettings(binding, operationGeneration);
|
|
72051
|
+
this.assertReconciliationCurrent(binding, operationGeneration, connectionSettings);
|
|
72052
|
+
const connectionBinding = {
|
|
72053
|
+
...binding,
|
|
72054
|
+
settings: connectionSettings
|
|
72055
|
+
};
|
|
72056
|
+
candidate = this.createSession(this.buildSessionEnv(connectionBinding));
|
|
72057
|
+
if (hasManagedP2PTurnConfiguration(binding.settings)) await this.withRoomOpenDeadline(candidate.open());
|
|
72058
|
+
else await candidate.open();
|
|
71615
72059
|
if (!candidate.host.isServing) throw new Error("The P2P room did not start serving.");
|
|
71616
72060
|
const currentBinding = this.getEffectiveBinding();
|
|
71617
|
-
if (!currentBinding.enabled || !this.hasRoomDemand() || !this.bindingsMatch(binding, currentBinding)) {
|
|
72061
|
+
if (!currentBinding.enabled || !this.hasRoomDemand() || !this.bindingsMatch(binding, currentBinding) || operationGeneration !== this.runtimeGeneration || !this.connectionSettingsRemainUsable(connectionSettings)) {
|
|
71618
72062
|
await candidate.retire();
|
|
71619
72063
|
return;
|
|
71620
72064
|
}
|
|
71621
72065
|
this.current = candidate;
|
|
71622
|
-
this.activeBinding =
|
|
72066
|
+
this.activeBinding = connectionBinding;
|
|
71623
72067
|
this.reconcileCurrentSessionPolicy(candidate);
|
|
71624
72068
|
} catch (error) {
|
|
71625
72069
|
await candidate?.retire(error).catch((retirementError) => {
|
|
71626
|
-
Logger(
|
|
72070
|
+
if (hasManagedP2PTurnConfiguration(binding.settings)) Logger("The managed P2P room could not be retired cleanly.", 16);
|
|
72071
|
+
else Logger(retirementError, 16);
|
|
71627
72072
|
});
|
|
71628
|
-
Logger(error instanceof Error ? error.message : "Error while opening P2P connection", 64);
|
|
71629
|
-
Logger(error, 16);
|
|
71630
72073
|
this.current = void 0;
|
|
71631
72074
|
this.activeBinding = void 0;
|
|
72075
|
+
if (error instanceof StaleRoomReconciliationError || operationGeneration !== this.runtimeGeneration) return;
|
|
72076
|
+
if (hasManagedP2PTurnConfiguration(binding.settings)) {
|
|
72077
|
+
Logger("The managed P2P room could not be prepared or opened.", 64);
|
|
72078
|
+
Logger("Managed P2P room failure details were omitted.", 16);
|
|
72079
|
+
throw new Error("The managed P2P room could not be prepared or opened.");
|
|
72080
|
+
}
|
|
72081
|
+
Logger(error instanceof Error ? error.message : "Error while opening P2P connection", 64);
|
|
72082
|
+
Logger(error, 16);
|
|
71632
72083
|
}
|
|
71633
72084
|
});
|
|
71634
72085
|
}
|
|
71635
72086
|
async close() {
|
|
71636
72087
|
this.persistentDemands.clear();
|
|
71637
72088
|
this.finiteDemands.clear();
|
|
72089
|
+
this.invalidatePreparation();
|
|
71638
72090
|
await this.enqueueLifecycleOperation(async () => {
|
|
71639
72091
|
await this.closeTransport();
|
|
71640
72092
|
});
|
|
@@ -71656,9 +72108,125 @@ var P2PRoomSessionOwner = class {
|
|
|
71656
72108
|
bindingsMatch(current, candidate) {
|
|
71657
72109
|
return current?.database === candidate.database && current.signature === candidate.signature;
|
|
71658
72110
|
}
|
|
72111
|
+
connectionSettingsRemainUsable(settings) {
|
|
72112
|
+
if (!settings) return false;
|
|
72113
|
+
const managed = hasManagedP2PTurnConfiguration(settings);
|
|
72114
|
+
const iceServers = settings.P2P_iceServers;
|
|
72115
|
+
if (iceServers === void 0) return !managed;
|
|
72116
|
+
if (!this.hasUsableIceServer(iceServers)) return false;
|
|
72117
|
+
const hasTurnServer = this.hasUsableTurnServer(iceServers);
|
|
72118
|
+
if (managed && !hasTurnServer) return false;
|
|
72119
|
+
if (normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && !hasTurnServer) return false;
|
|
72120
|
+
const expiresAt = settings.P2P_iceServersExpiresAt;
|
|
72121
|
+
if (expiresAt === void 0) return !managed;
|
|
72122
|
+
return Number.isFinite(expiresAt) && expiresAt > Date.now() + 3e4;
|
|
72123
|
+
}
|
|
72124
|
+
fencePreparationForCurrentSettings(enabled) {
|
|
72125
|
+
if (!enabled) {
|
|
72126
|
+
this.invalidatePreparation();
|
|
72127
|
+
return;
|
|
72128
|
+
}
|
|
72129
|
+
if (this.pendingPreparation !== void 0 && this.pendingPreparation.signature !== this.getEffectiveBinding().signature) this.invalidatePreparation();
|
|
72130
|
+
}
|
|
72131
|
+
invalidatePreparation() {
|
|
72132
|
+
this.runtimeGeneration += 1;
|
|
72133
|
+
const pending = this.pendingPreparation;
|
|
72134
|
+
this.pendingPreparation = void 0;
|
|
72135
|
+
if (pending && !pending.controller.signal.aborted) pending.controller.abort(/* @__PURE__ */ new Error("The P2P settings preparation was cancelled."));
|
|
72136
|
+
}
|
|
72137
|
+
async prepareConnectionSettings(binding, operationGeneration) {
|
|
72138
|
+
const managed = hasManagedP2PTurnConfiguration(binding.settings);
|
|
72139
|
+
const prepare = this.options.prepareP2PSettings;
|
|
72140
|
+
if (!prepare) {
|
|
72141
|
+
if (managed) throw new Error("The selected managed TURN configuration is not supported by this host.");
|
|
72142
|
+
return binding.settings;
|
|
72143
|
+
}
|
|
72144
|
+
const controller = new AbortController();
|
|
72145
|
+
const pending = {
|
|
72146
|
+
signature: binding.signature,
|
|
72147
|
+
controller
|
|
72148
|
+
};
|
|
72149
|
+
this.pendingPreparation = pending;
|
|
72150
|
+
try {
|
|
72151
|
+
const prepared = await this.prepareWithDeadline(prepare, binding.settings, controller);
|
|
72152
|
+
if (prepared.P2P_iceServers === void 0 && prepared.P2P_iceServersExpiresAt === void 0) {
|
|
72153
|
+
if (managed) throw new Error("The prepared managed TURN settings do not include ICE servers.");
|
|
72154
|
+
return binding.settings;
|
|
72155
|
+
}
|
|
72156
|
+
const iceServers = this.copyPreparedIceServers(prepared.P2P_iceServers);
|
|
72157
|
+
const expiresAt = prepared.P2P_iceServersExpiresAt;
|
|
72158
|
+
const connectionSettings = {
|
|
72159
|
+
...binding.settings,
|
|
72160
|
+
P2P_iceServers: iceServers,
|
|
72161
|
+
P2P_iceServersExpiresAt: expiresAt
|
|
72162
|
+
};
|
|
72163
|
+
if (!this.connectionSettingsRemainUsable(connectionSettings)) throw new Error("The prepared managed TURN settings are missing usable ICE servers or expiry.");
|
|
72164
|
+
this.assertReconciliationCurrent(binding, operationGeneration, connectionSettings);
|
|
72165
|
+
return connectionSettings;
|
|
72166
|
+
} finally {
|
|
72167
|
+
if (this.pendingPreparation === pending) this.pendingPreparation = void 0;
|
|
72168
|
+
}
|
|
72169
|
+
}
|
|
72170
|
+
prepareWithDeadline(prepare, settings, controller) {
|
|
72171
|
+
const preparation = Promise.resolve().then(() => prepare(Object.freeze({ ...settings }), controller.signal));
|
|
72172
|
+
return new Promise((resolve, reject) => {
|
|
72173
|
+
let settled = false;
|
|
72174
|
+
const finish = (operation) => {
|
|
72175
|
+
if (settled) return;
|
|
72176
|
+
settled = true;
|
|
72177
|
+
globalThis.clearTimeout(timeout);
|
|
72178
|
+
controller.signal.removeEventListener("abort", onAbort);
|
|
72179
|
+
operation();
|
|
72180
|
+
};
|
|
72181
|
+
const onAbort = () => finish(() => reject(controller.signal.reason instanceof Error ? controller.signal.reason : /* @__PURE__ */ new Error("The P2P settings preparation was cancelled.")));
|
|
72182
|
+
const timeout = globalThis.setTimeout(() => {
|
|
72183
|
+
controller.abort(/* @__PURE__ */ new Error("The P2P settings preparation timed out."));
|
|
72184
|
+
}, P2P_SETTINGS_PREPARATION_TIMEOUT_MS);
|
|
72185
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
72186
|
+
if (controller.signal.aborted) onAbort();
|
|
72187
|
+
preparation.then((prepared) => finish(() => resolve(prepared)), () => finish(() => reject(/* @__PURE__ */ new Error("The P2P settings preparation failed."))));
|
|
72188
|
+
});
|
|
72189
|
+
}
|
|
72190
|
+
copyPreparedIceServers(iceServers) {
|
|
72191
|
+
if (!Array.isArray(iceServers) || iceServers.length === 0) return [];
|
|
72192
|
+
return iceServers.map((server) => ({
|
|
72193
|
+
urls: typeof server.urls === "string" ? server.urls : [...server.urls],
|
|
72194
|
+
...server.username === void 0 ? {} : { username: server.username },
|
|
72195
|
+
...server.credential === void 0 ? {} : { credential: server.credential }
|
|
72196
|
+
}));
|
|
72197
|
+
}
|
|
72198
|
+
hasUsableIceServer(iceServers) {
|
|
72199
|
+
return Array.isArray(iceServers) && iceServers.some((server) => {
|
|
72200
|
+
const urls = typeof server?.urls === "string" ? [server.urls] : server?.urls;
|
|
72201
|
+
return Array.isArray(urls) && urls.some((url) => typeof url === "string" && url.trim().length > 0);
|
|
72202
|
+
});
|
|
72203
|
+
}
|
|
72204
|
+
hasUsableTurnServer(iceServers) {
|
|
72205
|
+
return Array.isArray(iceServers) && iceServers.some((server) => {
|
|
72206
|
+
const urls = typeof server?.urls === "string" ? [server.urls] : server?.urls;
|
|
72207
|
+
return Array.isArray(urls) && urls.some((url) => typeof url === "string" && /^turns?:/iu.test(url));
|
|
72208
|
+
});
|
|
72209
|
+
}
|
|
72210
|
+
async withRoomOpenDeadline(opening) {
|
|
72211
|
+
let timeout;
|
|
72212
|
+
try {
|
|
72213
|
+
await Promise.race([opening, new Promise((_resolve, reject) => {
|
|
72214
|
+
timeout = globalThis.setTimeout(() => reject(/* @__PURE__ */ new Error("The P2P room opening timed out.")), P2P_ROOM_OPEN_TIMEOUT_MS);
|
|
72215
|
+
})]);
|
|
72216
|
+
} finally {
|
|
72217
|
+
if (timeout !== void 0) globalThis.clearTimeout(timeout);
|
|
72218
|
+
}
|
|
72219
|
+
}
|
|
72220
|
+
assertReconciliationCurrent(binding, operationGeneration, connectionSettings) {
|
|
72221
|
+
if (operationGeneration !== this.runtimeGeneration || !this.hasRoomDemand()) throw new StaleRoomReconciliationError();
|
|
72222
|
+
const currentBinding = this.getEffectiveBinding();
|
|
72223
|
+
if (!currentBinding.enabled) throw new StaleRoomReconciliationError();
|
|
72224
|
+
if (binding && !this.bindingsMatch(binding, currentBinding)) throw new StaleRoomReconciliationError();
|
|
72225
|
+
if (connectionSettings && !this.connectionSettingsRemainUsable(connectionSettings)) throw new StaleRoomReconciliationError();
|
|
72226
|
+
}
|
|
71659
72227
|
/** Capture immutable session inputs while keeping policy live. */
|
|
71660
72228
|
getEffectiveBinding() {
|
|
71661
|
-
const settings = { ...this.env.services.setting.currentSettings() };
|
|
72229
|
+
const settings = omitP2PRuntimeSettings({ ...this.env.services.setting.currentSettings() });
|
|
71662
72230
|
const deviceName = this.env.services.config.getSmallConfig("p2p_device_name") || this.env.services.vault.getVaultName();
|
|
71663
72231
|
const database = this.env.services.database.localDatabase.localDatabase;
|
|
71664
72232
|
this.automationCoordinator.reconcileIdentity(JSON.stringify([
|
|
@@ -72035,10 +72603,15 @@ function closeForLifecycle(owner, state) {
|
|
|
72035
72603
|
cancelDelayedAutomation(owner, state);
|
|
72036
72604
|
return owner.close();
|
|
72037
72605
|
}
|
|
72038
|
-
function reconcileAutoStart(context, settings) {
|
|
72039
|
-
if (!settings.P2P_Enabled || !settings.P2P_AutoStart)
|
|
72040
|
-
|
|
72041
|
-
|
|
72606
|
+
async function reconcileAutoStart(context, settings) {
|
|
72607
|
+
if (!settings.P2P_Enabled || !settings.P2P_AutoStart) {
|
|
72608
|
+
await context.roomSessionOwner.setPersistentDemand("automatic", false);
|
|
72609
|
+
return;
|
|
72610
|
+
}
|
|
72611
|
+
if (context.state.explicitDisconnectVeto || context.state.lifecycleClosed) return;
|
|
72612
|
+
try {
|
|
72613
|
+
await context.roomSessionOwner.setPersistentDemand("automatic", true);
|
|
72614
|
+
} catch {}
|
|
72042
72615
|
}
|
|
72043
72616
|
function scheduleAutoStart(context, delayMs = 100) {
|
|
72044
72617
|
clearDelayedAutoStart(context.state);
|
|
@@ -72144,8 +72717,8 @@ function createServiceLifecycle(context) {
|
|
|
72144
72717
|
scheduleAutoStart: (delayMs) => scheduleAutoStart(context, delayMs)
|
|
72145
72718
|
};
|
|
72146
72719
|
}
|
|
72147
|
-
function createP2PService(env) {
|
|
72148
|
-
const roomSessionOwner = new P2PRoomSessionOwner(env);
|
|
72720
|
+
function createP2PService(env, options = {}) {
|
|
72721
|
+
const roomSessionOwner = new P2PRoomSessionOwner(env, void 0, options);
|
|
72149
72722
|
const state = {
|
|
72150
72723
|
explicitDisconnectVeto: false,
|
|
72151
72724
|
lifecycleClosed: false,
|
|
@@ -72226,8 +72799,8 @@ function addP2PEventHandlers(source, events) {
|
|
|
72226
72799
|
}
|
|
72227
72800
|
//#endregion
|
|
72228
72801
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/replication/trystero/useP2PReplicatorFeature.js
|
|
72229
|
-
function useP2PReplicatorFeature(host, openReplicationUIFactory, openRebuildUIFactory) {
|
|
72230
|
-
const service = createP2PService({ services: host.services });
|
|
72802
|
+
function useP2PReplicatorFeature(host, openReplicationUIFactory, openRebuildUIFactory, options = {}) {
|
|
72803
|
+
const service = createP2PService({ services: host.services }, options);
|
|
72231
72804
|
const replicator = service.compatibilityReplicator;
|
|
72232
72805
|
const { views, lifecycle } = service;
|
|
72233
72806
|
const configureReplicator = (instance) => {
|
|
@@ -72406,6 +72979,24 @@ function applyStoredSetting(target, storedText, key) {
|
|
|
72406
72979
|
//#endregion
|
|
72407
72980
|
//#region main.ts
|
|
72408
72981
|
var SETTINGS_FILE = ".livesync/settings.json";
|
|
72982
|
+
var VAULT_SYNC_MODES = {
|
|
72983
|
+
daemon: {
|
|
72984
|
+
watchFiles: true,
|
|
72985
|
+
reflectReplicationResults: true,
|
|
72986
|
+
startupDatabaseOptions: {
|
|
72987
|
+
ignoreSuspending: false,
|
|
72988
|
+
continueOnFileFailure: true
|
|
72989
|
+
}
|
|
72990
|
+
},
|
|
72991
|
+
mirror: {
|
|
72992
|
+
watchFiles: false,
|
|
72993
|
+
reflectReplicationResults: false,
|
|
72994
|
+
startupDatabaseOptions: {
|
|
72995
|
+
ignoreSuspending: true,
|
|
72996
|
+
continueOnFileFailure: false
|
|
72997
|
+
}
|
|
72998
|
+
}
|
|
72999
|
+
};
|
|
72409
73000
|
ensureGlobalNodeLocalStorage();
|
|
72410
73001
|
defaultLoggerEnv.minLogLevel = -1;
|
|
72411
73002
|
function printHelp(standardIo) {
|
|
@@ -72627,6 +73218,7 @@ async function createDefaultSettingsFile(options, standardIo) {
|
|
|
72627
73218
|
}
|
|
72628
73219
|
async function main(standardIo = createNodeStandardIo(), commandRunner = runCommand) {
|
|
72629
73220
|
const options = parseArgs(standardIo);
|
|
73221
|
+
const vaultSyncMode = VAULT_SYNC_MODES[options.command];
|
|
72630
73222
|
if (options.interval && options.command !== "daemon") writeStderrLine(standardIo, `Warning: --interval is only used in daemon mode, ignored for '${options.command}'`);
|
|
72631
73223
|
const avoidStdoutNoise = options.command === "cat" || options.command === "cat-rev" || options.command === "ls" || options.command === "remote-add" || options.command === "remote-ls" || options.command === "remote-export" || options.command === "p2p-peers" || options.command === "info" || options.command === "rm" || options.command === "resolve" || options.command === "mark-resolved" || options.command === "unlock-remote" || options.command === "lock-remote" || options.command === "remote-status";
|
|
72632
73224
|
const infoLog = (...values) => {
|
|
@@ -72652,7 +73244,6 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
|
|
|
72652
73244
|
}
|
|
72653
73245
|
const settingsPath = options.settingsPath ? path.resolve(options.settingsPath) : path.join(databasePath, SETTINGS_FILE);
|
|
72654
73246
|
configureNodeLocalStorage(path.join(databasePath, ".livesync", "runtime", "local-storage.json"));
|
|
72655
|
-
const watchEnabled = options.command === "daemon";
|
|
72656
73247
|
const vaultPath = options.command === "mirror" && options.commandArgs[0] ? path.resolve(options.commandArgs[0]) : options.vaultPath ? path.resolve(options.vaultPath) : databasePath;
|
|
72657
73248
|
try {
|
|
72658
73249
|
if (!(await fsPromises.stat(vaultPath)).isDirectory()) {
|
|
@@ -72669,7 +73260,7 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
|
|
|
72669
73260
|
infoLog(`Settings: ${settingsPath}`);
|
|
72670
73261
|
infoLog("");
|
|
72671
73262
|
let ignoreRules;
|
|
72672
|
-
if (
|
|
73263
|
+
if (vaultSyncMode) {
|
|
72673
73264
|
ignoreRules = new IgnoreRules(vaultPath, (message, detail) => {
|
|
72674
73265
|
if (detail === void 0) writeStderrLine(standardIo, message);
|
|
72675
73266
|
else writeStderrLine(standardIo, message, detail);
|
|
@@ -72703,7 +73294,7 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
|
|
|
72703
73294
|
}
|
|
72704
73295
|
writeStderrLine(standardIo, prefix, message);
|
|
72705
73296
|
}, true);
|
|
72706
|
-
if (
|
|
73297
|
+
if (!vaultSyncMode?.reflectReplicationResults) serviceHubInstance.replication.processSynchroniseResult.addHandler(async () => {
|
|
72707
73298
|
writeStderrLine(standardIo, `[Info] Replication result received, but not processed automatically in CLI mode.`);
|
|
72708
73299
|
return await Promise.resolve(true);
|
|
72709
73300
|
}, -100);
|
|
@@ -72741,10 +73332,11 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
|
|
|
72741
73332
|
let p2pReplicator;
|
|
72742
73333
|
let replicationScheduling;
|
|
72743
73334
|
const core = new LiveSyncBaseCore(serviceHubInstance, (core, serviceHub) => {
|
|
72744
|
-
return initialiseServiceModulesCLI(vaultPath, core, serviceHub, ignoreRules,
|
|
73335
|
+
return initialiseServiceModulesCLI(vaultPath, core, serviceHub, ignoreRules, vaultSyncMode?.watchFiles ?? false);
|
|
72745
73336
|
}, (core) => [], () => [], (core, coreFeatureViews) => {
|
|
72746
73337
|
replicationScheduling = coreFeatureViews.replicationScheduling;
|
|
72747
|
-
|
|
73338
|
+
if (vaultSyncMode) useOfflineScanner(core);
|
|
73339
|
+
p2pReplicator = useP2PReplicatorFeature(core, void 0, void 0, { prepareP2PSettings: useP2PSettingsPreparation(core.services.API.webCompatFetch.bind(core.services.API)) });
|
|
72748
73340
|
core.services.vault.isTargetFile.addHandler(async (target) => {
|
|
72749
73341
|
const parts = stripAllPrefixes(getPathFromUXFileInfo(target)).split(path.sep);
|
|
72750
73342
|
if (parts.some((part) => part.startsWith("."))) return await Promise.resolve(false);
|
|
@@ -72759,7 +73351,7 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
|
|
|
72759
73351
|
return true;
|
|
72760
73352
|
}, 0);
|
|
72761
73353
|
}
|
|
72762
|
-
});
|
|
73354
|
+
}, vaultSyncMode?.startupDatabaseOptions);
|
|
72763
73355
|
if (!replicationScheduling) throw new Error("Replication scheduling was not provided during core feature composition.");
|
|
72764
73356
|
const shutdown = async (signal) => {
|
|
72765
73357
|
writeStdoutLine(standardIo);
|
|
@@ -72809,7 +73401,13 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
|
|
|
72809
73401
|
};
|
|
72810
73402
|
await core.services.setting.suspendAllSync();
|
|
72811
73403
|
const settingsAfterSuspend = cloneSettings(core.services.setting.currentSettings());
|
|
72812
|
-
|
|
73404
|
+
let readyResult = false;
|
|
73405
|
+
try {
|
|
73406
|
+
readyResult = await core.services.control.onReady();
|
|
73407
|
+
} finally {
|
|
73408
|
+
if (!readyResult) await core.services.control.onUnload();
|
|
73409
|
+
}
|
|
73410
|
+
if (!readyResult) throw new Error("Failed to initialise LiveSync.");
|
|
72813
73411
|
const settingsBeforeCommand = cloneSettings(core.services.setting.currentSettings());
|
|
72814
73412
|
const transientSettingKeys = changedSettingKeys(settingsBeforeSuspend, settingsAfterSuspend);
|
|
72815
73413
|
for (const key of CLI_RUNTIME_ONLY_SETTING_KEYS) transientSettingKeys.add(key);
|