drivekit 1.1.2 → 1.2.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/dist/cli.js CHANGED
@@ -347,8 +347,8 @@ var init_path_resolver = __esm({
347
347
  /**
348
348
  * Gets cache key for a path
349
349
  */
350
- getCacheKey(path10) {
351
- return `${this.rootFolderId}:${this.normalizePath(path10)}`;
350
+ getCacheKey(path12) {
351
+ return `${this.rootFolderId}:${this.normalizePath(path12)}`;
352
352
  }
353
353
  /**
354
354
  * Clears the path cache
@@ -362,8 +362,8 @@ var init_path_resolver = __esm({
362
362
  /**
363
363
  * Invalidate a single path from cache
364
364
  */
365
- invalidatePath(path10) {
366
- const norm = this.normalizePath(path10);
365
+ invalidatePath(path12) {
366
+ const norm = this.normalizePath(path12);
367
367
  const key = this.getCacheKey(norm);
368
368
  this.cache.delete(key);
369
369
  if (this.metadataCache) {
@@ -1959,6 +1959,10 @@ var init_resource_refs = __esm({
1959
1959
  async getLink() {
1960
1960
  return await this.drive.getShareableLink(this.pathOrId);
1961
1961
  }
1962
+ /** Access historical revisions & version control for this file */
1963
+ get revisions() {
1964
+ return this.drive.getRevisions(this.pathOrId);
1965
+ }
1962
1966
  /** Returns a ReadableStream for this file, optionally with byte Range requests */
1963
1967
  async createReadStream(options) {
1964
1968
  return await this.drive.createReadStream(this.pathOrId, options);
@@ -2449,66 +2453,1265 @@ var init_cache = __esm({
2449
2453
  upsertFiles(entries) {
2450
2454
  for (const e of entries) this.upsertFile(e);
2451
2455
  }
2452
- deleteFile(id) {
2453
- this.files.delete(id);
2456
+ deleteFile(id) {
2457
+ this.files.delete(id);
2458
+ }
2459
+ pruneMissing(activeIds) {
2460
+ const idSet = new Set(activeIds);
2461
+ let pruned = 0;
2462
+ for (const id of Array.from(this.files.keys())) {
2463
+ if (!idSet.has(id)) {
2464
+ this.files.delete(id);
2465
+ pruned++;
2466
+ }
2467
+ }
2468
+ return pruned;
2469
+ }
2470
+ clear() {
2471
+ this.files.clear();
2472
+ this.meta.clear();
2473
+ }
2474
+ getMeta(key) {
2475
+ return this.meta.get(key) || null;
2476
+ }
2477
+ setMeta(key, value) {
2478
+ this.meta.set(key, value);
2479
+ }
2480
+ getStats() {
2481
+ let fileCount = 0;
2482
+ let folderCount = 0;
2483
+ let totalSizeBytes = 0;
2484
+ for (const f of this.files.values()) {
2485
+ if (f.trashed) continue;
2486
+ if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
2487
+ else {
2488
+ fileCount++;
2489
+ totalSizeBytes += f.size || 0;
2490
+ }
2491
+ }
2492
+ return {
2493
+ fileCount,
2494
+ folderCount,
2495
+ totalSizeBytes,
2496
+ lastSyncTime: this.meta.get("last_sync_timestamp") || null,
2497
+ databasePath: ":memory:"
2498
+ };
2499
+ }
2500
+ close() {
2501
+ this.clear();
2502
+ }
2503
+ };
2504
+ }
2505
+ });
2506
+
2507
+ // src/crypto/encryption.ts
2508
+ import crypto2 from "crypto";
2509
+ import { Transform as Transform3 } from "stream";
2510
+ function deriveKey(password, salt) {
2511
+ return crypto2.pbkdf2Sync(password, salt, PBKDF2_ROUNDS, 32, "sha512");
2512
+ }
2513
+ var MAGIC_HEADER, MAGIC_STREAM_HEADER, SALT_LENGTH, IV_LENGTH, TAG_LENGTH, PBKDF2_ROUNDS, DriveKitCrypto;
2514
+ var init_encryption = __esm({
2515
+ "src/crypto/encryption.ts"() {
2516
+ "use strict";
2517
+ init_esm_shims();
2518
+ MAGIC_HEADER = Buffer.from("DKENC1", "utf8");
2519
+ MAGIC_STREAM_HEADER = Buffer.from("DKENCS", "utf8");
2520
+ SALT_LENGTH = 16;
2521
+ IV_LENGTH = 12;
2522
+ TAG_LENGTH = 16;
2523
+ PBKDF2_ROUNDS = 1e5;
2524
+ DriveKitCrypto = class {
2525
+ config;
2526
+ constructor(config) {
2527
+ if (!config.password && !config.key) {
2528
+ throw new Error("DriveKitCrypto requires either a password or a 32-byte key.");
2529
+ }
2530
+ if (config.key && config.key.length !== 32) {
2531
+ throw new Error(`DriveKitCrypto raw key must be exactly 32 bytes, got ${config.key.length} bytes.`);
2532
+ }
2533
+ this.config = config;
2534
+ }
2535
+ /**
2536
+ * Encrypts a Buffer using AES-256-GCM.
2537
+ * Format: [MAGIC (6B)][SALT (16B)][IV (12B)][TAG (16B)][CIPHERTEXT]
2538
+ */
2539
+ encryptBuffer(data) {
2540
+ const salt = crypto2.randomBytes(SALT_LENGTH);
2541
+ const iv = crypto2.randomBytes(IV_LENGTH);
2542
+ const key = this.config.key || deriveKey(this.config.password, salt);
2543
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
2544
+ const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
2545
+ const tag = cipher.getAuthTag();
2546
+ return Buffer.concat([MAGIC_HEADER, salt, iv, tag, ciphertext]);
2547
+ }
2548
+ /**
2549
+ * Decrypts a Buffer previously encrypted with encryptBuffer or createEncryptStream.
2550
+ */
2551
+ decryptBuffer(encryptedData) {
2552
+ if (encryptedData.length < MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH + TAG_LENGTH) {
2553
+ throw new Error("Encrypted payload is too short to be valid DriveKit ciphertext.");
2554
+ }
2555
+ const magic = encryptedData.subarray(0, MAGIC_HEADER.length);
2556
+ const isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
2557
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
2558
+ if (!isStreamFormat && !isBufferFormat) {
2559
+ throw new Error("Invalid magic header: file was not encrypted by DriveKit or is corrupted.");
2560
+ }
2561
+ const salt = encryptedData.subarray(6, 6 + SALT_LENGTH);
2562
+ const iv = encryptedData.subarray(6 + SALT_LENGTH, 6 + SALT_LENGTH + IV_LENGTH);
2563
+ const key = this.config.key || deriveKey(this.config.password, salt);
2564
+ let tag;
2565
+ let ciphertext;
2566
+ if (isStreamFormat) {
2567
+ tag = encryptedData.subarray(encryptedData.length - TAG_LENGTH);
2568
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, encryptedData.length - TAG_LENGTH);
2569
+ } else {
2570
+ tag = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, 6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
2571
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
2572
+ }
2573
+ const decipher = crypto2.createDecipheriv("aes-256-gcm", key, iv);
2574
+ decipher.setAuthTag(tag);
2575
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
2576
+ }
2577
+ /**
2578
+ * Creates an encryption Transform stream that prepends stream header and appends GCM auth tag
2579
+ */
2580
+ createEncryptStream() {
2581
+ const salt = crypto2.randomBytes(SALT_LENGTH);
2582
+ const iv = crypto2.randomBytes(IV_LENGTH);
2583
+ const key = this.config.key || deriveKey(this.config.password, salt);
2584
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
2585
+ let headerPushed = false;
2586
+ return new Transform3({
2587
+ transform(chunk, _encoding, callback) {
2588
+ if (!headerPushed) {
2589
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
2590
+ headerPushed = true;
2591
+ }
2592
+ const encrypted = cipher.update(chunk);
2593
+ if (encrypted.length > 0) {
2594
+ this.push(encrypted);
2595
+ }
2596
+ callback();
2597
+ },
2598
+ flush(callback) {
2599
+ if (!headerPushed) {
2600
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
2601
+ headerPushed = true;
2602
+ }
2603
+ const finalChunk = cipher.final();
2604
+ const tag = cipher.getAuthTag();
2605
+ this.push(Buffer.concat([finalChunk, tag]));
2606
+ callback();
2607
+ }
2608
+ });
2609
+ }
2610
+ /**
2611
+ * Creates a decryption Transform stream that verifies magic header and validates GCM authentication tag
2612
+ */
2613
+ createDecryptStream() {
2614
+ const HEADER_BASE_LEN = MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH;
2615
+ let headerBuffer = Buffer.alloc(0);
2616
+ let decipher = null;
2617
+ let isStreamFormat = false;
2618
+ let pendingTail = Buffer.alloc(0);
2619
+ const self = this;
2620
+ return new Transform3({
2621
+ transform(chunk, _encoding, callback) {
2622
+ try {
2623
+ let data = chunk;
2624
+ if (!decipher) {
2625
+ headerBuffer = Buffer.concat([headerBuffer, data]);
2626
+ if (headerBuffer.length < HEADER_BASE_LEN) {
2627
+ return callback();
2628
+ }
2629
+ const magic = headerBuffer.subarray(0, MAGIC_HEADER.length);
2630
+ isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
2631
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
2632
+ if (!isStreamFormat && !isBufferFormat) {
2633
+ return callback(new Error("Invalid magic header: stream was not encrypted by DriveKit or is corrupted."));
2634
+ }
2635
+ const salt = headerBuffer.subarray(MAGIC_HEADER.length, MAGIC_HEADER.length + SALT_LENGTH);
2636
+ const iv = headerBuffer.subarray(MAGIC_HEADER.length + SALT_LENGTH, HEADER_BASE_LEN);
2637
+ const key = self.config.key || deriveKey(self.config.password, salt);
2638
+ decipher = crypto2.createDecipheriv("aes-256-gcm", key, iv);
2639
+ if (isBufferFormat) {
2640
+ if (headerBuffer.length < HEADER_BASE_LEN + TAG_LENGTH) {
2641
+ return callback();
2642
+ }
2643
+ const tag = headerBuffer.subarray(HEADER_BASE_LEN, HEADER_BASE_LEN + TAG_LENGTH);
2644
+ decipher.setAuthTag(tag);
2645
+ data = headerBuffer.subarray(HEADER_BASE_LEN + TAG_LENGTH);
2646
+ headerBuffer = Buffer.alloc(0);
2647
+ } else {
2648
+ data = headerBuffer.subarray(HEADER_BASE_LEN);
2649
+ headerBuffer = Buffer.alloc(0);
2650
+ }
2651
+ }
2652
+ if (data.length > 0) {
2653
+ if (isStreamFormat) {
2654
+ pendingTail = Buffer.concat([pendingTail, data]);
2655
+ if (pendingTail.length > TAG_LENGTH) {
2656
+ const toProcess = pendingTail.subarray(0, pendingTail.length - TAG_LENGTH);
2657
+ pendingTail = pendingTail.subarray(pendingTail.length - TAG_LENGTH);
2658
+ const decryptedChunk = decipher.update(toProcess);
2659
+ if (decryptedChunk.length > 0) {
2660
+ this.push(decryptedChunk);
2661
+ }
2662
+ }
2663
+ } else {
2664
+ const decryptedChunk = decipher.update(data);
2665
+ if (decryptedChunk.length > 0) {
2666
+ this.push(decryptedChunk);
2667
+ }
2668
+ }
2669
+ }
2670
+ callback();
2671
+ } catch (err) {
2672
+ callback(err);
2673
+ }
2674
+ },
2675
+ flush(callback) {
2676
+ try {
2677
+ if (!decipher) {
2678
+ return callback(new Error("Encrypted stream is too short: missing header."));
2679
+ }
2680
+ if (isStreamFormat) {
2681
+ if (pendingTail.length !== TAG_LENGTH) {
2682
+ return callback(new Error("Encrypted stream is truncated: missing authentication tag."));
2683
+ }
2684
+ decipher.setAuthTag(pendingTail);
2685
+ }
2686
+ const finalChunk = decipher.final();
2687
+ if (finalChunk.length > 0) {
2688
+ this.push(finalChunk);
2689
+ }
2690
+ callback();
2691
+ } catch (err) {
2692
+ callback(new Error(`Authentication failed: corrupted data or invalid authentication tag (${err.message})`));
2693
+ }
2694
+ }
2695
+ });
2696
+ }
2697
+ /**
2698
+ * Encrypts a filename into a safe base64url string
2699
+ */
2700
+ encryptFilename(plainName) {
2701
+ const iv = crypto2.randomBytes(12);
2702
+ const salt = crypto2.randomBytes(8);
2703
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
2704
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
2705
+ const encrypted = Buffer.concat([cipher.update(Buffer.from(plainName, "utf8")), cipher.final()]);
2706
+ const tag = cipher.getAuthTag();
2707
+ const payload = Buffer.concat([salt, iv, tag, encrypted]);
2708
+ return `dk_${payload.toString("base64url")}.enc`;
2709
+ }
2710
+ /**
2711
+ * Decrypts a filename generated by encryptFilename
2712
+ */
2713
+ decryptFilename(encryptedName) {
2714
+ if (!encryptedName.startsWith("dk_") || !encryptedName.endsWith(".enc")) {
2715
+ return encryptedName;
2716
+ }
2717
+ try {
2718
+ const raw = encryptedName.slice(3, -4);
2719
+ const payload = Buffer.from(raw, "base64url");
2720
+ if (payload.length < 8 + 12 + 16) return encryptedName;
2721
+ const salt = payload.subarray(0, 8);
2722
+ const iv = payload.subarray(8, 20);
2723
+ const tag = payload.subarray(20, 36);
2724
+ const ciphertext = payload.subarray(36);
2725
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
2726
+ const decipher = crypto2.createDecipheriv("aes-256-gcm", key, iv);
2727
+ decipher.setAuthTag(tag);
2728
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
2729
+ return decrypted.toString("utf8");
2730
+ } catch {
2731
+ return encryptedName;
2732
+ }
2733
+ }
2734
+ };
2735
+ }
2736
+ });
2737
+
2738
+ // src/core/revisions.ts
2739
+ var DriveFileRevisions;
2740
+ var init_revisions = __esm({
2741
+ "src/core/revisions.ts"() {
2742
+ "use strict";
2743
+ init_esm_shims();
2744
+ init_retry();
2745
+ DriveFileRevisions = class {
2746
+ drive;
2747
+ pathOrId;
2748
+ idResolver;
2749
+ constructor(drive2, pathOrId, idResolver) {
2750
+ this.drive = drive2;
2751
+ this.pathOrId = pathOrId;
2752
+ this.idResolver = idResolver;
2753
+ }
2754
+ async getId() {
2755
+ if (this.idResolver && (this.pathOrId.startsWith("/") || this.pathOrId.includes("/"))) {
2756
+ return await this.idResolver(this.pathOrId);
2757
+ }
2758
+ return this.pathOrId;
2759
+ }
2760
+ /**
2761
+ * Lists all historical revisions of the file
2762
+ */
2763
+ async list() {
2764
+ const fileId = await this.getId();
2765
+ const res = await withRetry(async () => {
2766
+ return await this.drive.revisions.list({
2767
+ fileId,
2768
+ fields: "revisions(id, mimeType, modifiedTime, keepForever, size, originalFilename)"
2769
+ });
2770
+ });
2771
+ const revs = res.data.revisions || [];
2772
+ return revs.map((r) => ({
2773
+ id: r.id,
2774
+ mimeType: r.mimeType || void 0,
2775
+ modifiedTime: r.modifiedTime || void 0,
2776
+ keepForever: r.keepForever ?? false,
2777
+ size: r.size ? parseInt(r.size, 10) : void 0,
2778
+ originalFilename: r.originalFilename || void 0
2779
+ }));
2780
+ }
2781
+ /**
2782
+ * Gets metadata for a specific revision
2783
+ */
2784
+ async get(revisionId) {
2785
+ const fileId = await this.getId();
2786
+ const res = await withRetry(async () => {
2787
+ return await this.drive.revisions.get({
2788
+ fileId,
2789
+ revisionId,
2790
+ fields: "id, mimeType, modifiedTime, keepForever, size, originalFilename"
2791
+ });
2792
+ });
2793
+ const r = res.data;
2794
+ return {
2795
+ id: r.id,
2796
+ mimeType: r.mimeType || void 0,
2797
+ modifiedTime: r.modifiedTime || void 0,
2798
+ keepForever: r.keepForever ?? false,
2799
+ size: r.size ? parseInt(r.size, 10) : void 0,
2800
+ originalFilename: r.originalFilename || void 0
2801
+ };
2802
+ }
2803
+ /**
2804
+ * Pins or unpins a revision so Google Drive never automatically purges it after 30 days
2805
+ */
2806
+ async keepForever(revisionId, keep = true) {
2807
+ const fileId = await this.getId();
2808
+ const res = await withRetry(async () => {
2809
+ return await this.drive.revisions.update({
2810
+ fileId,
2811
+ revisionId,
2812
+ requestBody: {
2813
+ keepForever: keep
2814
+ },
2815
+ fields: "id, keepForever, modifiedTime"
2816
+ });
2817
+ });
2818
+ return {
2819
+ id: res.data.id,
2820
+ keepForever: res.data.keepForever ?? keep,
2821
+ modifiedTime: res.data.modifiedTime || void 0
2822
+ };
2823
+ }
2824
+ /**
2825
+ * Deletes a specific historical revision
2826
+ */
2827
+ async delete(revisionId) {
2828
+ const fileId = await this.getId();
2829
+ await withRetry(async () => {
2830
+ return await this.drive.revisions.delete({
2831
+ fileId,
2832
+ revisionId
2833
+ });
2834
+ });
2835
+ }
2836
+ /**
2837
+ * Gets a readable stream of a specific historical revision
2838
+ */
2839
+ async getStream(revisionId) {
2840
+ const fileId = await this.getId();
2841
+ const res = await withRetry(async () => {
2842
+ return await this.drive.revisions.get(
2843
+ { fileId, revisionId, alt: "media" },
2844
+ { responseType: "stream" }
2845
+ );
2846
+ });
2847
+ return res.data;
2848
+ }
2849
+ /**
2850
+ * Restores the file content to a specific previous revision
2851
+ */
2852
+ async restore(revisionId) {
2853
+ const fileId = await this.getId();
2854
+ const stream = await this.getStream(revisionId);
2855
+ const meta = await this.get(revisionId);
2856
+ await withRetry(async () => {
2857
+ return await this.drive.files.update({
2858
+ fileId,
2859
+ media: {
2860
+ mimeType: meta.mimeType || "application/octet-stream",
2861
+ body: stream
2862
+ }
2863
+ });
2864
+ });
2865
+ }
2866
+ };
2867
+ }
2868
+ });
2869
+
2870
+ // src/core/bidirectional-sync.ts
2871
+ import fs6 from "fs";
2872
+ import path7 from "path";
2873
+ var BidirectionalSyncEngine;
2874
+ var init_bidirectional_sync = __esm({
2875
+ "src/core/bidirectional-sync.ts"() {
2876
+ "use strict";
2877
+ init_esm_shims();
2878
+ init_smart_sync();
2879
+ BidirectionalSyncEngine = class {
2880
+ drive;
2881
+ ledger = /* @__PURE__ */ new Map();
2882
+ constructor(drive2) {
2883
+ this.drive = drive2;
2884
+ }
2885
+ /**
2886
+ * Performs a two-way synchronization cycle between local and remote directories
2887
+ */
2888
+ async sync(options) {
2889
+ const startTime = Date.now();
2890
+ const {
2891
+ localDir,
2892
+ remoteDir,
2893
+ conflictStrategy = "rename-conflict",
2894
+ deleteMissing = false,
2895
+ dryRun = false,
2896
+ onProgress
2897
+ } = options;
2898
+ const result = {
2899
+ uploaded: [],
2900
+ downloaded: [],
2901
+ deletedLocal: [],
2902
+ deletedRemote: [],
2903
+ conflicts: [],
2904
+ skipped: [],
2905
+ durationMs: 0
2906
+ };
2907
+ if (!fs6.existsSync(localDir)) {
2908
+ await fs6.promises.mkdir(localDir, { recursive: true });
2909
+ }
2910
+ const remoteFolderId = await this.drive.mkdirp(remoteDir);
2911
+ const localFiles = await this.scanLocalDir(localDir);
2912
+ const remoteFiles = await this.scanRemoteDir(remoteFolderId, "");
2913
+ const allPaths = /* @__PURE__ */ new Set([
2914
+ ...localFiles.keys(),
2915
+ ...remoteFiles.keys(),
2916
+ ...this.ledger.keys()
2917
+ ]);
2918
+ for (const relPath of allPaths) {
2919
+ const resolvedLocal = path7.resolve(localDir, relPath);
2920
+ const resolvedRoot = path7.resolve(localDir);
2921
+ if (!resolvedLocal.startsWith(resolvedRoot + path7.sep) && resolvedLocal !== resolvedRoot) {
2922
+ throw new Error(`Security Violation: Path traversal detected in sync path: "${relPath}"`);
2923
+ }
2924
+ const local = localFiles.get(relPath);
2925
+ const remote = remoteFiles.get(relPath);
2926
+ const prev = this.ledger.get(relPath);
2927
+ if (local && remote) {
2928
+ const localChanged = !prev || local.md5 !== prev.localMd5 || Math.abs(local.mtime - prev.localMtime) > 1e3;
2929
+ const remoteChanged = !prev || remote.md5 !== prev.remoteMd5 || Math.abs(remote.mtime - prev.remoteMtime) > 1e3;
2930
+ if (local.md5 === remote.md5) {
2931
+ result.skipped.push(relPath);
2932
+ onProgress?.({ action: "skip-identical", relPath });
2933
+ this.ledger.set(relPath, {
2934
+ relPath,
2935
+ localMtime: local.mtime,
2936
+ remoteMtime: remote.mtime,
2937
+ localMd5: local.md5,
2938
+ remoteMd5: remote.md5,
2939
+ remoteId: remote.id
2940
+ });
2941
+ continue;
2942
+ }
2943
+ if (localChanged && !remoteChanged) {
2944
+ if (!dryRun) {
2945
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
2946
+ const freshRemote = await this.drive.getFile(remote.id);
2947
+ this.updateLedger(relPath, local, freshRemote);
2948
+ }
2949
+ result.uploaded.push(relPath);
2950
+ onProgress?.({ action: "upload", relPath, details: "Local modification propagated" });
2951
+ continue;
2952
+ }
2953
+ if (remoteChanged && !localChanged) {
2954
+ if (!dryRun) {
2955
+ await this.downloadFile(remote.id, local.fullPath);
2956
+ const freshStat = await fs6.promises.stat(local.fullPath);
2957
+ this.ledger.set(relPath, {
2958
+ relPath,
2959
+ localMtime: freshStat.mtimeMs,
2960
+ remoteMtime: remote.mtime,
2961
+ localMd5: remote.md5,
2962
+ remoteMd5: remote.md5,
2963
+ remoteId: remote.id
2964
+ });
2965
+ }
2966
+ result.downloaded.push(relPath);
2967
+ onProgress?.({ action: "download", relPath, details: "Remote modification propagated" });
2968
+ continue;
2969
+ }
2970
+ result.conflicts.push(relPath);
2971
+ onProgress?.({ action: "conflict-resolved", relPath, details: `Strategy: ${conflictStrategy}` });
2972
+ if (!dryRun) {
2973
+ if (conflictStrategy === "prefer-local") {
2974
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
2975
+ const freshRemote = await this.drive.getFile(remote.id);
2976
+ this.updateLedger(relPath, local, freshRemote);
2977
+ result.uploaded.push(relPath);
2978
+ } else if (conflictStrategy === "prefer-cloud") {
2979
+ await this.downloadFile(remote.id, local.fullPath);
2980
+ const freshStat = await fs6.promises.stat(local.fullPath);
2981
+ this.ledger.set(relPath, {
2982
+ relPath,
2983
+ localMtime: freshStat.mtimeMs,
2984
+ remoteMtime: remote.mtime,
2985
+ localMd5: remote.md5,
2986
+ remoteMd5: remote.md5,
2987
+ remoteId: remote.id
2988
+ });
2989
+ result.downloaded.push(relPath);
2990
+ } else if (conflictStrategy === "keep-newer") {
2991
+ if (local.mtime >= remote.mtime) {
2992
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
2993
+ const freshRemote = await this.drive.getFile(remote.id);
2994
+ this.updateLedger(relPath, local, freshRemote);
2995
+ result.uploaded.push(relPath);
2996
+ } else {
2997
+ await this.downloadFile(remote.id, local.fullPath);
2998
+ const freshStat = await fs6.promises.stat(local.fullPath);
2999
+ this.ledger.set(relPath, {
3000
+ relPath,
3001
+ localMtime: freshStat.mtimeMs,
3002
+ remoteMtime: remote.mtime,
3003
+ localMd5: remote.md5,
3004
+ remoteMd5: remote.md5,
3005
+ remoteId: remote.id
3006
+ });
3007
+ result.downloaded.push(relPath);
3008
+ }
3009
+ } else {
3010
+ const ext = path7.extname(relPath);
3011
+ const base = relPath.slice(0, relPath.length - ext.length);
3012
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3013
+ const conflictRelPath = `${base} (Conflict ${timestamp})${ext}`;
3014
+ const conflictFullPath = path7.join(localDir, conflictRelPath);
3015
+ await this.downloadFile(remote.id, conflictFullPath);
3016
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3017
+ const freshRemote = await this.drive.getFile(remote.id);
3018
+ this.updateLedger(relPath, local, freshRemote);
3019
+ }
3020
+ }
3021
+ continue;
3022
+ }
3023
+ if (local && !remote) {
3024
+ if (prev && deleteMissing) {
3025
+ if (!dryRun) {
3026
+ await fs6.promises.unlink(local.fullPath);
3027
+ this.ledger.delete(relPath);
3028
+ }
3029
+ result.deletedLocal.push(relPath);
3030
+ onProgress?.({ action: "delete-local", relPath, details: "Deleted remotely" });
3031
+ } else {
3032
+ if (!dryRun) {
3033
+ const uploadedFile = await this.uploadFile(local.fullPath, remoteDir, relPath);
3034
+ this.updateLedger(relPath, local, uploadedFile);
3035
+ }
3036
+ result.uploaded.push(relPath);
3037
+ onProgress?.({ action: "upload", relPath, details: "New local file" });
3038
+ }
3039
+ continue;
3040
+ }
3041
+ if (!local && remote) {
3042
+ if (prev && deleteMissing) {
3043
+ if (!dryRun) {
3044
+ await this.drive.delete(remote.id, true);
3045
+ this.ledger.delete(relPath);
3046
+ }
3047
+ result.deletedRemote.push(relPath);
3048
+ onProgress?.({ action: "delete-remote", relPath, details: "Deleted locally" });
3049
+ } else {
3050
+ if (!dryRun) {
3051
+ const localDest = path7.join(localDir, relPath);
3052
+ await fs6.promises.mkdir(path7.dirname(localDest), { recursive: true });
3053
+ await this.downloadFile(remote.id, localDest);
3054
+ const stat = await fs6.promises.stat(localDest);
3055
+ this.ledger.set(relPath, {
3056
+ relPath,
3057
+ localMtime: stat.mtimeMs,
3058
+ remoteMtime: remote.mtime,
3059
+ localMd5: remote.md5,
3060
+ remoteMd5: remote.md5,
3061
+ remoteId: remote.id
3062
+ });
3063
+ }
3064
+ result.downloaded.push(relPath);
3065
+ onProgress?.({ action: "download", relPath, details: "New remote file" });
3066
+ }
3067
+ continue;
3068
+ }
3069
+ if (prev && !local && !remote) {
3070
+ this.ledger.delete(relPath);
3071
+ }
3072
+ }
3073
+ result.durationMs = Date.now() - startTime;
3074
+ return result;
3075
+ }
3076
+ async scanLocalDir(dir, baseDir = dir) {
3077
+ const map = /* @__PURE__ */ new Map();
3078
+ if (!fs6.existsSync(dir)) return map;
3079
+ const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
3080
+ for (const entry of entries) {
3081
+ const fullPath = path7.join(dir, entry.name);
3082
+ if (entry.isDirectory()) {
3083
+ const sub = await this.scanLocalDir(fullPath, baseDir);
3084
+ for (const [k, v] of sub) map.set(k, v);
3085
+ } else if (entry.isFile()) {
3086
+ const rel = path7.relative(baseDir, fullPath).replace(/\\/g, "/");
3087
+ const stat = await fs6.promises.stat(fullPath);
3088
+ const md5 = await calculateFileMd5(fullPath);
3089
+ map.set(rel, { fullPath, mtime: stat.mtimeMs, md5 });
3090
+ }
3091
+ }
3092
+ return map;
3093
+ }
3094
+ async scanRemoteDir(folderId, relPrefix) {
3095
+ const map = /* @__PURE__ */ new Map();
3096
+ const items = await this.drive.query().inFolder(folderId).notTrashed().list();
3097
+ for (const item of items) {
3098
+ if (!item.id || !item.name) continue;
3099
+ const cleanName = path7.basename(item.name.replace(/\\/g, "/")).replace(/\0/g, "");
3100
+ if (!cleanName || cleanName === "." || cleanName === "..") continue;
3101
+ const relPath = relPrefix ? `${relPrefix}/${cleanName}` : cleanName;
3102
+ if (item.mimeType === "application/vnd.google-apps.folder") {
3103
+ const sub = await this.scanRemoteDir(item.id, relPath);
3104
+ for (const [k, v] of sub) map.set(k, v);
3105
+ } else {
3106
+ const mtime = item.modifiedTime ? new Date(item.modifiedTime).getTime() : 0;
3107
+ map.set(relPath, {
3108
+ id: item.id,
3109
+ name: item.name,
3110
+ mtime,
3111
+ md5: item.md5Checksum || ""
3112
+ });
3113
+ }
3114
+ }
3115
+ return map;
3116
+ }
3117
+ async uploadFile(localPath, remoteDir, relPath) {
3118
+ const remoteSubDir = path7.dirname(relPath);
3119
+ const targetFolder = remoteSubDir === "." ? remoteDir : `${remoteDir}/${remoteSubDir}`;
3120
+ return await this.drive.upload({
3121
+ source: localPath,
3122
+ name: path7.basename(relPath),
3123
+ parent: targetFolder,
3124
+ overwrite: true
3125
+ });
3126
+ }
3127
+ async downloadFile(fileId, destPath) {
3128
+ await fs6.promises.mkdir(path7.dirname(destPath), { recursive: true });
3129
+ await this.drive.download(fileId, { destination: destPath });
3130
+ }
3131
+ updateLedger(relPath, local, remote) {
3132
+ this.ledger.set(relPath, {
3133
+ relPath,
3134
+ localMtime: local.mtime,
3135
+ remoteMtime: remote.modifiedTime ? new Date(remote.modifiedTime).getTime() : Date.now(),
3136
+ localMd5: local.md5,
3137
+ remoteMd5: remote.md5Checksum || local.md5,
3138
+ remoteId: remote.id
3139
+ });
3140
+ }
3141
+ };
3142
+ }
3143
+ });
3144
+
3145
+ // src/server/s3-gateway.ts
3146
+ import http3 from "http";
3147
+ import path8 from "path";
3148
+ import { parse as parseUrl } from "url";
3149
+ var S3GatewayServer;
3150
+ var init_s3_gateway = __esm({
3151
+ "src/server/s3-gateway.ts"() {
3152
+ "use strict";
3153
+ init_esm_shims();
3154
+ S3GatewayServer = class {
3155
+ drive;
3156
+ options;
3157
+ server = null;
3158
+ constructor(drive2, options = {}) {
3159
+ this.drive = drive2;
3160
+ this.options = {
3161
+ port: options.port || 9e3,
3162
+ host: options.host || "127.0.0.1",
3163
+ bucketRoot: options.bucketRoot || "/",
3164
+ ...options
3165
+ };
3166
+ }
3167
+ /**
3168
+ * Starts the S3 gateway HTTP server
3169
+ */
3170
+ async start() {
3171
+ return new Promise((resolve, reject) => {
3172
+ this.server = http3.createServer(async (req, res) => {
3173
+ try {
3174
+ await this.handleRequest(req, res);
3175
+ } catch (err) {
3176
+ this.sendXmlError(res, 500, "InternalError", err.message || "Internal S3 Gateway Error");
3177
+ }
3178
+ });
3179
+ this.server.on("error", reject);
3180
+ this.server.listen(this.options.port, this.options.host, () => {
3181
+ resolve({ port: this.options.port, host: this.options.host });
3182
+ });
3183
+ });
3184
+ }
3185
+ /**
3186
+ * Stops the S3 gateway HTTP server
3187
+ */
3188
+ async stop() {
3189
+ return new Promise((resolve) => {
3190
+ if (this.server) {
3191
+ this.server.close(() => resolve());
3192
+ } else {
3193
+ resolve();
3194
+ }
3195
+ });
3196
+ }
3197
+ async handleRequest(req, res) {
3198
+ const parsed = parseUrl(req.url || "/", true);
3199
+ const rawPathname = decodeURIComponent(parsed.pathname || "/");
3200
+ const pathname = path8.posix.normalize(rawPathname);
3201
+ if (rawPathname.includes("..") || pathname.includes("..") || pathname === ".") {
3202
+ this.sendXmlError(res, 400, "InvalidURI", "Path traversal characters are not permitted");
3203
+ return;
3204
+ }
3205
+ const method = req.method?.toUpperCase() || "GET";
3206
+ if (this.options.accessKeyId) {
3207
+ const authHeader = req.headers["authorization"];
3208
+ if (!authHeader || !authHeader.includes(this.options.accessKeyId)) {
3209
+ res.setHeader("WWW-Authenticate", "AWS4-HMAC-SHA256");
3210
+ this.sendXmlError(res, 403, "AccessDenied", "Invalid or missing AWS credentials");
3211
+ return;
3212
+ }
3213
+ }
3214
+ const segments = pathname.split("/").filter(Boolean);
3215
+ if (segments.some((s) => s === ".." || s === ".")) {
3216
+ this.sendXmlError(res, 400, "InvalidURI", "Invalid path segment");
3217
+ return;
3218
+ }
3219
+ if (segments.length === 0) {
3220
+ if (method === "GET") {
3221
+ await this.handleListBuckets(res);
3222
+ return;
3223
+ }
3224
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on root");
3225
+ return;
3226
+ }
3227
+ const bucket = segments[0];
3228
+ const key = segments.slice(1).join("/");
3229
+ if (!key) {
3230
+ if (method === "GET") {
3231
+ const prefix = parsed.query.prefix || "";
3232
+ await this.handleListObjects(bucket, prefix, res);
3233
+ return;
3234
+ }
3235
+ if (method === "PUT") {
3236
+ await this.drive.mkdirp(`/${bucket}`);
3237
+ res.statusCode = 200;
3238
+ res.end();
3239
+ return;
3240
+ }
3241
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on bucket");
3242
+ return;
3243
+ }
3244
+ const remotePath = `/${bucket}/${key}`;
3245
+ if (method === "HEAD") {
3246
+ try {
3247
+ const file = await this.drive.getFile(remotePath);
3248
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3249
+ res.setHeader("Content-Length", file.size || "0");
3250
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3251
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3252
+ res.statusCode = 200;
3253
+ res.end();
3254
+ } catch {
3255
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3256
+ }
3257
+ return;
3258
+ }
3259
+ if (method === "GET") {
3260
+ try {
3261
+ const file = await this.drive.getFile(remotePath);
3262
+ const range = req.headers["range"];
3263
+ let options = void 0;
3264
+ if (range && range.startsWith("bytes=")) {
3265
+ const parts = range.replace("bytes=", "").split("-");
3266
+ options = {
3267
+ start: parts[0] ? parseInt(parts[0], 10) : 0,
3268
+ end: parts[1] ? parseInt(parts[1], 10) : void 0
3269
+ };
3270
+ res.statusCode = 206;
3271
+ const end = options.end !== void 0 ? options.end : parseInt(file.size || "0", 10) - 1;
3272
+ res.setHeader("Content-Range", `bytes ${options.start}-${end}/${file.size}`);
3273
+ } else {
3274
+ res.statusCode = 200;
3275
+ }
3276
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3277
+ res.setHeader("Content-Length", file.size || "0");
3278
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3279
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3280
+ const stream = await this.drive.createReadStream(remotePath, options);
3281
+ stream.pipe(res);
3282
+ } catch {
3283
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3284
+ }
3285
+ return;
3286
+ }
3287
+ if (method === "PUT") {
3288
+ const upload = await this.drive.createWriteStream(remotePath);
3289
+ req.pipe(upload);
3290
+ try {
3291
+ const file = await upload.done;
3292
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3293
+ res.statusCode = 200;
3294
+ res.end();
3295
+ } catch (err) {
3296
+ this.sendXmlError(res, 500, "InternalError", err.message);
3297
+ }
3298
+ return;
3299
+ }
3300
+ if (method === "DELETE") {
3301
+ try {
3302
+ const file = await this.drive.resolvePath(remotePath);
3303
+ await this.drive.delete(file.id, true);
3304
+ res.statusCode = 204;
3305
+ res.end();
3306
+ } catch {
3307
+ res.statusCode = 204;
3308
+ res.end();
3309
+ }
3310
+ return;
3311
+ }
3312
+ this.sendXmlError(res, 405, "MethodNotAllowed", `HTTP method ${method} not allowed`);
3313
+ }
3314
+ async handleListBuckets(res) {
3315
+ const items = await this.drive.ls("/");
3316
+ const folders = items.filter((i) => i.mimeType === "application/vnd.google-apps.folder");
3317
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3318
+ xml += " <Buckets>\n";
3319
+ for (const f of folders) {
3320
+ xml += " <Bucket>\n";
3321
+ xml += ` <Name>${this.escapeXml(f.name || "bucket")}</Name>
3322
+ `;
3323
+ xml += ` <CreationDate>${f.createdTime || (/* @__PURE__ */ new Date()).toISOString()}</CreationDate>
3324
+ `;
3325
+ xml += " </Bucket>\n";
3326
+ }
3327
+ xml += " </Buckets>\n</ListAllMyBucketsResult>";
3328
+ res.setHeader("Content-Type", "application/xml");
3329
+ res.statusCode = 200;
3330
+ res.end(xml);
3331
+ }
3332
+ async handleListObjects(bucket, prefix, res) {
3333
+ const targetPath = `/${bucket}${prefix ? `/${prefix}` : ""}`;
3334
+ let items = [];
3335
+ try {
3336
+ items = await this.drive.ls(targetPath);
3337
+ } catch {
3338
+ items = [];
3339
+ }
3340
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3341
+ xml += ` <Name>${this.escapeXml(bucket)}</Name>
3342
+ `;
3343
+ xml += ` <Prefix>${this.escapeXml(prefix)}</Prefix>
3344
+ `;
3345
+ xml += " <IsTruncated>false</IsTruncated>\n";
3346
+ for (const item of items) {
3347
+ if (item.mimeType === "application/vnd.google-apps.folder") continue;
3348
+ const key = prefix ? `${prefix}/${item.name}` : item.name;
3349
+ xml += " <Contents>\n";
3350
+ xml += ` <Key>${this.escapeXml(key)}</Key>
3351
+ `;
3352
+ xml += ` <LastModified>${item.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()}</LastModified>
3353
+ `;
3354
+ xml += ` <ETag>"${item.md5Checksum || item.id}"</ETag>
3355
+ `;
3356
+ xml += ` <Size>${item.size || 0}</Size>
3357
+ `;
3358
+ xml += " <StorageClass>STANDARD</StorageClass>\n";
3359
+ xml += " </Contents>\n";
3360
+ }
3361
+ xml += "</ListBucketResult>";
3362
+ res.setHeader("Content-Type", "application/xml");
3363
+ res.statusCode = 200;
3364
+ res.end(xml);
3365
+ }
3366
+ sendXmlError(res, status, code, message) {
3367
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
3368
+ <Error>
3369
+ <Code>${this.escapeXml(code)}</Code>
3370
+ <Message>${this.escapeXml(message)}</Message>
3371
+ </Error>`;
3372
+ res.setHeader("Content-Type", "application/xml");
3373
+ res.statusCode = status;
3374
+ res.end(xml);
3375
+ }
3376
+ escapeXml(unsafe) {
3377
+ return unsafe.replace(/[<>&'"]/g, (c) => {
3378
+ switch (c) {
3379
+ case "<":
3380
+ return "&lt;";
3381
+ case ">":
3382
+ return "&gt;";
3383
+ case "&":
3384
+ return "&amp;";
3385
+ case "'":
3386
+ return "&apos;";
3387
+ case '"':
3388
+ return "&quot;";
3389
+ default:
3390
+ return c;
3391
+ }
3392
+ });
3393
+ }
3394
+ };
3395
+ }
3396
+ });
3397
+
3398
+ // src/core/security-auditor.ts
3399
+ var SecurityAuditor;
3400
+ var init_security_auditor = __esm({
3401
+ "src/core/security-auditor.ts"() {
3402
+ "use strict";
3403
+ init_esm_shims();
3404
+ init_retry();
3405
+ SecurityAuditor = class {
3406
+ drive;
3407
+ constructor(drive2) {
3408
+ this.drive = drive2;
3409
+ }
3410
+ /**
3411
+ * Scans Google Drive files and audits their permission grants
3412
+ */
3413
+ async audit(options = {}) {
3414
+ const limit = options.scanLimit || 500;
3415
+ const allowedDomains = new Set((options.allowedDomains || []).map((d) => d.toLowerCase()));
3416
+ const issues = [];
3417
+ let publicCount = 0;
3418
+ let domainCount = 0;
3419
+ let externalCount = 0;
3420
+ let scannedTotal = 0;
3421
+ let pageToken = void 0;
3422
+ do {
3423
+ const res = await withRetry(async () => {
3424
+ return await this.drive.files.list({
3425
+ q: "trashed = false",
3426
+ fields: "nextPageToken, files(id, name, mimeType, webViewLink, shared, permissions(id, type, role, emailAddress, domain))",
3427
+ pageSize: Math.min(100, limit - scannedTotal),
3428
+ supportsAllDrives: true,
3429
+ includeItemsFromAllDrives: true,
3430
+ pageToken
3431
+ });
3432
+ });
3433
+ const files = res.data.files || [];
3434
+ for (const file of files) {
3435
+ if (!file.id || !file.name) continue;
3436
+ scannedTotal++;
3437
+ const perms = file.permissions || [];
3438
+ for (const p of perms) {
3439
+ if (p.type === "anyone") {
3440
+ publicCount++;
3441
+ const isCritical = ["writer", "owner", "organizer", "fileOrganizer"].includes(p.role || "");
3442
+ issues.push({
3443
+ fileId: file.id,
3444
+ fileName: file.name,
3445
+ risk: isCritical ? "CRITICAL" : "HIGH",
3446
+ reason: `Publicly accessible to anyone (${p.role} access)`,
3447
+ permissionId: p.id,
3448
+ type: p.type,
3449
+ role: p.role || "reader",
3450
+ webViewLink: file.webViewLink || void 0
3451
+ });
3452
+ continue;
3453
+ }
3454
+ if (p.type === "domain") {
3455
+ domainCount++;
3456
+ issues.push({
3457
+ fileId: file.id,
3458
+ fileName: file.name,
3459
+ risk: "MEDIUM",
3460
+ reason: `Shared with entire organization domain (${p.domain})`,
3461
+ permissionId: p.id,
3462
+ type: p.type,
3463
+ role: p.role || "reader",
3464
+ domain: p.domain || void 0,
3465
+ webViewLink: file.webViewLink || void 0
3466
+ });
3467
+ continue;
3468
+ }
3469
+ if (p.type === "user" && p.emailAddress && allowedDomains.size > 0) {
3470
+ const userDomain = p.emailAddress.split("@")[1]?.toLowerCase();
3471
+ if (userDomain && !allowedDomains.has(userDomain)) {
3472
+ externalCount++;
3473
+ issues.push({
3474
+ fileId: file.id,
3475
+ fileName: file.name,
3476
+ risk: "HIGH",
3477
+ reason: `Shared with external user outside allowed domains: ${p.emailAddress}`,
3478
+ permissionId: p.id,
3479
+ type: p.type,
3480
+ role: p.role || "reader",
3481
+ emailAddress: p.emailAddress,
3482
+ webViewLink: file.webViewLink || void 0
3483
+ });
3484
+ }
3485
+ }
3486
+ }
3487
+ }
3488
+ pageToken = res.data.nextPageToken || void 0;
3489
+ } while (pageToken && scannedTotal < limit);
3490
+ return {
3491
+ totalScanned: scannedTotal,
3492
+ publicFilesCount: publicCount,
3493
+ domainSharedCount: domainCount,
3494
+ externalSharesCount: externalCount,
3495
+ issues,
3496
+ scannedAt: (/* @__PURE__ */ new Date()).toISOString()
3497
+ };
2454
3498
  }
2455
- pruneMissing(activeIds) {
2456
- const idSet = new Set(activeIds);
2457
- let pruned = 0;
2458
- for (const id of Array.from(this.files.keys())) {
2459
- if (!idSet.has(id)) {
2460
- this.files.delete(id);
2461
- pruned++;
3499
+ /**
3500
+ * Revokes public 'anyone' permissions on specified files
3501
+ */
3502
+ async revokePublicAccess(fileIds) {
3503
+ const revoked = [];
3504
+ const errors = [];
3505
+ for (const fileId of fileIds) {
3506
+ try {
3507
+ const fileRes = await withRetry(async () => {
3508
+ return await this.drive.files.get({
3509
+ fileId,
3510
+ fields: "id, permissions(id, type)",
3511
+ supportsAllDrives: true
3512
+ });
3513
+ });
3514
+ const publicPerms = (fileRes.data.permissions || []).filter((p) => p.type === "anyone");
3515
+ for (const p of publicPerms) {
3516
+ if (p.id) {
3517
+ await withRetry(async () => {
3518
+ return await this.drive.permissions.delete({
3519
+ fileId,
3520
+ permissionId: p.id,
3521
+ supportsAllDrives: true
3522
+ });
3523
+ });
3524
+ }
3525
+ }
3526
+ revoked.push(fileId);
3527
+ } catch (err) {
3528
+ errors.push({ fileId, error: err.message });
2462
3529
  }
2463
3530
  }
2464
- return pruned;
2465
- }
2466
- clear() {
2467
- this.files.clear();
2468
- this.meta.clear();
3531
+ return { revoked, errors };
2469
3532
  }
2470
- getMeta(key) {
2471
- return this.meta.get(key) || null;
3533
+ };
3534
+ }
3535
+ });
3536
+
3537
+ // src/core/semantic-search.ts
3538
+ function levenshtein(a, b) {
3539
+ const an = a.length;
3540
+ const bn = b.length;
3541
+ if (an === 0) return bn;
3542
+ if (bn === 0) return an;
3543
+ const matrix = Array.from({ length: bn + 1 }, (_, i) => [i]);
3544
+ for (let j = 0; j <= an; j++) matrix[0][j] = j;
3545
+ for (let i = 1; i <= bn; i++) {
3546
+ for (let j = 1; j <= an; j++) {
3547
+ if (b.charAt(i - 1) === a.charAt(j - 1)) {
3548
+ matrix[i][j] = matrix[i - 1][j - 1];
3549
+ } else {
3550
+ matrix[i][j] = Math.min(
3551
+ matrix[i - 1][j - 1] + 1,
3552
+ // substitution
3553
+ matrix[i][j - 1] + 1,
3554
+ // insertion
3555
+ matrix[i - 1][j] + 1
3556
+ // deletion
3557
+ );
2472
3558
  }
2473
- setMeta(key, value) {
2474
- this.meta.set(key, value);
3559
+ }
3560
+ }
3561
+ return matrix[bn][an];
3562
+ }
3563
+ function cosineSimilarity(vecA, vecB) {
3564
+ if (vecA.length !== vecB.length || vecA.length === 0) return 0;
3565
+ let dot = 0;
3566
+ let normA = 0;
3567
+ let normB = 0;
3568
+ for (let i = 0; i < vecA.length; i++) {
3569
+ dot += vecA[i] * vecB[i];
3570
+ normA += vecA[i] * vecA[i];
3571
+ normB += vecB[i] * vecB[i];
3572
+ }
3573
+ if (normA === 0 || normB === 0) return 0;
3574
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
3575
+ }
3576
+ var SmartSearchEngine;
3577
+ var init_semantic_search = __esm({
3578
+ "src/core/semantic-search.ts"() {
3579
+ "use strict";
3580
+ init_esm_shims();
3581
+ SmartSearchEngine = class {
3582
+ drive;
3583
+ constructor(drive2) {
3584
+ this.drive = drive2;
2475
3585
  }
2476
- getStats() {
2477
- let fileCount = 0;
2478
- let folderCount = 0;
2479
- let totalSizeBytes = 0;
2480
- for (const f of this.files.values()) {
2481
- if (f.trashed) continue;
2482
- if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
2483
- else {
2484
- fileCount++;
2485
- totalSizeBytes += f.size || 0;
3586
+ /**
3587
+ * Searches Drive using tokenized fuzzy matching and optional semantic embeddings
3588
+ */
3589
+ async search(query, options = {}) {
3590
+ const limit = options.limit || 20;
3591
+ const minScore = options.minScore ?? 0.3;
3592
+ const queryTokens = query.toLowerCase().split(/\s+/).filter(Boolean);
3593
+ if (queryTokens.length === 0) return [];
3594
+ let candidates = [];
3595
+ if (options.parent) {
3596
+ candidates = await this.drive.ls(options.parent);
3597
+ } else {
3598
+ candidates = await this.drive.query().notTrashed().pageSize(100).list();
3599
+ }
3600
+ let queryVector = null;
3601
+ if (options.embedder) {
3602
+ try {
3603
+ queryVector = await options.embedder(query);
3604
+ } catch {
3605
+ queryVector = null;
2486
3606
  }
2487
3607
  }
2488
- return {
2489
- fileCount,
2490
- folderCount,
2491
- totalSizeBytes,
2492
- lastSyncTime: this.meta.get("last_sync_timestamp") || null,
2493
- databasePath: ":memory:"
2494
- };
2495
- }
2496
- close() {
2497
- this.clear();
3608
+ const scored = [];
3609
+ for (const file of candidates) {
3610
+ const fileName = (file.name || "").toLowerCase();
3611
+ const desc = (file.description || "").toLowerCase();
3612
+ const matchedOn = [];
3613
+ let nameScore = 0;
3614
+ let descScore = 0;
3615
+ let semanticScore = 0;
3616
+ if (fileName.includes(query.toLowerCase())) {
3617
+ nameScore = 0.95;
3618
+ matchedOn.push("name");
3619
+ } else {
3620
+ let tokensMatched = 0;
3621
+ for (const token of queryTokens) {
3622
+ if (fileName.includes(token)) {
3623
+ tokensMatched += 1;
3624
+ continue;
3625
+ }
3626
+ const words = fileName.split(/[\s._-]+/);
3627
+ for (const word of words) {
3628
+ const dist = levenshtein(token, word);
3629
+ const maxLen = Math.max(token.length, word.length);
3630
+ if (maxLen > 3 && dist <= 2) {
3631
+ tokensMatched += 1 - dist / maxLen;
3632
+ break;
3633
+ }
3634
+ }
3635
+ }
3636
+ nameScore = tokensMatched / queryTokens.length;
3637
+ if (nameScore > 0.4) matchedOn.push("name");
3638
+ }
3639
+ if (desc) {
3640
+ if (desc.includes(query.toLowerCase())) {
3641
+ descScore = 0.8;
3642
+ matchedOn.push("description");
3643
+ }
3644
+ }
3645
+ if (queryVector && options.embedder) {
3646
+ try {
3647
+ const fileVector = await options.embedder(`${file.name} ${file.description || ""}`);
3648
+ semanticScore = cosineSimilarity(queryVector, fileVector);
3649
+ if (semanticScore > 0.6) matchedOn.push("semantic");
3650
+ } catch {
3651
+ }
3652
+ }
3653
+ const totalScore = Math.min(1, nameScore * 0.7 + descScore * 0.15 + semanticScore * 0.15);
3654
+ if (totalScore >= minScore) {
3655
+ scored.push({
3656
+ file,
3657
+ score: Math.round(totalScore * 100) / 100,
3658
+ matchedOn: matchedOn.length > 0 ? matchedOn : ["name"]
3659
+ });
3660
+ }
3661
+ }
3662
+ scored.sort((a, b) => b.score - a.score);
3663
+ return scored.slice(0, limit);
2498
3664
  }
2499
3665
  };
2500
3666
  }
2501
3667
  });
2502
3668
 
3669
+ // src/utils/compression.ts
3670
+ import zlib from "zlib";
3671
+ import { promisify } from "util";
3672
+ async function compressBuffer(buffer, algorithm = "gzip") {
3673
+ switch (algorithm) {
3674
+ case "brotli":
3675
+ return await brotliCompressAsync(buffer);
3676
+ case "deflate":
3677
+ return await promisify(zlib.deflate)(buffer);
3678
+ case "gzip":
3679
+ default:
3680
+ return await gzipAsync(buffer);
3681
+ }
3682
+ }
3683
+ async function decompressBuffer(buffer, algorithm = "gzip") {
3684
+ switch (algorithm) {
3685
+ case "brotli":
3686
+ return await brotliDecompressAsync(buffer);
3687
+ case "deflate":
3688
+ return await promisify(zlib.inflate)(buffer);
3689
+ case "gzip":
3690
+ default:
3691
+ return await gunzipAsync(buffer);
3692
+ }
3693
+ }
3694
+ var gzipAsync, gunzipAsync, brotliCompressAsync, brotliDecompressAsync;
3695
+ var init_compression = __esm({
3696
+ "src/utils/compression.ts"() {
3697
+ "use strict";
3698
+ init_esm_shims();
3699
+ gzipAsync = promisify(zlib.gzip);
3700
+ gunzipAsync = promisify(zlib.gunzip);
3701
+ brotliCompressAsync = promisify(zlib.brotliCompress);
3702
+ brotliDecompressAsync = promisify(zlib.brotliDecompress);
3703
+ }
3704
+ });
3705
+
2503
3706
  // src/server/webdav.ts
2504
3707
  var webdav_exports = {};
2505
3708
  __export(webdav_exports, {
2506
3709
  escapeXml: () => escapeXml,
2507
3710
  startWebDAVServer: () => startWebDAVServer
2508
3711
  });
2509
- import http3 from "http";
3712
+ import http4 from "http";
2510
3713
  import url from "url";
2511
- import path7 from "path";
3714
+ import path9 from "path";
2512
3715
  function escapeXml(unsafe) {
2513
3716
  return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2514
3717
  }
@@ -2516,7 +3719,7 @@ async function startWebDAVServer(drive2, options = {}) {
2516
3719
  const port = options.port || 8080;
2517
3720
  const host = options.host || "127.0.0.1";
2518
3721
  await drive2.init();
2519
- const server = http3.createServer(async (req, res) => {
3722
+ const server = http4.createServer(async (req, res) => {
2520
3723
  try {
2521
3724
  if (options.auth?.username && options.auth?.password) {
2522
3725
  const authHeader = req.headers["authorization"];
@@ -2541,8 +3744,9 @@ async function startWebDAVServer(drive2, options = {}) {
2541
3744
  }
2542
3745
  const parsedUrl = url.parse(req.url || "/", true);
2543
3746
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
2544
- const virtualPath = decodedPath === "" ? "/" : decodedPath;
2545
- const baseName = path7.basename(virtualPath);
3747
+ const normalizedPath = path9.posix.normalize(decodedPath);
3748
+ const virtualPath = normalizedPath.startsWith("/") ? normalizedPath : `/${normalizedPath}`;
3749
+ const baseName = path9.basename(virtualPath);
2546
3750
  if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
2547
3751
  res.writeHead(404, { "Content-Type": "text/plain" });
2548
3752
  res.end("Not Found");
@@ -2631,7 +3835,7 @@ async function startWebDAVServer(drive2, options = {}) {
2631
3835
  return;
2632
3836
  }
2633
3837
  case "PUT": {
2634
- const remoteDir = path7.dirname(virtualPath);
3838
+ const remoteDir = path9.dirname(virtualPath);
2635
3839
  await drive2.mkdirp(remoteDir);
2636
3840
  let existed = false;
2637
3841
  try {
@@ -2694,14 +3898,14 @@ async function startWebDAVServer(drive2, options = {}) {
2694
3898
  }
2695
3899
  const destUrl = url.parse(destination);
2696
3900
  const destPath = decodeURIComponent(destUrl.pathname || "");
2697
- const newName = path7.basename(destPath);
2698
- const newParentDir = path7.dirname(destPath);
3901
+ const newName = path9.basename(destPath);
3902
+ const newParentDir = path9.dirname(destPath);
2699
3903
  const newParentFolderId = await drive2.mkdirp(newParentDir);
2700
- const currentParentDir = path7.dirname(virtualPath);
3904
+ const currentParentDir = path9.dirname(virtualPath);
2701
3905
  if (newParentDir !== currentParentDir) {
2702
3906
  await drive2.move(file.id, newParentFolderId);
2703
3907
  }
2704
- if (newName !== path7.basename(virtualPath)) {
3908
+ if (newName !== path9.basename(virtualPath)) {
2705
3909
  await drive2.rename(file.id, newName);
2706
3910
  }
2707
3911
  res.writeHead(201);
@@ -2728,8 +3932,8 @@ async function startWebDAVServer(drive2, options = {}) {
2728
3932
  }
2729
3933
  const destUrl = url.parse(destination);
2730
3934
  const destPath = decodeURIComponent(destUrl.pathname || "");
2731
- const newName = path7.basename(destPath);
2732
- const newParentDir = path7.dirname(destPath);
3935
+ const newName = path9.basename(destPath);
3936
+ const newParentDir = path9.dirname(destPath);
2733
3937
  const newParentFolderId = await drive2.mkdirp(newParentDir);
2734
3938
  await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
2735
3939
  res.writeHead(201);
@@ -2794,8 +3998,8 @@ async function handlePropfind(drive2, virtualPath, depth) {
2794
3998
  if (seenNames.has(childName)) {
2795
3999
  const count = seenNames.get(childName) + 1;
2796
4000
  seenNames.set(childName, count);
2797
- const ext = path7.extname(childName);
2798
- const base = path7.basename(childName, ext);
4001
+ const ext = path9.extname(childName);
4002
+ const base = path9.basename(childName, ext);
2799
4003
  childName = `${base} (${count})${ext}`;
2800
4004
  } else {
2801
4005
  seenNames.set(childName, 0);
@@ -2826,7 +4030,7 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
2826
4030
  cleanHref += "/";
2827
4031
  }
2828
4032
  const encodedHref = encodeURI(cleanHref);
2829
- const displayName = escapeXml(path7.basename(href) || "root");
4033
+ const displayName = escapeXml(path9.basename(href) || "root");
2830
4034
  const resourceType = isDir ? "<D:collection/>" : "";
2831
4035
  const dateFormatted = new Date(modifiedTime).toUTCString();
2832
4036
  const contentTypeTag = !isDir && mimeType ? `
@@ -2856,8 +4060,9 @@ var client_exports = {};
2856
4060
  __export(client_exports, {
2857
4061
  DriveKit: () => DriveKit
2858
4062
  });
2859
- import fs6 from "fs";
2860
- import path8 from "path";
4063
+ import fs7 from "fs";
4064
+ import path10 from "path";
4065
+ import crypto3 from "crypto";
2861
4066
  import { drive } from "@googleapis/drive";
2862
4067
  var DriveKit;
2863
4068
  var init_client = __esm({
@@ -2881,6 +4086,13 @@ var init_client = __esm({
2881
4086
  init_mime();
2882
4087
  init_cache();
2883
4088
  init_http_agent();
4089
+ init_encryption();
4090
+ init_revisions();
4091
+ init_bidirectional_sync();
4092
+ init_s3_gateway();
4093
+ init_security_auditor();
4094
+ init_semantic_search();
4095
+ init_compression();
2884
4096
  DriveKit = class _DriveKit {
2885
4097
  options;
2886
4098
  authenticator;
@@ -2889,12 +4101,34 @@ var init_client = __esm({
2889
4101
  uploaderInstance = null;
2890
4102
  downloaderInstance = null;
2891
4103
  metadataCacheInstance = null;
4104
+ cryptoInstance = null;
2892
4105
  rootFolderId;
2893
4106
  pluginManager = new PluginManager();
2894
4107
  constructor(options = {}) {
2895
4108
  this.options = options;
2896
4109
  this.rootFolderId = options.rootFolderId || "root";
2897
4110
  this.authenticator = new DriveAuthenticator(options.auth);
4111
+ if (options.encryption) {
4112
+ this.cryptoInstance = new DriveKitCrypto(options.encryption);
4113
+ }
4114
+ }
4115
+ /**
4116
+ * Access the client-side AES-256-GCM encryption engine
4117
+ */
4118
+ get crypto() {
4119
+ if (!this.cryptoInstance) {
4120
+ throw new Error("Encryption is not configured on this DriveKit instance. Pass { encryption: { password: ... } } in options.");
4121
+ }
4122
+ return this.cryptoInstance;
4123
+ }
4124
+ /**
4125
+ * Access historical revisions & version control for a file
4126
+ */
4127
+ getRevisions(fileIdOrPath) {
4128
+ if (!this.driveClient) {
4129
+ throw new Error("DriveKit is not initialized. Call await drive.init() first.");
4130
+ }
4131
+ return new DriveFileRevisions(this.driveClient, fileIdOrPath, (p) => this.resolveId(p));
2898
4132
  }
2899
4133
  /**
2900
4134
  * Registers a middleware plugin into DriveKit lifecycle
@@ -3074,58 +4308,89 @@ var init_client = __esm({
3074
4308
  if (parentId && parentId.startsWith("/")) {
3075
4309
  parentId = await this.mkdirp(parentId);
3076
4310
  }
3077
- const targetName = opts.name || opts.filename || (typeof opts.source === "string" ? path8.basename(opts.source) : void 0);
3078
- if (opts.overwrite && targetName && parentId) {
4311
+ let uploadOpts = { ...opts };
4312
+ if (uploadOpts.compress) {
4313
+ const algo = typeof uploadOpts.compress === "string" ? uploadOpts.compress : "gzip";
4314
+ if (typeof uploadOpts.source === "string" && fs7.existsSync(uploadOpts.source)) {
4315
+ const plainBuf = await fs7.promises.readFile(uploadOpts.source);
4316
+ uploadOpts.source = await compressBuffer(plainBuf, algo);
4317
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4318
+ uploadOpts.source = await compressBuffer(uploadOpts.source, algo);
4319
+ }
4320
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_compressed: algo };
4321
+ }
4322
+ if ((uploadOpts.encrypt || this.options.encryption) && this.cryptoInstance) {
4323
+ const origName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? path10.basename(uploadOpts.source) : "encrypted.bin");
4324
+ if (typeof uploadOpts.source === "string" && fs7.existsSync(uploadOpts.source)) {
4325
+ const plainBuf = await fs7.promises.readFile(uploadOpts.source);
4326
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(plainBuf);
4327
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4328
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(uploadOpts.source);
4329
+ }
4330
+ if (this.options.encryption?.encryptFilenames) {
4331
+ uploadOpts.name = this.cryptoInstance.encryptFilename(origName);
4332
+ }
4333
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_encrypted: "true" };
4334
+ }
4335
+ const targetName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? path10.basename(uploadOpts.source) : void 0);
4336
+ if (uploadOpts.overwrite && targetName && parentId) {
3079
4337
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
3080
4338
  if (existing?.id) {
3081
4339
  await this.delete(existing.id, true);
3082
4340
  }
3083
4341
  }
3084
- if (opts.deduplicate && typeof opts.source === "string" && fs6.existsSync(opts.source)) {
3085
- const localMd5 = await calculateFileMd5(opts.source);
3086
- let existingId;
3087
- if (this.metadataCacheInstance) {
3088
- const cached = this.metadataCacheInstance.findByMd5(localMd5);
3089
- if (cached) existingId = cached.id;
4342
+ if (uploadOpts.deduplicate) {
4343
+ let localMd5;
4344
+ if (typeof uploadOpts.source === "string" && fs7.existsSync(uploadOpts.source)) {
4345
+ localMd5 = await calculateFileMd5(uploadOpts.source);
4346
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4347
+ localMd5 = crypto3.createHash("md5").update(uploadOpts.source).digest("hex");
3090
4348
  }
3091
- if (!existingId) {
3092
- const found = await this.query().md5(localMd5).notTrashed().first();
3093
- if (found?.id) {
3094
- existingId = found.id;
4349
+ if (localMd5) {
4350
+ let existingId;
4351
+ if (this.metadataCacheInstance) {
4352
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
4353
+ if (cached) existingId = cached.id;
3095
4354
  }
3096
- }
3097
- if (existingId) {
3098
- const fileName = targetName || path8.basename(opts.source);
3099
- const raw = await this.getRawClient();
3100
- const copyRes = await withRetry(async () => {
3101
- return await raw.files.copy({
3102
- fileId: existingId,
3103
- requestBody: {
3104
- name: fileName,
3105
- parents: parentId ? [parentId] : void 0,
3106
- description: opts.description
3107
- },
3108
- fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
3109
- supportsAllDrives: true
3110
- });
3111
- });
3112
- const file = copyRes.data;
3113
- if (this.metadataCacheInstance && file.id) {
3114
- this.metadataCacheInstance.upsertFile({
3115
- id: file.id,
3116
- name: file.name || fileName,
3117
- mimeType: file.mimeType || "",
3118
- size: file.size ? parseInt(file.size, 10) : void 0,
3119
- parentId,
3120
- md5Checksum: localMd5,
3121
- trashed: false
4355
+ if (!existingId) {
4356
+ const found = await this.query().md5(localMd5).notTrashed().first();
4357
+ if (found?.id) {
4358
+ existingId = found.id;
4359
+ }
4360
+ }
4361
+ if (existingId) {
4362
+ const fileName = targetName || (typeof uploadOpts.source === "string" ? path10.basename(uploadOpts.source) : "file.bin");
4363
+ const raw = await this.getRawClient();
4364
+ const copyRes = await withRetry(async () => {
4365
+ return await raw.files.copy({
4366
+ fileId: existingId,
4367
+ requestBody: {
4368
+ name: fileName,
4369
+ parents: parentId ? [parentId] : void 0,
4370
+ description: uploadOpts.description
4371
+ },
4372
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
4373
+ supportsAllDrives: true
4374
+ });
3122
4375
  });
4376
+ const file = copyRes.data;
4377
+ if (this.metadataCacheInstance && file.id) {
4378
+ this.metadataCacheInstance.upsertFile({
4379
+ id: file.id,
4380
+ name: file.name || fileName,
4381
+ mimeType: file.mimeType || "",
4382
+ size: file.size ? parseInt(file.size, 10) : void 0,
4383
+ parentId,
4384
+ md5Checksum: localMd5,
4385
+ trashed: false
4386
+ });
4387
+ }
4388
+ return await this.pluginManager.runAfterUpload(file);
3123
4389
  }
3124
- return await this.pluginManager.runAfterUpload(file);
3125
4390
  }
3126
4391
  }
3127
4392
  const uploaded = await uploader.upload({
3128
- ...opts,
4393
+ ...uploadOpts,
3129
4394
  name: targetName,
3130
4395
  parent: parentId
3131
4396
  });
@@ -3163,6 +4428,16 @@ var init_client = __esm({
3163
4428
  const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
3164
4429
  const downloader = await this.getDownloader();
3165
4430
  const result = await downloader.download(fileId, processedOpts);
4431
+ if (processedOpts.decrypt && this.cryptoInstance && result.filePath && fs7.existsSync(result.filePath)) {
4432
+ const encrypted = await fs7.promises.readFile(result.filePath);
4433
+ const decrypted = this.cryptoInstance.decryptBuffer(encrypted);
4434
+ await fs7.promises.writeFile(result.filePath, decrypted);
4435
+ }
4436
+ if (processedOpts.decompress && result.filePath && fs7.existsSync(result.filePath)) {
4437
+ const comp = await fs7.promises.readFile(result.filePath);
4438
+ const decomp = await decompressBuffer(comp);
4439
+ await fs7.promises.writeFile(result.filePath, decomp);
4440
+ }
3166
4441
  return await this.pluginManager.runAfterDownload(result);
3167
4442
  }
3168
4443
  /**
@@ -3296,10 +4571,7 @@ var init_client = __esm({
3296
4571
  async copy(fileIdOrPath, options = {}) {
3297
4572
  const fileId = await this.resolveId(fileIdOrPath);
3298
4573
  const raw = await this.getRawClient();
3299
- let parentId = options.parent;
3300
- if (parentId && parentId.startsWith("/")) {
3301
- parentId = await this.mkdirp(parentId);
3302
- }
4574
+ const parentId = options.parent ? await this.resolveId(options.parent, true) : void 0;
3303
4575
  const requestBody = {};
3304
4576
  if (options.name) requestBody.name = options.name;
3305
4577
  if (parentId) requestBody.parents = [parentId];
@@ -3426,16 +4698,16 @@ var init_client = __esm({
3426
4698
  durationMs: 0
3427
4699
  };
3428
4700
  const collectFiles = async (dir, base) => {
3429
- const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
4701
+ const entries = await fs7.promises.readdir(dir, { withFileTypes: true });
3430
4702
  const files = [];
3431
4703
  for (const entry of entries) {
3432
- const fullPath = path8.join(dir, entry.name);
3433
- const relPath = path8.join(base, entry.name);
4704
+ const fullPath = path10.join(dir, entry.name);
4705
+ const relPath = path10.join(base, entry.name);
3434
4706
  if (entry.isDirectory()) {
3435
4707
  const sub = await collectFiles(fullPath, relPath);
3436
4708
  files.push(...sub);
3437
4709
  } else if (entry.isFile()) {
3438
- const stat = await fs6.promises.stat(fullPath);
4710
+ const stat = await fs7.promises.stat(fullPath);
3439
4711
  files.push({ fullPath, relPath, size: stat.size });
3440
4712
  }
3441
4713
  }
@@ -3448,11 +4720,11 @@ var init_client = __esm({
3448
4720
  if (remoteDirCache.has(relDir)) {
3449
4721
  return remoteDirCache.get(relDir);
3450
4722
  }
3451
- const parts = relDir.split(path8.sep).filter(Boolean);
4723
+ const parts = relDir.split(path10.sep).filter(Boolean);
3452
4724
  let currentParent = targetFolderId;
3453
4725
  let currentRel = "";
3454
4726
  for (const part of parts) {
3455
- currentRel = currentRel ? path8.join(currentRel, part) : part;
4727
+ currentRel = currentRel ? path10.join(currentRel, part) : part;
3456
4728
  if (remoteDirCache.has(currentRel)) {
3457
4729
  currentParent = remoteDirCache.get(currentRel);
3458
4730
  continue;
@@ -3481,8 +4753,8 @@ var init_client = __esm({
3481
4753
  };
3482
4754
  await pool.map(allFiles, async (fileItem) => {
3483
4755
  try {
3484
- const relDir = path8.dirname(fileItem.relPath);
3485
- const fileName = path8.basename(fileItem.relPath);
4756
+ const relDir = path10.dirname(fileItem.relPath);
4757
+ const fileName = path10.basename(fileItem.relPath);
3486
4758
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3487
4759
  if (options.onFileStart) {
3488
4760
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3625,8 +4897,8 @@ var init_client = __esm({
3625
4897
  rejectDone = reject;
3626
4898
  });
3627
4899
  passThrough.done = donePromise;
3628
- const remoteDir = path8.dirname(remotePath);
3629
- const fileName = options.name || options.filename || path8.basename(remotePath);
4900
+ const remoteDir = path10.dirname(remotePath);
4901
+ const fileName = options.name || options.filename || path10.basename(remotePath);
3630
4902
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3631
4903
  const mimeType = options.mimeType || "application/octet-stream";
3632
4904
  const raw = this.driveClient;
@@ -3859,6 +5131,47 @@ var init_client = __esm({
3859
5131
  const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3860
5132
  return await startWebDAVServer2(this, options);
3861
5133
  }
5134
+ /**
5135
+ * Performs an intelligent two-way bidirectional sync between local and Google Drive directories
5136
+ */
5137
+ async syncBiDirectional(options) {
5138
+ await this.init();
5139
+ const engine = new BidirectionalSyncEngine(this);
5140
+ return await engine.sync(options);
5141
+ }
5142
+ /**
5143
+ * Starts an embedded S3-compatible HTTP gateway server
5144
+ */
5145
+ async serveS3(options = {}) {
5146
+ await this.init();
5147
+ const gateway = new S3GatewayServer(this, options);
5148
+ await gateway.start();
5149
+ return gateway;
5150
+ }
5151
+ /**
5152
+ * Scans Google Drive files and generates a security & permission audit report
5153
+ */
5154
+ async auditPermissions(options = {}) {
5155
+ await this.init();
5156
+ const auditor = new SecurityAuditor(this.driveClient);
5157
+ return await auditor.audit(options);
5158
+ }
5159
+ /**
5160
+ * Revokes public 'anyone' link permissions from the given files
5161
+ */
5162
+ async revokePublicPermissions(fileIds) {
5163
+ await this.init();
5164
+ const auditor = new SecurityAuditor(this.driveClient);
5165
+ return await auditor.revokePublicAccess(fileIds);
5166
+ }
5167
+ /**
5168
+ * Multi-word fuzzy and semantic search across files
5169
+ */
5170
+ async searchSmart(query, options = {}) {
5171
+ await this.init();
5172
+ const engine = new SmartSearchEngine(this);
5173
+ return await engine.search(query, options);
5174
+ }
3862
5175
  /**
3863
5176
  * Calculates local file MD5 hash for integrity and deduplication checks
3864
5177
  */
@@ -3879,8 +5192,8 @@ var init_client = __esm({
3879
5192
  init_esm_shims();
3880
5193
  init_client();
3881
5194
  init_format();
3882
- import fs7 from "fs";
3883
- import path9 from "path";
5195
+ import fs8 from "fs";
5196
+ import path11 from "path";
3884
5197
  import { Command } from "commander";
3885
5198
  import chalk2 from "chalk";
3886
5199
  import ora from "ora";
@@ -4041,10 +5354,10 @@ ${chalk.cyan("\u{1F517} Getting shareable link for:")} ${chalk.bold(item.name)}.
4041
5354
 
4042
5355
  // src/cli.ts
4043
5356
  var program = new Command();
4044
- var pkgVersion = "1.1.2";
5357
+ var pkgVersion = "1.2.0";
4045
5358
  try {
4046
5359
  const pkgPath = new URL("../package.json", import.meta.url);
4047
- const pkg = JSON.parse(fs7.readFileSync(pkgPath, "utf8"));
5360
+ const pkg = JSON.parse(fs8.readFileSync(pkgPath, "utf8"));
4048
5361
  if (pkg.version) pkgVersion = pkg.version;
4049
5362
  } catch {
4050
5363
  }
@@ -4053,10 +5366,10 @@ function getAuthConfig(cmdOptions) {
4053
5366
  const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
4054
5367
  let accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
4055
5368
  if (!keyFilePath && !accessToken) {
4056
- const tokensFile = path9.resolve(process.cwd(), "gdrive-tokens.json");
4057
- if (fs7.existsSync(tokensFile)) {
5369
+ const tokensFile = path11.resolve(process.cwd(), "gdrive-tokens.json");
5370
+ if (fs8.existsSync(tokensFile)) {
4058
5371
  try {
4059
- const tokens = JSON.parse(fs7.readFileSync(tokensFile, "utf8"));
5372
+ const tokens = JSON.parse(fs8.readFileSync(tokensFile, "utf8"));
4060
5373
  if (tokens.access_token) {
4061
5374
  accessToken = tokens.access_token;
4062
5375
  }
@@ -4133,11 +5446,11 @@ program.command("explore [folder]").description("Interactive terminal keyboard f
4133
5446
  }
4134
5447
  });
4135
5448
  program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").option("-d, --dedup", "Enable instant cloud deduplication via MD5 hash check").action(async (localFile, remotePath = "/", options) => {
4136
- if (!fs7.existsSync(localFile)) {
5449
+ if (!fs8.existsSync(localFile)) {
4137
5450
  console.error(chalk2.red(`\u274C Local file not found: ${localFile}`));
4138
5451
  process.exit(1);
4139
5452
  }
4140
- const fileName = path9.basename(localFile);
5453
+ const fileName = path11.basename(localFile);
4141
5454
  const spinner = ora(`Preparing upload: ${fileName}...`).start();
4142
5455
  try {
4143
5456
  const client = await getClient(options);
@@ -4233,7 +5546,7 @@ program.command("delete <fileIdOrPath>").description("Move a file/folder to tras
4233
5546
  }
4234
5547
  });
4235
5548
  program.command("sync <localDir> <remoteFolder>").description("Sync a local directory to Google Drive recursively with high concurrency").option("-c, --concurrency <number>", "Number of parallel uploads", "4").option("-o, --overwrite", "Overwrite files if they already exist").action(async (localDir, remoteFolder, options) => {
4236
- if (!fs7.existsSync(localDir)) {
5549
+ if (!fs8.existsSync(localDir)) {
4237
5550
  console.error(chalk2.red(`\u274C Local directory not found: ${localDir}`));
4238
5551
  process.exit(1);
4239
5552
  }
@@ -4401,8 +5714,8 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
4401
5714
  if (result.tokens.refresh_token) {
4402
5715
  console.log(`Refresh Token: ${chalk2.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
4403
5716
  }
4404
- const outPath = path9.resolve("./gdrive-tokens.json");
4405
- fs7.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
5717
+ const outPath = path11.resolve("./gdrive-tokens.json");
5718
+ fs8.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
4406
5719
  console.log(`\u{1F4BE} Saved tokens to: ${chalk2.bold(outPath)}
4407
5720
  `);
4408
5721
  } catch (err) {
@@ -4514,6 +5827,186 @@ program.command("serve").description("Start embedded WebDAV server to mount Driv
4514
5827
  process.exit(1);
4515
5828
  }
4516
5829
  });
5830
+ program.command("sync-2way <localDir> <remoteDir>").description("Two-way bidirectional synchronization with conflict resolution").option("-s, --strategy <strategy>", "Conflict strategy: rename-conflict, keep-newer, prefer-cloud, prefer-local", "rename-conflict").option("--delete-missing", "Propagate deletions in both directions").option("--dry-run", "Preview changes without modifying any files").action(async (localDir, remoteDir, options) => {
5831
+ console.log(chalk2.bold.cyan(`
5832
+ \u{1F504} Two-Way Sync: "${localDir}" \u21C4 "${remoteDir}"`));
5833
+ console.log(`Conflict Strategy: ${chalk2.yellow(options.strategy)} | Delete Missing: ${options.deleteMissing ? chalk2.red("YES") : chalk2.dim("NO")}
5834
+ `);
5835
+ try {
5836
+ const client = await getClient(options);
5837
+ const res = await client.syncBiDirectional({
5838
+ localDir: path11.resolve(localDir),
5839
+ remoteDir,
5840
+ conflictStrategy: options.strategy,
5841
+ deleteMissing: !!options.deleteMissing,
5842
+ dryRun: !!options.dryRun,
5843
+ onProgress: (ev) => {
5844
+ const actionColors = {
5845
+ upload: chalk2.green("[UPLOAD]"),
5846
+ download: chalk2.blue("[DOWNLOAD]"),
5847
+ "delete-local": chalk2.red("[DELETE LOCAL]"),
5848
+ "delete-remote": chalk2.red("[DELETE REMOTE]"),
5849
+ "conflict-resolved": chalk2.yellow("[CONFLICT]"),
5850
+ "skip-identical": chalk2.dim("[IDENTICAL]")
5851
+ };
5852
+ const prefix = actionColors[ev.action] || `[${ev.action}]`;
5853
+ console.log(` ${prefix} ${chalk2.white(ev.relPath)} ${ev.details ? chalk2.dim(`(${ev.details})`) : ""}`);
5854
+ }
5855
+ });
5856
+ console.log(chalk2.bold.green(`
5857
+ \u2705 Two-Way Sync Completed in ${(res.durationMs / 1e3).toFixed(2)}s!`));
5858
+ console.log(` \u2B06\uFE0F Uploaded: ${chalk2.bold(res.uploaded.length)}`);
5859
+ console.log(` \u2B07\uFE0F Downloaded: ${chalk2.bold(res.downloaded.length)}`);
5860
+ console.log(` \u{1F5D1}\uFE0F Deleted Local: ${chalk2.bold(res.deletedLocal.length)}`);
5861
+ console.log(` \u{1F5D1}\uFE0F Deleted Remote:${chalk2.bold(res.deletedRemote.length)}`);
5862
+ console.log(` \u26A1 Conflicts: ${chalk2.bold(res.conflicts.length)}`);
5863
+ console.log(` \u23ED\uFE0F Identical: ${chalk2.bold(res.skipped.length)}
5864
+ `);
5865
+ } catch (err) {
5866
+ console.error(chalk2.red(`
5867
+ Two-Way sync failed: ${err.message}`));
5868
+ process.exit(1);
5869
+ }
5870
+ });
5871
+ program.command("serve-s3").description("Start S3-compatible HTTP gateway server to treat Drive as an S3 Bucket").option("-p, --port <port>", "Port number to listen on", "9000").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").option("-b, --bucket-root <path>", "Virtual path root for S3 buckets", "/").option("--key <accessKey>", "Optional S3 access key ID").option("--secret <secretKey>", "Optional S3 secret access key").action(async (options) => {
5872
+ try {
5873
+ const client = await getClient(options);
5874
+ const port = parseInt(options.port, 10) || 9e3;
5875
+ const host = options.host || "127.0.0.1";
5876
+ console.log(chalk2.bold.cyan("\n\u{1F4E6} DriveKit S3-Compatible Gateway"));
5877
+ console.log("Starting S3 REST API bridge to Google Drive...\n");
5878
+ const gateway = await client.serveS3({
5879
+ port,
5880
+ host,
5881
+ bucketRoot: options.bucketRoot,
5882
+ accessKeyId: options.key,
5883
+ secretAccessKey: options.secret
5884
+ });
5885
+ console.log(chalk2.bold.green(`\u{1F680} S3 Gateway active at: ${chalk2.underline(`http://${host}:${port}`)}`));
5886
+ console.log(chalk2.white("\n\u{1F4CC} Connect with AWS CLI:"));
5887
+ console.log(chalk2.yellow(` aws s3 ls --endpoint-url http://${host}:${port}`));
5888
+ console.log(chalk2.white("\u{1F4CC} Connect with MinIO client:"));
5889
+ console.log(chalk2.yellow(` mc alias set drivekit http://${host}:${port} ${options.key || "dummy"} ${options.secret || "dummy"}
5890
+ `));
5891
+ console.log(chalk2.dim("Press Ctrl+C to stop the S3 Gateway.\n"));
5892
+ process.on("SIGINT", async () => {
5893
+ await gateway.stop();
5894
+ console.log(chalk2.yellow("\nS3 Gateway stopped. Goodbye!"));
5895
+ process.exit(0);
5896
+ });
5897
+ } catch (err) {
5898
+ console.error(chalk2.red(`Failed to start S3 gateway: ${err.message}`));
5899
+ process.exit(1);
5900
+ }
5901
+ });
5902
+ program.command("audit").description("Audit Drive security & permissions: detect public leaks and external shares").option("-l, --limit <count>", "Maximum files to scan", "200").option("--allowed-domains <domains>", "Comma-separated allowed organization domains").option("--revoke-public", 'Automatically revoke public "anyone" links').action(async (options) => {
5903
+ const spinner = ora("Auditing Google Drive permissions...").start();
5904
+ try {
5905
+ const client = await getClient(options);
5906
+ const limit = parseInt(options.limit, 10) || 200;
5907
+ const allowedDomains = options.allowedDomains ? options.allowedDomains.split(",").map((d) => d.trim()) : [];
5908
+ const report = await client.auditPermissions({ scanLimit: limit, allowedDomains });
5909
+ spinner.stop();
5910
+ console.log(chalk2.bold.cyan("\n\u{1F6E1}\uFE0F Google Drive Security & Permission Audit Report"));
5911
+ console.log(`Scanned files: ${chalk2.bold(report.totalScanned)} | Audit time: ${chalk2.dim(report.scannedAt)}
5912
+ `);
5913
+ console.log(`\u{1F310} Publicly Accessible (Anyone with Link): ${report.publicFilesCount > 0 ? chalk2.bold.red(report.publicFilesCount) : chalk2.green("0")}`);
5914
+ console.log(`\u{1F3E2} Organization Domain Shares: ${chalk2.yellow(report.domainSharedCount)}`);
5915
+ console.log(`\u{1F464} External Collaborators: ${report.externalSharesCount > 0 ? chalk2.bold.yellow(report.externalSharesCount) : chalk2.green("0")}
5916
+ `);
5917
+ if (report.issues.length > 0) {
5918
+ console.log(chalk2.bold.yellow("\u26A0\uFE0F Detected Security Issues:"));
5919
+ for (const issue of report.issues.slice(0, 30)) {
5920
+ const riskColor = issue.risk === "CRITICAL" ? chalk2.bold.bgRed : issue.risk === "HIGH" ? chalk2.red : chalk2.yellow;
5921
+ console.log(` ${riskColor(`[${issue.risk}]`)} ${chalk2.bold(issue.fileName)}`);
5922
+ console.log(` \u21B3 Reason: ${issue.reason}`);
5923
+ if (issue.webViewLink) console.log(` \u21B3 URL: ${chalk2.dim(issue.webViewLink)}`);
5924
+ }
5925
+ if (report.issues.length > 30) {
5926
+ console.log(chalk2.dim(`
5927
+ ... and ${report.issues.length - 30} more issues.`));
5928
+ }
5929
+ console.log("");
5930
+ } else {
5931
+ console.log(chalk2.green("\u2728 No critical security leaks detected!\n"));
5932
+ }
5933
+ if (options.revokePublic && report.publicFilesCount > 0) {
5934
+ const publicFileIds = Array.from(new Set(report.issues.filter((i) => i.type === "anyone").map((i) => i.fileId)));
5935
+ const revSpinner = ora(`Revoking public access on ${publicFileIds.length} files...`).start();
5936
+ const revRes = await client.revokePublicPermissions(publicFileIds);
5937
+ revSpinner.succeed(chalk2.green(`Successfully revoked public access on ${revRes.revoked.length} files!`));
5938
+ }
5939
+ } catch (err) {
5940
+ spinner.fail(chalk2.red(`Security audit failed: ${err.message}`));
5941
+ process.exit(1);
5942
+ }
5943
+ });
5944
+ program.command("revisions <fileIdOrPath>").description("List and manage historical file revisions").option("--keep-forever <revId>", "Pin a revision to prevent automatic purging after 30 days").option("--restore <revId>", "Restore file to a specific previous revision").action(async (fileIdOrPath, options) => {
5945
+ try {
5946
+ const client = await getClient(options);
5947
+ const revsManager = client.getRevisions(fileIdOrPath);
5948
+ if (options.keepForever) {
5949
+ const spinner2 = ora(`Pinning revision ${options.keepForever}...`).start();
5950
+ await revsManager.keepForever(options.keepForever, true);
5951
+ spinner2.succeed(chalk2.green(`Revision ${options.keepForever} is now pinned forever!`));
5952
+ return;
5953
+ }
5954
+ if (options.restore) {
5955
+ const spinner2 = ora(`Restoring file to revision ${options.restore}...`).start();
5956
+ await revsManager.restore(options.restore);
5957
+ spinner2.succeed(chalk2.green(`File content successfully restored to revision ${options.restore}!`));
5958
+ return;
5959
+ }
5960
+ const spinner = ora("Fetching revision history...").start();
5961
+ const revisions = await revsManager.list();
5962
+ spinner.stop();
5963
+ console.log(chalk2.bold.cyan(`
5964
+ \u{1F4DC} Revision History for "${fileIdOrPath}" (${revisions.length} versions):
5965
+ `));
5966
+ for (const r of revisions) {
5967
+ const pinned = r.keepForever ? chalk2.green("\u{1F4CC} [PINNED]") : chalk2.dim("[EXPIRABLE]");
5968
+ console.log(` ID: ${chalk2.bold.yellow(r.id.padEnd(20))} Modified: ${chalk2.white(r.modifiedTime || "unknown")} ${pinned} ${r.size ? formatBytes(r.size) : ""}`);
5969
+ }
5970
+ console.log("");
5971
+ } catch (err) {
5972
+ console.error(chalk2.red(`Failed to manage revisions: ${err.message}`));
5973
+ process.exit(1);
5974
+ }
5975
+ });
5976
+ program.command("search <query>").description("Search Google Drive files by name, description, or fuzzy matching").option("--smart", "Use multi-word fuzzy relevance scoring").option("-l, --limit <count>", "Maximum results to return", "20").action(async (query, options) => {
5977
+ const spinner = ora(`Searching for "${query}"...`).start();
5978
+ try {
5979
+ const client = await getClient(options);
5980
+ const limit = parseInt(options.limit, 10) || 20;
5981
+ if (options.smart) {
5982
+ const results = await client.searchSmart(query, { limit });
5983
+ spinner.stop();
5984
+ console.log(chalk2.bold.cyan(`
5985
+ \u{1F50D} Smart Search Results for "${query}" (${results.length}):
5986
+ `));
5987
+ for (const res of results) {
5988
+ const scorePercent = Math.round(res.score * 100);
5989
+ const scoreColor = scorePercent >= 80 ? chalk2.green : scorePercent >= 50 ? chalk2.yellow : chalk2.dim;
5990
+ console.log(` ${scoreColor(`[${scorePercent}%]`)} ${chalk2.bold(res.file.name)} ${chalk2.dim(`(Matched on: ${res.matchedOn.join(", ")})`)}`);
5991
+ console.log(` \u21B3 ID: ${chalk2.dim(res.file.id)} | Size: ${formatBytes(res.file.size ? parseInt(res.file.size, 10) : 0)}`);
5992
+ }
5993
+ console.log("");
5994
+ return;
5995
+ }
5996
+ const files = await client.query().nameContains(query).notTrashed().pageSize(limit).list();
5997
+ spinner.stop();
5998
+ console.log(chalk2.bold.cyan(`
5999
+ \u{1F50D} Found ${files.length} matching files:
6000
+ `));
6001
+ for (const f of files) {
6002
+ console.log(` \u{1F4C4} ${chalk2.white((f.name || "untitled").padEnd(35))} ${chalk2.dim(`ID: ${f.id}`)} [${formatBytes(f.size ? parseInt(f.size, 10) : 0)}]`);
6003
+ }
6004
+ console.log("");
6005
+ } catch (err) {
6006
+ spinner.fail(chalk2.red(`Search failed: ${err.message}`));
6007
+ process.exit(1);
6008
+ }
6009
+ });
4517
6010
  function runCLI() {
4518
6011
  program.parse(process.argv);
4519
6012
  }