@narumitw/pi-sync 0.30.0 → 0.34.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.
@@ -0,0 +1,678 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { decodeSnapshot, encodeSnapshot } from "./snapshot-codec.js";
3
+ import {
4
+ type BackendDiagnostic,
5
+ type ExpectedRemoteHead,
6
+ type PublishSnapshotOptions,
7
+ type PublishSnapshotResult,
8
+ type RemoteHead,
9
+ type RemoteHistoryEntry,
10
+ type SyncBackend,
11
+ SyncBackendConflictError,
12
+ SyncBackendPublicationOutcomeUnknownError,
13
+ } from "./sync-backend.js";
14
+ import type { LatestPointer, RemoteObject, ResolvedWebDavBackend, Snapshot } from "./types.js";
15
+ import { WebDavClient, WebDavHttpError, WebDavPreconditionError } from "./webdav-client.js";
16
+
17
+ const VERSION = 1;
18
+ const POST_COMMIT_TIMEOUT_MS = 30_000;
19
+
20
+ export class WebDavSyncBackend implements SyncBackend {
21
+ readonly identity: string;
22
+ readonly destination: string;
23
+ private conditionalVerified = false;
24
+ private readonly checksums = new Map<string, string>();
25
+ private capabilityCheck?: Promise<void>;
26
+
27
+ constructor(
28
+ private readonly config: ResolvedWebDavBackend,
29
+ private readonly postCommitTimeoutMs = POST_COMMIT_TIMEOUT_MS,
30
+ ) {
31
+ assertSafeDestination(config);
32
+ this.identity = webDavBackendIdentity(config);
33
+ this.destination = webDavStorageLocation(config);
34
+ }
35
+
36
+ get capability() {
37
+ return this.conditionalVerified
38
+ ? ("atomic-conditional" as const)
39
+ : ("conditional-required" as const);
40
+ }
41
+
42
+ sameRevision(left: string, right: string) {
43
+ return left === right;
44
+ }
45
+
46
+ async readHead(signal?: AbortSignal): Promise<RemoteHead | undefined> {
47
+ const object = await new WebDavClient(this.config, signal).getJson<LatestPointer>(
48
+ latestPath(this.config),
49
+ );
50
+ throwIfAborted(signal);
51
+ if (object.missing) return undefined;
52
+ const pointer = requirePointer(object.value, this.config.destination.namespace);
53
+ this.registerChecksum(pointer.snapshot, pointer.sha256);
54
+ return remoteHead(pointer, this.identity, object.etag);
55
+ }
56
+
57
+ async readSnapshot(reference: string, signal?: AbortSignal): Promise<Snapshot> {
58
+ requireSnapshotReference(reference);
59
+ const expectedChecksum =
60
+ this.checksums.get(reference) ?? (await this.resolveChecksum(reference, signal));
61
+ const object = await new WebDavClient(this.config, signal).getBuffer(
62
+ snapshotPath(this.config, reference),
63
+ );
64
+ throwIfAborted(signal);
65
+ if (!object.value) throw new Error(`Snapshot not found: ${reference}`);
66
+ if (!expectedChecksum || sha256(object.value) !== expectedChecksum) {
67
+ throw new Error("Remote snapshot checksum mismatch.");
68
+ }
69
+ const snapshot = await decodeSnapshot(object.value, { signal });
70
+ if (snapshot.id !== reference || snapshot.profile !== this.config.destination.namespace) {
71
+ throw new Error("Remote snapshot identity mismatch.");
72
+ }
73
+ validateSnapshotBundle(snapshot);
74
+ return snapshot;
75
+ }
76
+
77
+ async publishSnapshot(
78
+ snapshot: Snapshot,
79
+ expected: ExpectedRemoteHead,
80
+ options: PublishSnapshotOptions = {},
81
+ ): Promise<PublishSnapshotResult> {
82
+ throwIfAborted(options.signal);
83
+ assertSnapshotIdentity(snapshot, this.config.destination.namespace);
84
+ await this.ensureAtomicConditions(options.signal);
85
+ throwIfAborted(options.signal);
86
+ const client = new WebDavClient(this.config, options.signal);
87
+ await client.ensureCollection(snapshotsPath(this.config));
88
+ const encoded = await encodeSnapshot(snapshot);
89
+ throwIfAborted(options.signal);
90
+ const pointer = pointerFor(this.config, snapshot, sha256(encoded));
91
+ const stagedPath = snapshotPath(this.config, snapshot.id);
92
+ try {
93
+ await client.putBuffer(stagedPath, encoded, "application/gzip", { ifAbsent: true });
94
+ } catch (error) {
95
+ if (!(error instanceof WebDavPreconditionError)) throw error;
96
+ const existing = await client.getBuffer(stagedPath);
97
+ if (!existing.value || sha256(existing.value) !== pointer.sha256) {
98
+ throw new SyncBackendConflictError(
99
+ `Immutable snapshot id already exists with different content: ${snapshot.id}`,
100
+ );
101
+ }
102
+ }
103
+ const currentObject = await client.getJson<LatestPointer>(latestPath(this.config));
104
+ throwIfAborted(options.signal);
105
+ const current = currentObject.missing
106
+ ? undefined
107
+ : remoteHead(
108
+ requirePointer(currentObject.value, this.config.destination.namespace),
109
+ this.identity,
110
+ currentObject.etag,
111
+ );
112
+ if (!matchesExpected(current, expected)) {
113
+ throw new SyncBackendConflictError(
114
+ "Remote changed while pushing. Run /sync pull first, then retry.",
115
+ {
116
+ currentHead: current,
117
+ },
118
+ );
119
+ }
120
+ const condition = publicationCondition(currentObject, expected, this.identity);
121
+ throwIfAborted(options.signal);
122
+ options.onCommit?.();
123
+ const commitClient = new WebDavClient(
124
+ this.config,
125
+ AbortSignal.timeout(this.postCommitTimeoutMs),
126
+ this.postCommitTimeoutMs,
127
+ );
128
+ try {
129
+ await commitClient.putJson(latestPath(this.config), pointer, condition);
130
+ } catch (error) {
131
+ if (error instanceof WebDavPreconditionError) {
132
+ const latest = await this.readHeadAfterCommit(commitClient).catch(() => undefined);
133
+ throw new SyncBackendConflictError("Remote changed while publishing the WebDAV pointer.", {
134
+ currentHead: latest,
135
+ });
136
+ }
137
+ throw new SyncBackendPublicationOutcomeUnknownError(
138
+ `Remote publication outcome is unknown: ${errorMessage(error)}`,
139
+ { cause: error },
140
+ );
141
+ }
142
+ let verifiedObject: RemoteObject<LatestPointer>;
143
+ try {
144
+ verifiedObject = await commitClient.getJson<LatestPointer>(latestPath(this.config));
145
+ } catch (error) {
146
+ throw new SyncBackendPublicationOutcomeUnknownError(
147
+ `Remote snapshot may be active, but publication could not be verified: ${errorMessage(error)}`,
148
+ { cause: error },
149
+ );
150
+ }
151
+ let verified: LatestPointer;
152
+ try {
153
+ verified = requirePointer(verifiedObject.value, this.config.destination.namespace);
154
+ } catch (error) {
155
+ throw new SyncBackendPublicationOutcomeUnknownError(
156
+ `Remote snapshot may be active, but publication verification was malformed: ${errorMessage(error)}`,
157
+ { cause: error },
158
+ );
159
+ }
160
+ if (!samePointer(pointer, verified)) {
161
+ throw new SyncBackendConflictError(
162
+ "Remote latest changed immediately after push. Run /sync status before continuing.",
163
+ {
164
+ phase: "after-commit",
165
+ currentHead: remoteHead(verified, this.identity, verifiedObject.etag),
166
+ candidateMayHaveBeenActive: true,
167
+ },
168
+ );
169
+ }
170
+ if (!strongEtag(verifiedObject.etag)) {
171
+ throw new SyncBackendPublicationOutcomeUnknownError(
172
+ "Remote snapshot is active, but the WebDAV server returned no strong ETag.",
173
+ );
174
+ }
175
+ this.registerChecksum(verified.snapshot, verified.sha256);
176
+ const head = remoteHead(verified, this.identity, verifiedObject.etag);
177
+ const warning = await this.updateHistorySafely(commitClient, pointer);
178
+ return { head, warnings: warning ? [warning] : [] };
179
+ }
180
+
181
+ async listHistory(signal?: AbortSignal): Promise<RemoteHistoryEntry[]> {
182
+ const object = await new WebDavClient(this.config, signal).getJson<{
183
+ version: number;
184
+ snapshots: LatestPointer[];
185
+ }>(historyPath(this.config));
186
+ throwIfAborted(signal);
187
+ if (object.missing) return [];
188
+ const pointers = requireHistory(object.value, this.config.destination.namespace);
189
+ for (const pointer of pointers) this.registerChecksum(pointer.snapshot, pointer.sha256);
190
+ return pointers.map(remoteHistoryEntry);
191
+ }
192
+
193
+ async diagnose(signal?: AbortSignal): Promise<BackendDiagnostic[]> {
194
+ const diagnostics: BackendDiagnostic[] = [
195
+ {
196
+ key: "webdav-url",
197
+ level: "info",
198
+ message: `webdav URL/TLS/auth: configured (${webDavStorageLocation(this.config)})`,
199
+ },
200
+ ];
201
+ try {
202
+ await this.runCapabilityProbe(signal);
203
+ diagnostics.push(
204
+ { key: "webdav-collection", level: "info", message: "webdav collection read/write: ok" },
205
+ {
206
+ key: "webdav-conditional",
207
+ level: "info",
208
+ message: "webdav conditional publication: atomic-conditional (verified)",
209
+ },
210
+ { key: "webdav-cleanup", level: "info", message: "webdav probe cleanup: ok" },
211
+ );
212
+ } catch (error) {
213
+ this.capabilityCheck = undefined;
214
+ this.conditionalVerified = false;
215
+ if (error instanceof Error && error.name === "AbortError") throw error;
216
+ diagnostics.push({
217
+ key: "webdav-probe",
218
+ level: "error",
219
+ message: `webdav publication is read-only until diagnostics pass: ${errorMessage(error)}`,
220
+ });
221
+ return diagnostics;
222
+ }
223
+ try {
224
+ diagnostics.push({
225
+ key: "webdav-history",
226
+ level: "info",
227
+ message: await this.reconcileActiveHistory(signal),
228
+ });
229
+ } catch (error) {
230
+ if (error instanceof Error && error.name === "AbortError") throw error;
231
+ diagnostics.push({
232
+ key: "webdav-history",
233
+ level: "error",
234
+ message: `webdav history repair failed: ${errorMessage(error)}`,
235
+ });
236
+ }
237
+ return diagnostics;
238
+ }
239
+
240
+ private ensureAtomicConditions(signal?: AbortSignal) {
241
+ if (this.capabilityCheck) return this.capabilityCheck;
242
+ this.conditionalVerified = false;
243
+ const check = this.runCapabilityProbe(signal).finally(() => {
244
+ if (this.capabilityCheck === check) this.capabilityCheck = undefined;
245
+ });
246
+ this.capabilityCheck = check;
247
+ return check;
248
+ }
249
+
250
+ private async runCapabilityProbe(signal?: AbortSignal) {
251
+ throwIfAborted(signal);
252
+ const probeCollection = `${rootPath(this.config)}/.pi-sync-probes/${randomUUID()}`;
253
+ const probe = `${probeCollection}/conditional.txt`;
254
+ const client = new WebDavClient(this.config, signal);
255
+ let created = false;
256
+ let operationError: unknown;
257
+ try {
258
+ created = true;
259
+ await client.ensureCollection(probeCollection);
260
+ await client.listCollection(probeCollection);
261
+ await client.putBuffer(probe, Buffer.from("first"), "text/plain", { ifAbsent: true });
262
+ const read = await client.getBuffer(probe);
263
+ const etag = strongEtag(read.etag);
264
+ if (!read.value || !etag) {
265
+ throw new Error("WebDAV server did not return a strong ETag for the capability probe.");
266
+ }
267
+ await expectPrecondition(
268
+ client.putBuffer(probe, Buffer.from("replace"), "text/plain", { ifAbsent: true }),
269
+ "If-None-Match",
270
+ );
271
+ await expectPrecondition(
272
+ client.putBuffer(probe, Buffer.from("replace"), "text/plain", {
273
+ ifMatch: '"pi-sync-deliberately-stale"',
274
+ }),
275
+ "If-Match",
276
+ );
277
+ const unchanged = await client.getBuffer(probe);
278
+ if (!unchanged.value?.equals(Buffer.from("first"))) {
279
+ throw new Error("WebDAV server changed a probe despite a failed precondition.");
280
+ }
281
+ await client.putBuffer(probe, Buffer.from("second"), "text/plain", { ifMatch: etag });
282
+ const changed = await client.getBuffer(probe);
283
+ const changedEtag = strongEtag(changed.etag);
284
+ if (!changed.value?.equals(Buffer.from("second")) || !changedEtag || changedEtag === etag) {
285
+ throw new Error(
286
+ "WebDAV server did not rotate its strong ETag after changing the capability probe.",
287
+ );
288
+ }
289
+ } catch (error) {
290
+ operationError = error;
291
+ }
292
+ if (created) {
293
+ try {
294
+ await new WebDavClient(this.config, undefined).delete(probeCollection);
295
+ } catch (cleanupError) {
296
+ const operationDetail = operationError
297
+ ? `WebDAV probe failed: ${errorMessage(operationError)}; `
298
+ : "";
299
+ throw new Error(
300
+ `${operationDetail}probe cleanup also failed; remove ${probeCollection}: ${errorMessage(cleanupError)}`,
301
+ { cause: operationError ?? cleanupError },
302
+ );
303
+ }
304
+ }
305
+ if (operationError) throw operationError;
306
+ this.conditionalVerified = true;
307
+ }
308
+
309
+ private async resolveChecksum(reference: string, signal?: AbortSignal) {
310
+ await this.readHead(signal);
311
+ if (this.checksums.has(reference)) return this.checksums.get(reference);
312
+ await this.listHistory(signal);
313
+ return this.checksums.get(reference);
314
+ }
315
+
316
+ private registerChecksum(reference: string, checksum: string) {
317
+ const known = this.checksums.get(reference);
318
+ if (known && known !== checksum) {
319
+ throw new Error("Remote snapshot reference was rebound to a different checksum.");
320
+ }
321
+ this.checksums.set(reference, checksum);
322
+ }
323
+
324
+ private async readHeadAfterCommit(client: WebDavClient) {
325
+ const object = await client.getJson<LatestPointer>(latestPath(this.config));
326
+ if (object.missing) return undefined;
327
+ return remoteHead(
328
+ requirePointer(object.value, this.config.destination.namespace),
329
+ this.identity,
330
+ object.etag,
331
+ );
332
+ }
333
+
334
+ private async reconcileActiveHistory(signal?: AbortSignal) {
335
+ const client = new WebDavClient(this.config, signal);
336
+ const object = await client.getJson<LatestPointer>(latestPath(this.config));
337
+ throwIfAborted(signal);
338
+ if (object.missing) return "webdav history: no active snapshot";
339
+ const pointer = requirePointer(object.value, this.config.destination.namespace);
340
+ this.registerChecksum(pointer.snapshot, pointer.sha256);
341
+ const repaired = await this.ensureHistoryPointer(client, pointer);
342
+ return repaired
343
+ ? "webdav history: repaired active snapshot entry"
344
+ : "webdav history: active snapshot entry present";
345
+ }
346
+
347
+ private async ensureHistoryPointer(client: WebDavClient, pointer: LatestPointer) {
348
+ const object = await client.getJson<{ version: number; snapshots: LatestPointer[] }>(
349
+ historyPath(this.config),
350
+ );
351
+ const snapshots = object.missing
352
+ ? []
353
+ : requireHistory(object.value, this.config.destination.namespace);
354
+ const existing = snapshots.find((entry) => entry.snapshot === pointer.snapshot);
355
+ if (existing) {
356
+ if (!samePointer(existing, pointer)) {
357
+ throw new Error("Remote history rebound an immutable snapshot reference.");
358
+ }
359
+ return false;
360
+ }
361
+ const next = [...snapshots, pointer].slice(-100);
362
+ const condition = object.missing
363
+ ? { ifAbsent: true }
364
+ : { ifMatch: requireStrongEtag(object.etag, "history") };
365
+ await client.putJson(
366
+ historyPath(this.config),
367
+ { version: VERSION, snapshots: next },
368
+ condition,
369
+ );
370
+ return true;
371
+ }
372
+
373
+ private async updateHistorySafely(client: WebDavClient, pointer: LatestPointer) {
374
+ try {
375
+ await this.ensureHistoryPointer(client, pointer);
376
+ return undefined;
377
+ } catch (error) {
378
+ return `Remote snapshot is active, but history could not be updated: ${errorMessage(error)}. Run /sync doctor before relying on history.`;
379
+ }
380
+ }
381
+ }
382
+
383
+ export function rootPath(config: ResolvedWebDavBackend) {
384
+ return config.destination.path;
385
+ }
386
+
387
+ export function latestPath(config: ResolvedWebDavBackend) {
388
+ return joinRemote(rootPath(config), "latest.json");
389
+ }
390
+
391
+ export function historyPath(config: ResolvedWebDavBackend) {
392
+ return joinRemote(rootPath(config), "history.json");
393
+ }
394
+
395
+ export function snapshotsPath(config: ResolvedWebDavBackend) {
396
+ return joinRemote(rootPath(config), "snapshots");
397
+ }
398
+
399
+ export function snapshotPath(config: ResolvedWebDavBackend, reference: string) {
400
+ requireSnapshotReference(reference);
401
+ return joinRemote(snapshotsPath(config), `${reference}.json.gz`);
402
+ }
403
+
404
+ export function webDavBackendIdentity(config: ResolvedWebDavBackend) {
405
+ return `webdav:${sha256(
406
+ Buffer.from(JSON.stringify([secretFreeUrl(config.profile.url), config.destination.path])),
407
+ )}`;
408
+ }
409
+
410
+ function webDavStorageLocation(config: ResolvedWebDavBackend) {
411
+ const url = new URL(secretFreeUrl(config.profile.url));
412
+ return `${url.host} · ${rootPath(config)}`;
413
+ }
414
+
415
+ function pointerFor(
416
+ config: ResolvedWebDavBackend,
417
+ snapshot: Snapshot,
418
+ checksum: string,
419
+ ): LatestPointer {
420
+ return {
421
+ version: VERSION,
422
+ profile: config.destination.namespace,
423
+ snapshot: snapshot.id,
424
+ sha256: checksum,
425
+ createdAt: snapshot.createdAt,
426
+ machine: snapshot.machine,
427
+ syncSessions:
428
+ snapshot.syncSessions === true ||
429
+ snapshot.files.some((file) => file.path.startsWith("sessions/")),
430
+ };
431
+ }
432
+
433
+ function remoteHead(pointer: LatestPointer, identity: string, etag?: string): RemoteHead {
434
+ return {
435
+ snapshotRef: pointer.snapshot,
436
+ snapshotId: pointer.snapshot,
437
+ revision: encodeRevision(identity, etag, pointer),
438
+ createdAt: pointer.createdAt,
439
+ machine: pointer.machine,
440
+ syncSessions: pointer.syncSessions === true,
441
+ };
442
+ }
443
+
444
+ function encodeRevision(identity: string, etag: string | undefined, pointer: LatestPointer) {
445
+ return `webdav-v1:${Buffer.from(JSON.stringify({ identity, etag: etag ?? null, pointer: sha256(Buffer.from(canonicalJson(pointer))) })).toString("base64url")}`;
446
+ }
447
+
448
+ function decodeRevision(value: string, identity: string) {
449
+ try {
450
+ if (!value.startsWith("webdav-v1:")) return undefined;
451
+ const parsed = JSON.parse(Buffer.from(value.slice(10), "base64url").toString("utf8")) as {
452
+ identity?: unknown;
453
+ etag?: unknown;
454
+ };
455
+ if (parsed.identity !== identity || typeof parsed.etag !== "string") return undefined;
456
+ return strongEtag(parsed.etag);
457
+ } catch {
458
+ return undefined;
459
+ }
460
+ }
461
+
462
+ function publicationCondition(
463
+ current: RemoteObject<LatestPointer>,
464
+ expected: ExpectedRemoteHead,
465
+ identity: string,
466
+ ) {
467
+ if (expected.kind === "missing") return { ifAbsent: true };
468
+ const etag = decodeRevision(expected.revision, identity) ?? strongEtag(current.etag);
469
+ if (!etag) throw new SyncBackendConflictError("WebDAV head has no usable strong ETag.");
470
+ return { ifMatch: etag };
471
+ }
472
+
473
+ async function expectPrecondition(operation: Promise<unknown>, header: string) {
474
+ try {
475
+ await operation;
476
+ } catch (error) {
477
+ if (error instanceof WebDavPreconditionError) return;
478
+ throw error;
479
+ }
480
+ throw new Error(`WebDAV server ignored ${header}; publication is read-only for safety.`);
481
+ }
482
+
483
+ function requireStrongEtag(value: string | undefined, resource: string) {
484
+ const etag = strongEtag(value);
485
+ if (!etag) throw new Error(`WebDAV ${resource} has no strong ETag.`);
486
+ return etag;
487
+ }
488
+
489
+ function strongEtag(value: string | undefined) {
490
+ return value && !value.startsWith("W/") && /^"[^"\r\n]+"$/u.test(value) ? value : undefined;
491
+ }
492
+
493
+ function requirePointer(value: LatestPointer | undefined, expectedProfile: string) {
494
+ if (
495
+ !value ||
496
+ value.version !== VERSION ||
497
+ value.profile !== expectedProfile ||
498
+ !isSafeReference(value.snapshot) ||
499
+ !/^[0-9a-f]{64}$/u.test(value.sha256) ||
500
+ !isSafeMetadata(value.createdAt, 64) ||
501
+ !isSafeMetadata(value.machine, 256) ||
502
+ (value.syncSessions !== undefined && typeof value.syncSessions !== "boolean")
503
+ ) {
504
+ throw new Error("Remote latest pointer is malformed.");
505
+ }
506
+ return value;
507
+ }
508
+
509
+ function requireHistory(
510
+ value: { version: number; snapshots: LatestPointer[] } | undefined,
511
+ expectedProfile: string,
512
+ ) {
513
+ if (!value || value.version !== VERSION || !Array.isArray(value.snapshots)) {
514
+ throw new Error("Remote history is malformed.");
515
+ }
516
+ const pointers = value.snapshots.map((item) => requirePointer(item, expectedProfile));
517
+ if (new Set(pointers.map((item) => item.snapshot)).size !== pointers.length) {
518
+ throw new Error("Remote history contains duplicate snapshot references.");
519
+ }
520
+ return pointers;
521
+ }
522
+
523
+ function remoteHistoryEntry(pointer: LatestPointer): RemoteHistoryEntry {
524
+ return {
525
+ snapshotRef: pointer.snapshot,
526
+ snapshotId: pointer.snapshot,
527
+ createdAt: pointer.createdAt,
528
+ machine: pointer.machine,
529
+ syncSessions: pointer.syncSessions === true,
530
+ };
531
+ }
532
+
533
+ function assertSnapshotIdentity(snapshot: Snapshot, namespace: string) {
534
+ if (
535
+ snapshot.version !== VERSION ||
536
+ snapshot.profile !== namespace ||
537
+ !isSafeReference(snapshot.id) ||
538
+ !isSafeMetadata(snapshot.createdAt, 64) ||
539
+ !isSafeMetadata(snapshot.machine, 256) ||
540
+ !Array.isArray(snapshot.files)
541
+ ) {
542
+ throw new Error("Invalid snapshot identity for WebDAV publication.");
543
+ }
544
+ }
545
+
546
+ function validateSnapshotBundle(snapshot: Snapshot) {
547
+ const paths = new Set<string>();
548
+ for (const file of snapshot.files) {
549
+ if (
550
+ !file ||
551
+ !isSafeSnapshotPath(file.path) ||
552
+ paths.has(file.path) ||
553
+ typeof file.contentBase64 !== "string" ||
554
+ typeof file.sha256 !== "string"
555
+ ) {
556
+ throw new Error("Remote snapshot bundle is malformed.");
557
+ }
558
+ const content = Buffer.from(file.contentBase64, "base64");
559
+ if (content.toString("base64") !== file.contentBase64 || sha256(content) !== file.sha256) {
560
+ throw new Error("Remote snapshot bundle is malformed.");
561
+ }
562
+ paths.add(file.path);
563
+ }
564
+ }
565
+
566
+ function isSafeSnapshotPath(value: unknown): value is string {
567
+ if (typeof value !== "string" || !value || value.length > 4096 || value.includes("\\")) {
568
+ return false;
569
+ }
570
+ if (
571
+ [...value].some((character) => {
572
+ const code = character.codePointAt(0) ?? 0;
573
+ return code < 0x20 || (code >= 0x7f && code <= 0x9f);
574
+ })
575
+ ) {
576
+ return false;
577
+ }
578
+ return value.split("/").every((segment) => segment && segment !== "." && segment !== "..");
579
+ }
580
+
581
+ function assertSafeDestination(config: ResolvedWebDavBackend) {
582
+ const url = new URL(config.profile.url);
583
+ if (url.username || url.password || url.search || url.hash)
584
+ throw new Error("Invalid WebDAV URL.");
585
+ for (const value of [config.destination.path, config.destination.namespace]) {
586
+ if (
587
+ !value ||
588
+ value.includes("\\") ||
589
+ [...value].some((character) => {
590
+ const code = character.codePointAt(0) ?? 0;
591
+ return code < 0x20 || (code >= 0x7f && code <= 0x9f);
592
+ }) ||
593
+ value.split("/").some((part) => part === "." || part === "..")
594
+ ) {
595
+ throw new Error("Invalid WebDAV storage location.");
596
+ }
597
+ }
598
+ }
599
+
600
+ function isSafeMetadata(value: unknown, maxLength: number): value is string {
601
+ return (
602
+ typeof value === "string" &&
603
+ value.length > 0 &&
604
+ value.length <= maxLength &&
605
+ ![...value].some((character) => {
606
+ const code = character.codePointAt(0) ?? 0;
607
+ return code < 0x20 || (code >= 0x7f && code <= 0x9f);
608
+ })
609
+ );
610
+ }
611
+
612
+ function requireSnapshotReference(reference: string) {
613
+ if (!isSafeReference(reference)) throw new Error("Invalid WebDAV snapshot reference.");
614
+ }
615
+
616
+ function isSafeReference(value: string) {
617
+ return (
618
+ !!value &&
619
+ value.length <= 512 &&
620
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Remote references cannot contain terminal controls.
621
+ !/[\\/\u0000-\u001f\u007f-\u009f]/u.test(value) &&
622
+ value !== "." &&
623
+ value !== ".."
624
+ );
625
+ }
626
+
627
+ function matchesExpected(head: RemoteHead | undefined, expected: ExpectedRemoteHead) {
628
+ return expected.kind === "missing" ? head === undefined : head?.revision === expected.revision;
629
+ }
630
+
631
+ function samePointer(left: LatestPointer, right: LatestPointer) {
632
+ return canonicalJson(left) === canonicalJson(right);
633
+ }
634
+
635
+ function canonicalJson(value: unknown): string {
636
+ if (Array.isArray(value))
637
+ return JSON.stringify(value.map((item) => JSON.parse(canonicalJson(item))));
638
+ if (!value || typeof value !== "object") return JSON.stringify(value);
639
+ return JSON.stringify(
640
+ Object.fromEntries(
641
+ Object.keys(value)
642
+ .sort()
643
+ .map((key) => [key, JSON.parse(canonicalJson((value as Record<string, unknown>)[key]))]),
644
+ ),
645
+ );
646
+ }
647
+
648
+ function joinRemote(...parts: string[]) {
649
+ return parts
650
+ .flatMap((part) => part.split("/"))
651
+ .filter(Boolean)
652
+ .join("/");
653
+ }
654
+
655
+ function secretFreeUrl(value: string) {
656
+ const url = new URL(value);
657
+ url.username = "";
658
+ url.password = "";
659
+ url.search = "";
660
+ url.hash = "";
661
+ return url.toString();
662
+ }
663
+
664
+ function sha256(value: Buffer) {
665
+ return createHash("sha256").update(value).digest("hex");
666
+ }
667
+
668
+ function throwIfAborted(signal?: AbortSignal) {
669
+ if (!signal?.aborted) return;
670
+ throw signal.reason instanceof Error
671
+ ? signal.reason
672
+ : new DOMException("The operation was aborted", "AbortError");
673
+ }
674
+
675
+ function errorMessage(error: unknown) {
676
+ if (error instanceof WebDavHttpError) return error.message;
677
+ return error instanceof Error ? error.message : String(error);
678
+ }