@narumitw/pi-sync 0.31.0 → 0.35.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.
- package/README.md +159 -236
- package/package.json +11 -3
- package/src/backend-factory.ts +20 -0
- package/src/command.ts +39 -39
- package/src/config-errors.ts +7 -0
- package/src/config-file.ts +156 -62
- package/src/config.ts +605 -476
- package/src/file-selection.ts +121 -140
- package/src/git-backend.ts +832 -0
- package/src/git-config.ts +136 -0
- package/src/git-runner.ts +276 -0
- package/src/git-storage.ts +288 -0
- package/src/git-ui.ts +307 -0
- package/src/manager-helpers.ts +64 -0
- package/src/manager-ui.ts +537 -542
- package/src/s3-backend.ts +498 -0
- package/src/s3-client.ts +147 -64
- package/src/s3-credentials-ui.ts +92 -0
- package/src/secret-input.ts +199 -0
- package/src/settings-management.ts +191 -277
- package/src/settings-ui.ts +94 -115
- package/src/setup-switch.ts +150 -0
- package/src/snapshot-apply.ts +13 -7
- package/src/snapshot-codec.ts +48 -0
- package/src/snapshot-transaction.ts +3 -1
- package/src/snapshot.ts +63 -32
- package/src/storage-connections-ui.ts +308 -0
- package/src/sync-backend.ts +97 -0
- package/src/sync-format.ts +31 -33
- package/src/sync-operations.ts +912 -0
- package/src/sync-policy.ts +137 -61
- package/src/sync-setups-ui.ts +177 -0
- package/src/sync-state.ts +48 -48
- package/src/sync.ts +180 -739
- package/src/types.ts +177 -53
- package/src/webdav-backend.ts +678 -0
- package/src/webdav-client.ts +390 -0
- package/src/webdav-config.ts +92 -0
- package/src/webdav-ui.ts +421 -0
- package/src/target-switch.ts +0 -119
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { sessionTokenWarnings } from "./config.js";
|
|
3
|
+
import { encodeKey, posixJoin } from "./paths.js";
|
|
4
|
+
import { S3Client, S3ObjectAlreadyExistsError } from "./s3-client.js";
|
|
5
|
+
import { decodeSnapshot, encodeSnapshot } from "./snapshot-codec.js";
|
|
6
|
+
import {
|
|
7
|
+
type BackendDiagnostic,
|
|
8
|
+
type ExpectedRemoteHead,
|
|
9
|
+
type PublishSnapshotOptions,
|
|
10
|
+
type PublishSnapshotResult,
|
|
11
|
+
type RemoteHead,
|
|
12
|
+
type RemoteHistoryEntry,
|
|
13
|
+
type SyncBackend,
|
|
14
|
+
SyncBackendConflictError,
|
|
15
|
+
SyncBackendPublicationOutcomeUnknownError,
|
|
16
|
+
} from "./sync-backend.js";
|
|
17
|
+
import type { LatestPointer, RemoteObject, ResolvedS3Backend, Snapshot } from "./types.js";
|
|
18
|
+
|
|
19
|
+
const VERSION = 1;
|
|
20
|
+
const POST_COMMIT_TIMEOUT_MS = 30_000;
|
|
21
|
+
|
|
22
|
+
export class S3SyncBackend implements SyncBackend {
|
|
23
|
+
readonly identity: string;
|
|
24
|
+
readonly destination: string;
|
|
25
|
+
readonly capability = "read-check-write-verify" as const;
|
|
26
|
+
private readonly checksums = new Map<string, string>();
|
|
27
|
+
|
|
28
|
+
constructor(
|
|
29
|
+
private readonly config: ResolvedS3Backend,
|
|
30
|
+
private readonly postCommitTimeoutMs = POST_COMMIT_TIMEOUT_MS,
|
|
31
|
+
) {
|
|
32
|
+
assertSafeDestination(config);
|
|
33
|
+
this.identity = s3BackendIdentity(config);
|
|
34
|
+
this.destination = s3Destination(config);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
sameRevision(left: string, right: string) {
|
|
38
|
+
return left === right;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async readHead(signal?: AbortSignal): Promise<RemoteHead | undefined> {
|
|
42
|
+
const object = await new S3Client(this.config, signal).getJson<LatestPointer>(
|
|
43
|
+
latestKey(this.config),
|
|
44
|
+
);
|
|
45
|
+
throwIfAborted(signal);
|
|
46
|
+
if (object.missing) return undefined;
|
|
47
|
+
const pointer = requirePointer(
|
|
48
|
+
object.value,
|
|
49
|
+
"Remote latest pointer is malformed.",
|
|
50
|
+
this.config.destination.namespace,
|
|
51
|
+
);
|
|
52
|
+
this.registerChecksum(pointer.snapshot, pointer.sha256);
|
|
53
|
+
return remoteHead(pointer, this.identity, object.etag);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async readSnapshot(reference: string, signal?: AbortSignal): Promise<Snapshot> {
|
|
57
|
+
const expectedChecksum =
|
|
58
|
+
this.checksums.get(reference) ?? (await this.resolveChecksum(reference, signal));
|
|
59
|
+
const object = await new S3Client(this.config, signal).getBuffer(
|
|
60
|
+
snapshotKey(this.config, reference),
|
|
61
|
+
);
|
|
62
|
+
throwIfAborted(signal);
|
|
63
|
+
if (!object.value) throw new Error(`Snapshot not found: ${reference}`);
|
|
64
|
+
if (expectedChecksum && sha256(object.value) !== expectedChecksum) {
|
|
65
|
+
throw new Error("Remote snapshot checksum mismatch.");
|
|
66
|
+
}
|
|
67
|
+
const snapshot = await decodeSnapshot(object.value, { signal });
|
|
68
|
+
if (snapshot.id !== reference || snapshot.profile !== this.config.destination.namespace) {
|
|
69
|
+
throw new Error("Remote snapshot identity mismatch.");
|
|
70
|
+
}
|
|
71
|
+
validateSnapshotBundle(snapshot);
|
|
72
|
+
return snapshot;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async publishSnapshot(
|
|
76
|
+
snapshot: Snapshot,
|
|
77
|
+
expected: ExpectedRemoteHead,
|
|
78
|
+
options: PublishSnapshotOptions = {},
|
|
79
|
+
): Promise<PublishSnapshotResult> {
|
|
80
|
+
throwIfAborted(options.signal);
|
|
81
|
+
assertSnapshotIdentity(snapshot, this.config.destination.namespace);
|
|
82
|
+
const stagedKey = snapshotKey(this.config, snapshot.id);
|
|
83
|
+
const encoded = await encodeSnapshot(snapshot);
|
|
84
|
+
throwIfAborted(options.signal);
|
|
85
|
+
const pointer = pointerFor(this.config, snapshot, sha256(encoded));
|
|
86
|
+
const cancellableClient = new S3Client(this.config, options.signal);
|
|
87
|
+
try {
|
|
88
|
+
await cancellableClient.putBuffer(stagedKey, encoded, "application/gzip", {
|
|
89
|
+
ifAbsent: true,
|
|
90
|
+
});
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (!(error instanceof S3ObjectAlreadyExistsError)) throw error;
|
|
93
|
+
const existing = await cancellableClient.getBuffer(stagedKey);
|
|
94
|
+
if (!existing.value || sha256(existing.value) !== pointer.sha256) {
|
|
95
|
+
throw new SyncBackendConflictError(
|
|
96
|
+
`Immutable snapshot id already exists with different content: ${snapshot.id}`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const currentObject = await cancellableClient.getJson<LatestPointer>(latestKey(this.config));
|
|
101
|
+
throwIfAborted(options.signal);
|
|
102
|
+
let current: RemoteHead | undefined;
|
|
103
|
+
if (!currentObject.missing) {
|
|
104
|
+
const currentPointer = requirePointer(
|
|
105
|
+
currentObject.value,
|
|
106
|
+
"Remote latest pointer is malformed.",
|
|
107
|
+
this.config.destination.namespace,
|
|
108
|
+
);
|
|
109
|
+
this.registerChecksum(currentPointer.snapshot, currentPointer.sha256);
|
|
110
|
+
current = remoteHead(currentPointer, this.identity, currentObject.etag);
|
|
111
|
+
}
|
|
112
|
+
if (!matchesExpected(current, expected)) {
|
|
113
|
+
throw new SyncBackendConflictError(
|
|
114
|
+
"Remote changed while pushing. Run /sync pull first, then retry.",
|
|
115
|
+
{ currentHead: current },
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
throwIfAborted(options.signal);
|
|
119
|
+
options.onCommit?.();
|
|
120
|
+
|
|
121
|
+
// The active-head PUT is the publication boundary. Do not bind it or its
|
|
122
|
+
// verification to a user-cancellation signal after the boundary begins.
|
|
123
|
+
const commitClient = new S3Client(this.config, AbortSignal.timeout(this.postCommitTimeoutMs));
|
|
124
|
+
try {
|
|
125
|
+
await commitClient.putJson(latestKey(this.config), pointer);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
throw new SyncBackendPublicationOutcomeUnknownError(
|
|
128
|
+
`Remote publication outcome is unknown: ${errorMessage(error)}`,
|
|
129
|
+
{ cause: error },
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
let verifiedObject: RemoteObject<LatestPointer>;
|
|
134
|
+
try {
|
|
135
|
+
verifiedObject = await commitClient.getJson<LatestPointer>(latestKey(this.config));
|
|
136
|
+
} catch (error) {
|
|
137
|
+
throw new SyncBackendPublicationOutcomeUnknownError(
|
|
138
|
+
`Remote snapshot may be active, but publication could not be verified: ${errorMessage(error)}`,
|
|
139
|
+
{ cause: error },
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
let verifiedPointer: LatestPointer;
|
|
143
|
+
try {
|
|
144
|
+
verifiedPointer = requirePointer(
|
|
145
|
+
verifiedObject.value,
|
|
146
|
+
"Remote latest pointer is malformed after publication.",
|
|
147
|
+
this.config.destination.namespace,
|
|
148
|
+
);
|
|
149
|
+
} catch (error) {
|
|
150
|
+
throw new SyncBackendPublicationOutcomeUnknownError(
|
|
151
|
+
`Remote snapshot may be active, but publication verification was malformed: ${errorMessage(error)}`,
|
|
152
|
+
{ cause: error },
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
if (!samePointer(verifiedPointer, pointer)) {
|
|
156
|
+
throw new SyncBackendConflictError(
|
|
157
|
+
"Remote latest changed immediately after push. Run /sync status before continuing.",
|
|
158
|
+
{
|
|
159
|
+
phase: "after-commit",
|
|
160
|
+
currentHead: remoteHead(verifiedPointer, this.identity, verifiedObject.etag),
|
|
161
|
+
candidateMayHaveBeenActive: true,
|
|
162
|
+
},
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
this.registerChecksum(verifiedPointer.snapshot, verifiedPointer.sha256);
|
|
166
|
+
const head = remoteHead(verifiedPointer, this.identity, verifiedObject.etag);
|
|
167
|
+
const warning = await this.updateHistorySafely(commitClient, pointer);
|
|
168
|
+
return { head, warnings: warning ? [warning] : [] };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async listHistory(signal?: AbortSignal): Promise<RemoteHistoryEntry[]> {
|
|
172
|
+
const object = await new S3Client(this.config, signal).getJson<{
|
|
173
|
+
version: number;
|
|
174
|
+
snapshots: LatestPointer[];
|
|
175
|
+
}>(historyKey(this.config));
|
|
176
|
+
throwIfAborted(signal);
|
|
177
|
+
if (object.missing) return [];
|
|
178
|
+
const pointers = requireHistory(object.value, this.config.destination.namespace);
|
|
179
|
+
for (const pointer of pointers) {
|
|
180
|
+
const known = this.checksums.get(pointer.snapshot);
|
|
181
|
+
if (known && known !== pointer.sha256) {
|
|
182
|
+
throw new Error("Remote history conflicts with an already observed snapshot checksum.");
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
for (const pointer of pointers) this.registerChecksum(pointer.snapshot, pointer.sha256);
|
|
186
|
+
return pointers.map(remoteHistoryEntry);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async diagnose(signal?: AbortSignal): Promise<BackendDiagnostic[]> {
|
|
190
|
+
throwIfAborted(signal);
|
|
191
|
+
return [
|
|
192
|
+
{
|
|
193
|
+
key: "s3-config",
|
|
194
|
+
level: "info",
|
|
195
|
+
message: `s3 config: ok (${this.config.destination.bucket}/${storageRoot(this.config)})`,
|
|
196
|
+
},
|
|
197
|
+
...sessionTokenWarnings(this.config.profile).map((message) => ({
|
|
198
|
+
key: "s3-session-token",
|
|
199
|
+
level: "warning" as const,
|
|
200
|
+
message,
|
|
201
|
+
})),
|
|
202
|
+
];
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private async resolveChecksum(reference: string, signal?: AbortSignal) {
|
|
206
|
+
await this.readHead(signal);
|
|
207
|
+
const headChecksum = this.checksums.get(reference);
|
|
208
|
+
if (headChecksum) return headChecksum;
|
|
209
|
+
await this.listHistory(signal);
|
|
210
|
+
return this.checksums.get(reference);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
private registerChecksum(reference: string, checksum: string) {
|
|
214
|
+
const known = this.checksums.get(reference);
|
|
215
|
+
if (known && known !== checksum) {
|
|
216
|
+
throw new Error("Remote snapshot reference was rebound to a different checksum.");
|
|
217
|
+
}
|
|
218
|
+
this.checksums.set(reference, checksum);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
private async updateHistorySafely(client: S3Client, pointer: LatestPointer) {
|
|
222
|
+
try {
|
|
223
|
+
await this.updateHistory(client, pointer);
|
|
224
|
+
return undefined;
|
|
225
|
+
} catch (error) {
|
|
226
|
+
return `Remote snapshot is active, but history could not be updated: ${errorMessage(error)}. Run /sync doctor before relying on history.`;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
private async updateHistory(client: S3Client, pointer: LatestPointer) {
|
|
231
|
+
const object = await client.getJson<{ version: number; snapshots: LatestPointer[] }>(
|
|
232
|
+
historyKey(this.config),
|
|
233
|
+
);
|
|
234
|
+
const snapshots = object.missing
|
|
235
|
+
? []
|
|
236
|
+
: requireHistory(object.value, this.config.destination.namespace);
|
|
237
|
+
const next = [
|
|
238
|
+
...snapshots.filter((snapshot) => snapshot.snapshot !== pointer.snapshot),
|
|
239
|
+
pointer,
|
|
240
|
+
].slice(-100);
|
|
241
|
+
await client.putJson(historyKey(this.config), { version: VERSION, snapshots: next });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export function latestKey(config: ResolvedS3Backend) {
|
|
246
|
+
return posixJoin(storageRoot(config), "latest.json");
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export function historyKey(config: ResolvedS3Backend) {
|
|
250
|
+
return posixJoin(storageRoot(config), "history.json");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function snapshotKey(config: ResolvedS3Backend, id: string) {
|
|
254
|
+
requireSnapshotReference(id);
|
|
255
|
+
return posixJoin(storageRoot(config), "snapshots", `${id}.json.gz`);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function storageRoot(config: ResolvedS3Backend) {
|
|
259
|
+
return config.destination.prefix;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export function pointerFor(
|
|
263
|
+
config: ResolvedS3Backend,
|
|
264
|
+
snapshot: Snapshot,
|
|
265
|
+
checksum: string,
|
|
266
|
+
): LatestPointer {
|
|
267
|
+
return {
|
|
268
|
+
version: VERSION,
|
|
269
|
+
profile: config.destination.namespace,
|
|
270
|
+
snapshot: snapshot.id,
|
|
271
|
+
sha256: checksum,
|
|
272
|
+
createdAt: snapshot.createdAt,
|
|
273
|
+
machine: snapshot.machine,
|
|
274
|
+
syncSessions:
|
|
275
|
+
snapshot.syncSessions === true ||
|
|
276
|
+
snapshot.files.some((file) => file.path.startsWith("sessions/")),
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function s3BackendIdentity(config: ResolvedS3Backend) {
|
|
281
|
+
const destination = JSON.stringify([
|
|
282
|
+
secretFreeEndpoint(config.profile.endpoint),
|
|
283
|
+
trimSlashes(config.destination.bucket),
|
|
284
|
+
trimSlashes(config.destination.prefix),
|
|
285
|
+
]);
|
|
286
|
+
return `s3:${sha256(Buffer.from(destination))}`;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function s3Destination(config: ResolvedS3Backend) {
|
|
290
|
+
let host = secretFreeEndpoint(config.profile.endpoint);
|
|
291
|
+
try {
|
|
292
|
+
host = new URL(host).hostname;
|
|
293
|
+
} catch {
|
|
294
|
+
host = "invalid S3 endpoint";
|
|
295
|
+
}
|
|
296
|
+
return `${host} · ${config.destination.bucket}/${storageRoot(config)}`;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function secretFreeEndpoint(value: string) {
|
|
300
|
+
const normalized = value.trim();
|
|
301
|
+
try {
|
|
302
|
+
const url = new URL(normalized);
|
|
303
|
+
url.username = "";
|
|
304
|
+
url.password = "";
|
|
305
|
+
return url.toString();
|
|
306
|
+
} catch {
|
|
307
|
+
return normalized.replace(/\/\/[^/@\s]+@/u, "//");
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function trimSlashes(value: string) {
|
|
312
|
+
return value.replace(/^\/+|\/+$/g, "");
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function remoteHistoryEntry(pointer: LatestPointer): RemoteHistoryEntry {
|
|
316
|
+
return {
|
|
317
|
+
snapshotRef: pointer.snapshot,
|
|
318
|
+
snapshotId: pointer.snapshot,
|
|
319
|
+
createdAt: pointer.createdAt,
|
|
320
|
+
machine: pointer.machine,
|
|
321
|
+
syncSessions: pointer.syncSessions === true,
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function remoteHead(pointer: LatestPointer, identity: string, etag?: string): RemoteHead {
|
|
326
|
+
return {
|
|
327
|
+
snapshotRef: pointer.snapshot,
|
|
328
|
+
snapshotId: pointer.snapshot,
|
|
329
|
+
revision: `s3:${sha256(Buffer.from(canonicalJson([identity, etag ?? null, pointer])))}`,
|
|
330
|
+
createdAt: pointer.createdAt,
|
|
331
|
+
machine: pointer.machine,
|
|
332
|
+
syncSessions: pointer.syncSessions === true,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function samePointer(left: LatestPointer, right: LatestPointer) {
|
|
337
|
+
return canonicalJson(left) === canonicalJson(right);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function canonicalJson(value: unknown) {
|
|
341
|
+
return JSON.stringify(canonicalValue(value));
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function canonicalValue(value: unknown): unknown {
|
|
345
|
+
if (Array.isArray(value)) return value.map(canonicalValue);
|
|
346
|
+
if (!value || typeof value !== "object") return value;
|
|
347
|
+
return Object.fromEntries(
|
|
348
|
+
Object.keys(value)
|
|
349
|
+
.sort()
|
|
350
|
+
.map((key) => [key, canonicalValue((value as Record<string, unknown>)[key])]),
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function matchesExpected(head: RemoteHead | undefined, expected: ExpectedRemoteHead) {
|
|
355
|
+
if (expected.kind === "missing") return head === undefined;
|
|
356
|
+
return head?.revision === expected.revision;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function requirePointer(
|
|
360
|
+
value: LatestPointer | undefined,
|
|
361
|
+
message: string,
|
|
362
|
+
expectedProfile: string,
|
|
363
|
+
) {
|
|
364
|
+
if (
|
|
365
|
+
!value ||
|
|
366
|
+
value.version !== VERSION ||
|
|
367
|
+
value.profile !== expectedProfile ||
|
|
368
|
+
typeof value.snapshot !== "string" ||
|
|
369
|
+
!isSafeSnapshotReference(value.snapshot) ||
|
|
370
|
+
typeof value.sha256 !== "string" ||
|
|
371
|
+
!/^[0-9a-f]{64}$/.test(value.sha256) ||
|
|
372
|
+
typeof value.createdAt !== "string" ||
|
|
373
|
+
!isSafeMetadata(value.createdAt, 64) ||
|
|
374
|
+
typeof value.machine !== "string" ||
|
|
375
|
+
!isSafeMetadata(value.machine, 256) ||
|
|
376
|
+
(value.syncSessions !== undefined && typeof value.syncSessions !== "boolean")
|
|
377
|
+
) {
|
|
378
|
+
throw new Error(message);
|
|
379
|
+
}
|
|
380
|
+
return value;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function requireHistory(
|
|
384
|
+
value: { version: number; snapshots: LatestPointer[] } | undefined,
|
|
385
|
+
expectedProfile: string,
|
|
386
|
+
) {
|
|
387
|
+
if (!value || value.version !== VERSION || !Array.isArray(value.snapshots)) {
|
|
388
|
+
throw new Error("Remote history is malformed.");
|
|
389
|
+
}
|
|
390
|
+
const pointers = value.snapshots.map((pointer) =>
|
|
391
|
+
requirePointer(pointer, "Remote history entry is malformed.", expectedProfile),
|
|
392
|
+
);
|
|
393
|
+
const references = new Set<string>();
|
|
394
|
+
for (const pointer of pointers) {
|
|
395
|
+
if (references.has(pointer.snapshot)) {
|
|
396
|
+
throw new Error("Remote history contains duplicate snapshot references.");
|
|
397
|
+
}
|
|
398
|
+
references.add(pointer.snapshot);
|
|
399
|
+
}
|
|
400
|
+
return pointers;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function assertSnapshotIdentity(snapshot: Snapshot, expectedProfile: string) {
|
|
404
|
+
if (
|
|
405
|
+
snapshot.version !== VERSION ||
|
|
406
|
+
snapshot.profile !== expectedProfile ||
|
|
407
|
+
!isSafeSnapshotReference(snapshot.id) ||
|
|
408
|
+
!isSafeMetadata(snapshot.createdAt, 64) ||
|
|
409
|
+
!isSafeMetadata(snapshot.machine, 256) ||
|
|
410
|
+
!Array.isArray(snapshot.files)
|
|
411
|
+
) {
|
|
412
|
+
throw new Error("Invalid snapshot identity for S3 publication.");
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function validateSnapshotBundle(snapshot: Snapshot) {
|
|
417
|
+
const paths = new Set<string>();
|
|
418
|
+
for (const file of snapshot.files) {
|
|
419
|
+
if (
|
|
420
|
+
!file ||
|
|
421
|
+
typeof file.path !== "string" ||
|
|
422
|
+
typeof file.contentBase64 !== "string" ||
|
|
423
|
+
typeof file.sha256 !== "string" ||
|
|
424
|
+
!/^[0-9a-f]{64}$/.test(file.sha256) ||
|
|
425
|
+
paths.has(file.path)
|
|
426
|
+
) {
|
|
427
|
+
throw new Error("Remote snapshot bundle is malformed.");
|
|
428
|
+
}
|
|
429
|
+
const content = Buffer.from(file.contentBase64, "base64");
|
|
430
|
+
if (content.toString("base64") !== file.contentBase64 || sha256(content) !== file.sha256) {
|
|
431
|
+
throw new Error("Remote snapshot file checksum mismatch.");
|
|
432
|
+
}
|
|
433
|
+
paths.add(file.path);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function assertSafeDestination(config: ResolvedS3Backend) {
|
|
438
|
+
for (const [label, value, allowEmpty] of [
|
|
439
|
+
["bucket", config.destination.bucket, false],
|
|
440
|
+
["prefix", config.destination.prefix, true],
|
|
441
|
+
["namespace", config.destination.namespace, false],
|
|
442
|
+
] as const) {
|
|
443
|
+
if (
|
|
444
|
+
(!allowEmpty && value.length === 0) ||
|
|
445
|
+
value.includes("\\") ||
|
|
446
|
+
hasControlCharacter(value) ||
|
|
447
|
+
value.split("/").some((segment) => segment === "." || segment === "..")
|
|
448
|
+
) {
|
|
449
|
+
throw new Error(`Invalid S3 storage location ${label}.`);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function requireSnapshotReference(reference: string) {
|
|
455
|
+
if (!isSafeSnapshotReference(reference)) {
|
|
456
|
+
throw new Error("Invalid S3 snapshot reference.");
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function isSafeSnapshotReference(reference: string) {
|
|
461
|
+
return (
|
|
462
|
+
reference.length > 0 &&
|
|
463
|
+
reference.length <= 512 &&
|
|
464
|
+
reference !== "." &&
|
|
465
|
+
reference !== ".." &&
|
|
466
|
+
!reference.includes("/") &&
|
|
467
|
+
!reference.includes("\\") &&
|
|
468
|
+
!hasControlCharacter(reference)
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function isSafeMetadata(value: string, maxLength: number) {
|
|
473
|
+
return value.length > 0 && value.length <= maxLength && !hasControlCharacter(value);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function hasControlCharacter(value: string) {
|
|
477
|
+
return [...value].some((character) => {
|
|
478
|
+
const code = character.codePointAt(0) ?? 0;
|
|
479
|
+
return code < 0x20 || code === 0x7f;
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function throwIfAborted(signal?: AbortSignal) {
|
|
484
|
+
if (!signal?.aborted) return;
|
|
485
|
+
throw signal.reason instanceof Error
|
|
486
|
+
? signal.reason
|
|
487
|
+
: new DOMException("The operation was aborted", "AbortError");
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function sha256(value: Buffer) {
|
|
491
|
+
return createHash("sha256").update(value).digest("hex");
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function errorMessage(error: unknown) {
|
|
495
|
+
return error instanceof Error ? error.message : String(error);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
export { encodeKey };
|