Repository navigation
Expand file tree
/
Copy pathsync-easycloud.js
More file actions
1861 lines (1855 loc) · 71.1 KB
/
Copy pathsync-easycloud.js
File metadata and controls
1861 lines (1855 loc) · 71.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// Generated from src/modules/sync-easycloud.ts; do not edit by hand.
// Run `node scripts/generate-ts-runtime-modules.mjs` or `npm run build:bg`.
// ============================================================================
const EasyCloudSync = (() => {
const module = { exports: {} };
const exports = module.exports;
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/modules/sync-easycloud.ts
var sync_easycloud_exports = {};
__export(sync_easycloud_exports, {
EasyCloudSync: () => EasyCloudSync
});
module.exports = __toCommonJS(sync_easycloud_exports);
// src/modules/sync-crypto.ts
var DEFAULT_KDF_ITERATIONS = 21e4;
var MAX_KDF_ITERATIONS = 1e7;
var SALT_BYTES = 16;
var IV_BYTES = 12;
var TEXT_ENCODER = new TextEncoder();
var TEXT_DECODER = new TextDecoder();
function getCryptoApi() {
const cryptoApi = globalThis.crypto;
if (!cryptoApi?.subtle) {
throw new Error("Web Crypto is not available for sync encryption");
}
return cryptoApi;
}
function bytesToBase64(bytes) {
let binary = "";
const chunkSize = 32768;
for (let i = 0; i < bytes.length; i += chunkSize) {
const chunk = bytes.subarray(i, i + chunkSize);
binary += String.fromCharCode(...chunk);
}
if (typeof btoa === "function") return btoa(binary);
const bufferCtor = globalThis.Buffer;
if (bufferCtor) return bufferCtor.from(bytes).toString("base64");
throw new Error("Base64 encoding is not available for sync encryption");
}
function base64ToBytes(value) {
if (typeof atob === "function") {
const binary = atob(value);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
const bufferCtor = globalThis.Buffer;
if (bufferCtor) return new Uint8Array(bufferCtor.from(value, "base64"));
throw new Error("Base64 decoding is not available for sync encryption");
}
function bytesToArrayBuffer(bytes) {
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
}
function randomBytes(length) {
const bytes = new Uint8Array(length);
getCryptoApi().getRandomValues(bytes);
return bytes;
}
function resolveIterations(settings) {
const configured = settings.syncEncryptionKdfIterations;
const candidate = Number.isFinite(configured) && configured && configured > 0 ? Math.floor(configured) : DEFAULT_KDF_ITERATIONS;
return Math.min(MAX_KDF_ITERATIONS, Math.max(1, candidate));
}
function getPassphrase(settings) {
const passphrase = settings.syncEncryptionPassphrase;
if (typeof passphrase !== "string" || passphrase.length === 0) {
throw new Error("Sync encryption passphrase is required");
}
return passphrase;
}
function isObject(value) {
return !!value && typeof value === "object" && !Array.isArray(value);
}
function normalizePlainSyncEnvelope(envelope) {
const version = typeof envelope.version === "number" || typeof envelope.version === "string" && envelope.version.trim() ? envelope.version : 1;
return {
...envelope,
version,
timestamp: typeof envelope.timestamp === "number" ? envelope.timestamp : Date.now(),
scripts: Array.isArray(envelope.scripts) ? envelope.scripts : [],
tombstones: isObject(envelope.tombstones) ? envelope.tombstones : {}
};
}
function isEncryptedSyncEnvelope(value) {
return isObject(value) && (value.encrypted === true || value.version === 2) && typeof value.ciphertext === "string" && typeof value.salt === "string" && typeof value.iv === "string";
}
function isEncryptionEnabled(settings) {
return settings.syncEncryptionEnabled === true;
}
async function deriveAesGcmKey(passphrase, salt, iterations, usages) {
const cryptoApi = getCryptoApi();
const passphraseBytes = TEXT_ENCODER.encode(passphrase);
const material = await cryptoApi.subtle.importKey(
"raw",
bytesToArrayBuffer(passphraseBytes),
"PBKDF2",
false,
["deriveKey"]
);
return cryptoApi.subtle.deriveKey(
{
name: "PBKDF2",
salt: bytesToArrayBuffer(salt),
iterations,
hash: "SHA-256"
},
material,
{ name: "AES-GCM", length: 256 },
false,
usages
);
}
async function encryptSyncEnvelope(envelope, settings) {
const salt = randomBytes(SALT_BYTES);
const iv = randomBytes(IV_BYTES);
const iterations = resolveIterations(settings);
const key = await deriveAesGcmKey(getPassphrase(settings), salt, iterations, ["encrypt"]);
const plaintext = TEXT_ENCODER.encode(JSON.stringify(normalizePlainSyncEnvelope(envelope)));
const ciphertext = new Uint8Array(await getCryptoApi().subtle.encrypt(
{ name: "AES-GCM", iv: bytesToArrayBuffer(iv) },
key,
bytesToArrayBuffer(plaintext)
));
return {
version: 2,
encrypted: true,
format: "scriptvault-sync-e2ee",
algorithm: "AES-256-GCM",
kdf: "PBKDF2-SHA-256",
iterations,
salt: bytesToBase64(salt),
iv: bytesToBase64(iv),
ciphertext: bytesToBase64(ciphertext),
timestamp: Date.now()
};
}
async function decryptSyncEnvelope(envelope, settings) {
if (!envelope) return null;
if (!isEncryptedSyncEnvelope(envelope)) {
if (isEncryptionEnabled(settings) && settings.syncEncryptionEstablished === true) {
throw new Error("Sync encryption is enabled but the remote data is not encrypted. Refusing to load possibly-tampered plaintext sync data.");
}
return normalizePlainSyncEnvelope(envelope);
}
const salt = base64ToBytes(envelope.salt);
const iv = base64ToBytes(envelope.iv);
const declaredIterations = envelope.iterations || DEFAULT_KDF_ITERATIONS;
if (!Number.isFinite(declaredIterations) || declaredIterations <= 0 || declaredIterations > MAX_KDF_ITERATIONS) {
throw new Error("Sync envelope declares an out-of-range KDF iteration count.");
}
const key = await deriveAesGcmKey(
getPassphrase(settings),
salt,
declaredIterations,
["decrypt"]
);
try {
const plaintext = await getCryptoApi().subtle.decrypt(
{ name: "AES-GCM", iv: bytesToArrayBuffer(iv) },
key,
bytesToArrayBuffer(base64ToBytes(envelope.ciphertext))
);
const parsed = JSON.parse(TEXT_DECODER.decode(plaintext));
if (!isObject(parsed)) {
throw new Error("Decrypted sync payload is not an object");
}
return normalizePlainSyncEnvelope(parsed);
} catch (_e) {
throw new Error("Unable to decrypt sync data. Check the sync encryption passphrase.");
}
}
async function prepareSyncEnvelopeForUpload(envelope, settings) {
const normalized = normalizePlainSyncEnvelope(envelope);
return isEncryptionEnabled(settings) ? encryptSyncEnvelope(normalized, settings) : normalized;
}
var SyncCrypto = {
DEFAULT_KDF_ITERATIONS,
MAX_KDF_ITERATIONS,
resolveIterations,
isEncryptedSyncEnvelope,
isEncryptionEnabled,
encryptSyncEnvelope,
decryptSyncEnvelope,
prepareSyncEnvelopeForUpload
};
// src/background/local-libraries.ts
var MAX_LOCAL_LIBRARIES = 8;
var MAX_LOCAL_LIBRARY_BYTES = 512 * 1024;
var SHA256_HEX = /^[a-f0-9]{64}$/;
var LOCAL_LIBRARY_ID = /^local-library-[a-z0-9_-]{8,96}$/;
function byteLength(value) {
return new TextEncoder().encode(value).length;
}
function safeLibraryName(value) {
const text = typeof value === "string" ? value.trim() : "";
const leaf = text.split(/[\\/]/).filter(Boolean).pop() || "local-library.js";
return leaf.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 160) || "local-library.js";
}
function safeLibraryId(value, fallbackSeed = "") {
const candidate = typeof value === "string" ? value.trim().toLowerCase() : "";
if (LOCAL_LIBRARY_ID.test(candidate)) return candidate;
const seed = fallbackSeed.replace(/[^a-z0-9_-]/gi, "-").replace(/^-+|-+$/g, "").slice(0, 56) || "snapshot";
return `local-library-${seed}-${Date.now().toString(36)}`;
}
async function sha256Hex(value) {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
}
async function createLocalLibrarySnapshot(input) {
const code = typeof input?.code === "string" ? input.code : "";
const name = safeLibraryName(input?.name);
if (!code.trim()) return { ok: false, error: "Choose a non-empty JavaScript library." };
if (code.includes("\0")) return { ok: false, error: "Local libraries cannot contain NUL characters." };
const bytes = byteLength(code);
if (bytes > MAX_LOCAL_LIBRARY_BYTES) {
return { ok: false, error: `Local library is too large. Maximum is ${MAX_LOCAL_LIBRARY_BYTES / 1024} KB.` };
}
const sha256 = await sha256Hex(code);
return {
ok: true,
snapshot: {
id: safeLibraryId(input?.id, name.replace(/\.m?js$/i, "")),
name,
code,
sha256,
bytes,
reviewedAt: Number.isFinite(Number(input?.reviewedAt)) && Number(input.reviewedAt) > 0 ? Number(input.reviewedAt) : Date.now()
}
};
}
function normalizeLocalLibrarySnapshots(input) {
const values = Array.isArray(input) ? input.slice(0, MAX_LOCAL_LIBRARIES) : [];
const normalized = [];
const seenIds = /* @__PURE__ */ new Set();
for (const value of values) {
if (!value || typeof value !== "object") continue;
const candidate = value;
const id = typeof candidate.id === "string" ? candidate.id.trim().toLowerCase() : "";
const code = typeof candidate.code === "string" ? candidate.code : "";
const sha256 = typeof candidate.sha256 === "string" ? candidate.sha256.trim().toLowerCase() : "";
const bytes = byteLength(code);
if (!LOCAL_LIBRARY_ID.test(id) || seenIds.has(id) || !code.trim() || code.includes("\0")) continue;
if (!SHA256_HEX.test(sha256) || bytes > MAX_LOCAL_LIBRARY_BYTES) continue;
seenIds.add(id);
normalized.push({
id,
name: safeLibraryName(candidate.name),
code,
sha256,
bytes,
reviewedAt: Number.isFinite(Number(candidate.reviewedAt)) && Number(candidate.reviewedAt) > 0 ? Number(candidate.reviewedAt) : 0
});
}
return normalized;
}
async function verifyLocalLibrarySnapshots(input) {
const normalized = normalizeLocalLibrarySnapshots(input);
const verified = [];
for (const snapshot of normalized) {
try {
if (await sha256Hex(snapshot.code) === snapshot.sha256) verified.push(snapshot);
} catch (_) {
}
}
return verified;
}
function getLocalLibraryRequireScripts(settings) {
const candidate = settings && typeof settings === "object" ? settings.localLibraries : void 0;
return normalizeLocalLibrarySnapshots(candidate).map((snapshot) => ({
url: `local-library://${encodeURIComponent(snapshot.name)}#sha256=${snapshot.sha256}`,
code: snapshot.code
}));
}
function getLocalLibraryReviewSignals(codeInput) {
const code = typeof codeInput === "string" ? codeInput : "";
const signals = [];
if (/\beval\s*\(|\bnew\s+Function\s*\(/.test(code)) signals.push("dynamic code execution");
if (/\b(?:fetch|XMLHttpRequest|WebSocket|GM_xmlhttpRequest)\b/.test(code)) signals.push("network access");
if (/\b(?:document\.cookie|localStorage|indexedDB)\b/.test(code)) signals.push("site or browser storage");
if (/\.innerHTML\s*=|document\.write\s*\(/.test(code)) signals.push("HTML injection");
return signals;
}
var LocalLibraries = Object.freeze({
MAX_LOCAL_LIBRARIES,
MAX_LOCAL_LIBRARY_BYTES,
createLocalLibrarySnapshot,
getLocalLibraryRequireScripts,
getLocalLibraryReviewSignals,
normalizeLocalLibrarySnapshots,
verifyLocalLibrarySnapshots
});
// src/background/gm-value-sync.ts
var GM_VALUE_SYNC_SCHEMA = "scriptvault-gm-value-sync/v1";
var GM_VALUE_SYNC_MAX_SCRIPT_BYTES = 64 * 1024;
var GM_VALUE_SYNC_MAX_KEYS = 128;
var GM_VALUE_SYNC_MAX_KEY_BYTES = 256;
var GM_VALUE_SYNC_MAX_CONFLICTS_PER_KEY = 4;
var GM_VALUE_SYNC_MAX_CONFLICT_KEYS = 128;
var GM_VALUE_SYNC_CONFLICT_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
function byteLength2(value) {
return new TextEncoder().encode(JSON.stringify(value)).length;
}
function cloneJsonValue(value) {
const json = JSON.stringify(value);
if (json === void 0) return void 0;
return JSON.parse(json);
}
function setRecordKey(record, key, value) {
Object.defineProperty(record, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
}
function normalizeTimestamp(value) {
const timestamp = Number(value);
if (!Number.isFinite(timestamp) || timestamp <= 0) return void 0;
return Math.floor(timestamp);
}
function normalizeDeviceId(value) {
if (typeof value !== "string") return void 0;
const deviceId = value.trim();
return deviceId && deviceId.length <= 128 ? deviceId : void 0;
}
function normalizeGmValueClock(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
const ts = Number(value.ts);
const counter = Number(value.counter);
const deviceId = normalizeDeviceId(value.deviceId);
if (!Number.isFinite(ts) || ts < 0 || !Number.isFinite(counter) || counter < 0 || !deviceId) {
return void 0;
}
return { ts: Math.floor(ts), counter: Math.floor(counter), deviceId };
}
function compareGmValueClocks(left, right) {
if (!left && !right) return 0;
if (!left) return -1;
if (!right) return 1;
if (left.ts !== right.ts) return left.ts > right.ts ? 1 : -1;
if (left.counter !== right.counter) return left.counter > right.counter ? 1 : -1;
return left.deviceId === right.deviceId ? 0 : left.deviceId > right.deviceId ? 1 : -1;
}
function normalizeGmValueSyncPolicy(value) {
return value === "prefer-local" || value === "prefer-remote" ? value : "hlc";
}
function normalizeKeyMetadataEntry(value, options = {}) {
const record = value && typeof value === "object" && !Array.isArray(value) ? value : null;
const timestamp = normalizeTimestamp(record?.updatedAt ?? value) ?? normalizeTimestamp(options.fallbackTimestamp);
const clock = normalizeGmValueClock(record?.clock) || (timestamp && normalizeDeviceId(options.deviceId) ? { ts: timestamp, counter: 0, deviceId: normalizeDeviceId(options.deviceId) } : void 0);
if (!timestamp && !clock) return void 0;
return {
...timestamp ? { updatedAt: timestamp } : {},
...clock ? { clock } : {}
};
}
function cloneClock(clock) {
return { ts: clock.ts, counter: clock.counter, deviceId: clock.deviceId };
}
function valueEquals(left, right) {
try {
return JSON.stringify(left) === JSON.stringify(right);
} catch (_) {
return false;
}
}
function normalizeConflictEntry(value, now) {
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
const clock = normalizeGmValueClock(value.clock);
const retainedAt = normalizeTimestamp(value.retainedAt) ?? now;
if (!clock) return void 0;
let cloned;
try {
cloned = cloneJsonValue(value.value);
} catch (_) {
return void 0;
}
if (cloned === void 0) return void 0;
return { value: cloned, clock, retainedAt };
}
function normalizeGmValueSyncConflicts(value, options = {}) {
const now = normalizeTimestamp(options.now) ?? Date.now();
const maxKeys = Math.max(1, Math.floor(options.maxKeys ?? GM_VALUE_SYNC_MAX_CONFLICT_KEYS));
const maxPerKey = Math.max(1, Math.floor(options.maxPerKey ?? GM_VALUE_SYNC_MAX_CONFLICTS_PER_KEY));
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
const result = {};
for (const key of Object.keys(value).sort((a, b) => a.localeCompare(b))) {
if (Object.keys(result).length >= maxKeys) break;
const rawEntries = value[key];
if (!Array.isArray(rawEntries)) continue;
const entries = [];
for (const rawEntry of rawEntries) {
const entry = normalizeConflictEntry(rawEntry, now);
if (!entry || entry.retainedAt < now - GM_VALUE_SYNC_CONFLICT_RETENTION_MS) continue;
const duplicate = entries.some((candidate) => compareGmValueClocks(candidate.clock, entry.clock) === 0 && valueEquals(candidate.value, entry.value));
if (duplicate) continue;
entries.push(entry);
}
entries.sort((a, b) => {
const clockOrder = compareGmValueClocks(b.clock, a.clock);
return clockOrder || b.retainedAt - a.retainedAt;
});
if (entries.length > 0) setRecordKey(result, key, entries.slice(0, maxPerKey));
}
return result;
}
function candidateForKey(source, values, metadata, key) {
if (!Object.prototype.hasOwnProperty.call(values, key)) return void 0;
const rawMetadata = metadata && Object.prototype.hasOwnProperty.call(metadata, key) ? metadata[key] : void 0;
const normalizedMetadata = normalizeKeyMetadataEntry(rawMetadata);
const clock = normalizedMetadata?.clock || (normalizedMetadata?.updatedAt ? { ts: normalizedMetadata.updatedAt, counter: 0, deviceId: source } : void 0);
const candidateMetadata = normalizedMetadata || clock ? {
...normalizedMetadata || {},
...clock && !normalizedMetadata?.clock ? { clock } : {}
} : void 0;
return {
value: cloneJsonValue(values[key]),
...candidateMetadata ? { metadata: candidateMetadata } : {},
...clock ? { clock } : {},
source
};
}
function chooseCandidate(local, remote, policy) {
if (policy === "prefer-local") return local;
if (policy === "prefer-remote") return remote;
return compareGmValueClocks(local.clock, remote.clock) >= 0 ? local : remote;
}
function addConflictEntry(conflicts, key, candidate, now) {
if (!candidate.clock) return;
const existing = conflicts[key] || [];
const entry = {
value: cloneJsonValue(candidate.value),
clock: cloneClock(candidate.clock),
retainedAt: now
};
if (!existing.some((item) => compareGmValueClocks(item.clock, entry.clock) === 0 && valueEquals(item.value, entry.value))) {
setRecordKey(conflicts, key, [...existing, entry]);
}
}
function mergeGmValueSyncValues(localValues, localMetadata, remoteValues, remoteMetadata, options = {}) {
const local = localValues && typeof localValues === "object" && !Array.isArray(localValues) ? localValues : {};
const remote = remoteValues && typeof remoteValues === "object" && !Array.isArray(remoteValues) ? remoteValues : {};
const localMeta = localMetadata && typeof localMetadata === "object" && !Array.isArray(localMetadata) ? localMetadata : {};
const remoteMeta = remoteMetadata && typeof remoteMetadata === "object" && !Array.isArray(remoteMetadata) ? remoteMetadata : {};
const policy = normalizeGmValueSyncPolicy(options.policy);
const now = normalizeTimestamp(options.now) ?? Date.now();
const conflicts = normalizeGmValueSyncConflicts(options.localConflicts, { now });
const remoteConflicts = normalizeGmValueSyncConflicts(options.remoteConflicts, { now });
for (const [key, entries] of Object.entries(remoteConflicts)) {
const current = conflicts[key] || [];
setRecordKey(conflicts, key, [...current, ...entries]);
}
const values = {};
const keyMetadata = {};
const changedKeys = [];
const metadataChangedKeys = [];
let conflictCount = 0;
const keys = [.../* @__PURE__ */ new Set([...Object.keys(local), ...Object.keys(remote)])].sort((a, b) => a.localeCompare(b));
for (const key of keys) {
const localCandidate = candidateForKey("local", local, localMeta, key);
const remoteCandidate = candidateForKey("remote", remote, remoteMeta, key);
const winner = !localCandidate ? remoteCandidate : !remoteCandidate ? localCandidate : chooseCandidate(localCandidate, remoteCandidate, policy);
if (!winner) continue;
setRecordKey(values, key, winner.value);
if (winner.metadata) setRecordKey(keyMetadata, key, winner.metadata);
if (localCandidate && remoteCandidate && !valueEquals(localCandidate.value, remoteCandidate.value)) {
conflictCount += 1;
const loser = winner.source === "local" ? remoteCandidate : localCandidate;
addConflictEntry(conflicts, key, loser, now);
if (winner.source === "remote") changedKeys.push(key);
} else if (winner.source === "remote" && (!localCandidate || !valueEquals(localCandidate.value, winner.value))) {
changedKeys.push(key);
}
if (winner.source === "remote" && compareGmValueClocks(winner.clock, localCandidate?.clock) > 0 && !metadataChangedKeys.includes(key)) {
metadataChangedKeys.push(key);
}
}
const normalizedConflicts = normalizeGmValueSyncConflicts(conflicts, { now });
const losersRetained = Object.values(normalizedConflicts).reduce((sum, entries) => sum + entries.length, 0);
return {
values,
keyMetadata,
conflicts: normalizedConflicts,
changedKeys,
metadataChangedKeys,
conflictCount,
losersRetained
};
}
function shouldSyncScriptValues(script) {
return script?.settings?.syncValues === true;
}
function buildGmValueSyncBundle(script, values, options = {}) {
const warnings = [];
if (!script?.id) {
return { included: false, reason: "missing-script", bundle: null, warnings };
}
if (!shouldSyncScriptValues(script)) {
return { included: false, reason: "not-opted-in", bundle: null, warnings };
}
const maxScriptBytes = options.maxScriptBytes ?? GM_VALUE_SYNC_MAX_SCRIPT_BYTES;
const maxKeys = options.maxKeys ?? GM_VALUE_SYNC_MAX_KEYS;
const maxKeyBytes = options.maxKeyBytes ?? GM_VALUE_SYNC_MAX_KEY_BYTES;
const lastValueUpdatedAt = normalizeTimestamp(options.lastValueUpdatedAt);
const sourceKeyMetadata = options.keyMetadata && typeof options.keyMetadata === "object" && !Array.isArray(options.keyMetadata) ? options.keyMetadata : {};
const sourceValues = values && typeof values === "object" && !Array.isArray(values) ? values : {};
const bundle = {
schema: GM_VALUE_SYNC_SCHEMA,
scriptId: script.id,
keyCount: 0,
bytes: 0,
values: {},
...lastValueUpdatedAt ? { lastValueUpdatedAt } : {}
};
for (const [rawKey, rawValue] of Object.entries(sourceValues).sort(([a], [b]) => a.localeCompare(b))) {
const key = String(rawKey);
if (bundle.keyCount >= maxKeys) {
warnings.push({ id: "maxKeysExceeded", message: `Only the first ${maxKeys} stored value keys can sync` });
break;
}
if (byteLength2(key) > maxKeyBytes) {
warnings.push({ id: "keyTooLarge", message: "Stored value key exceeds the sync key size cap" });
continue;
}
let cloned;
try {
cloned = cloneJsonValue(rawValue);
} catch (_) {
warnings.push({ id: "valueNotJsonSerializable", message: "Stored value is not JSON-serializable" });
continue;
}
if (cloned === void 0) {
warnings.push({ id: "valueNotJsonSerializable", message: "Stored value is not JSON-serializable" });
continue;
}
const nextValues = { ...bundle.values };
setRecordKey(nextValues, key, cloned);
const nextKeyMetadata = { ...bundle.keyMetadata ?? {} };
const keyMetadataEntry = normalizeKeyMetadataEntry(sourceKeyMetadata[key], {
deviceId: options.deviceId ?? void 0,
fallbackTimestamp: lastValueUpdatedAt
});
if (keyMetadataEntry) setRecordKey(nextKeyMetadata, key, keyMetadataEntry);
const nextBundle = {
...bundle,
values: nextValues,
keyCount: Object.keys(nextValues).length,
...Object.keys(nextKeyMetadata).length > 0 ? { keyMetadata: nextKeyMetadata } : {}
};
const nextBytes = byteLength2(nextBundle);
if (nextBytes > maxScriptBytes) {
warnings.push({ id: "scriptValueCapExceeded", message: "Stored values exceed the per-script sync size cap" });
continue;
}
bundle.values = nextValues;
bundle.keyCount = nextBundle.keyCount;
if (nextBundle.keyMetadata) bundle.keyMetadata = nextBundle.keyMetadata;
bundle.bytes = nextBytes;
}
const normalizedConflicts = normalizeGmValueSyncConflicts(options.conflicts, { now: Date.now() });
for (const [key, entries] of Object.entries(normalizedConflicts)) {
if (!Object.prototype.hasOwnProperty.call(bundle.values, key)) continue;
const nextConflicts = { ...bundle.conflicts ?? {} };
setRecordKey(nextConflicts, key, entries);
const nextBundle = { ...bundle, conflicts: nextConflicts };
const nextBytes = byteLength2(nextBundle);
if (nextBytes > maxScriptBytes) {
warnings.push({ id: "conflictCapExceeded", message: "Retained GM value conflicts exceed the per-script sync size cap" });
continue;
}
bundle.conflicts = nextConflicts;
bundle.bytes = nextBytes;
}
if (bundle.keyCount === 0) {
return { included: true, reason: "empty", bundle, warnings };
}
return { included: true, reason: "included", bundle, warnings };
}
// src/modules/sync-easycloud.ts
var SYNC_TOMBSTONE_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
function pruneSyncTombstones(tombstones, now = Date.now()) {
const cutoff = now - SYNC_TOMBSTONE_RETENTION_MS;
return Object.fromEntries(Object.entries(tombstones).filter(
([, timestamp]) => typeof timestamp !== "number" || !Number.isFinite(timestamp) || timestamp > cutoff
));
}
function tombstoneMapsDiffer(left, right) {
const leftIds = Object.keys(left);
const rightIds = Object.keys(right);
return leftIds.length !== rightIds.length || leftIds.some((id) => !(id in right)) || rightIds.some((id) => !(id in left));
}
function isRecord(value) {
return !!value && typeof value === "object" && !Array.isArray(value);
}
function getValueBundles(envelope) {
return isRecord(envelope?.valueBundles) ? envelope.valueBundles : {};
}
async function _buildValueBundles(scripts) {
if (typeof ScriptValues === "undefined" || typeof ScriptValues?.getAll !== "function") return {};
const result = {};
for (const script of scripts) {
if (!shouldSyncScriptValues(script)) continue;
const values = await ScriptValues.getAll(script.id);
const aggregateMetadata = typeof ScriptValues.getAllMetadata === "function" ? await ScriptValues.getAllMetadata(script.id) : null;
const keyMetadata = typeof ScriptValues.getAllKeyMetadata === "function" ? await ScriptValues.getAllKeyMetadata(script.id) : null;
const deviceId = typeof ScriptValues.getSyncDeviceId === "function" ? await ScriptValues.getSyncDeviceId() : null;
const conflicts = typeof ScriptValues.getSyncConflicts === "function" ? await ScriptValues.getSyncConflicts(script.id) : null;
const built = buildGmValueSyncBundle(script, values, {
lastValueUpdatedAt: aggregateMetadata?.lastUpdatedAt ?? null,
keyMetadata,
deviceId,
conflicts
});
if (built.bundle) result[script.id] = built.bundle;
}
return result;
}
async function _persistValueConflictCount(scriptId, count) {
try {
const script = await ScriptStorage.get(scriptId);
if (!script) return;
const current = Math.max(0, Math.floor(Number(script.settings?._gmValueSyncConflictCount) || 0));
const next = Math.max(0, Math.floor(Number(count) || 0));
if (current === next) return;
const settings = { ...script.settings || {} };
if (next > 0) settings._gmValueSyncConflictCount = next;
else delete settings._gmValueSyncConflictCount;
await ScriptStorage.set(scriptId, { ...script, settings });
} catch (error) {
warn("[EasyCloud] Failed to persist GM value conflict count:", scriptId, error);
}
}
async function _applyValueBundles(bundles, policy) {
const result = { applied: 0, conflicts: 0, losersRetained: 0 };
if (typeof ScriptValues === "undefined" || typeof ScriptValues?.getAll !== "function") return result;
for (const [scriptId, bundle] of Object.entries(bundles)) {
if (!bundle || !isRecord(bundle.values)) continue;
const localValues = await ScriptValues.getAll(scriptId);
const localMetadata = typeof ScriptValues.getAllKeyMetadata === "function" ? await ScriptValues.getAllKeyMetadata(scriptId) : {};
const localConflicts = typeof ScriptValues.getSyncConflicts === "function" ? await ScriptValues.getSyncConflicts(scriptId) : null;
const merged = mergeGmValueSyncValues(
localValues,
localMetadata,
bundle.values,
bundle.keyMetadata,
{
policy,
localConflicts,
remoteConflicts: bundle.conflicts
}
);
result.conflicts += merged.conflictCount;
result.losersRetained += merged.losersRetained;
if (merged.changedKeys.length > 0 || merged.metadataChangedKeys.length > 0) {
if (typeof ScriptValues.setAllWithClocks === "function") {
await ScriptValues.setAllWithClocks(scriptId, merged.values, merged.keyMetadata);
} else if (typeof ScriptValues.setAll === "function") {
await ScriptValues.setAll(scriptId, merged.values);
}
result.applied += 1;
}
if (typeof ScriptValues.setSyncConflicts === "function") {
await ScriptValues.setSyncConflicts(scriptId, merged.conflicts);
}
await _persistValueConflictCount(scriptId, merged.losersRetained);
}
return result;
}
var TAG = "[EasyCloud]";
var ALARM_NAME = "easycloud-periodic-sync";
var DEBOUNCE_ALARM_NAME = "easycloud-debounce-sync";
var ALARM_PERIOD_MINUTES = 15;
var DEBOUNCE_MS = 5e3;
var DRIVE_API = "https://www.googleapis.com/drive/v3";
var DRIVE_UPLOAD_API = "https://www.googleapis.com/upload/drive/v3";
var SYNC_FILE_NAME = "scriptvault-sync.json";
var STORAGE_KEY_PREFIX = "easycloud_";
var EASYCLOUD_RATE_LIMIT_DEFAULT_RETRY_MS = 6e4;
var EASYCLOUD_RATE_LIMIT_MAX_RETRY_MS = 6 * 60 * 60 * 1e3;
var KEYS = {
CONNECTED: STORAGE_KEY_PREFIX + "connected",
DEVICE_ID: STORAGE_KEY_PREFIX + "deviceId",
LAST_SYNC: STORAGE_KEY_PREFIX + "lastSync",
STATUS: STORAGE_KEY_PREFIX + "status",
OFFLINE_QUEUE: STORAGE_KEY_PREFIX + "offlineQueue",
USER_EMAIL: STORAGE_KEY_PREFIX + "userEmail",
USER_NAME: STORAGE_KEY_PREFIX + "userName",
FILE_ID: STORAGE_KEY_PREFIX + "fileId"
};
var STATUS = {
IDLE: "synced",
SYNCING: "syncing",
ERROR: "error",
OFFLINE: "offline"
};
var _status = STATUS.IDLE;
var _syncInProgress = false;
var _statusListeners = [];
var _cachedToken = null;
var _cachedFileId = null;
var _deviceId = null;
var _initialized = false;
function acquireSyncEngineLock(owner) {
const host = globalThis;
if (host.__scriptVaultSyncEngineLock) return null;
const token = Symbol(owner);
host.__scriptVaultSyncEngineLock = { owner, token, startedAt: Date.now() };
return () => {
if (host.__scriptVaultSyncEngineLock?.token === token) {
delete host.__scriptVaultSyncEngineLock;
}
};
}
async function fetchWithTimeout(url, options = {}, timeoutMs = 3e4) {
const externalSignal = options.signal;
const { signal: _ignoredSignal, ...fetchOptions } = options;
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const signal = externalSignal ? AbortSignal.any([externalSignal, timeoutSignal]) : timeoutSignal;
const response = await fetch(url, { ...fetchOptions, signal });
await throwIfEasyCloudRateLimited(response, url);
return response;
}
function isEasyCloudRateLimitError(error) {
return Boolean(error && typeof error === "object" && error.rateLimited === true && Number.isFinite(error.retryAfterMs));
}
function parseEasyCloudRetryAfterMs(response) {
const raw = response.headers?.get?.("Retry-After")?.trim() || "";
let requestedMs = EASYCLOUD_RATE_LIMIT_DEFAULT_RETRY_MS;
const seconds = Number(raw);
if (raw && Number.isFinite(seconds) && seconds >= 0) {
requestedMs = seconds * 1e3;
} else if (raw) {
const retryAt = Date.parse(raw);
if (Number.isFinite(retryAt)) requestedMs = retryAt - Date.now();
}
return Math.min(EASYCLOUD_RATE_LIMIT_MAX_RETRY_MS, Math.max(1e3, Math.round(requestedMs)));
}
async function isEasyCloudQuotaResponse(response) {
if (response.status !== 403) return false;
try {
const body = await response.clone().json();
const text = JSON.stringify(body).toLowerCase();
return text.includes("userratelimitexceeded") || text.includes("ratelimitexceeded") || text.includes("quotaexceeded") || text.includes("rate limit exceeded");
} catch (_) {
return false;
}
}
async function throwIfEasyCloudRateLimited(response, url) {
const quota = response.status === 403 && /googleapis\.com/i.test(url) && await isEasyCloudQuotaResponse(response);
if (response.status !== 429 && !quota) return;
const retryAfterMs = parseEasyCloudRetryAfterMs(response);
const error = new Error(
`Google Drive rate limited (${response.status}); retry after ${Math.ceil(retryAfterMs / 1e3)}s`
);
error.rateLimited = true;
error.retryAfterMs = retryAfterMs;
error.status = response.status;
throw error;
}
var EASYCLOUD_SYNC_PAYLOAD_MAX_BYTES = 64 * 1024 * 1024;
var EASYCLOUD_METADATA_MAX_BYTES = 4 * 1024 * 1024;
var EASYCLOUD_ERROR_MAX_BYTES = 256 * 1024;
async function readEasyCloudTextBounded(response, maxBytes, label) {
const declared = Number.parseInt(response.headers?.get?.("content-length") || "0", 10);
if (Number.isFinite(declared) && declared > maxBytes) {
throw new Error(`${label} exceeds the ${Math.round(maxBytes / 1024 / 1024)} MB limit`);
}
if (!response.body?.getReader) {
const text2 = await response.text();
if (new TextEncoder().encode(text2).byteLength > maxBytes) {
throw new Error(`${label} exceeds the ${Math.round(maxBytes / 1024 / 1024)} MB limit`);
}
return text2;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let total = 0;
let text = "";
try {
for (; ; ) {
const { value, done } = await reader.read();
if (done) break;
if (!value) continue;
total += value.byteLength;
if (total > maxBytes) {
await reader.cancel().catch(() => void 0);
throw new Error(`${label} exceeds the ${Math.round(maxBytes / 1024 / 1024)} MB limit`);
}
text += decoder.decode(value, { stream: true });
}
return text + decoder.decode();
} finally {
try {
reader.releaseLock();
} catch (_) {
}
}
}
async function readEasyCloudJsonBounded(response, maxBytes, label) {
const text = await readEasyCloudTextBounded(response, maxBytes, label);
try {
return JSON.parse(text);
} catch (_) {
throw new Error(`${label} returned invalid JSON`);
}
}
async function discardEasyCloudResponse(response) {
try {
await response.body?.cancel();
} catch (_) {
}
}
function log(...args) {
console.log(TAG, ...args);
}
function warn(...args) {
console.warn(TAG, ...args);
}
function _getRuntimeHooks() {
return globalThis;
}
async function _refreshScriptRuntime(script) {
const hooks = _getRuntimeHooks();
if (typeof hooks.unregisterScript === "function") {
try {
await hooks.unregisterScript(script.id);
} catch (e) {
warn(`Failed to unregister synced script ${script.id}:`, e);
}
}
if (script.enabled !== false && typeof hooks.registerScript === "function") {
try {
await hooks.registerScript(script);
} catch (e) {
warn(`Failed to register synced script ${script.id}:`, e);
}
}
}
async function _deleteSyncedScript(scriptId) {
const hooks = _getRuntimeHooks();
if (typeof hooks.unregisterScript === "function") {
try {
await hooks.unregisterScript(scriptId);
} catch (e) {
warn(`Failed to unregister deleted synced script ${scriptId}:`, e);
}
}
await ScriptStorage.delete(scriptId);
}
async function _updateBadgeIfAvailable() {
const hooks = _getRuntimeHooks();
if (typeof hooks.updateBadge === "function") {
try {
await hooks.updateBadge();
} catch (e) {
warn("Failed to refresh badge after sync:", e);
}
}
}
async function _mergeScriptText(base, local, remote) {
if (typeof ScriptAnalyzer !== "undefined" && typeof ScriptAnalyzer.mergeText === "function") {
return ScriptAnalyzer.mergeText(base, local, remote);
}
if (typeof ScriptAnalyzer !== "undefined" && typeof ScriptAnalyzer._ensureOffscreen === "function") {
const ready = await ScriptAnalyzer._ensureOffscreen();
if (!ready) throw new Error("No script merge engine available");
return chrome.runtime.sendMessage({
type: "offscreen_merge",
base,
local,
remote
});
}
throw new Error("No script merge engine available");
}
var SYNC_SAFE_SCRIPT_SETTING_KEYS = /* @__PURE__ */ new Set([
"autoUpdate",
"notifyUpdates",
"runAt",
"injectInto",
"frameMode",
"notifyErrors",
"notes",
"useOriginalIncludes",
"useOriginalMatches",
"useOriginalExcludes",
"userIncludes",
"userMatches",
"userExcludes",
"pinned",
"perfBudget",
"syncValues",
"tags",
"localLibraries"
]);
var LOCAL_ONLY_SCRIPT_SETTING_KEYS = /* @__PURE__ */ new Set([
"userModified",
"mergeConflict",
"syncLock",
"sourceIdentityChanged",
"_failedRequires",
"_failedRequireErrors",
"_registrationError"
]);
function cloneScriptSettingValue(value) {
if (value == null || typeof value !== "object") return value;
if (typeof structuredClone === "function") {
try {
return structuredClone(value);
} catch (_) {
}
}
try {
return JSON.parse(JSON.stringify(value));
} catch (_) {
return void 0;
}
}
function cloneSyncSafeScriptSettings(settings) {
if (!settings || typeof settings !== "object") return {};
const result = {};
for (const [key, value] of Object.entries(settings)) {
if (!SYNC_SAFE_SCRIPT_SETTING_KEYS.has(key) || LOCAL_ONLY_SCRIPT_SETTING_KEYS.has(key)) {
continue;
}
result[key] = key === "localLibraries" ? normalizeLocalLibrarySnapshots(value) : cloneScriptSettingValue(value);
}
return result;
}
function mergeSyncedScriptSettings(localSettings, remoteSettings, options = {}) {
return {
...localSettings && typeof localSettings === "object" ? localSettings : {},
...cloneSyncSafeScriptSettings(remoteSettings),
...options.mergeConflict ? { mergeConflict: true } : {}
};
}
function sanitizeSyncScriptForEnvelope(script) {
return {
...script,
settings: cloneSyncSafeScriptSettings(script.settings)
};
}
function sanitizeSyncEnvelopeForUpload(envelope) {
return {
...envelope,
scripts: (envelope.scripts || []).map((script) => sanitizeSyncScriptForEnvelope(script))
};
}
async function getSyncCryptoSettings() {
if (typeof SettingsManager.get !== "function") {
throw new Error("Settings unavailable for sync encryption");
}
return await SettingsManager.get();
}
async function markSyncEncryptionEstablished(settings) {
if (settings.syncEncryptionEnabled === true && settings.syncEncryptionEstablished !== true) {
try {
await SettingsManager.set("syncEncryptionEstablished", true);
} catch (_) {
}
}
}
async function readSyncEnvelopeFromRemote(remoteEnvelope) {
const settings = await getSyncCryptoSettings();
const decrypted = await SyncCrypto.decryptSyncEnvelope(
remoteEnvelope,
settings
);
if (remoteEnvelope && SyncCrypto.isEncryptedSyncEnvelope(remoteEnvelope)) {
await markSyncEncryptionEstablished(settings);
}
return decrypted;
}
async function prepareSyncEnvelopeForRemoteUpload(envelope) {
const settings = await getSyncCryptoSettings();
return {