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/index.cjs CHANGED
@@ -50,7 +50,7 @@ async function startWebDAVServer(drive2, options = {}) {
50
50
  const port = options.port || 8080;
51
51
  const host = options.host || "127.0.0.1";
52
52
  await drive2.init();
53
- const server = import_node_http3.default.createServer(async (req, res) => {
53
+ const server = import_node_http4.default.createServer(async (req, res) => {
54
54
  try {
55
55
  if (options.auth?.username && options.auth?.password) {
56
56
  const authHeader = req.headers["authorization"];
@@ -73,10 +73,11 @@ async function startWebDAVServer(drive2, options = {}) {
73
73
  return;
74
74
  }
75
75
  }
76
- const parsedUrl = import_node_url.default.parse(req.url || "/", true);
76
+ const parsedUrl = import_node_url2.default.parse(req.url || "/", true);
77
77
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
78
- const virtualPath = decodedPath === "" ? "/" : decodedPath;
79
- const baseName = import_node_path6.default.basename(virtualPath);
78
+ const normalizedPath = import_node_path8.default.posix.normalize(decodedPath);
79
+ const virtualPath = normalizedPath.startsWith("/") ? normalizedPath : `/${normalizedPath}`;
80
+ const baseName = import_node_path8.default.basename(virtualPath);
80
81
  if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
81
82
  res.writeHead(404, { "Content-Type": "text/plain" });
82
83
  res.end("Not Found");
@@ -165,7 +166,7 @@ async function startWebDAVServer(drive2, options = {}) {
165
166
  return;
166
167
  }
167
168
  case "PUT": {
168
- const remoteDir = import_node_path6.default.dirname(virtualPath);
169
+ const remoteDir = import_node_path8.default.dirname(virtualPath);
169
170
  await drive2.mkdirp(remoteDir);
170
171
  let existed = false;
171
172
  try {
@@ -226,16 +227,16 @@ async function startWebDAVServer(drive2, options = {}) {
226
227
  res.end("Source file not found");
227
228
  return;
228
229
  }
229
- const destUrl = import_node_url.default.parse(destination);
230
+ const destUrl = import_node_url2.default.parse(destination);
230
231
  const destPath = decodeURIComponent(destUrl.pathname || "");
231
- const newName = import_node_path6.default.basename(destPath);
232
- const newParentDir = import_node_path6.default.dirname(destPath);
232
+ const newName = import_node_path8.default.basename(destPath);
233
+ const newParentDir = import_node_path8.default.dirname(destPath);
233
234
  const newParentFolderId = await drive2.mkdirp(newParentDir);
234
- const currentParentDir = import_node_path6.default.dirname(virtualPath);
235
+ const currentParentDir = import_node_path8.default.dirname(virtualPath);
235
236
  if (newParentDir !== currentParentDir) {
236
237
  await drive2.move(file.id, newParentFolderId);
237
238
  }
238
- if (newName !== import_node_path6.default.basename(virtualPath)) {
239
+ if (newName !== import_node_path8.default.basename(virtualPath)) {
239
240
  await drive2.rename(file.id, newName);
240
241
  }
241
242
  res.writeHead(201);
@@ -260,10 +261,10 @@ async function startWebDAVServer(drive2, options = {}) {
260
261
  res.end("Source file not found");
261
262
  return;
262
263
  }
263
- const destUrl = import_node_url.default.parse(destination);
264
+ const destUrl = import_node_url2.default.parse(destination);
264
265
  const destPath = decodeURIComponent(destUrl.pathname || "");
265
- const newName = import_node_path6.default.basename(destPath);
266
- const newParentDir = import_node_path6.default.dirname(destPath);
266
+ const newName = import_node_path8.default.basename(destPath);
267
+ const newParentDir = import_node_path8.default.dirname(destPath);
267
268
  const newParentFolderId = await drive2.mkdirp(newParentDir);
268
269
  await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
269
270
  res.writeHead(201);
@@ -328,8 +329,8 @@ async function handlePropfind(drive2, virtualPath, depth) {
328
329
  if (seenNames.has(childName)) {
329
330
  const count = seenNames.get(childName) + 1;
330
331
  seenNames.set(childName, count);
331
- const ext = import_node_path6.default.extname(childName);
332
- const base = import_node_path6.default.basename(childName, ext);
332
+ const ext = import_node_path8.default.extname(childName);
333
+ const base = import_node_path8.default.basename(childName, ext);
333
334
  childName = `${base} (${count})${ext}`;
334
335
  } else {
335
336
  seenNames.set(childName, 0);
@@ -360,7 +361,7 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
360
361
  cleanHref += "/";
361
362
  }
362
363
  const encodedHref = encodeURI(cleanHref);
363
- const displayName = escapeXml(import_node_path6.default.basename(href) || "root");
364
+ const displayName = escapeXml(import_node_path8.default.basename(href) || "root");
364
365
  const resourceType = isDir ? "<D:collection/>" : "";
365
366
  const dateFormatted = new Date(modifiedTime).toUTCString();
366
367
  const contentTypeTag = !isDir && mimeType ? `
@@ -378,20 +379,21 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
378
379
  </D:propstat>
379
380
  </D:response>`;
380
381
  }
381
- var import_node_http3, import_node_url, import_node_path6;
382
+ var import_node_http4, import_node_url2, import_node_path8;
382
383
  var init_webdav = __esm({
383
384
  "src/server/webdav.ts"() {
384
385
  "use strict";
385
386
  init_cjs_shims();
386
- import_node_http3 = __toESM(require("http"), 1);
387
- import_node_url = __toESM(require("url"), 1);
388
- import_node_path6 = __toESM(require("path"), 1);
387
+ import_node_http4 = __toESM(require("http"), 1);
388
+ import_node_url2 = __toESM(require("url"), 1);
389
+ import_node_path8 = __toESM(require("path"), 1);
389
390
  }
390
391
  });
391
392
 
392
393
  // src/index.ts
393
394
  var index_exports = {};
394
395
  __export(index_exports, {
396
+ BidirectionalSyncEngine: () => BidirectionalSyncEngine,
395
397
  ConcurrencyPool: () => ConcurrencyPool,
396
398
  DEFAULT_CHUNK_SIZE: () => DEFAULT_CHUNK_SIZE,
397
399
  DEFAULT_EXPORT_MIMES: () => DEFAULT_EXPORT_MIMES,
@@ -400,8 +402,10 @@ __export(index_exports, {
400
402
  DriveAuthError: () => DriveAuthError,
401
403
  DriveAuthenticator: () => DriveAuthenticator,
402
404
  DriveFileRef: () => DriveFileRef,
405
+ DriveFileRevisions: () => DriveFileRevisions,
403
406
  DriveFolderRef: () => DriveFolderRef,
404
407
  DriveKit: () => DriveKit,
408
+ DriveKitCrypto: () => DriveKitCrypto,
405
409
  DriveKitError: () => DriveKitError,
406
410
  DriveNotFoundError: () => DriveNotFoundError,
407
411
  DriveQueryBuilder: () => DriveQueryBuilder,
@@ -409,20 +413,36 @@ __export(index_exports, {
409
413
  DriveUploadError: () => DriveUploadError,
410
414
  DriveWatcher: () => DriveWatcher,
411
415
  GOOGLE_WORKSPACE_MIME_TYPES: () => GOOGLE_WORKSPACE_MIME_TYPES,
416
+ IV_LENGTH: () => IV_LENGTH,
417
+ MAGIC_HEADER: () => MAGIC_HEADER,
418
+ MAGIC_STREAM_HEADER: () => MAGIC_STREAM_HEADER,
412
419
  MIN_CHUNK_SIZE: () => MIN_CHUNK_SIZE,
413
420
  MULTIPART_THRESHOLD: () => MULTIPART_THRESHOLD,
414
421
  MemoryMetadataCache: () => MemoryMetadataCache,
422
+ PBKDF2_ROUNDS: () => PBKDF2_ROUNDS,
415
423
  PathResolver: () => PathResolver,
416
424
  PluginManager: () => PluginManager,
417
425
  ResumableUploader: () => ResumableUploader,
426
+ S3GatewayServer: () => S3GatewayServer,
427
+ SALT_LENGTH: () => SALT_LENGTH,
428
+ SecurityAuditor: () => SecurityAuditor,
429
+ SmartSearchEngine: () => SmartSearchEngine,
418
430
  SmartSyncEngine: () => SmartSyncEngine,
419
431
  SqliteMetadataCache: () => SqliteMetadataCache,
420
432
  StorageCleaner: () => StorageCleaner,
433
+ TAG_LENGTH: () => TAG_LENGTH,
421
434
  calculateFileMd5: () => calculateFileMd5,
435
+ compressBuffer: () => compressBuffer,
436
+ cosineSimilarity: () => cosineSimilarity,
422
437
  createAutoNamePlugin: () => createAutoNamePlugin,
438
+ createCompressStream: () => createCompressStream,
439
+ createDecompressStream: () => createDecompressStream,
423
440
  createDrive: () => createDrive,
441
+ createDriveUploadMiddleware: () => createDriveUploadMiddleware,
424
442
  createWebhookPlugin: () => createWebhookPlugin,
443
+ decompressBuffer: () => decompressBuffer,
425
444
  default: () => index_default,
445
+ deriveKey: () => deriveKey,
426
446
  escapeXml: () => escapeXml,
427
447
  formatBytes: () => formatBytes,
428
448
  formatDuration: () => formatDuration,
@@ -431,7 +451,9 @@ __export(index_exports, {
431
451
  getFileIcon: () => getFileIcon,
432
452
  getOptimizedHttpAgent: () => getOptimizedHttpAgent,
433
453
  getOptimizedHttpsAgent: () => getOptimizedHttpsAgent,
454
+ handleNextJsUpload: () => handleNextJsUpload,
434
455
  isGoogleWorkspaceDoc: () => isGoogleWorkspaceDoc,
456
+ isGzipBuffer: () => isGzipBuffer,
435
457
  isRetryableError: () => isRetryableError,
436
458
  loginWithBrowser: () => loginWithBrowser,
437
459
  lookupMimeType: () => lookupMimeType,
@@ -446,8 +468,9 @@ init_cjs_shims();
446
468
 
447
469
  // src/core/client.ts
448
470
  init_cjs_shims();
449
- var import_node_fs6 = __toESM(require("fs"), 1);
450
- var import_node_path7 = __toESM(require("path"), 1);
471
+ var import_node_fs7 = __toESM(require("fs"), 1);
472
+ var import_node_path9 = __toESM(require("path"), 1);
473
+ var import_node_crypto3 = __toESM(require("crypto"), 1);
451
474
  var import_drive3 = require("@googleapis/drive");
452
475
 
453
476
  // src/auth/authenticator.ts
@@ -752,8 +775,8 @@ var PathResolver = class {
752
775
  /**
753
776
  * Gets cache key for a path
754
777
  */
755
- getCacheKey(path8) {
756
- return `${this.rootFolderId}:${this.normalizePath(path8)}`;
778
+ getCacheKey(path11) {
779
+ return `${this.rootFolderId}:${this.normalizePath(path11)}`;
757
780
  }
758
781
  /**
759
782
  * Clears the path cache
@@ -767,8 +790,8 @@ var PathResolver = class {
767
790
  /**
768
791
  * Invalidate a single path from cache
769
792
  */
770
- invalidatePath(path8) {
771
- const norm = this.normalizePath(path8);
793
+ invalidatePath(path11) {
794
+ const norm = this.normalizePath(path11);
772
795
  const key = this.getCacheKey(norm);
773
796
  this.cache.delete(key);
774
797
  if (this.metadataCache) {
@@ -2302,6 +2325,10 @@ var DriveFileRef = class {
2302
2325
  async getLink() {
2303
2326
  return await this.drive.getShareableLink(this.pathOrId);
2304
2327
  }
2328
+ /** Access historical revisions & version control for this file */
2329
+ get revisions() {
2330
+ return this.drive.getRevisions(this.pathOrId);
2331
+ }
2305
2332
  /** Returns a ReadableStream for this file, optionally with byte Range requests */
2306
2333
  async createReadStream(options) {
2307
2334
  return await this.drive.createReadStream(this.pathOrId, options);
@@ -2916,6 +2943,1185 @@ var MemoryMetadataCache = class {
2916
2943
  }
2917
2944
  };
2918
2945
 
2946
+ // src/crypto/encryption.ts
2947
+ init_cjs_shims();
2948
+ var import_node_crypto2 = __toESM(require("crypto"), 1);
2949
+ var import_node_stream3 = require("stream");
2950
+ var MAGIC_HEADER = Buffer.from("DKENC1", "utf8");
2951
+ var MAGIC_STREAM_HEADER = Buffer.from("DKENCS", "utf8");
2952
+ var SALT_LENGTH = 16;
2953
+ var IV_LENGTH = 12;
2954
+ var TAG_LENGTH = 16;
2955
+ var PBKDF2_ROUNDS = 1e5;
2956
+ function deriveKey(password, salt) {
2957
+ return import_node_crypto2.default.pbkdf2Sync(password, salt, PBKDF2_ROUNDS, 32, "sha512");
2958
+ }
2959
+ var DriveKitCrypto = class {
2960
+ config;
2961
+ constructor(config) {
2962
+ if (!config.password && !config.key) {
2963
+ throw new Error("DriveKitCrypto requires either a password or a 32-byte key.");
2964
+ }
2965
+ if (config.key && config.key.length !== 32) {
2966
+ throw new Error(`DriveKitCrypto raw key must be exactly 32 bytes, got ${config.key.length} bytes.`);
2967
+ }
2968
+ this.config = config;
2969
+ }
2970
+ /**
2971
+ * Encrypts a Buffer using AES-256-GCM.
2972
+ * Format: [MAGIC (6B)][SALT (16B)][IV (12B)][TAG (16B)][CIPHERTEXT]
2973
+ */
2974
+ encryptBuffer(data) {
2975
+ const salt = import_node_crypto2.default.randomBytes(SALT_LENGTH);
2976
+ const iv = import_node_crypto2.default.randomBytes(IV_LENGTH);
2977
+ const key = this.config.key || deriveKey(this.config.password, salt);
2978
+ const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
2979
+ const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
2980
+ const tag = cipher.getAuthTag();
2981
+ return Buffer.concat([MAGIC_HEADER, salt, iv, tag, ciphertext]);
2982
+ }
2983
+ /**
2984
+ * Decrypts a Buffer previously encrypted with encryptBuffer or createEncryptStream.
2985
+ */
2986
+ decryptBuffer(encryptedData) {
2987
+ if (encryptedData.length < MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH + TAG_LENGTH) {
2988
+ throw new Error("Encrypted payload is too short to be valid DriveKit ciphertext.");
2989
+ }
2990
+ const magic = encryptedData.subarray(0, MAGIC_HEADER.length);
2991
+ const isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
2992
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
2993
+ if (!isStreamFormat && !isBufferFormat) {
2994
+ throw new Error("Invalid magic header: file was not encrypted by DriveKit or is corrupted.");
2995
+ }
2996
+ const salt = encryptedData.subarray(6, 6 + SALT_LENGTH);
2997
+ const iv = encryptedData.subarray(6 + SALT_LENGTH, 6 + SALT_LENGTH + IV_LENGTH);
2998
+ const key = this.config.key || deriveKey(this.config.password, salt);
2999
+ let tag;
3000
+ let ciphertext;
3001
+ if (isStreamFormat) {
3002
+ tag = encryptedData.subarray(encryptedData.length - TAG_LENGTH);
3003
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, encryptedData.length - TAG_LENGTH);
3004
+ } else {
3005
+ tag = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, 6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
3006
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
3007
+ }
3008
+ const decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
3009
+ decipher.setAuthTag(tag);
3010
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
3011
+ }
3012
+ /**
3013
+ * Creates an encryption Transform stream that prepends stream header and appends GCM auth tag
3014
+ */
3015
+ createEncryptStream() {
3016
+ const salt = import_node_crypto2.default.randomBytes(SALT_LENGTH);
3017
+ const iv = import_node_crypto2.default.randomBytes(IV_LENGTH);
3018
+ const key = this.config.key || deriveKey(this.config.password, salt);
3019
+ const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
3020
+ let headerPushed = false;
3021
+ return new import_node_stream3.Transform({
3022
+ transform(chunk, _encoding, callback) {
3023
+ if (!headerPushed) {
3024
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
3025
+ headerPushed = true;
3026
+ }
3027
+ const encrypted = cipher.update(chunk);
3028
+ if (encrypted.length > 0) {
3029
+ this.push(encrypted);
3030
+ }
3031
+ callback();
3032
+ },
3033
+ flush(callback) {
3034
+ if (!headerPushed) {
3035
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
3036
+ headerPushed = true;
3037
+ }
3038
+ const finalChunk = cipher.final();
3039
+ const tag = cipher.getAuthTag();
3040
+ this.push(Buffer.concat([finalChunk, tag]));
3041
+ callback();
3042
+ }
3043
+ });
3044
+ }
3045
+ /**
3046
+ * Creates a decryption Transform stream that verifies magic header and validates GCM authentication tag
3047
+ */
3048
+ createDecryptStream() {
3049
+ const HEADER_BASE_LEN = MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH;
3050
+ let headerBuffer = Buffer.alloc(0);
3051
+ let decipher = null;
3052
+ let isStreamFormat = false;
3053
+ let pendingTail = Buffer.alloc(0);
3054
+ const self = this;
3055
+ return new import_node_stream3.Transform({
3056
+ transform(chunk, _encoding, callback) {
3057
+ try {
3058
+ let data = chunk;
3059
+ if (!decipher) {
3060
+ headerBuffer = Buffer.concat([headerBuffer, data]);
3061
+ if (headerBuffer.length < HEADER_BASE_LEN) {
3062
+ return callback();
3063
+ }
3064
+ const magic = headerBuffer.subarray(0, MAGIC_HEADER.length);
3065
+ isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
3066
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
3067
+ if (!isStreamFormat && !isBufferFormat) {
3068
+ return callback(new Error("Invalid magic header: stream was not encrypted by DriveKit or is corrupted."));
3069
+ }
3070
+ const salt = headerBuffer.subarray(MAGIC_HEADER.length, MAGIC_HEADER.length + SALT_LENGTH);
3071
+ const iv = headerBuffer.subarray(MAGIC_HEADER.length + SALT_LENGTH, HEADER_BASE_LEN);
3072
+ const key = self.config.key || deriveKey(self.config.password, salt);
3073
+ decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
3074
+ if (isBufferFormat) {
3075
+ if (headerBuffer.length < HEADER_BASE_LEN + TAG_LENGTH) {
3076
+ return callback();
3077
+ }
3078
+ const tag = headerBuffer.subarray(HEADER_BASE_LEN, HEADER_BASE_LEN + TAG_LENGTH);
3079
+ decipher.setAuthTag(tag);
3080
+ data = headerBuffer.subarray(HEADER_BASE_LEN + TAG_LENGTH);
3081
+ headerBuffer = Buffer.alloc(0);
3082
+ } else {
3083
+ data = headerBuffer.subarray(HEADER_BASE_LEN);
3084
+ headerBuffer = Buffer.alloc(0);
3085
+ }
3086
+ }
3087
+ if (data.length > 0) {
3088
+ if (isStreamFormat) {
3089
+ pendingTail = Buffer.concat([pendingTail, data]);
3090
+ if (pendingTail.length > TAG_LENGTH) {
3091
+ const toProcess = pendingTail.subarray(0, pendingTail.length - TAG_LENGTH);
3092
+ pendingTail = pendingTail.subarray(pendingTail.length - TAG_LENGTH);
3093
+ const decryptedChunk = decipher.update(toProcess);
3094
+ if (decryptedChunk.length > 0) {
3095
+ this.push(decryptedChunk);
3096
+ }
3097
+ }
3098
+ } else {
3099
+ const decryptedChunk = decipher.update(data);
3100
+ if (decryptedChunk.length > 0) {
3101
+ this.push(decryptedChunk);
3102
+ }
3103
+ }
3104
+ }
3105
+ callback();
3106
+ } catch (err) {
3107
+ callback(err);
3108
+ }
3109
+ },
3110
+ flush(callback) {
3111
+ try {
3112
+ if (!decipher) {
3113
+ return callback(new Error("Encrypted stream is too short: missing header."));
3114
+ }
3115
+ if (isStreamFormat) {
3116
+ if (pendingTail.length !== TAG_LENGTH) {
3117
+ return callback(new Error("Encrypted stream is truncated: missing authentication tag."));
3118
+ }
3119
+ decipher.setAuthTag(pendingTail);
3120
+ }
3121
+ const finalChunk = decipher.final();
3122
+ if (finalChunk.length > 0) {
3123
+ this.push(finalChunk);
3124
+ }
3125
+ callback();
3126
+ } catch (err) {
3127
+ callback(new Error(`Authentication failed: corrupted data or invalid authentication tag (${err.message})`));
3128
+ }
3129
+ }
3130
+ });
3131
+ }
3132
+ /**
3133
+ * Encrypts a filename into a safe base64url string
3134
+ */
3135
+ encryptFilename(plainName) {
3136
+ const iv = import_node_crypto2.default.randomBytes(12);
3137
+ const salt = import_node_crypto2.default.randomBytes(8);
3138
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
3139
+ const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
3140
+ const encrypted = Buffer.concat([cipher.update(Buffer.from(plainName, "utf8")), cipher.final()]);
3141
+ const tag = cipher.getAuthTag();
3142
+ const payload = Buffer.concat([salt, iv, tag, encrypted]);
3143
+ return `dk_${payload.toString("base64url")}.enc`;
3144
+ }
3145
+ /**
3146
+ * Decrypts a filename generated by encryptFilename
3147
+ */
3148
+ decryptFilename(encryptedName) {
3149
+ if (!encryptedName.startsWith("dk_") || !encryptedName.endsWith(".enc")) {
3150
+ return encryptedName;
3151
+ }
3152
+ try {
3153
+ const raw = encryptedName.slice(3, -4);
3154
+ const payload = Buffer.from(raw, "base64url");
3155
+ if (payload.length < 8 + 12 + 16) return encryptedName;
3156
+ const salt = payload.subarray(0, 8);
3157
+ const iv = payload.subarray(8, 20);
3158
+ const tag = payload.subarray(20, 36);
3159
+ const ciphertext = payload.subarray(36);
3160
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
3161
+ const decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
3162
+ decipher.setAuthTag(tag);
3163
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
3164
+ return decrypted.toString("utf8");
3165
+ } catch {
3166
+ return encryptedName;
3167
+ }
3168
+ }
3169
+ };
3170
+
3171
+ // src/core/revisions.ts
3172
+ init_cjs_shims();
3173
+ var DriveFileRevisions = class {
3174
+ drive;
3175
+ pathOrId;
3176
+ idResolver;
3177
+ constructor(drive2, pathOrId, idResolver) {
3178
+ this.drive = drive2;
3179
+ this.pathOrId = pathOrId;
3180
+ this.idResolver = idResolver;
3181
+ }
3182
+ async getId() {
3183
+ if (this.idResolver && (this.pathOrId.startsWith("/") || this.pathOrId.includes("/"))) {
3184
+ return await this.idResolver(this.pathOrId);
3185
+ }
3186
+ return this.pathOrId;
3187
+ }
3188
+ /**
3189
+ * Lists all historical revisions of the file
3190
+ */
3191
+ async list() {
3192
+ const fileId = await this.getId();
3193
+ const res = await withRetry(async () => {
3194
+ return await this.drive.revisions.list({
3195
+ fileId,
3196
+ fields: "revisions(id, mimeType, modifiedTime, keepForever, size, originalFilename)"
3197
+ });
3198
+ });
3199
+ const revs = res.data.revisions || [];
3200
+ return revs.map((r) => ({
3201
+ id: r.id,
3202
+ mimeType: r.mimeType || void 0,
3203
+ modifiedTime: r.modifiedTime || void 0,
3204
+ keepForever: r.keepForever ?? false,
3205
+ size: r.size ? parseInt(r.size, 10) : void 0,
3206
+ originalFilename: r.originalFilename || void 0
3207
+ }));
3208
+ }
3209
+ /**
3210
+ * Gets metadata for a specific revision
3211
+ */
3212
+ async get(revisionId) {
3213
+ const fileId = await this.getId();
3214
+ const res = await withRetry(async () => {
3215
+ return await this.drive.revisions.get({
3216
+ fileId,
3217
+ revisionId,
3218
+ fields: "id, mimeType, modifiedTime, keepForever, size, originalFilename"
3219
+ });
3220
+ });
3221
+ const r = res.data;
3222
+ return {
3223
+ id: r.id,
3224
+ mimeType: r.mimeType || void 0,
3225
+ modifiedTime: r.modifiedTime || void 0,
3226
+ keepForever: r.keepForever ?? false,
3227
+ size: r.size ? parseInt(r.size, 10) : void 0,
3228
+ originalFilename: r.originalFilename || void 0
3229
+ };
3230
+ }
3231
+ /**
3232
+ * Pins or unpins a revision so Google Drive never automatically purges it after 30 days
3233
+ */
3234
+ async keepForever(revisionId, keep = true) {
3235
+ const fileId = await this.getId();
3236
+ const res = await withRetry(async () => {
3237
+ return await this.drive.revisions.update({
3238
+ fileId,
3239
+ revisionId,
3240
+ requestBody: {
3241
+ keepForever: keep
3242
+ },
3243
+ fields: "id, keepForever, modifiedTime"
3244
+ });
3245
+ });
3246
+ return {
3247
+ id: res.data.id,
3248
+ keepForever: res.data.keepForever ?? keep,
3249
+ modifiedTime: res.data.modifiedTime || void 0
3250
+ };
3251
+ }
3252
+ /**
3253
+ * Deletes a specific historical revision
3254
+ */
3255
+ async delete(revisionId) {
3256
+ const fileId = await this.getId();
3257
+ await withRetry(async () => {
3258
+ return await this.drive.revisions.delete({
3259
+ fileId,
3260
+ revisionId
3261
+ });
3262
+ });
3263
+ }
3264
+ /**
3265
+ * Gets a readable stream of a specific historical revision
3266
+ */
3267
+ async getStream(revisionId) {
3268
+ const fileId = await this.getId();
3269
+ const res = await withRetry(async () => {
3270
+ return await this.drive.revisions.get(
3271
+ { fileId, revisionId, alt: "media" },
3272
+ { responseType: "stream" }
3273
+ );
3274
+ });
3275
+ return res.data;
3276
+ }
3277
+ /**
3278
+ * Restores the file content to a specific previous revision
3279
+ */
3280
+ async restore(revisionId) {
3281
+ const fileId = await this.getId();
3282
+ const stream = await this.getStream(revisionId);
3283
+ const meta = await this.get(revisionId);
3284
+ await withRetry(async () => {
3285
+ return await this.drive.files.update({
3286
+ fileId,
3287
+ media: {
3288
+ mimeType: meta.mimeType || "application/octet-stream",
3289
+ body: stream
3290
+ }
3291
+ });
3292
+ });
3293
+ }
3294
+ };
3295
+
3296
+ // src/core/bidirectional-sync.ts
3297
+ init_cjs_shims();
3298
+ var import_node_fs6 = __toESM(require("fs"), 1);
3299
+ var import_node_path6 = __toESM(require("path"), 1);
3300
+ var BidirectionalSyncEngine = class {
3301
+ drive;
3302
+ ledger = /* @__PURE__ */ new Map();
3303
+ constructor(drive2) {
3304
+ this.drive = drive2;
3305
+ }
3306
+ /**
3307
+ * Performs a two-way synchronization cycle between local and remote directories
3308
+ */
3309
+ async sync(options) {
3310
+ const startTime = Date.now();
3311
+ const {
3312
+ localDir,
3313
+ remoteDir,
3314
+ conflictStrategy = "rename-conflict",
3315
+ deleteMissing = false,
3316
+ dryRun = false,
3317
+ onProgress
3318
+ } = options;
3319
+ const result = {
3320
+ uploaded: [],
3321
+ downloaded: [],
3322
+ deletedLocal: [],
3323
+ deletedRemote: [],
3324
+ conflicts: [],
3325
+ skipped: [],
3326
+ durationMs: 0
3327
+ };
3328
+ if (!import_node_fs6.default.existsSync(localDir)) {
3329
+ await import_node_fs6.default.promises.mkdir(localDir, { recursive: true });
3330
+ }
3331
+ const remoteFolderId = await this.drive.mkdirp(remoteDir);
3332
+ const localFiles = await this.scanLocalDir(localDir);
3333
+ const remoteFiles = await this.scanRemoteDir(remoteFolderId, "");
3334
+ const allPaths = /* @__PURE__ */ new Set([
3335
+ ...localFiles.keys(),
3336
+ ...remoteFiles.keys(),
3337
+ ...this.ledger.keys()
3338
+ ]);
3339
+ for (const relPath of allPaths) {
3340
+ const resolvedLocal = import_node_path6.default.resolve(localDir, relPath);
3341
+ const resolvedRoot = import_node_path6.default.resolve(localDir);
3342
+ if (!resolvedLocal.startsWith(resolvedRoot + import_node_path6.default.sep) && resolvedLocal !== resolvedRoot) {
3343
+ throw new Error(`Security Violation: Path traversal detected in sync path: "${relPath}"`);
3344
+ }
3345
+ const local = localFiles.get(relPath);
3346
+ const remote = remoteFiles.get(relPath);
3347
+ const prev = this.ledger.get(relPath);
3348
+ if (local && remote) {
3349
+ const localChanged = !prev || local.md5 !== prev.localMd5 || Math.abs(local.mtime - prev.localMtime) > 1e3;
3350
+ const remoteChanged = !prev || remote.md5 !== prev.remoteMd5 || Math.abs(remote.mtime - prev.remoteMtime) > 1e3;
3351
+ if (local.md5 === remote.md5) {
3352
+ result.skipped.push(relPath);
3353
+ onProgress?.({ action: "skip-identical", relPath });
3354
+ this.ledger.set(relPath, {
3355
+ relPath,
3356
+ localMtime: local.mtime,
3357
+ remoteMtime: remote.mtime,
3358
+ localMd5: local.md5,
3359
+ remoteMd5: remote.md5,
3360
+ remoteId: remote.id
3361
+ });
3362
+ continue;
3363
+ }
3364
+ if (localChanged && !remoteChanged) {
3365
+ if (!dryRun) {
3366
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3367
+ const freshRemote = await this.drive.getFile(remote.id);
3368
+ this.updateLedger(relPath, local, freshRemote);
3369
+ }
3370
+ result.uploaded.push(relPath);
3371
+ onProgress?.({ action: "upload", relPath, details: "Local modification propagated" });
3372
+ continue;
3373
+ }
3374
+ if (remoteChanged && !localChanged) {
3375
+ if (!dryRun) {
3376
+ await this.downloadFile(remote.id, local.fullPath);
3377
+ const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
3378
+ this.ledger.set(relPath, {
3379
+ relPath,
3380
+ localMtime: freshStat.mtimeMs,
3381
+ remoteMtime: remote.mtime,
3382
+ localMd5: remote.md5,
3383
+ remoteMd5: remote.md5,
3384
+ remoteId: remote.id
3385
+ });
3386
+ }
3387
+ result.downloaded.push(relPath);
3388
+ onProgress?.({ action: "download", relPath, details: "Remote modification propagated" });
3389
+ continue;
3390
+ }
3391
+ result.conflicts.push(relPath);
3392
+ onProgress?.({ action: "conflict-resolved", relPath, details: `Strategy: ${conflictStrategy}` });
3393
+ if (!dryRun) {
3394
+ if (conflictStrategy === "prefer-local") {
3395
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3396
+ const freshRemote = await this.drive.getFile(remote.id);
3397
+ this.updateLedger(relPath, local, freshRemote);
3398
+ result.uploaded.push(relPath);
3399
+ } else if (conflictStrategy === "prefer-cloud") {
3400
+ await this.downloadFile(remote.id, local.fullPath);
3401
+ const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
3402
+ this.ledger.set(relPath, {
3403
+ relPath,
3404
+ localMtime: freshStat.mtimeMs,
3405
+ remoteMtime: remote.mtime,
3406
+ localMd5: remote.md5,
3407
+ remoteMd5: remote.md5,
3408
+ remoteId: remote.id
3409
+ });
3410
+ result.downloaded.push(relPath);
3411
+ } else if (conflictStrategy === "keep-newer") {
3412
+ if (local.mtime >= remote.mtime) {
3413
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3414
+ const freshRemote = await this.drive.getFile(remote.id);
3415
+ this.updateLedger(relPath, local, freshRemote);
3416
+ result.uploaded.push(relPath);
3417
+ } else {
3418
+ await this.downloadFile(remote.id, local.fullPath);
3419
+ const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
3420
+ this.ledger.set(relPath, {
3421
+ relPath,
3422
+ localMtime: freshStat.mtimeMs,
3423
+ remoteMtime: remote.mtime,
3424
+ localMd5: remote.md5,
3425
+ remoteMd5: remote.md5,
3426
+ remoteId: remote.id
3427
+ });
3428
+ result.downloaded.push(relPath);
3429
+ }
3430
+ } else {
3431
+ const ext = import_node_path6.default.extname(relPath);
3432
+ const base = relPath.slice(0, relPath.length - ext.length);
3433
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3434
+ const conflictRelPath = `${base} (Conflict ${timestamp})${ext}`;
3435
+ const conflictFullPath = import_node_path6.default.join(localDir, conflictRelPath);
3436
+ await this.downloadFile(remote.id, conflictFullPath);
3437
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3438
+ const freshRemote = await this.drive.getFile(remote.id);
3439
+ this.updateLedger(relPath, local, freshRemote);
3440
+ }
3441
+ }
3442
+ continue;
3443
+ }
3444
+ if (local && !remote) {
3445
+ if (prev && deleteMissing) {
3446
+ if (!dryRun) {
3447
+ await import_node_fs6.default.promises.unlink(local.fullPath);
3448
+ this.ledger.delete(relPath);
3449
+ }
3450
+ result.deletedLocal.push(relPath);
3451
+ onProgress?.({ action: "delete-local", relPath, details: "Deleted remotely" });
3452
+ } else {
3453
+ if (!dryRun) {
3454
+ const uploadedFile = await this.uploadFile(local.fullPath, remoteDir, relPath);
3455
+ this.updateLedger(relPath, local, uploadedFile);
3456
+ }
3457
+ result.uploaded.push(relPath);
3458
+ onProgress?.({ action: "upload", relPath, details: "New local file" });
3459
+ }
3460
+ continue;
3461
+ }
3462
+ if (!local && remote) {
3463
+ if (prev && deleteMissing) {
3464
+ if (!dryRun) {
3465
+ await this.drive.delete(remote.id, true);
3466
+ this.ledger.delete(relPath);
3467
+ }
3468
+ result.deletedRemote.push(relPath);
3469
+ onProgress?.({ action: "delete-remote", relPath, details: "Deleted locally" });
3470
+ } else {
3471
+ if (!dryRun) {
3472
+ const localDest = import_node_path6.default.join(localDir, relPath);
3473
+ await import_node_fs6.default.promises.mkdir(import_node_path6.default.dirname(localDest), { recursive: true });
3474
+ await this.downloadFile(remote.id, localDest);
3475
+ const stat = await import_node_fs6.default.promises.stat(localDest);
3476
+ this.ledger.set(relPath, {
3477
+ relPath,
3478
+ localMtime: stat.mtimeMs,
3479
+ remoteMtime: remote.mtime,
3480
+ localMd5: remote.md5,
3481
+ remoteMd5: remote.md5,
3482
+ remoteId: remote.id
3483
+ });
3484
+ }
3485
+ result.downloaded.push(relPath);
3486
+ onProgress?.({ action: "download", relPath, details: "New remote file" });
3487
+ }
3488
+ continue;
3489
+ }
3490
+ if (prev && !local && !remote) {
3491
+ this.ledger.delete(relPath);
3492
+ }
3493
+ }
3494
+ result.durationMs = Date.now() - startTime;
3495
+ return result;
3496
+ }
3497
+ async scanLocalDir(dir, baseDir = dir) {
3498
+ const map = /* @__PURE__ */ new Map();
3499
+ if (!import_node_fs6.default.existsSync(dir)) return map;
3500
+ const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
3501
+ for (const entry of entries) {
3502
+ const fullPath = import_node_path6.default.join(dir, entry.name);
3503
+ if (entry.isDirectory()) {
3504
+ const sub = await this.scanLocalDir(fullPath, baseDir);
3505
+ for (const [k, v] of sub) map.set(k, v);
3506
+ } else if (entry.isFile()) {
3507
+ const rel = import_node_path6.default.relative(baseDir, fullPath).replace(/\\/g, "/");
3508
+ const stat = await import_node_fs6.default.promises.stat(fullPath);
3509
+ const md5 = await calculateFileMd5(fullPath);
3510
+ map.set(rel, { fullPath, mtime: stat.mtimeMs, md5 });
3511
+ }
3512
+ }
3513
+ return map;
3514
+ }
3515
+ async scanRemoteDir(folderId, relPrefix) {
3516
+ const map = /* @__PURE__ */ new Map();
3517
+ const items = await this.drive.query().inFolder(folderId).notTrashed().list();
3518
+ for (const item of items) {
3519
+ if (!item.id || !item.name) continue;
3520
+ const cleanName = import_node_path6.default.basename(item.name.replace(/\\/g, "/")).replace(/\0/g, "");
3521
+ if (!cleanName || cleanName === "." || cleanName === "..") continue;
3522
+ const relPath = relPrefix ? `${relPrefix}/${cleanName}` : cleanName;
3523
+ if (item.mimeType === "application/vnd.google-apps.folder") {
3524
+ const sub = await this.scanRemoteDir(item.id, relPath);
3525
+ for (const [k, v] of sub) map.set(k, v);
3526
+ } else {
3527
+ const mtime = item.modifiedTime ? new Date(item.modifiedTime).getTime() : 0;
3528
+ map.set(relPath, {
3529
+ id: item.id,
3530
+ name: item.name,
3531
+ mtime,
3532
+ md5: item.md5Checksum || ""
3533
+ });
3534
+ }
3535
+ }
3536
+ return map;
3537
+ }
3538
+ async uploadFile(localPath, remoteDir, relPath) {
3539
+ const remoteSubDir = import_node_path6.default.dirname(relPath);
3540
+ const targetFolder = remoteSubDir === "." ? remoteDir : `${remoteDir}/${remoteSubDir}`;
3541
+ return await this.drive.upload({
3542
+ source: localPath,
3543
+ name: import_node_path6.default.basename(relPath),
3544
+ parent: targetFolder,
3545
+ overwrite: true
3546
+ });
3547
+ }
3548
+ async downloadFile(fileId, destPath) {
3549
+ await import_node_fs6.default.promises.mkdir(import_node_path6.default.dirname(destPath), { recursive: true });
3550
+ await this.drive.download(fileId, { destination: destPath });
3551
+ }
3552
+ updateLedger(relPath, local, remote) {
3553
+ this.ledger.set(relPath, {
3554
+ relPath,
3555
+ localMtime: local.mtime,
3556
+ remoteMtime: remote.modifiedTime ? new Date(remote.modifiedTime).getTime() : Date.now(),
3557
+ localMd5: local.md5,
3558
+ remoteMd5: remote.md5Checksum || local.md5,
3559
+ remoteId: remote.id
3560
+ });
3561
+ }
3562
+ };
3563
+
3564
+ // src/server/s3-gateway.ts
3565
+ init_cjs_shims();
3566
+ var import_node_http3 = __toESM(require("http"), 1);
3567
+ var import_node_path7 = __toESM(require("path"), 1);
3568
+ var import_node_url = require("url");
3569
+ var S3GatewayServer = class {
3570
+ drive;
3571
+ options;
3572
+ server = null;
3573
+ constructor(drive2, options = {}) {
3574
+ this.drive = drive2;
3575
+ this.options = {
3576
+ port: options.port || 9e3,
3577
+ host: options.host || "127.0.0.1",
3578
+ bucketRoot: options.bucketRoot || "/",
3579
+ ...options
3580
+ };
3581
+ }
3582
+ /**
3583
+ * Starts the S3 gateway HTTP server
3584
+ */
3585
+ async start() {
3586
+ return new Promise((resolve, reject) => {
3587
+ this.server = import_node_http3.default.createServer(async (req, res) => {
3588
+ try {
3589
+ await this.handleRequest(req, res);
3590
+ } catch (err) {
3591
+ this.sendXmlError(res, 500, "InternalError", err.message || "Internal S3 Gateway Error");
3592
+ }
3593
+ });
3594
+ this.server.on("error", reject);
3595
+ this.server.listen(this.options.port, this.options.host, () => {
3596
+ resolve({ port: this.options.port, host: this.options.host });
3597
+ });
3598
+ });
3599
+ }
3600
+ /**
3601
+ * Stops the S3 gateway HTTP server
3602
+ */
3603
+ async stop() {
3604
+ return new Promise((resolve) => {
3605
+ if (this.server) {
3606
+ this.server.close(() => resolve());
3607
+ } else {
3608
+ resolve();
3609
+ }
3610
+ });
3611
+ }
3612
+ async handleRequest(req, res) {
3613
+ const parsed = (0, import_node_url.parse)(req.url || "/", true);
3614
+ const rawPathname = decodeURIComponent(parsed.pathname || "/");
3615
+ const pathname = import_node_path7.default.posix.normalize(rawPathname);
3616
+ if (rawPathname.includes("..") || pathname.includes("..") || pathname === ".") {
3617
+ this.sendXmlError(res, 400, "InvalidURI", "Path traversal characters are not permitted");
3618
+ return;
3619
+ }
3620
+ const method = req.method?.toUpperCase() || "GET";
3621
+ if (this.options.accessKeyId) {
3622
+ const authHeader = req.headers["authorization"];
3623
+ if (!authHeader || !authHeader.includes(this.options.accessKeyId)) {
3624
+ res.setHeader("WWW-Authenticate", "AWS4-HMAC-SHA256");
3625
+ this.sendXmlError(res, 403, "AccessDenied", "Invalid or missing AWS credentials");
3626
+ return;
3627
+ }
3628
+ }
3629
+ const segments = pathname.split("/").filter(Boolean);
3630
+ if (segments.some((s) => s === ".." || s === ".")) {
3631
+ this.sendXmlError(res, 400, "InvalidURI", "Invalid path segment");
3632
+ return;
3633
+ }
3634
+ if (segments.length === 0) {
3635
+ if (method === "GET") {
3636
+ await this.handleListBuckets(res);
3637
+ return;
3638
+ }
3639
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on root");
3640
+ return;
3641
+ }
3642
+ const bucket = segments[0];
3643
+ const key = segments.slice(1).join("/");
3644
+ if (!key) {
3645
+ if (method === "GET") {
3646
+ const prefix = parsed.query.prefix || "";
3647
+ await this.handleListObjects(bucket, prefix, res);
3648
+ return;
3649
+ }
3650
+ if (method === "PUT") {
3651
+ await this.drive.mkdirp(`/${bucket}`);
3652
+ res.statusCode = 200;
3653
+ res.end();
3654
+ return;
3655
+ }
3656
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on bucket");
3657
+ return;
3658
+ }
3659
+ const remotePath = `/${bucket}/${key}`;
3660
+ if (method === "HEAD") {
3661
+ try {
3662
+ const file = await this.drive.getFile(remotePath);
3663
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3664
+ res.setHeader("Content-Length", file.size || "0");
3665
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3666
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3667
+ res.statusCode = 200;
3668
+ res.end();
3669
+ } catch {
3670
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3671
+ }
3672
+ return;
3673
+ }
3674
+ if (method === "GET") {
3675
+ try {
3676
+ const file = await this.drive.getFile(remotePath);
3677
+ const range = req.headers["range"];
3678
+ let options = void 0;
3679
+ if (range && range.startsWith("bytes=")) {
3680
+ const parts = range.replace("bytes=", "").split("-");
3681
+ options = {
3682
+ start: parts[0] ? parseInt(parts[0], 10) : 0,
3683
+ end: parts[1] ? parseInt(parts[1], 10) : void 0
3684
+ };
3685
+ res.statusCode = 206;
3686
+ const end = options.end !== void 0 ? options.end : parseInt(file.size || "0", 10) - 1;
3687
+ res.setHeader("Content-Range", `bytes ${options.start}-${end}/${file.size}`);
3688
+ } else {
3689
+ res.statusCode = 200;
3690
+ }
3691
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3692
+ res.setHeader("Content-Length", file.size || "0");
3693
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3694
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3695
+ const stream = await this.drive.createReadStream(remotePath, options);
3696
+ stream.pipe(res);
3697
+ } catch {
3698
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3699
+ }
3700
+ return;
3701
+ }
3702
+ if (method === "PUT") {
3703
+ const upload = await this.drive.createWriteStream(remotePath);
3704
+ req.pipe(upload);
3705
+ try {
3706
+ const file = await upload.done;
3707
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3708
+ res.statusCode = 200;
3709
+ res.end();
3710
+ } catch (err) {
3711
+ this.sendXmlError(res, 500, "InternalError", err.message);
3712
+ }
3713
+ return;
3714
+ }
3715
+ if (method === "DELETE") {
3716
+ try {
3717
+ const file = await this.drive.resolvePath(remotePath);
3718
+ await this.drive.delete(file.id, true);
3719
+ res.statusCode = 204;
3720
+ res.end();
3721
+ } catch {
3722
+ res.statusCode = 204;
3723
+ res.end();
3724
+ }
3725
+ return;
3726
+ }
3727
+ this.sendXmlError(res, 405, "MethodNotAllowed", `HTTP method ${method} not allowed`);
3728
+ }
3729
+ async handleListBuckets(res) {
3730
+ const items = await this.drive.ls("/");
3731
+ const folders = items.filter((i) => i.mimeType === "application/vnd.google-apps.folder");
3732
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3733
+ xml += " <Buckets>\n";
3734
+ for (const f of folders) {
3735
+ xml += " <Bucket>\n";
3736
+ xml += ` <Name>${this.escapeXml(f.name || "bucket")}</Name>
3737
+ `;
3738
+ xml += ` <CreationDate>${f.createdTime || (/* @__PURE__ */ new Date()).toISOString()}</CreationDate>
3739
+ `;
3740
+ xml += " </Bucket>\n";
3741
+ }
3742
+ xml += " </Buckets>\n</ListAllMyBucketsResult>";
3743
+ res.setHeader("Content-Type", "application/xml");
3744
+ res.statusCode = 200;
3745
+ res.end(xml);
3746
+ }
3747
+ async handleListObjects(bucket, prefix, res) {
3748
+ const targetPath = `/${bucket}${prefix ? `/${prefix}` : ""}`;
3749
+ let items = [];
3750
+ try {
3751
+ items = await this.drive.ls(targetPath);
3752
+ } catch {
3753
+ items = [];
3754
+ }
3755
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3756
+ xml += ` <Name>${this.escapeXml(bucket)}</Name>
3757
+ `;
3758
+ xml += ` <Prefix>${this.escapeXml(prefix)}</Prefix>
3759
+ `;
3760
+ xml += " <IsTruncated>false</IsTruncated>\n";
3761
+ for (const item of items) {
3762
+ if (item.mimeType === "application/vnd.google-apps.folder") continue;
3763
+ const key = prefix ? `${prefix}/${item.name}` : item.name;
3764
+ xml += " <Contents>\n";
3765
+ xml += ` <Key>${this.escapeXml(key)}</Key>
3766
+ `;
3767
+ xml += ` <LastModified>${item.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()}</LastModified>
3768
+ `;
3769
+ xml += ` <ETag>"${item.md5Checksum || item.id}"</ETag>
3770
+ `;
3771
+ xml += ` <Size>${item.size || 0}</Size>
3772
+ `;
3773
+ xml += " <StorageClass>STANDARD</StorageClass>\n";
3774
+ xml += " </Contents>\n";
3775
+ }
3776
+ xml += "</ListBucketResult>";
3777
+ res.setHeader("Content-Type", "application/xml");
3778
+ res.statusCode = 200;
3779
+ res.end(xml);
3780
+ }
3781
+ sendXmlError(res, status, code, message) {
3782
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
3783
+ <Error>
3784
+ <Code>${this.escapeXml(code)}</Code>
3785
+ <Message>${this.escapeXml(message)}</Message>
3786
+ </Error>`;
3787
+ res.setHeader("Content-Type", "application/xml");
3788
+ res.statusCode = status;
3789
+ res.end(xml);
3790
+ }
3791
+ escapeXml(unsafe) {
3792
+ return unsafe.replace(/[<>&'"]/g, (c) => {
3793
+ switch (c) {
3794
+ case "<":
3795
+ return "&lt;";
3796
+ case ">":
3797
+ return "&gt;";
3798
+ case "&":
3799
+ return "&amp;";
3800
+ case "'":
3801
+ return "&apos;";
3802
+ case '"':
3803
+ return "&quot;";
3804
+ default:
3805
+ return c;
3806
+ }
3807
+ });
3808
+ }
3809
+ };
3810
+
3811
+ // src/core/security-auditor.ts
3812
+ init_cjs_shims();
3813
+ var SecurityAuditor = class {
3814
+ drive;
3815
+ constructor(drive2) {
3816
+ this.drive = drive2;
3817
+ }
3818
+ /**
3819
+ * Scans Google Drive files and audits their permission grants
3820
+ */
3821
+ async audit(options = {}) {
3822
+ const limit = options.scanLimit || 500;
3823
+ const allowedDomains = new Set((options.allowedDomains || []).map((d) => d.toLowerCase()));
3824
+ const issues = [];
3825
+ let publicCount = 0;
3826
+ let domainCount = 0;
3827
+ let externalCount = 0;
3828
+ let scannedTotal = 0;
3829
+ let pageToken = void 0;
3830
+ do {
3831
+ const res = await withRetry(async () => {
3832
+ return await this.drive.files.list({
3833
+ q: "trashed = false",
3834
+ fields: "nextPageToken, files(id, name, mimeType, webViewLink, shared, permissions(id, type, role, emailAddress, domain))",
3835
+ pageSize: Math.min(100, limit - scannedTotal),
3836
+ supportsAllDrives: true,
3837
+ includeItemsFromAllDrives: true,
3838
+ pageToken
3839
+ });
3840
+ });
3841
+ const files = res.data.files || [];
3842
+ for (const file of files) {
3843
+ if (!file.id || !file.name) continue;
3844
+ scannedTotal++;
3845
+ const perms = file.permissions || [];
3846
+ for (const p of perms) {
3847
+ if (p.type === "anyone") {
3848
+ publicCount++;
3849
+ const isCritical = ["writer", "owner", "organizer", "fileOrganizer"].includes(p.role || "");
3850
+ issues.push({
3851
+ fileId: file.id,
3852
+ fileName: file.name,
3853
+ risk: isCritical ? "CRITICAL" : "HIGH",
3854
+ reason: `Publicly accessible to anyone (${p.role} access)`,
3855
+ permissionId: p.id,
3856
+ type: p.type,
3857
+ role: p.role || "reader",
3858
+ webViewLink: file.webViewLink || void 0
3859
+ });
3860
+ continue;
3861
+ }
3862
+ if (p.type === "domain") {
3863
+ domainCount++;
3864
+ issues.push({
3865
+ fileId: file.id,
3866
+ fileName: file.name,
3867
+ risk: "MEDIUM",
3868
+ reason: `Shared with entire organization domain (${p.domain})`,
3869
+ permissionId: p.id,
3870
+ type: p.type,
3871
+ role: p.role || "reader",
3872
+ domain: p.domain || void 0,
3873
+ webViewLink: file.webViewLink || void 0
3874
+ });
3875
+ continue;
3876
+ }
3877
+ if (p.type === "user" && p.emailAddress && allowedDomains.size > 0) {
3878
+ const userDomain = p.emailAddress.split("@")[1]?.toLowerCase();
3879
+ if (userDomain && !allowedDomains.has(userDomain)) {
3880
+ externalCount++;
3881
+ issues.push({
3882
+ fileId: file.id,
3883
+ fileName: file.name,
3884
+ risk: "HIGH",
3885
+ reason: `Shared with external user outside allowed domains: ${p.emailAddress}`,
3886
+ permissionId: p.id,
3887
+ type: p.type,
3888
+ role: p.role || "reader",
3889
+ emailAddress: p.emailAddress,
3890
+ webViewLink: file.webViewLink || void 0
3891
+ });
3892
+ }
3893
+ }
3894
+ }
3895
+ }
3896
+ pageToken = res.data.nextPageToken || void 0;
3897
+ } while (pageToken && scannedTotal < limit);
3898
+ return {
3899
+ totalScanned: scannedTotal,
3900
+ publicFilesCount: publicCount,
3901
+ domainSharedCount: domainCount,
3902
+ externalSharesCount: externalCount,
3903
+ issues,
3904
+ scannedAt: (/* @__PURE__ */ new Date()).toISOString()
3905
+ };
3906
+ }
3907
+ /**
3908
+ * Revokes public 'anyone' permissions on specified files
3909
+ */
3910
+ async revokePublicAccess(fileIds) {
3911
+ const revoked = [];
3912
+ const errors = [];
3913
+ for (const fileId of fileIds) {
3914
+ try {
3915
+ const fileRes = await withRetry(async () => {
3916
+ return await this.drive.files.get({
3917
+ fileId,
3918
+ fields: "id, permissions(id, type)",
3919
+ supportsAllDrives: true
3920
+ });
3921
+ });
3922
+ const publicPerms = (fileRes.data.permissions || []).filter((p) => p.type === "anyone");
3923
+ for (const p of publicPerms) {
3924
+ if (p.id) {
3925
+ await withRetry(async () => {
3926
+ return await this.drive.permissions.delete({
3927
+ fileId,
3928
+ permissionId: p.id,
3929
+ supportsAllDrives: true
3930
+ });
3931
+ });
3932
+ }
3933
+ }
3934
+ revoked.push(fileId);
3935
+ } catch (err) {
3936
+ errors.push({ fileId, error: err.message });
3937
+ }
3938
+ }
3939
+ return { revoked, errors };
3940
+ }
3941
+ };
3942
+
3943
+ // src/core/semantic-search.ts
3944
+ init_cjs_shims();
3945
+ function levenshtein(a, b) {
3946
+ const an = a.length;
3947
+ const bn = b.length;
3948
+ if (an === 0) return bn;
3949
+ if (bn === 0) return an;
3950
+ const matrix = Array.from({ length: bn + 1 }, (_, i) => [i]);
3951
+ for (let j = 0; j <= an; j++) matrix[0][j] = j;
3952
+ for (let i = 1; i <= bn; i++) {
3953
+ for (let j = 1; j <= an; j++) {
3954
+ if (b.charAt(i - 1) === a.charAt(j - 1)) {
3955
+ matrix[i][j] = matrix[i - 1][j - 1];
3956
+ } else {
3957
+ matrix[i][j] = Math.min(
3958
+ matrix[i - 1][j - 1] + 1,
3959
+ // substitution
3960
+ matrix[i][j - 1] + 1,
3961
+ // insertion
3962
+ matrix[i - 1][j] + 1
3963
+ // deletion
3964
+ );
3965
+ }
3966
+ }
3967
+ }
3968
+ return matrix[bn][an];
3969
+ }
3970
+ function cosineSimilarity(vecA, vecB) {
3971
+ if (vecA.length !== vecB.length || vecA.length === 0) return 0;
3972
+ let dot = 0;
3973
+ let normA = 0;
3974
+ let normB = 0;
3975
+ for (let i = 0; i < vecA.length; i++) {
3976
+ dot += vecA[i] * vecB[i];
3977
+ normA += vecA[i] * vecA[i];
3978
+ normB += vecB[i] * vecB[i];
3979
+ }
3980
+ if (normA === 0 || normB === 0) return 0;
3981
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
3982
+ }
3983
+ var SmartSearchEngine = class {
3984
+ drive;
3985
+ constructor(drive2) {
3986
+ this.drive = drive2;
3987
+ }
3988
+ /**
3989
+ * Searches Drive using tokenized fuzzy matching and optional semantic embeddings
3990
+ */
3991
+ async search(query, options = {}) {
3992
+ const limit = options.limit || 20;
3993
+ const minScore = options.minScore ?? 0.3;
3994
+ const queryTokens = query.toLowerCase().split(/\s+/).filter(Boolean);
3995
+ if (queryTokens.length === 0) return [];
3996
+ let candidates = [];
3997
+ if (options.parent) {
3998
+ candidates = await this.drive.ls(options.parent);
3999
+ } else {
4000
+ candidates = await this.drive.query().notTrashed().pageSize(100).list();
4001
+ }
4002
+ let queryVector = null;
4003
+ if (options.embedder) {
4004
+ try {
4005
+ queryVector = await options.embedder(query);
4006
+ } catch {
4007
+ queryVector = null;
4008
+ }
4009
+ }
4010
+ const scored = [];
4011
+ for (const file of candidates) {
4012
+ const fileName = (file.name || "").toLowerCase();
4013
+ const desc = (file.description || "").toLowerCase();
4014
+ const matchedOn = [];
4015
+ let nameScore = 0;
4016
+ let descScore = 0;
4017
+ let semanticScore = 0;
4018
+ if (fileName.includes(query.toLowerCase())) {
4019
+ nameScore = 0.95;
4020
+ matchedOn.push("name");
4021
+ } else {
4022
+ let tokensMatched = 0;
4023
+ for (const token of queryTokens) {
4024
+ if (fileName.includes(token)) {
4025
+ tokensMatched += 1;
4026
+ continue;
4027
+ }
4028
+ const words = fileName.split(/[\s._-]+/);
4029
+ for (const word of words) {
4030
+ const dist = levenshtein(token, word);
4031
+ const maxLen = Math.max(token.length, word.length);
4032
+ if (maxLen > 3 && dist <= 2) {
4033
+ tokensMatched += 1 - dist / maxLen;
4034
+ break;
4035
+ }
4036
+ }
4037
+ }
4038
+ nameScore = tokensMatched / queryTokens.length;
4039
+ if (nameScore > 0.4) matchedOn.push("name");
4040
+ }
4041
+ if (desc) {
4042
+ if (desc.includes(query.toLowerCase())) {
4043
+ descScore = 0.8;
4044
+ matchedOn.push("description");
4045
+ }
4046
+ }
4047
+ if (queryVector && options.embedder) {
4048
+ try {
4049
+ const fileVector = await options.embedder(`${file.name} ${file.description || ""}`);
4050
+ semanticScore = cosineSimilarity(queryVector, fileVector);
4051
+ if (semanticScore > 0.6) matchedOn.push("semantic");
4052
+ } catch {
4053
+ }
4054
+ }
4055
+ const totalScore = Math.min(1, nameScore * 0.7 + descScore * 0.15 + semanticScore * 0.15);
4056
+ if (totalScore >= minScore) {
4057
+ scored.push({
4058
+ file,
4059
+ score: Math.round(totalScore * 100) / 100,
4060
+ matchedOn: matchedOn.length > 0 ? matchedOn : ["name"]
4061
+ });
4062
+ }
4063
+ }
4064
+ scored.sort((a, b) => b.score - a.score);
4065
+ return scored.slice(0, limit);
4066
+ }
4067
+ };
4068
+
4069
+ // src/utils/compression.ts
4070
+ init_cjs_shims();
4071
+ var import_node_zlib = __toESM(require("zlib"), 1);
4072
+ var import_node_util = require("util");
4073
+ var gzipAsync = (0, import_node_util.promisify)(import_node_zlib.default.gzip);
4074
+ var gunzipAsync = (0, import_node_util.promisify)(import_node_zlib.default.gunzip);
4075
+ var brotliCompressAsync = (0, import_node_util.promisify)(import_node_zlib.default.brotliCompress);
4076
+ var brotliDecompressAsync = (0, import_node_util.promisify)(import_node_zlib.default.brotliDecompress);
4077
+ function createCompressStream(algorithm = "gzip") {
4078
+ switch (algorithm) {
4079
+ case "brotli":
4080
+ return import_node_zlib.default.createBrotliCompress();
4081
+ case "deflate":
4082
+ return import_node_zlib.default.createDeflate();
4083
+ case "gzip":
4084
+ default:
4085
+ return import_node_zlib.default.createGzip();
4086
+ }
4087
+ }
4088
+ function createDecompressStream(algorithm = "gzip") {
4089
+ switch (algorithm) {
4090
+ case "brotli":
4091
+ return import_node_zlib.default.createBrotliDecompress();
4092
+ case "deflate":
4093
+ return import_node_zlib.default.createInflate();
4094
+ case "gzip":
4095
+ default:
4096
+ return import_node_zlib.default.createGunzip();
4097
+ }
4098
+ }
4099
+ async function compressBuffer(buffer, algorithm = "gzip") {
4100
+ switch (algorithm) {
4101
+ case "brotli":
4102
+ return await brotliCompressAsync(buffer);
4103
+ case "deflate":
4104
+ return await (0, import_node_util.promisify)(import_node_zlib.default.deflate)(buffer);
4105
+ case "gzip":
4106
+ default:
4107
+ return await gzipAsync(buffer);
4108
+ }
4109
+ }
4110
+ async function decompressBuffer(buffer, algorithm = "gzip") {
4111
+ switch (algorithm) {
4112
+ case "brotli":
4113
+ return await brotliDecompressAsync(buffer);
4114
+ case "deflate":
4115
+ return await (0, import_node_util.promisify)(import_node_zlib.default.inflate)(buffer);
4116
+ case "gzip":
4117
+ default:
4118
+ return await gunzipAsync(buffer);
4119
+ }
4120
+ }
4121
+ function isGzipBuffer(buffer) {
4122
+ return buffer.length >= 2 && buffer[0] === 31 && buffer[1] === 139;
4123
+ }
4124
+
2919
4125
  // src/core/client.ts
2920
4126
  var DriveKit = class _DriveKit {
2921
4127
  options;
@@ -2925,12 +4131,34 @@ var DriveKit = class _DriveKit {
2925
4131
  uploaderInstance = null;
2926
4132
  downloaderInstance = null;
2927
4133
  metadataCacheInstance = null;
4134
+ cryptoInstance = null;
2928
4135
  rootFolderId;
2929
4136
  pluginManager = new PluginManager();
2930
4137
  constructor(options = {}) {
2931
4138
  this.options = options;
2932
4139
  this.rootFolderId = options.rootFolderId || "root";
2933
4140
  this.authenticator = new DriveAuthenticator(options.auth);
4141
+ if (options.encryption) {
4142
+ this.cryptoInstance = new DriveKitCrypto(options.encryption);
4143
+ }
4144
+ }
4145
+ /**
4146
+ * Access the client-side AES-256-GCM encryption engine
4147
+ */
4148
+ get crypto() {
4149
+ if (!this.cryptoInstance) {
4150
+ throw new Error("Encryption is not configured on this DriveKit instance. Pass { encryption: { password: ... } } in options.");
4151
+ }
4152
+ return this.cryptoInstance;
4153
+ }
4154
+ /**
4155
+ * Access historical revisions & version control for a file
4156
+ */
4157
+ getRevisions(fileIdOrPath) {
4158
+ if (!this.driveClient) {
4159
+ throw new Error("DriveKit is not initialized. Call await drive.init() first.");
4160
+ }
4161
+ return new DriveFileRevisions(this.driveClient, fileIdOrPath, (p) => this.resolveId(p));
2934
4162
  }
2935
4163
  /**
2936
4164
  * Registers a middleware plugin into DriveKit lifecycle
@@ -3110,58 +4338,89 @@ var DriveKit = class _DriveKit {
3110
4338
  if (parentId && parentId.startsWith("/")) {
3111
4339
  parentId = await this.mkdirp(parentId);
3112
4340
  }
3113
- const targetName = opts.name || opts.filename || (typeof opts.source === "string" ? import_node_path7.default.basename(opts.source) : void 0);
3114
- if (opts.overwrite && targetName && parentId) {
4341
+ let uploadOpts = { ...opts };
4342
+ if (uploadOpts.compress) {
4343
+ const algo = typeof uploadOpts.compress === "string" ? uploadOpts.compress : "gzip";
4344
+ if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
4345
+ const plainBuf = await import_node_fs7.default.promises.readFile(uploadOpts.source);
4346
+ uploadOpts.source = await compressBuffer(plainBuf, algo);
4347
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4348
+ uploadOpts.source = await compressBuffer(uploadOpts.source, algo);
4349
+ }
4350
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_compressed: algo };
4351
+ }
4352
+ if ((uploadOpts.encrypt || this.options.encryption) && this.cryptoInstance) {
4353
+ const origName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : "encrypted.bin");
4354
+ if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
4355
+ const plainBuf = await import_node_fs7.default.promises.readFile(uploadOpts.source);
4356
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(plainBuf);
4357
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4358
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(uploadOpts.source);
4359
+ }
4360
+ if (this.options.encryption?.encryptFilenames) {
4361
+ uploadOpts.name = this.cryptoInstance.encryptFilename(origName);
4362
+ }
4363
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_encrypted: "true" };
4364
+ }
4365
+ const targetName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : void 0);
4366
+ if (uploadOpts.overwrite && targetName && parentId) {
3115
4367
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
3116
4368
  if (existing?.id) {
3117
4369
  await this.delete(existing.id, true);
3118
4370
  }
3119
4371
  }
3120
- if (opts.deduplicate && typeof opts.source === "string" && import_node_fs6.default.existsSync(opts.source)) {
3121
- const localMd5 = await calculateFileMd5(opts.source);
3122
- let existingId;
3123
- if (this.metadataCacheInstance) {
3124
- const cached = this.metadataCacheInstance.findByMd5(localMd5);
3125
- if (cached) existingId = cached.id;
4372
+ if (uploadOpts.deduplicate) {
4373
+ let localMd5;
4374
+ if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
4375
+ localMd5 = await calculateFileMd5(uploadOpts.source);
4376
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4377
+ localMd5 = import_node_crypto3.default.createHash("md5").update(uploadOpts.source).digest("hex");
3126
4378
  }
3127
- if (!existingId) {
3128
- const found = await this.query().md5(localMd5).notTrashed().first();
3129
- if (found?.id) {
3130
- existingId = found.id;
4379
+ if (localMd5) {
4380
+ let existingId;
4381
+ if (this.metadataCacheInstance) {
4382
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
4383
+ if (cached) existingId = cached.id;
3131
4384
  }
3132
- }
3133
- if (existingId) {
3134
- const fileName = targetName || import_node_path7.default.basename(opts.source);
3135
- const raw = await this.getRawClient();
3136
- const copyRes = await withRetry(async () => {
3137
- return await raw.files.copy({
3138
- fileId: existingId,
3139
- requestBody: {
3140
- name: fileName,
3141
- parents: parentId ? [parentId] : void 0,
3142
- description: opts.description
3143
- },
3144
- fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
3145
- supportsAllDrives: true
3146
- });
3147
- });
3148
- const file = copyRes.data;
3149
- if (this.metadataCacheInstance && file.id) {
3150
- this.metadataCacheInstance.upsertFile({
3151
- id: file.id,
3152
- name: file.name || fileName,
3153
- mimeType: file.mimeType || "",
3154
- size: file.size ? parseInt(file.size, 10) : void 0,
3155
- parentId,
3156
- md5Checksum: localMd5,
3157
- trashed: false
4385
+ if (!existingId) {
4386
+ const found = await this.query().md5(localMd5).notTrashed().first();
4387
+ if (found?.id) {
4388
+ existingId = found.id;
4389
+ }
4390
+ }
4391
+ if (existingId) {
4392
+ const fileName = targetName || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : "file.bin");
4393
+ const raw = await this.getRawClient();
4394
+ const copyRes = await withRetry(async () => {
4395
+ return await raw.files.copy({
4396
+ fileId: existingId,
4397
+ requestBody: {
4398
+ name: fileName,
4399
+ parents: parentId ? [parentId] : void 0,
4400
+ description: uploadOpts.description
4401
+ },
4402
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
4403
+ supportsAllDrives: true
4404
+ });
3158
4405
  });
4406
+ const file = copyRes.data;
4407
+ if (this.metadataCacheInstance && file.id) {
4408
+ this.metadataCacheInstance.upsertFile({
4409
+ id: file.id,
4410
+ name: file.name || fileName,
4411
+ mimeType: file.mimeType || "",
4412
+ size: file.size ? parseInt(file.size, 10) : void 0,
4413
+ parentId,
4414
+ md5Checksum: localMd5,
4415
+ trashed: false
4416
+ });
4417
+ }
4418
+ return await this.pluginManager.runAfterUpload(file);
3159
4419
  }
3160
- return await this.pluginManager.runAfterUpload(file);
3161
4420
  }
3162
4421
  }
3163
4422
  const uploaded = await uploader.upload({
3164
- ...opts,
4423
+ ...uploadOpts,
3165
4424
  name: targetName,
3166
4425
  parent: parentId
3167
4426
  });
@@ -3199,6 +4458,16 @@ var DriveKit = class _DriveKit {
3199
4458
  const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
3200
4459
  const downloader = await this.getDownloader();
3201
4460
  const result = await downloader.download(fileId, processedOpts);
4461
+ if (processedOpts.decrypt && this.cryptoInstance && result.filePath && import_node_fs7.default.existsSync(result.filePath)) {
4462
+ const encrypted = await import_node_fs7.default.promises.readFile(result.filePath);
4463
+ const decrypted = this.cryptoInstance.decryptBuffer(encrypted);
4464
+ await import_node_fs7.default.promises.writeFile(result.filePath, decrypted);
4465
+ }
4466
+ if (processedOpts.decompress && result.filePath && import_node_fs7.default.existsSync(result.filePath)) {
4467
+ const comp = await import_node_fs7.default.promises.readFile(result.filePath);
4468
+ const decomp = await decompressBuffer(comp);
4469
+ await import_node_fs7.default.promises.writeFile(result.filePath, decomp);
4470
+ }
3202
4471
  return await this.pluginManager.runAfterDownload(result);
3203
4472
  }
3204
4473
  /**
@@ -3332,10 +4601,7 @@ var DriveKit = class _DriveKit {
3332
4601
  async copy(fileIdOrPath, options = {}) {
3333
4602
  const fileId = await this.resolveId(fileIdOrPath);
3334
4603
  const raw = await this.getRawClient();
3335
- let parentId = options.parent;
3336
- if (parentId && parentId.startsWith("/")) {
3337
- parentId = await this.mkdirp(parentId);
3338
- }
4604
+ const parentId = options.parent ? await this.resolveId(options.parent, true) : void 0;
3339
4605
  const requestBody = {};
3340
4606
  if (options.name) requestBody.name = options.name;
3341
4607
  if (parentId) requestBody.parents = [parentId];
@@ -3462,16 +4728,16 @@ var DriveKit = class _DriveKit {
3462
4728
  durationMs: 0
3463
4729
  };
3464
4730
  const collectFiles = async (dir, base) => {
3465
- const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
4731
+ const entries = await import_node_fs7.default.promises.readdir(dir, { withFileTypes: true });
3466
4732
  const files = [];
3467
4733
  for (const entry of entries) {
3468
- const fullPath = import_node_path7.default.join(dir, entry.name);
3469
- const relPath = import_node_path7.default.join(base, entry.name);
4734
+ const fullPath = import_node_path9.default.join(dir, entry.name);
4735
+ const relPath = import_node_path9.default.join(base, entry.name);
3470
4736
  if (entry.isDirectory()) {
3471
4737
  const sub = await collectFiles(fullPath, relPath);
3472
4738
  files.push(...sub);
3473
4739
  } else if (entry.isFile()) {
3474
- const stat = await import_node_fs6.default.promises.stat(fullPath);
4740
+ const stat = await import_node_fs7.default.promises.stat(fullPath);
3475
4741
  files.push({ fullPath, relPath, size: stat.size });
3476
4742
  }
3477
4743
  }
@@ -3484,11 +4750,11 @@ var DriveKit = class _DriveKit {
3484
4750
  if (remoteDirCache.has(relDir)) {
3485
4751
  return remoteDirCache.get(relDir);
3486
4752
  }
3487
- const parts = relDir.split(import_node_path7.default.sep).filter(Boolean);
4753
+ const parts = relDir.split(import_node_path9.default.sep).filter(Boolean);
3488
4754
  let currentParent = targetFolderId;
3489
4755
  let currentRel = "";
3490
4756
  for (const part of parts) {
3491
- currentRel = currentRel ? import_node_path7.default.join(currentRel, part) : part;
4757
+ currentRel = currentRel ? import_node_path9.default.join(currentRel, part) : part;
3492
4758
  if (remoteDirCache.has(currentRel)) {
3493
4759
  currentParent = remoteDirCache.get(currentRel);
3494
4760
  continue;
@@ -3517,8 +4783,8 @@ var DriveKit = class _DriveKit {
3517
4783
  };
3518
4784
  await pool.map(allFiles, async (fileItem) => {
3519
4785
  try {
3520
- const relDir = import_node_path7.default.dirname(fileItem.relPath);
3521
- const fileName = import_node_path7.default.basename(fileItem.relPath);
4786
+ const relDir = import_node_path9.default.dirname(fileItem.relPath);
4787
+ const fileName = import_node_path9.default.basename(fileItem.relPath);
3522
4788
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3523
4789
  if (options.onFileStart) {
3524
4790
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3661,8 +4927,8 @@ var DriveKit = class _DriveKit {
3661
4927
  rejectDone = reject;
3662
4928
  });
3663
4929
  passThrough.done = donePromise;
3664
- const remoteDir = import_node_path7.default.dirname(remotePath);
3665
- const fileName = options.name || options.filename || import_node_path7.default.basename(remotePath);
4930
+ const remoteDir = import_node_path9.default.dirname(remotePath);
4931
+ const fileName = options.name || options.filename || import_node_path9.default.basename(remotePath);
3666
4932
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3667
4933
  const mimeType = options.mimeType || "application/octet-stream";
3668
4934
  const raw = this.driveClient;
@@ -3895,6 +5161,47 @@ var DriveKit = class _DriveKit {
3895
5161
  const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3896
5162
  return await startWebDAVServer2(this, options);
3897
5163
  }
5164
+ /**
5165
+ * Performs an intelligent two-way bidirectional sync between local and Google Drive directories
5166
+ */
5167
+ async syncBiDirectional(options) {
5168
+ await this.init();
5169
+ const engine = new BidirectionalSyncEngine(this);
5170
+ return await engine.sync(options);
5171
+ }
5172
+ /**
5173
+ * Starts an embedded S3-compatible HTTP gateway server
5174
+ */
5175
+ async serveS3(options = {}) {
5176
+ await this.init();
5177
+ const gateway = new S3GatewayServer(this, options);
5178
+ await gateway.start();
5179
+ return gateway;
5180
+ }
5181
+ /**
5182
+ * Scans Google Drive files and generates a security & permission audit report
5183
+ */
5184
+ async auditPermissions(options = {}) {
5185
+ await this.init();
5186
+ const auditor = new SecurityAuditor(this.driveClient);
5187
+ return await auditor.audit(options);
5188
+ }
5189
+ /**
5190
+ * Revokes public 'anyone' link permissions from the given files
5191
+ */
5192
+ async revokePublicPermissions(fileIds) {
5193
+ await this.init();
5194
+ const auditor = new SecurityAuditor(this.driveClient);
5195
+ return await auditor.revokePublicAccess(fileIds);
5196
+ }
5197
+ /**
5198
+ * Multi-word fuzzy and semantic search across files
5199
+ */
5200
+ async searchSmart(query, options = {}) {
5201
+ await this.init();
5202
+ const engine = new SmartSearchEngine(this);
5203
+ return await engine.search(query, options);
5204
+ }
3898
5205
  /**
3899
5206
  * Calculates local file MD5 hash for integrity and deduplication checks
3900
5207
  */
@@ -4068,6 +5375,90 @@ ${import_chalk.default.cyan("\u{1F517} Getting shareable link for:")} ${import_c
4068
5375
  });
4069
5376
  }
4070
5377
 
5378
+ // src/integrations/middleware.ts
5379
+ init_cjs_shims();
5380
+ var import_node_path10 = __toESM(require("path"), 1);
5381
+ var import_busboy = __toESM(require("busboy"), 1);
5382
+ function createDriveUploadMiddleware(drive2, options = {}) {
5383
+ const targetDir = options.destination || "/Uploads";
5384
+ return async (req, res, next) => {
5385
+ const contentType = req.headers["content-type"] || "";
5386
+ if (!contentType.includes("multipart/form-data")) {
5387
+ return next();
5388
+ }
5389
+ req.drivekitFiles = [];
5390
+ req.drivekitFields = {};
5391
+ const uploadPromises = [];
5392
+ try {
5393
+ const bb = (0, import_busboy.default)({
5394
+ headers: req.headers,
5395
+ limits: {
5396
+ fileSize: options.maxFileSize
5397
+ }
5398
+ });
5399
+ bb.on("file", (name, fileStream, info) => {
5400
+ const { filename, mimeType } = info;
5401
+ const rawName = filename || "upload.bin";
5402
+ const sanitizedName = import_node_path10.default.basename(rawName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5403
+ const rawFinalName = options.filenameGenerator ? options.filenameGenerator(sanitizedName, mimeType) : sanitizedName;
5404
+ const finalName = import_node_path10.default.basename(rawFinalName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5405
+ const remotePath = `${targetDir === "/" ? "" : targetDir}/${finalName}`;
5406
+ const uploadTask = (async () => {
5407
+ const driveStream = await drive2.createWriteStream(remotePath, {
5408
+ mimeType
5409
+ });
5410
+ fileStream.pipe(driveStream);
5411
+ const uploadedFile = await driveStream.done;
5412
+ req.drivekitFiles?.push(uploadedFile);
5413
+ return uploadedFile;
5414
+ })();
5415
+ uploadPromises.push(uploadTask);
5416
+ });
5417
+ bb.on("field", (name, val) => {
5418
+ if (req.drivekitFields) {
5419
+ req.drivekitFields[name] = val;
5420
+ }
5421
+ });
5422
+ bb.on("close", async () => {
5423
+ try {
5424
+ await Promise.all(uploadPromises);
5425
+ next();
5426
+ } catch (err) {
5427
+ next(err);
5428
+ }
5429
+ });
5430
+ bb.on("error", (err) => {
5431
+ next(err);
5432
+ });
5433
+ req.pipe(bb);
5434
+ } catch (err) {
5435
+ next(err);
5436
+ }
5437
+ };
5438
+ }
5439
+ async function handleNextJsUpload(formData, drive2, options = {}) {
5440
+ const targetDir = options.destination || "/Uploads";
5441
+ const results = [];
5442
+ for (const [key, value] of formData.entries()) {
5443
+ if (value && typeof value === "object" && "arrayBuffer" in value) {
5444
+ const file = value;
5445
+ const buffer = Buffer.from(await file.arrayBuffer());
5446
+ const rawName = file.name || "upload.bin";
5447
+ const sanitizedName = import_node_path10.default.basename(rawName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5448
+ const rawFinalName = options.filenameGenerator ? options.filenameGenerator(sanitizedName, file.type) : sanitizedName;
5449
+ const finalName = import_node_path10.default.basename(rawFinalName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5450
+ const uploaded = await drive2.upload({
5451
+ source: buffer,
5452
+ name: finalName,
5453
+ parent: targetDir,
5454
+ mimeType: file.type || "application/octet-stream"
5455
+ });
5456
+ results.push(uploaded);
5457
+ }
5458
+ }
5459
+ return results;
5460
+ }
5461
+
4071
5462
  // src/index.ts
4072
5463
  async function createDrive(options) {
4073
5464
  const instance = new DriveKit(options);
@@ -4077,6 +5468,7 @@ async function createDrive(options) {
4077
5468
  var index_default = DriveKit;
4078
5469
  // Annotate the CommonJS export names for ESM import in node:
4079
5470
  0 && (module.exports = {
5471
+ BidirectionalSyncEngine,
4080
5472
  ConcurrencyPool,
4081
5473
  DEFAULT_CHUNK_SIZE,
4082
5474
  DEFAULT_EXPORT_MIMES,
@@ -4085,8 +5477,10 @@ var index_default = DriveKit;
4085
5477
  DriveAuthError,
4086
5478
  DriveAuthenticator,
4087
5479
  DriveFileRef,
5480
+ DriveFileRevisions,
4088
5481
  DriveFolderRef,
4089
5482
  DriveKit,
5483
+ DriveKitCrypto,
4090
5484
  DriveKitError,
4091
5485
  DriveNotFoundError,
4092
5486
  DriveQueryBuilder,
@@ -4094,19 +5488,35 @@ var index_default = DriveKit;
4094
5488
  DriveUploadError,
4095
5489
  DriveWatcher,
4096
5490
  GOOGLE_WORKSPACE_MIME_TYPES,
5491
+ IV_LENGTH,
5492
+ MAGIC_HEADER,
5493
+ MAGIC_STREAM_HEADER,
4097
5494
  MIN_CHUNK_SIZE,
4098
5495
  MULTIPART_THRESHOLD,
4099
5496
  MemoryMetadataCache,
5497
+ PBKDF2_ROUNDS,
4100
5498
  PathResolver,
4101
5499
  PluginManager,
4102
5500
  ResumableUploader,
5501
+ S3GatewayServer,
5502
+ SALT_LENGTH,
5503
+ SecurityAuditor,
5504
+ SmartSearchEngine,
4103
5505
  SmartSyncEngine,
4104
5506
  SqliteMetadataCache,
4105
5507
  StorageCleaner,
5508
+ TAG_LENGTH,
4106
5509
  calculateFileMd5,
5510
+ compressBuffer,
5511
+ cosineSimilarity,
4107
5512
  createAutoNamePlugin,
5513
+ createCompressStream,
5514
+ createDecompressStream,
4108
5515
  createDrive,
5516
+ createDriveUploadMiddleware,
4109
5517
  createWebhookPlugin,
5518
+ decompressBuffer,
5519
+ deriveKey,
4110
5520
  escapeXml,
4111
5521
  formatBytes,
4112
5522
  formatDuration,
@@ -4115,7 +5525,9 @@ var index_default = DriveKit;
4115
5525
  getFileIcon,
4116
5526
  getOptimizedHttpAgent,
4117
5527
  getOptimizedHttpsAgent,
5528
+ handleNextJsUpload,
4118
5529
  isGoogleWorkspaceDoc,
5530
+ isGzipBuffer,
4119
5531
  isRetryableError,
4120
5532
  loginWithBrowser,
4121
5533
  lookupMimeType,