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.js CHANGED
@@ -29,9 +29,9 @@ __export(webdav_exports, {
29
29
  escapeXml: () => escapeXml,
30
30
  startWebDAVServer: () => startWebDAVServer
31
31
  });
32
- import http3 from "http";
32
+ import http4 from "http";
33
33
  import url from "url";
34
- import path7 from "path";
34
+ import path9 from "path";
35
35
  function escapeXml(unsafe) {
36
36
  return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
37
37
  }
@@ -39,7 +39,7 @@ async function startWebDAVServer(drive2, options = {}) {
39
39
  const port = options.port || 8080;
40
40
  const host = options.host || "127.0.0.1";
41
41
  await drive2.init();
42
- const server = http3.createServer(async (req, res) => {
42
+ const server = http4.createServer(async (req, res) => {
43
43
  try {
44
44
  if (options.auth?.username && options.auth?.password) {
45
45
  const authHeader = req.headers["authorization"];
@@ -64,8 +64,9 @@ async function startWebDAVServer(drive2, options = {}) {
64
64
  }
65
65
  const parsedUrl = url.parse(req.url || "/", true);
66
66
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
67
- const virtualPath = decodedPath === "" ? "/" : decodedPath;
68
- const baseName = path7.basename(virtualPath);
67
+ const normalizedPath = path9.posix.normalize(decodedPath);
68
+ const virtualPath = normalizedPath.startsWith("/") ? normalizedPath : `/${normalizedPath}`;
69
+ const baseName = path9.basename(virtualPath);
69
70
  if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
70
71
  res.writeHead(404, { "Content-Type": "text/plain" });
71
72
  res.end("Not Found");
@@ -154,7 +155,7 @@ async function startWebDAVServer(drive2, options = {}) {
154
155
  return;
155
156
  }
156
157
  case "PUT": {
157
- const remoteDir = path7.dirname(virtualPath);
158
+ const remoteDir = path9.dirname(virtualPath);
158
159
  await drive2.mkdirp(remoteDir);
159
160
  let existed = false;
160
161
  try {
@@ -217,14 +218,14 @@ async function startWebDAVServer(drive2, options = {}) {
217
218
  }
218
219
  const destUrl = url.parse(destination);
219
220
  const destPath = decodeURIComponent(destUrl.pathname || "");
220
- const newName = path7.basename(destPath);
221
- const newParentDir = path7.dirname(destPath);
221
+ const newName = path9.basename(destPath);
222
+ const newParentDir = path9.dirname(destPath);
222
223
  const newParentFolderId = await drive2.mkdirp(newParentDir);
223
- const currentParentDir = path7.dirname(virtualPath);
224
+ const currentParentDir = path9.dirname(virtualPath);
224
225
  if (newParentDir !== currentParentDir) {
225
226
  await drive2.move(file.id, newParentFolderId);
226
227
  }
227
- if (newName !== path7.basename(virtualPath)) {
228
+ if (newName !== path9.basename(virtualPath)) {
228
229
  await drive2.rename(file.id, newName);
229
230
  }
230
231
  res.writeHead(201);
@@ -251,8 +252,8 @@ async function startWebDAVServer(drive2, options = {}) {
251
252
  }
252
253
  const destUrl = url.parse(destination);
253
254
  const destPath = decodeURIComponent(destUrl.pathname || "");
254
- const newName = path7.basename(destPath);
255
- const newParentDir = path7.dirname(destPath);
255
+ const newName = path9.basename(destPath);
256
+ const newParentDir = path9.dirname(destPath);
256
257
  const newParentFolderId = await drive2.mkdirp(newParentDir);
257
258
  await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
258
259
  res.writeHead(201);
@@ -317,8 +318,8 @@ async function handlePropfind(drive2, virtualPath, depth) {
317
318
  if (seenNames.has(childName)) {
318
319
  const count = seenNames.get(childName) + 1;
319
320
  seenNames.set(childName, count);
320
- const ext = path7.extname(childName);
321
- const base = path7.basename(childName, ext);
321
+ const ext = path9.extname(childName);
322
+ const base = path9.basename(childName, ext);
322
323
  childName = `${base} (${count})${ext}`;
323
324
  } else {
324
325
  seenNames.set(childName, 0);
@@ -349,7 +350,7 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
349
350
  cleanHref += "/";
350
351
  }
351
352
  const encodedHref = encodeURI(cleanHref);
352
- const displayName = escapeXml(path7.basename(href) || "root");
353
+ const displayName = escapeXml(path9.basename(href) || "root");
353
354
  const resourceType = isDir ? "<D:collection/>" : "";
354
355
  const dateFormatted = new Date(modifiedTime).toUTCString();
355
356
  const contentTypeTag = !isDir && mimeType ? `
@@ -379,8 +380,9 @@ init_esm_shims();
379
380
 
380
381
  // src/core/client.ts
381
382
  init_esm_shims();
382
- import fs6 from "fs";
383
- import path8 from "path";
383
+ import fs7 from "fs";
384
+ import path10 from "path";
385
+ import crypto3 from "crypto";
384
386
  import { drive } from "@googleapis/drive";
385
387
 
386
388
  // src/auth/authenticator.ts
@@ -685,8 +687,8 @@ var PathResolver = class {
685
687
  /**
686
688
  * Gets cache key for a path
687
689
  */
688
- getCacheKey(path9) {
689
- return `${this.rootFolderId}:${this.normalizePath(path9)}`;
690
+ getCacheKey(path12) {
691
+ return `${this.rootFolderId}:${this.normalizePath(path12)}`;
690
692
  }
691
693
  /**
692
694
  * Clears the path cache
@@ -700,8 +702,8 @@ var PathResolver = class {
700
702
  /**
701
703
  * Invalidate a single path from cache
702
704
  */
703
- invalidatePath(path9) {
704
- const norm = this.normalizePath(path9);
705
+ invalidatePath(path12) {
706
+ const norm = this.normalizePath(path12);
705
707
  const key = this.getCacheKey(norm);
706
708
  this.cache.delete(key);
707
709
  if (this.metadataCache) {
@@ -2235,6 +2237,10 @@ var DriveFileRef = class {
2235
2237
  async getLink() {
2236
2238
  return await this.drive.getShareableLink(this.pathOrId);
2237
2239
  }
2240
+ /** Access historical revisions & version control for this file */
2241
+ get revisions() {
2242
+ return this.drive.getRevisions(this.pathOrId);
2243
+ }
2238
2244
  /** Returns a ReadableStream for this file, optionally with byte Range requests */
2239
2245
  async createReadStream(options) {
2240
2246
  return await this.drive.createReadStream(this.pathOrId, options);
@@ -2849,6 +2855,1185 @@ var MemoryMetadataCache = class {
2849
2855
  }
2850
2856
  };
2851
2857
 
2858
+ // src/crypto/encryption.ts
2859
+ init_esm_shims();
2860
+ import crypto2 from "crypto";
2861
+ import { Transform as Transform3 } from "stream";
2862
+ var MAGIC_HEADER = Buffer.from("DKENC1", "utf8");
2863
+ var MAGIC_STREAM_HEADER = Buffer.from("DKENCS", "utf8");
2864
+ var SALT_LENGTH = 16;
2865
+ var IV_LENGTH = 12;
2866
+ var TAG_LENGTH = 16;
2867
+ var PBKDF2_ROUNDS = 1e5;
2868
+ function deriveKey(password, salt) {
2869
+ return crypto2.pbkdf2Sync(password, salt, PBKDF2_ROUNDS, 32, "sha512");
2870
+ }
2871
+ var DriveKitCrypto = class {
2872
+ config;
2873
+ constructor(config) {
2874
+ if (!config.password && !config.key) {
2875
+ throw new Error("DriveKitCrypto requires either a password or a 32-byte key.");
2876
+ }
2877
+ if (config.key && config.key.length !== 32) {
2878
+ throw new Error(`DriveKitCrypto raw key must be exactly 32 bytes, got ${config.key.length} bytes.`);
2879
+ }
2880
+ this.config = config;
2881
+ }
2882
+ /**
2883
+ * Encrypts a Buffer using AES-256-GCM.
2884
+ * Format: [MAGIC (6B)][SALT (16B)][IV (12B)][TAG (16B)][CIPHERTEXT]
2885
+ */
2886
+ encryptBuffer(data) {
2887
+ const salt = crypto2.randomBytes(SALT_LENGTH);
2888
+ const iv = crypto2.randomBytes(IV_LENGTH);
2889
+ const key = this.config.key || deriveKey(this.config.password, salt);
2890
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
2891
+ const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
2892
+ const tag = cipher.getAuthTag();
2893
+ return Buffer.concat([MAGIC_HEADER, salt, iv, tag, ciphertext]);
2894
+ }
2895
+ /**
2896
+ * Decrypts a Buffer previously encrypted with encryptBuffer or createEncryptStream.
2897
+ */
2898
+ decryptBuffer(encryptedData) {
2899
+ if (encryptedData.length < MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH + TAG_LENGTH) {
2900
+ throw new Error("Encrypted payload is too short to be valid DriveKit ciphertext.");
2901
+ }
2902
+ const magic = encryptedData.subarray(0, MAGIC_HEADER.length);
2903
+ const isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
2904
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
2905
+ if (!isStreamFormat && !isBufferFormat) {
2906
+ throw new Error("Invalid magic header: file was not encrypted by DriveKit or is corrupted.");
2907
+ }
2908
+ const salt = encryptedData.subarray(6, 6 + SALT_LENGTH);
2909
+ const iv = encryptedData.subarray(6 + SALT_LENGTH, 6 + SALT_LENGTH + IV_LENGTH);
2910
+ const key = this.config.key || deriveKey(this.config.password, salt);
2911
+ let tag;
2912
+ let ciphertext;
2913
+ if (isStreamFormat) {
2914
+ tag = encryptedData.subarray(encryptedData.length - TAG_LENGTH);
2915
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, encryptedData.length - TAG_LENGTH);
2916
+ } else {
2917
+ tag = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, 6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
2918
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
2919
+ }
2920
+ const decipher = crypto2.createDecipheriv("aes-256-gcm", key, iv);
2921
+ decipher.setAuthTag(tag);
2922
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
2923
+ }
2924
+ /**
2925
+ * Creates an encryption Transform stream that prepends stream header and appends GCM auth tag
2926
+ */
2927
+ createEncryptStream() {
2928
+ const salt = crypto2.randomBytes(SALT_LENGTH);
2929
+ const iv = crypto2.randomBytes(IV_LENGTH);
2930
+ const key = this.config.key || deriveKey(this.config.password, salt);
2931
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
2932
+ let headerPushed = false;
2933
+ return new Transform3({
2934
+ transform(chunk, _encoding, callback) {
2935
+ if (!headerPushed) {
2936
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
2937
+ headerPushed = true;
2938
+ }
2939
+ const encrypted = cipher.update(chunk);
2940
+ if (encrypted.length > 0) {
2941
+ this.push(encrypted);
2942
+ }
2943
+ callback();
2944
+ },
2945
+ flush(callback) {
2946
+ if (!headerPushed) {
2947
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
2948
+ headerPushed = true;
2949
+ }
2950
+ const finalChunk = cipher.final();
2951
+ const tag = cipher.getAuthTag();
2952
+ this.push(Buffer.concat([finalChunk, tag]));
2953
+ callback();
2954
+ }
2955
+ });
2956
+ }
2957
+ /**
2958
+ * Creates a decryption Transform stream that verifies magic header and validates GCM authentication tag
2959
+ */
2960
+ createDecryptStream() {
2961
+ const HEADER_BASE_LEN = MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH;
2962
+ let headerBuffer = Buffer.alloc(0);
2963
+ let decipher = null;
2964
+ let isStreamFormat = false;
2965
+ let pendingTail = Buffer.alloc(0);
2966
+ const self = this;
2967
+ return new Transform3({
2968
+ transform(chunk, _encoding, callback) {
2969
+ try {
2970
+ let data = chunk;
2971
+ if (!decipher) {
2972
+ headerBuffer = Buffer.concat([headerBuffer, data]);
2973
+ if (headerBuffer.length < HEADER_BASE_LEN) {
2974
+ return callback();
2975
+ }
2976
+ const magic = headerBuffer.subarray(0, MAGIC_HEADER.length);
2977
+ isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
2978
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
2979
+ if (!isStreamFormat && !isBufferFormat) {
2980
+ return callback(new Error("Invalid magic header: stream was not encrypted by DriveKit or is corrupted."));
2981
+ }
2982
+ const salt = headerBuffer.subarray(MAGIC_HEADER.length, MAGIC_HEADER.length + SALT_LENGTH);
2983
+ const iv = headerBuffer.subarray(MAGIC_HEADER.length + SALT_LENGTH, HEADER_BASE_LEN);
2984
+ const key = self.config.key || deriveKey(self.config.password, salt);
2985
+ decipher = crypto2.createDecipheriv("aes-256-gcm", key, iv);
2986
+ if (isBufferFormat) {
2987
+ if (headerBuffer.length < HEADER_BASE_LEN + TAG_LENGTH) {
2988
+ return callback();
2989
+ }
2990
+ const tag = headerBuffer.subarray(HEADER_BASE_LEN, HEADER_BASE_LEN + TAG_LENGTH);
2991
+ decipher.setAuthTag(tag);
2992
+ data = headerBuffer.subarray(HEADER_BASE_LEN + TAG_LENGTH);
2993
+ headerBuffer = Buffer.alloc(0);
2994
+ } else {
2995
+ data = headerBuffer.subarray(HEADER_BASE_LEN);
2996
+ headerBuffer = Buffer.alloc(0);
2997
+ }
2998
+ }
2999
+ if (data.length > 0) {
3000
+ if (isStreamFormat) {
3001
+ pendingTail = Buffer.concat([pendingTail, data]);
3002
+ if (pendingTail.length > TAG_LENGTH) {
3003
+ const toProcess = pendingTail.subarray(0, pendingTail.length - TAG_LENGTH);
3004
+ pendingTail = pendingTail.subarray(pendingTail.length - TAG_LENGTH);
3005
+ const decryptedChunk = decipher.update(toProcess);
3006
+ if (decryptedChunk.length > 0) {
3007
+ this.push(decryptedChunk);
3008
+ }
3009
+ }
3010
+ } else {
3011
+ const decryptedChunk = decipher.update(data);
3012
+ if (decryptedChunk.length > 0) {
3013
+ this.push(decryptedChunk);
3014
+ }
3015
+ }
3016
+ }
3017
+ callback();
3018
+ } catch (err) {
3019
+ callback(err);
3020
+ }
3021
+ },
3022
+ flush(callback) {
3023
+ try {
3024
+ if (!decipher) {
3025
+ return callback(new Error("Encrypted stream is too short: missing header."));
3026
+ }
3027
+ if (isStreamFormat) {
3028
+ if (pendingTail.length !== TAG_LENGTH) {
3029
+ return callback(new Error("Encrypted stream is truncated: missing authentication tag."));
3030
+ }
3031
+ decipher.setAuthTag(pendingTail);
3032
+ }
3033
+ const finalChunk = decipher.final();
3034
+ if (finalChunk.length > 0) {
3035
+ this.push(finalChunk);
3036
+ }
3037
+ callback();
3038
+ } catch (err) {
3039
+ callback(new Error(`Authentication failed: corrupted data or invalid authentication tag (${err.message})`));
3040
+ }
3041
+ }
3042
+ });
3043
+ }
3044
+ /**
3045
+ * Encrypts a filename into a safe base64url string
3046
+ */
3047
+ encryptFilename(plainName) {
3048
+ const iv = crypto2.randomBytes(12);
3049
+ const salt = crypto2.randomBytes(8);
3050
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
3051
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
3052
+ const encrypted = Buffer.concat([cipher.update(Buffer.from(plainName, "utf8")), cipher.final()]);
3053
+ const tag = cipher.getAuthTag();
3054
+ const payload = Buffer.concat([salt, iv, tag, encrypted]);
3055
+ return `dk_${payload.toString("base64url")}.enc`;
3056
+ }
3057
+ /**
3058
+ * Decrypts a filename generated by encryptFilename
3059
+ */
3060
+ decryptFilename(encryptedName) {
3061
+ if (!encryptedName.startsWith("dk_") || !encryptedName.endsWith(".enc")) {
3062
+ return encryptedName;
3063
+ }
3064
+ try {
3065
+ const raw = encryptedName.slice(3, -4);
3066
+ const payload = Buffer.from(raw, "base64url");
3067
+ if (payload.length < 8 + 12 + 16) return encryptedName;
3068
+ const salt = payload.subarray(0, 8);
3069
+ const iv = payload.subarray(8, 20);
3070
+ const tag = payload.subarray(20, 36);
3071
+ const ciphertext = payload.subarray(36);
3072
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
3073
+ const decipher = crypto2.createDecipheriv("aes-256-gcm", key, iv);
3074
+ decipher.setAuthTag(tag);
3075
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
3076
+ return decrypted.toString("utf8");
3077
+ } catch {
3078
+ return encryptedName;
3079
+ }
3080
+ }
3081
+ };
3082
+
3083
+ // src/core/revisions.ts
3084
+ init_esm_shims();
3085
+ var DriveFileRevisions = class {
3086
+ drive;
3087
+ pathOrId;
3088
+ idResolver;
3089
+ constructor(drive2, pathOrId, idResolver) {
3090
+ this.drive = drive2;
3091
+ this.pathOrId = pathOrId;
3092
+ this.idResolver = idResolver;
3093
+ }
3094
+ async getId() {
3095
+ if (this.idResolver && (this.pathOrId.startsWith("/") || this.pathOrId.includes("/"))) {
3096
+ return await this.idResolver(this.pathOrId);
3097
+ }
3098
+ return this.pathOrId;
3099
+ }
3100
+ /**
3101
+ * Lists all historical revisions of the file
3102
+ */
3103
+ async list() {
3104
+ const fileId = await this.getId();
3105
+ const res = await withRetry(async () => {
3106
+ return await this.drive.revisions.list({
3107
+ fileId,
3108
+ fields: "revisions(id, mimeType, modifiedTime, keepForever, size, originalFilename)"
3109
+ });
3110
+ });
3111
+ const revs = res.data.revisions || [];
3112
+ return revs.map((r) => ({
3113
+ id: r.id,
3114
+ mimeType: r.mimeType || void 0,
3115
+ modifiedTime: r.modifiedTime || void 0,
3116
+ keepForever: r.keepForever ?? false,
3117
+ size: r.size ? parseInt(r.size, 10) : void 0,
3118
+ originalFilename: r.originalFilename || void 0
3119
+ }));
3120
+ }
3121
+ /**
3122
+ * Gets metadata for a specific revision
3123
+ */
3124
+ async get(revisionId) {
3125
+ const fileId = await this.getId();
3126
+ const res = await withRetry(async () => {
3127
+ return await this.drive.revisions.get({
3128
+ fileId,
3129
+ revisionId,
3130
+ fields: "id, mimeType, modifiedTime, keepForever, size, originalFilename"
3131
+ });
3132
+ });
3133
+ const r = res.data;
3134
+ return {
3135
+ id: r.id,
3136
+ mimeType: r.mimeType || void 0,
3137
+ modifiedTime: r.modifiedTime || void 0,
3138
+ keepForever: r.keepForever ?? false,
3139
+ size: r.size ? parseInt(r.size, 10) : void 0,
3140
+ originalFilename: r.originalFilename || void 0
3141
+ };
3142
+ }
3143
+ /**
3144
+ * Pins or unpins a revision so Google Drive never automatically purges it after 30 days
3145
+ */
3146
+ async keepForever(revisionId, keep = true) {
3147
+ const fileId = await this.getId();
3148
+ const res = await withRetry(async () => {
3149
+ return await this.drive.revisions.update({
3150
+ fileId,
3151
+ revisionId,
3152
+ requestBody: {
3153
+ keepForever: keep
3154
+ },
3155
+ fields: "id, keepForever, modifiedTime"
3156
+ });
3157
+ });
3158
+ return {
3159
+ id: res.data.id,
3160
+ keepForever: res.data.keepForever ?? keep,
3161
+ modifiedTime: res.data.modifiedTime || void 0
3162
+ };
3163
+ }
3164
+ /**
3165
+ * Deletes a specific historical revision
3166
+ */
3167
+ async delete(revisionId) {
3168
+ const fileId = await this.getId();
3169
+ await withRetry(async () => {
3170
+ return await this.drive.revisions.delete({
3171
+ fileId,
3172
+ revisionId
3173
+ });
3174
+ });
3175
+ }
3176
+ /**
3177
+ * Gets a readable stream of a specific historical revision
3178
+ */
3179
+ async getStream(revisionId) {
3180
+ const fileId = await this.getId();
3181
+ const res = await withRetry(async () => {
3182
+ return await this.drive.revisions.get(
3183
+ { fileId, revisionId, alt: "media" },
3184
+ { responseType: "stream" }
3185
+ );
3186
+ });
3187
+ return res.data;
3188
+ }
3189
+ /**
3190
+ * Restores the file content to a specific previous revision
3191
+ */
3192
+ async restore(revisionId) {
3193
+ const fileId = await this.getId();
3194
+ const stream = await this.getStream(revisionId);
3195
+ const meta = await this.get(revisionId);
3196
+ await withRetry(async () => {
3197
+ return await this.drive.files.update({
3198
+ fileId,
3199
+ media: {
3200
+ mimeType: meta.mimeType || "application/octet-stream",
3201
+ body: stream
3202
+ }
3203
+ });
3204
+ });
3205
+ }
3206
+ };
3207
+
3208
+ // src/core/bidirectional-sync.ts
3209
+ init_esm_shims();
3210
+ import fs6 from "fs";
3211
+ import path7 from "path";
3212
+ var BidirectionalSyncEngine = class {
3213
+ drive;
3214
+ ledger = /* @__PURE__ */ new Map();
3215
+ constructor(drive2) {
3216
+ this.drive = drive2;
3217
+ }
3218
+ /**
3219
+ * Performs a two-way synchronization cycle between local and remote directories
3220
+ */
3221
+ async sync(options) {
3222
+ const startTime = Date.now();
3223
+ const {
3224
+ localDir,
3225
+ remoteDir,
3226
+ conflictStrategy = "rename-conflict",
3227
+ deleteMissing = false,
3228
+ dryRun = false,
3229
+ onProgress
3230
+ } = options;
3231
+ const result = {
3232
+ uploaded: [],
3233
+ downloaded: [],
3234
+ deletedLocal: [],
3235
+ deletedRemote: [],
3236
+ conflicts: [],
3237
+ skipped: [],
3238
+ durationMs: 0
3239
+ };
3240
+ if (!fs6.existsSync(localDir)) {
3241
+ await fs6.promises.mkdir(localDir, { recursive: true });
3242
+ }
3243
+ const remoteFolderId = await this.drive.mkdirp(remoteDir);
3244
+ const localFiles = await this.scanLocalDir(localDir);
3245
+ const remoteFiles = await this.scanRemoteDir(remoteFolderId, "");
3246
+ const allPaths = /* @__PURE__ */ new Set([
3247
+ ...localFiles.keys(),
3248
+ ...remoteFiles.keys(),
3249
+ ...this.ledger.keys()
3250
+ ]);
3251
+ for (const relPath of allPaths) {
3252
+ const resolvedLocal = path7.resolve(localDir, relPath);
3253
+ const resolvedRoot = path7.resolve(localDir);
3254
+ if (!resolvedLocal.startsWith(resolvedRoot + path7.sep) && resolvedLocal !== resolvedRoot) {
3255
+ throw new Error(`Security Violation: Path traversal detected in sync path: "${relPath}"`);
3256
+ }
3257
+ const local = localFiles.get(relPath);
3258
+ const remote = remoteFiles.get(relPath);
3259
+ const prev = this.ledger.get(relPath);
3260
+ if (local && remote) {
3261
+ const localChanged = !prev || local.md5 !== prev.localMd5 || Math.abs(local.mtime - prev.localMtime) > 1e3;
3262
+ const remoteChanged = !prev || remote.md5 !== prev.remoteMd5 || Math.abs(remote.mtime - prev.remoteMtime) > 1e3;
3263
+ if (local.md5 === remote.md5) {
3264
+ result.skipped.push(relPath);
3265
+ onProgress?.({ action: "skip-identical", relPath });
3266
+ this.ledger.set(relPath, {
3267
+ relPath,
3268
+ localMtime: local.mtime,
3269
+ remoteMtime: remote.mtime,
3270
+ localMd5: local.md5,
3271
+ remoteMd5: remote.md5,
3272
+ remoteId: remote.id
3273
+ });
3274
+ continue;
3275
+ }
3276
+ if (localChanged && !remoteChanged) {
3277
+ if (!dryRun) {
3278
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3279
+ const freshRemote = await this.drive.getFile(remote.id);
3280
+ this.updateLedger(relPath, local, freshRemote);
3281
+ }
3282
+ result.uploaded.push(relPath);
3283
+ onProgress?.({ action: "upload", relPath, details: "Local modification propagated" });
3284
+ continue;
3285
+ }
3286
+ if (remoteChanged && !localChanged) {
3287
+ if (!dryRun) {
3288
+ await this.downloadFile(remote.id, local.fullPath);
3289
+ const freshStat = await fs6.promises.stat(local.fullPath);
3290
+ this.ledger.set(relPath, {
3291
+ relPath,
3292
+ localMtime: freshStat.mtimeMs,
3293
+ remoteMtime: remote.mtime,
3294
+ localMd5: remote.md5,
3295
+ remoteMd5: remote.md5,
3296
+ remoteId: remote.id
3297
+ });
3298
+ }
3299
+ result.downloaded.push(relPath);
3300
+ onProgress?.({ action: "download", relPath, details: "Remote modification propagated" });
3301
+ continue;
3302
+ }
3303
+ result.conflicts.push(relPath);
3304
+ onProgress?.({ action: "conflict-resolved", relPath, details: `Strategy: ${conflictStrategy}` });
3305
+ if (!dryRun) {
3306
+ if (conflictStrategy === "prefer-local") {
3307
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3308
+ const freshRemote = await this.drive.getFile(remote.id);
3309
+ this.updateLedger(relPath, local, freshRemote);
3310
+ result.uploaded.push(relPath);
3311
+ } else if (conflictStrategy === "prefer-cloud") {
3312
+ await this.downloadFile(remote.id, local.fullPath);
3313
+ const freshStat = await fs6.promises.stat(local.fullPath);
3314
+ this.ledger.set(relPath, {
3315
+ relPath,
3316
+ localMtime: freshStat.mtimeMs,
3317
+ remoteMtime: remote.mtime,
3318
+ localMd5: remote.md5,
3319
+ remoteMd5: remote.md5,
3320
+ remoteId: remote.id
3321
+ });
3322
+ result.downloaded.push(relPath);
3323
+ } else if (conflictStrategy === "keep-newer") {
3324
+ if (local.mtime >= remote.mtime) {
3325
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3326
+ const freshRemote = await this.drive.getFile(remote.id);
3327
+ this.updateLedger(relPath, local, freshRemote);
3328
+ result.uploaded.push(relPath);
3329
+ } else {
3330
+ await this.downloadFile(remote.id, local.fullPath);
3331
+ const freshStat = await fs6.promises.stat(local.fullPath);
3332
+ this.ledger.set(relPath, {
3333
+ relPath,
3334
+ localMtime: freshStat.mtimeMs,
3335
+ remoteMtime: remote.mtime,
3336
+ localMd5: remote.md5,
3337
+ remoteMd5: remote.md5,
3338
+ remoteId: remote.id
3339
+ });
3340
+ result.downloaded.push(relPath);
3341
+ }
3342
+ } else {
3343
+ const ext = path7.extname(relPath);
3344
+ const base = relPath.slice(0, relPath.length - ext.length);
3345
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3346
+ const conflictRelPath = `${base} (Conflict ${timestamp})${ext}`;
3347
+ const conflictFullPath = path7.join(localDir, conflictRelPath);
3348
+ await this.downloadFile(remote.id, conflictFullPath);
3349
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3350
+ const freshRemote = await this.drive.getFile(remote.id);
3351
+ this.updateLedger(relPath, local, freshRemote);
3352
+ }
3353
+ }
3354
+ continue;
3355
+ }
3356
+ if (local && !remote) {
3357
+ if (prev && deleteMissing) {
3358
+ if (!dryRun) {
3359
+ await fs6.promises.unlink(local.fullPath);
3360
+ this.ledger.delete(relPath);
3361
+ }
3362
+ result.deletedLocal.push(relPath);
3363
+ onProgress?.({ action: "delete-local", relPath, details: "Deleted remotely" });
3364
+ } else {
3365
+ if (!dryRun) {
3366
+ const uploadedFile = await this.uploadFile(local.fullPath, remoteDir, relPath);
3367
+ this.updateLedger(relPath, local, uploadedFile);
3368
+ }
3369
+ result.uploaded.push(relPath);
3370
+ onProgress?.({ action: "upload", relPath, details: "New local file" });
3371
+ }
3372
+ continue;
3373
+ }
3374
+ if (!local && remote) {
3375
+ if (prev && deleteMissing) {
3376
+ if (!dryRun) {
3377
+ await this.drive.delete(remote.id, true);
3378
+ this.ledger.delete(relPath);
3379
+ }
3380
+ result.deletedRemote.push(relPath);
3381
+ onProgress?.({ action: "delete-remote", relPath, details: "Deleted locally" });
3382
+ } else {
3383
+ if (!dryRun) {
3384
+ const localDest = path7.join(localDir, relPath);
3385
+ await fs6.promises.mkdir(path7.dirname(localDest), { recursive: true });
3386
+ await this.downloadFile(remote.id, localDest);
3387
+ const stat = await fs6.promises.stat(localDest);
3388
+ this.ledger.set(relPath, {
3389
+ relPath,
3390
+ localMtime: stat.mtimeMs,
3391
+ remoteMtime: remote.mtime,
3392
+ localMd5: remote.md5,
3393
+ remoteMd5: remote.md5,
3394
+ remoteId: remote.id
3395
+ });
3396
+ }
3397
+ result.downloaded.push(relPath);
3398
+ onProgress?.({ action: "download", relPath, details: "New remote file" });
3399
+ }
3400
+ continue;
3401
+ }
3402
+ if (prev && !local && !remote) {
3403
+ this.ledger.delete(relPath);
3404
+ }
3405
+ }
3406
+ result.durationMs = Date.now() - startTime;
3407
+ return result;
3408
+ }
3409
+ async scanLocalDir(dir, baseDir = dir) {
3410
+ const map = /* @__PURE__ */ new Map();
3411
+ if (!fs6.existsSync(dir)) return map;
3412
+ const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
3413
+ for (const entry of entries) {
3414
+ const fullPath = path7.join(dir, entry.name);
3415
+ if (entry.isDirectory()) {
3416
+ const sub = await this.scanLocalDir(fullPath, baseDir);
3417
+ for (const [k, v] of sub) map.set(k, v);
3418
+ } else if (entry.isFile()) {
3419
+ const rel = path7.relative(baseDir, fullPath).replace(/\\/g, "/");
3420
+ const stat = await fs6.promises.stat(fullPath);
3421
+ const md5 = await calculateFileMd5(fullPath);
3422
+ map.set(rel, { fullPath, mtime: stat.mtimeMs, md5 });
3423
+ }
3424
+ }
3425
+ return map;
3426
+ }
3427
+ async scanRemoteDir(folderId, relPrefix) {
3428
+ const map = /* @__PURE__ */ new Map();
3429
+ const items = await this.drive.query().inFolder(folderId).notTrashed().list();
3430
+ for (const item of items) {
3431
+ if (!item.id || !item.name) continue;
3432
+ const cleanName = path7.basename(item.name.replace(/\\/g, "/")).replace(/\0/g, "");
3433
+ if (!cleanName || cleanName === "." || cleanName === "..") continue;
3434
+ const relPath = relPrefix ? `${relPrefix}/${cleanName}` : cleanName;
3435
+ if (item.mimeType === "application/vnd.google-apps.folder") {
3436
+ const sub = await this.scanRemoteDir(item.id, relPath);
3437
+ for (const [k, v] of sub) map.set(k, v);
3438
+ } else {
3439
+ const mtime = item.modifiedTime ? new Date(item.modifiedTime).getTime() : 0;
3440
+ map.set(relPath, {
3441
+ id: item.id,
3442
+ name: item.name,
3443
+ mtime,
3444
+ md5: item.md5Checksum || ""
3445
+ });
3446
+ }
3447
+ }
3448
+ return map;
3449
+ }
3450
+ async uploadFile(localPath, remoteDir, relPath) {
3451
+ const remoteSubDir = path7.dirname(relPath);
3452
+ const targetFolder = remoteSubDir === "." ? remoteDir : `${remoteDir}/${remoteSubDir}`;
3453
+ return await this.drive.upload({
3454
+ source: localPath,
3455
+ name: path7.basename(relPath),
3456
+ parent: targetFolder,
3457
+ overwrite: true
3458
+ });
3459
+ }
3460
+ async downloadFile(fileId, destPath) {
3461
+ await fs6.promises.mkdir(path7.dirname(destPath), { recursive: true });
3462
+ await this.drive.download(fileId, { destination: destPath });
3463
+ }
3464
+ updateLedger(relPath, local, remote) {
3465
+ this.ledger.set(relPath, {
3466
+ relPath,
3467
+ localMtime: local.mtime,
3468
+ remoteMtime: remote.modifiedTime ? new Date(remote.modifiedTime).getTime() : Date.now(),
3469
+ localMd5: local.md5,
3470
+ remoteMd5: remote.md5Checksum || local.md5,
3471
+ remoteId: remote.id
3472
+ });
3473
+ }
3474
+ };
3475
+
3476
+ // src/server/s3-gateway.ts
3477
+ init_esm_shims();
3478
+ import http3 from "http";
3479
+ import path8 from "path";
3480
+ import { parse as parseUrl } from "url";
3481
+ var S3GatewayServer = class {
3482
+ drive;
3483
+ options;
3484
+ server = null;
3485
+ constructor(drive2, options = {}) {
3486
+ this.drive = drive2;
3487
+ this.options = {
3488
+ port: options.port || 9e3,
3489
+ host: options.host || "127.0.0.1",
3490
+ bucketRoot: options.bucketRoot || "/",
3491
+ ...options
3492
+ };
3493
+ }
3494
+ /**
3495
+ * Starts the S3 gateway HTTP server
3496
+ */
3497
+ async start() {
3498
+ return new Promise((resolve, reject) => {
3499
+ this.server = http3.createServer(async (req, res) => {
3500
+ try {
3501
+ await this.handleRequest(req, res);
3502
+ } catch (err) {
3503
+ this.sendXmlError(res, 500, "InternalError", err.message || "Internal S3 Gateway Error");
3504
+ }
3505
+ });
3506
+ this.server.on("error", reject);
3507
+ this.server.listen(this.options.port, this.options.host, () => {
3508
+ resolve({ port: this.options.port, host: this.options.host });
3509
+ });
3510
+ });
3511
+ }
3512
+ /**
3513
+ * Stops the S3 gateway HTTP server
3514
+ */
3515
+ async stop() {
3516
+ return new Promise((resolve) => {
3517
+ if (this.server) {
3518
+ this.server.close(() => resolve());
3519
+ } else {
3520
+ resolve();
3521
+ }
3522
+ });
3523
+ }
3524
+ async handleRequest(req, res) {
3525
+ const parsed = parseUrl(req.url || "/", true);
3526
+ const rawPathname = decodeURIComponent(parsed.pathname || "/");
3527
+ const pathname = path8.posix.normalize(rawPathname);
3528
+ if (rawPathname.includes("..") || pathname.includes("..") || pathname === ".") {
3529
+ this.sendXmlError(res, 400, "InvalidURI", "Path traversal characters are not permitted");
3530
+ return;
3531
+ }
3532
+ const method = req.method?.toUpperCase() || "GET";
3533
+ if (this.options.accessKeyId) {
3534
+ const authHeader = req.headers["authorization"];
3535
+ if (!authHeader || !authHeader.includes(this.options.accessKeyId)) {
3536
+ res.setHeader("WWW-Authenticate", "AWS4-HMAC-SHA256");
3537
+ this.sendXmlError(res, 403, "AccessDenied", "Invalid or missing AWS credentials");
3538
+ return;
3539
+ }
3540
+ }
3541
+ const segments = pathname.split("/").filter(Boolean);
3542
+ if (segments.some((s) => s === ".." || s === ".")) {
3543
+ this.sendXmlError(res, 400, "InvalidURI", "Invalid path segment");
3544
+ return;
3545
+ }
3546
+ if (segments.length === 0) {
3547
+ if (method === "GET") {
3548
+ await this.handleListBuckets(res);
3549
+ return;
3550
+ }
3551
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on root");
3552
+ return;
3553
+ }
3554
+ const bucket = segments[0];
3555
+ const key = segments.slice(1).join("/");
3556
+ if (!key) {
3557
+ if (method === "GET") {
3558
+ const prefix = parsed.query.prefix || "";
3559
+ await this.handleListObjects(bucket, prefix, res);
3560
+ return;
3561
+ }
3562
+ if (method === "PUT") {
3563
+ await this.drive.mkdirp(`/${bucket}`);
3564
+ res.statusCode = 200;
3565
+ res.end();
3566
+ return;
3567
+ }
3568
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on bucket");
3569
+ return;
3570
+ }
3571
+ const remotePath = `/${bucket}/${key}`;
3572
+ if (method === "HEAD") {
3573
+ try {
3574
+ const file = await this.drive.getFile(remotePath);
3575
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3576
+ res.setHeader("Content-Length", file.size || "0");
3577
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3578
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3579
+ res.statusCode = 200;
3580
+ res.end();
3581
+ } catch {
3582
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3583
+ }
3584
+ return;
3585
+ }
3586
+ if (method === "GET") {
3587
+ try {
3588
+ const file = await this.drive.getFile(remotePath);
3589
+ const range = req.headers["range"];
3590
+ let options = void 0;
3591
+ if (range && range.startsWith("bytes=")) {
3592
+ const parts = range.replace("bytes=", "").split("-");
3593
+ options = {
3594
+ start: parts[0] ? parseInt(parts[0], 10) : 0,
3595
+ end: parts[1] ? parseInt(parts[1], 10) : void 0
3596
+ };
3597
+ res.statusCode = 206;
3598
+ const end = options.end !== void 0 ? options.end : parseInt(file.size || "0", 10) - 1;
3599
+ res.setHeader("Content-Range", `bytes ${options.start}-${end}/${file.size}`);
3600
+ } else {
3601
+ res.statusCode = 200;
3602
+ }
3603
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3604
+ res.setHeader("Content-Length", file.size || "0");
3605
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3606
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3607
+ const stream = await this.drive.createReadStream(remotePath, options);
3608
+ stream.pipe(res);
3609
+ } catch {
3610
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3611
+ }
3612
+ return;
3613
+ }
3614
+ if (method === "PUT") {
3615
+ const upload = await this.drive.createWriteStream(remotePath);
3616
+ req.pipe(upload);
3617
+ try {
3618
+ const file = await upload.done;
3619
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3620
+ res.statusCode = 200;
3621
+ res.end();
3622
+ } catch (err) {
3623
+ this.sendXmlError(res, 500, "InternalError", err.message);
3624
+ }
3625
+ return;
3626
+ }
3627
+ if (method === "DELETE") {
3628
+ try {
3629
+ const file = await this.drive.resolvePath(remotePath);
3630
+ await this.drive.delete(file.id, true);
3631
+ res.statusCode = 204;
3632
+ res.end();
3633
+ } catch {
3634
+ res.statusCode = 204;
3635
+ res.end();
3636
+ }
3637
+ return;
3638
+ }
3639
+ this.sendXmlError(res, 405, "MethodNotAllowed", `HTTP method ${method} not allowed`);
3640
+ }
3641
+ async handleListBuckets(res) {
3642
+ const items = await this.drive.ls("/");
3643
+ const folders = items.filter((i) => i.mimeType === "application/vnd.google-apps.folder");
3644
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3645
+ xml += " <Buckets>\n";
3646
+ for (const f of folders) {
3647
+ xml += " <Bucket>\n";
3648
+ xml += ` <Name>${this.escapeXml(f.name || "bucket")}</Name>
3649
+ `;
3650
+ xml += ` <CreationDate>${f.createdTime || (/* @__PURE__ */ new Date()).toISOString()}</CreationDate>
3651
+ `;
3652
+ xml += " </Bucket>\n";
3653
+ }
3654
+ xml += " </Buckets>\n</ListAllMyBucketsResult>";
3655
+ res.setHeader("Content-Type", "application/xml");
3656
+ res.statusCode = 200;
3657
+ res.end(xml);
3658
+ }
3659
+ async handleListObjects(bucket, prefix, res) {
3660
+ const targetPath = `/${bucket}${prefix ? `/${prefix}` : ""}`;
3661
+ let items = [];
3662
+ try {
3663
+ items = await this.drive.ls(targetPath);
3664
+ } catch {
3665
+ items = [];
3666
+ }
3667
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3668
+ xml += ` <Name>${this.escapeXml(bucket)}</Name>
3669
+ `;
3670
+ xml += ` <Prefix>${this.escapeXml(prefix)}</Prefix>
3671
+ `;
3672
+ xml += " <IsTruncated>false</IsTruncated>\n";
3673
+ for (const item of items) {
3674
+ if (item.mimeType === "application/vnd.google-apps.folder") continue;
3675
+ const key = prefix ? `${prefix}/${item.name}` : item.name;
3676
+ xml += " <Contents>\n";
3677
+ xml += ` <Key>${this.escapeXml(key)}</Key>
3678
+ `;
3679
+ xml += ` <LastModified>${item.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()}</LastModified>
3680
+ `;
3681
+ xml += ` <ETag>"${item.md5Checksum || item.id}"</ETag>
3682
+ `;
3683
+ xml += ` <Size>${item.size || 0}</Size>
3684
+ `;
3685
+ xml += " <StorageClass>STANDARD</StorageClass>\n";
3686
+ xml += " </Contents>\n";
3687
+ }
3688
+ xml += "</ListBucketResult>";
3689
+ res.setHeader("Content-Type", "application/xml");
3690
+ res.statusCode = 200;
3691
+ res.end(xml);
3692
+ }
3693
+ sendXmlError(res, status, code, message) {
3694
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
3695
+ <Error>
3696
+ <Code>${this.escapeXml(code)}</Code>
3697
+ <Message>${this.escapeXml(message)}</Message>
3698
+ </Error>`;
3699
+ res.setHeader("Content-Type", "application/xml");
3700
+ res.statusCode = status;
3701
+ res.end(xml);
3702
+ }
3703
+ escapeXml(unsafe) {
3704
+ return unsafe.replace(/[<>&'"]/g, (c) => {
3705
+ switch (c) {
3706
+ case "<":
3707
+ return "&lt;";
3708
+ case ">":
3709
+ return "&gt;";
3710
+ case "&":
3711
+ return "&amp;";
3712
+ case "'":
3713
+ return "&apos;";
3714
+ case '"':
3715
+ return "&quot;";
3716
+ default:
3717
+ return c;
3718
+ }
3719
+ });
3720
+ }
3721
+ };
3722
+
3723
+ // src/core/security-auditor.ts
3724
+ init_esm_shims();
3725
+ var SecurityAuditor = class {
3726
+ drive;
3727
+ constructor(drive2) {
3728
+ this.drive = drive2;
3729
+ }
3730
+ /**
3731
+ * Scans Google Drive files and audits their permission grants
3732
+ */
3733
+ async audit(options = {}) {
3734
+ const limit = options.scanLimit || 500;
3735
+ const allowedDomains = new Set((options.allowedDomains || []).map((d) => d.toLowerCase()));
3736
+ const issues = [];
3737
+ let publicCount = 0;
3738
+ let domainCount = 0;
3739
+ let externalCount = 0;
3740
+ let scannedTotal = 0;
3741
+ let pageToken = void 0;
3742
+ do {
3743
+ const res = await withRetry(async () => {
3744
+ return await this.drive.files.list({
3745
+ q: "trashed = false",
3746
+ fields: "nextPageToken, files(id, name, mimeType, webViewLink, shared, permissions(id, type, role, emailAddress, domain))",
3747
+ pageSize: Math.min(100, limit - scannedTotal),
3748
+ supportsAllDrives: true,
3749
+ includeItemsFromAllDrives: true,
3750
+ pageToken
3751
+ });
3752
+ });
3753
+ const files = res.data.files || [];
3754
+ for (const file of files) {
3755
+ if (!file.id || !file.name) continue;
3756
+ scannedTotal++;
3757
+ const perms = file.permissions || [];
3758
+ for (const p of perms) {
3759
+ if (p.type === "anyone") {
3760
+ publicCount++;
3761
+ const isCritical = ["writer", "owner", "organizer", "fileOrganizer"].includes(p.role || "");
3762
+ issues.push({
3763
+ fileId: file.id,
3764
+ fileName: file.name,
3765
+ risk: isCritical ? "CRITICAL" : "HIGH",
3766
+ reason: `Publicly accessible to anyone (${p.role} access)`,
3767
+ permissionId: p.id,
3768
+ type: p.type,
3769
+ role: p.role || "reader",
3770
+ webViewLink: file.webViewLink || void 0
3771
+ });
3772
+ continue;
3773
+ }
3774
+ if (p.type === "domain") {
3775
+ domainCount++;
3776
+ issues.push({
3777
+ fileId: file.id,
3778
+ fileName: file.name,
3779
+ risk: "MEDIUM",
3780
+ reason: `Shared with entire organization domain (${p.domain})`,
3781
+ permissionId: p.id,
3782
+ type: p.type,
3783
+ role: p.role || "reader",
3784
+ domain: p.domain || void 0,
3785
+ webViewLink: file.webViewLink || void 0
3786
+ });
3787
+ continue;
3788
+ }
3789
+ if (p.type === "user" && p.emailAddress && allowedDomains.size > 0) {
3790
+ const userDomain = p.emailAddress.split("@")[1]?.toLowerCase();
3791
+ if (userDomain && !allowedDomains.has(userDomain)) {
3792
+ externalCount++;
3793
+ issues.push({
3794
+ fileId: file.id,
3795
+ fileName: file.name,
3796
+ risk: "HIGH",
3797
+ reason: `Shared with external user outside allowed domains: ${p.emailAddress}`,
3798
+ permissionId: p.id,
3799
+ type: p.type,
3800
+ role: p.role || "reader",
3801
+ emailAddress: p.emailAddress,
3802
+ webViewLink: file.webViewLink || void 0
3803
+ });
3804
+ }
3805
+ }
3806
+ }
3807
+ }
3808
+ pageToken = res.data.nextPageToken || void 0;
3809
+ } while (pageToken && scannedTotal < limit);
3810
+ return {
3811
+ totalScanned: scannedTotal,
3812
+ publicFilesCount: publicCount,
3813
+ domainSharedCount: domainCount,
3814
+ externalSharesCount: externalCount,
3815
+ issues,
3816
+ scannedAt: (/* @__PURE__ */ new Date()).toISOString()
3817
+ };
3818
+ }
3819
+ /**
3820
+ * Revokes public 'anyone' permissions on specified files
3821
+ */
3822
+ async revokePublicAccess(fileIds) {
3823
+ const revoked = [];
3824
+ const errors = [];
3825
+ for (const fileId of fileIds) {
3826
+ try {
3827
+ const fileRes = await withRetry(async () => {
3828
+ return await this.drive.files.get({
3829
+ fileId,
3830
+ fields: "id, permissions(id, type)",
3831
+ supportsAllDrives: true
3832
+ });
3833
+ });
3834
+ const publicPerms = (fileRes.data.permissions || []).filter((p) => p.type === "anyone");
3835
+ for (const p of publicPerms) {
3836
+ if (p.id) {
3837
+ await withRetry(async () => {
3838
+ return await this.drive.permissions.delete({
3839
+ fileId,
3840
+ permissionId: p.id,
3841
+ supportsAllDrives: true
3842
+ });
3843
+ });
3844
+ }
3845
+ }
3846
+ revoked.push(fileId);
3847
+ } catch (err) {
3848
+ errors.push({ fileId, error: err.message });
3849
+ }
3850
+ }
3851
+ return { revoked, errors };
3852
+ }
3853
+ };
3854
+
3855
+ // src/core/semantic-search.ts
3856
+ init_esm_shims();
3857
+ function levenshtein(a, b) {
3858
+ const an = a.length;
3859
+ const bn = b.length;
3860
+ if (an === 0) return bn;
3861
+ if (bn === 0) return an;
3862
+ const matrix = Array.from({ length: bn + 1 }, (_, i) => [i]);
3863
+ for (let j = 0; j <= an; j++) matrix[0][j] = j;
3864
+ for (let i = 1; i <= bn; i++) {
3865
+ for (let j = 1; j <= an; j++) {
3866
+ if (b.charAt(i - 1) === a.charAt(j - 1)) {
3867
+ matrix[i][j] = matrix[i - 1][j - 1];
3868
+ } else {
3869
+ matrix[i][j] = Math.min(
3870
+ matrix[i - 1][j - 1] + 1,
3871
+ // substitution
3872
+ matrix[i][j - 1] + 1,
3873
+ // insertion
3874
+ matrix[i - 1][j] + 1
3875
+ // deletion
3876
+ );
3877
+ }
3878
+ }
3879
+ }
3880
+ return matrix[bn][an];
3881
+ }
3882
+ function cosineSimilarity(vecA, vecB) {
3883
+ if (vecA.length !== vecB.length || vecA.length === 0) return 0;
3884
+ let dot = 0;
3885
+ let normA = 0;
3886
+ let normB = 0;
3887
+ for (let i = 0; i < vecA.length; i++) {
3888
+ dot += vecA[i] * vecB[i];
3889
+ normA += vecA[i] * vecA[i];
3890
+ normB += vecB[i] * vecB[i];
3891
+ }
3892
+ if (normA === 0 || normB === 0) return 0;
3893
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
3894
+ }
3895
+ var SmartSearchEngine = class {
3896
+ drive;
3897
+ constructor(drive2) {
3898
+ this.drive = drive2;
3899
+ }
3900
+ /**
3901
+ * Searches Drive using tokenized fuzzy matching and optional semantic embeddings
3902
+ */
3903
+ async search(query, options = {}) {
3904
+ const limit = options.limit || 20;
3905
+ const minScore = options.minScore ?? 0.3;
3906
+ const queryTokens = query.toLowerCase().split(/\s+/).filter(Boolean);
3907
+ if (queryTokens.length === 0) return [];
3908
+ let candidates = [];
3909
+ if (options.parent) {
3910
+ candidates = await this.drive.ls(options.parent);
3911
+ } else {
3912
+ candidates = await this.drive.query().notTrashed().pageSize(100).list();
3913
+ }
3914
+ let queryVector = null;
3915
+ if (options.embedder) {
3916
+ try {
3917
+ queryVector = await options.embedder(query);
3918
+ } catch {
3919
+ queryVector = null;
3920
+ }
3921
+ }
3922
+ const scored = [];
3923
+ for (const file of candidates) {
3924
+ const fileName = (file.name || "").toLowerCase();
3925
+ const desc = (file.description || "").toLowerCase();
3926
+ const matchedOn = [];
3927
+ let nameScore = 0;
3928
+ let descScore = 0;
3929
+ let semanticScore = 0;
3930
+ if (fileName.includes(query.toLowerCase())) {
3931
+ nameScore = 0.95;
3932
+ matchedOn.push("name");
3933
+ } else {
3934
+ let tokensMatched = 0;
3935
+ for (const token of queryTokens) {
3936
+ if (fileName.includes(token)) {
3937
+ tokensMatched += 1;
3938
+ continue;
3939
+ }
3940
+ const words = fileName.split(/[\s._-]+/);
3941
+ for (const word of words) {
3942
+ const dist = levenshtein(token, word);
3943
+ const maxLen = Math.max(token.length, word.length);
3944
+ if (maxLen > 3 && dist <= 2) {
3945
+ tokensMatched += 1 - dist / maxLen;
3946
+ break;
3947
+ }
3948
+ }
3949
+ }
3950
+ nameScore = tokensMatched / queryTokens.length;
3951
+ if (nameScore > 0.4) matchedOn.push("name");
3952
+ }
3953
+ if (desc) {
3954
+ if (desc.includes(query.toLowerCase())) {
3955
+ descScore = 0.8;
3956
+ matchedOn.push("description");
3957
+ }
3958
+ }
3959
+ if (queryVector && options.embedder) {
3960
+ try {
3961
+ const fileVector = await options.embedder(`${file.name} ${file.description || ""}`);
3962
+ semanticScore = cosineSimilarity(queryVector, fileVector);
3963
+ if (semanticScore > 0.6) matchedOn.push("semantic");
3964
+ } catch {
3965
+ }
3966
+ }
3967
+ const totalScore = Math.min(1, nameScore * 0.7 + descScore * 0.15 + semanticScore * 0.15);
3968
+ if (totalScore >= minScore) {
3969
+ scored.push({
3970
+ file,
3971
+ score: Math.round(totalScore * 100) / 100,
3972
+ matchedOn: matchedOn.length > 0 ? matchedOn : ["name"]
3973
+ });
3974
+ }
3975
+ }
3976
+ scored.sort((a, b) => b.score - a.score);
3977
+ return scored.slice(0, limit);
3978
+ }
3979
+ };
3980
+
3981
+ // src/utils/compression.ts
3982
+ init_esm_shims();
3983
+ import zlib from "zlib";
3984
+ import { promisify } from "util";
3985
+ var gzipAsync = promisify(zlib.gzip);
3986
+ var gunzipAsync = promisify(zlib.gunzip);
3987
+ var brotliCompressAsync = promisify(zlib.brotliCompress);
3988
+ var brotliDecompressAsync = promisify(zlib.brotliDecompress);
3989
+ function createCompressStream(algorithm = "gzip") {
3990
+ switch (algorithm) {
3991
+ case "brotli":
3992
+ return zlib.createBrotliCompress();
3993
+ case "deflate":
3994
+ return zlib.createDeflate();
3995
+ case "gzip":
3996
+ default:
3997
+ return zlib.createGzip();
3998
+ }
3999
+ }
4000
+ function createDecompressStream(algorithm = "gzip") {
4001
+ switch (algorithm) {
4002
+ case "brotli":
4003
+ return zlib.createBrotliDecompress();
4004
+ case "deflate":
4005
+ return zlib.createInflate();
4006
+ case "gzip":
4007
+ default:
4008
+ return zlib.createGunzip();
4009
+ }
4010
+ }
4011
+ async function compressBuffer(buffer, algorithm = "gzip") {
4012
+ switch (algorithm) {
4013
+ case "brotli":
4014
+ return await brotliCompressAsync(buffer);
4015
+ case "deflate":
4016
+ return await promisify(zlib.deflate)(buffer);
4017
+ case "gzip":
4018
+ default:
4019
+ return await gzipAsync(buffer);
4020
+ }
4021
+ }
4022
+ async function decompressBuffer(buffer, algorithm = "gzip") {
4023
+ switch (algorithm) {
4024
+ case "brotli":
4025
+ return await brotliDecompressAsync(buffer);
4026
+ case "deflate":
4027
+ return await promisify(zlib.inflate)(buffer);
4028
+ case "gzip":
4029
+ default:
4030
+ return await gunzipAsync(buffer);
4031
+ }
4032
+ }
4033
+ function isGzipBuffer(buffer) {
4034
+ return buffer.length >= 2 && buffer[0] === 31 && buffer[1] === 139;
4035
+ }
4036
+
2852
4037
  // src/core/client.ts
2853
4038
  var DriveKit = class _DriveKit {
2854
4039
  options;
@@ -2858,12 +4043,34 @@ var DriveKit = class _DriveKit {
2858
4043
  uploaderInstance = null;
2859
4044
  downloaderInstance = null;
2860
4045
  metadataCacheInstance = null;
4046
+ cryptoInstance = null;
2861
4047
  rootFolderId;
2862
4048
  pluginManager = new PluginManager();
2863
4049
  constructor(options = {}) {
2864
4050
  this.options = options;
2865
4051
  this.rootFolderId = options.rootFolderId || "root";
2866
4052
  this.authenticator = new DriveAuthenticator(options.auth);
4053
+ if (options.encryption) {
4054
+ this.cryptoInstance = new DriveKitCrypto(options.encryption);
4055
+ }
4056
+ }
4057
+ /**
4058
+ * Access the client-side AES-256-GCM encryption engine
4059
+ */
4060
+ get crypto() {
4061
+ if (!this.cryptoInstance) {
4062
+ throw new Error("Encryption is not configured on this DriveKit instance. Pass { encryption: { password: ... } } in options.");
4063
+ }
4064
+ return this.cryptoInstance;
4065
+ }
4066
+ /**
4067
+ * Access historical revisions & version control for a file
4068
+ */
4069
+ getRevisions(fileIdOrPath) {
4070
+ if (!this.driveClient) {
4071
+ throw new Error("DriveKit is not initialized. Call await drive.init() first.");
4072
+ }
4073
+ return new DriveFileRevisions(this.driveClient, fileIdOrPath, (p) => this.resolveId(p));
2867
4074
  }
2868
4075
  /**
2869
4076
  * Registers a middleware plugin into DriveKit lifecycle
@@ -3043,58 +4250,89 @@ var DriveKit = class _DriveKit {
3043
4250
  if (parentId && parentId.startsWith("/")) {
3044
4251
  parentId = await this.mkdirp(parentId);
3045
4252
  }
3046
- const targetName = opts.name || opts.filename || (typeof opts.source === "string" ? path8.basename(opts.source) : void 0);
3047
- if (opts.overwrite && targetName && parentId) {
4253
+ let uploadOpts = { ...opts };
4254
+ if (uploadOpts.compress) {
4255
+ const algo = typeof uploadOpts.compress === "string" ? uploadOpts.compress : "gzip";
4256
+ if (typeof uploadOpts.source === "string" && fs7.existsSync(uploadOpts.source)) {
4257
+ const plainBuf = await fs7.promises.readFile(uploadOpts.source);
4258
+ uploadOpts.source = await compressBuffer(plainBuf, algo);
4259
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4260
+ uploadOpts.source = await compressBuffer(uploadOpts.source, algo);
4261
+ }
4262
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_compressed: algo };
4263
+ }
4264
+ if ((uploadOpts.encrypt || this.options.encryption) && this.cryptoInstance) {
4265
+ const origName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? path10.basename(uploadOpts.source) : "encrypted.bin");
4266
+ if (typeof uploadOpts.source === "string" && fs7.existsSync(uploadOpts.source)) {
4267
+ const plainBuf = await fs7.promises.readFile(uploadOpts.source);
4268
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(plainBuf);
4269
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4270
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(uploadOpts.source);
4271
+ }
4272
+ if (this.options.encryption?.encryptFilenames) {
4273
+ uploadOpts.name = this.cryptoInstance.encryptFilename(origName);
4274
+ }
4275
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_encrypted: "true" };
4276
+ }
4277
+ const targetName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? path10.basename(uploadOpts.source) : void 0);
4278
+ if (uploadOpts.overwrite && targetName && parentId) {
3048
4279
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
3049
4280
  if (existing?.id) {
3050
4281
  await this.delete(existing.id, true);
3051
4282
  }
3052
4283
  }
3053
- if (opts.deduplicate && typeof opts.source === "string" && fs6.existsSync(opts.source)) {
3054
- const localMd5 = await calculateFileMd5(opts.source);
3055
- let existingId;
3056
- if (this.metadataCacheInstance) {
3057
- const cached = this.metadataCacheInstance.findByMd5(localMd5);
3058
- if (cached) existingId = cached.id;
3059
- }
3060
- if (!existingId) {
3061
- const found = await this.query().md5(localMd5).notTrashed().first();
3062
- if (found?.id) {
3063
- existingId = found.id;
3064
- }
3065
- }
3066
- if (existingId) {
3067
- const fileName = targetName || path8.basename(opts.source);
3068
- const raw = await this.getRawClient();
3069
- const copyRes = await withRetry(async () => {
3070
- return await raw.files.copy({
3071
- fileId: existingId,
3072
- requestBody: {
3073
- name: fileName,
3074
- parents: parentId ? [parentId] : void 0,
3075
- description: opts.description
3076
- },
3077
- fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
3078
- supportsAllDrives: true
3079
- });
3080
- });
3081
- const file = copyRes.data;
3082
- if (this.metadataCacheInstance && file.id) {
3083
- this.metadataCacheInstance.upsertFile({
3084
- id: file.id,
3085
- name: file.name || fileName,
3086
- mimeType: file.mimeType || "",
3087
- size: file.size ? parseInt(file.size, 10) : void 0,
3088
- parentId,
3089
- md5Checksum: localMd5,
3090
- trashed: false
4284
+ if (uploadOpts.deduplicate) {
4285
+ let localMd5;
4286
+ if (typeof uploadOpts.source === "string" && fs7.existsSync(uploadOpts.source)) {
4287
+ localMd5 = await calculateFileMd5(uploadOpts.source);
4288
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4289
+ localMd5 = crypto3.createHash("md5").update(uploadOpts.source).digest("hex");
4290
+ }
4291
+ if (localMd5) {
4292
+ let existingId;
4293
+ if (this.metadataCacheInstance) {
4294
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
4295
+ if (cached) existingId = cached.id;
4296
+ }
4297
+ if (!existingId) {
4298
+ const found = await this.query().md5(localMd5).notTrashed().first();
4299
+ if (found?.id) {
4300
+ existingId = found.id;
4301
+ }
4302
+ }
4303
+ if (existingId) {
4304
+ const fileName = targetName || (typeof uploadOpts.source === "string" ? path10.basename(uploadOpts.source) : "file.bin");
4305
+ const raw = await this.getRawClient();
4306
+ const copyRes = await withRetry(async () => {
4307
+ return await raw.files.copy({
4308
+ fileId: existingId,
4309
+ requestBody: {
4310
+ name: fileName,
4311
+ parents: parentId ? [parentId] : void 0,
4312
+ description: uploadOpts.description
4313
+ },
4314
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
4315
+ supportsAllDrives: true
4316
+ });
3091
4317
  });
4318
+ const file = copyRes.data;
4319
+ if (this.metadataCacheInstance && file.id) {
4320
+ this.metadataCacheInstance.upsertFile({
4321
+ id: file.id,
4322
+ name: file.name || fileName,
4323
+ mimeType: file.mimeType || "",
4324
+ size: file.size ? parseInt(file.size, 10) : void 0,
4325
+ parentId,
4326
+ md5Checksum: localMd5,
4327
+ trashed: false
4328
+ });
4329
+ }
4330
+ return await this.pluginManager.runAfterUpload(file);
3092
4331
  }
3093
- return await this.pluginManager.runAfterUpload(file);
3094
4332
  }
3095
4333
  }
3096
4334
  const uploaded = await uploader.upload({
3097
- ...opts,
4335
+ ...uploadOpts,
3098
4336
  name: targetName,
3099
4337
  parent: parentId
3100
4338
  });
@@ -3132,6 +4370,16 @@ var DriveKit = class _DriveKit {
3132
4370
  const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
3133
4371
  const downloader = await this.getDownloader();
3134
4372
  const result = await downloader.download(fileId, processedOpts);
4373
+ if (processedOpts.decrypt && this.cryptoInstance && result.filePath && fs7.existsSync(result.filePath)) {
4374
+ const encrypted = await fs7.promises.readFile(result.filePath);
4375
+ const decrypted = this.cryptoInstance.decryptBuffer(encrypted);
4376
+ await fs7.promises.writeFile(result.filePath, decrypted);
4377
+ }
4378
+ if (processedOpts.decompress && result.filePath && fs7.existsSync(result.filePath)) {
4379
+ const comp = await fs7.promises.readFile(result.filePath);
4380
+ const decomp = await decompressBuffer(comp);
4381
+ await fs7.promises.writeFile(result.filePath, decomp);
4382
+ }
3135
4383
  return await this.pluginManager.runAfterDownload(result);
3136
4384
  }
3137
4385
  /**
@@ -3265,10 +4513,7 @@ var DriveKit = class _DriveKit {
3265
4513
  async copy(fileIdOrPath, options = {}) {
3266
4514
  const fileId = await this.resolveId(fileIdOrPath);
3267
4515
  const raw = await this.getRawClient();
3268
- let parentId = options.parent;
3269
- if (parentId && parentId.startsWith("/")) {
3270
- parentId = await this.mkdirp(parentId);
3271
- }
4516
+ const parentId = options.parent ? await this.resolveId(options.parent, true) : void 0;
3272
4517
  const requestBody = {};
3273
4518
  if (options.name) requestBody.name = options.name;
3274
4519
  if (parentId) requestBody.parents = [parentId];
@@ -3395,16 +4640,16 @@ var DriveKit = class _DriveKit {
3395
4640
  durationMs: 0
3396
4641
  };
3397
4642
  const collectFiles = async (dir, base) => {
3398
- const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
4643
+ const entries = await fs7.promises.readdir(dir, { withFileTypes: true });
3399
4644
  const files = [];
3400
4645
  for (const entry of entries) {
3401
- const fullPath = path8.join(dir, entry.name);
3402
- const relPath = path8.join(base, entry.name);
4646
+ const fullPath = path10.join(dir, entry.name);
4647
+ const relPath = path10.join(base, entry.name);
3403
4648
  if (entry.isDirectory()) {
3404
4649
  const sub = await collectFiles(fullPath, relPath);
3405
4650
  files.push(...sub);
3406
4651
  } else if (entry.isFile()) {
3407
- const stat = await fs6.promises.stat(fullPath);
4652
+ const stat = await fs7.promises.stat(fullPath);
3408
4653
  files.push({ fullPath, relPath, size: stat.size });
3409
4654
  }
3410
4655
  }
@@ -3417,11 +4662,11 @@ var DriveKit = class _DriveKit {
3417
4662
  if (remoteDirCache.has(relDir)) {
3418
4663
  return remoteDirCache.get(relDir);
3419
4664
  }
3420
- const parts = relDir.split(path8.sep).filter(Boolean);
4665
+ const parts = relDir.split(path10.sep).filter(Boolean);
3421
4666
  let currentParent = targetFolderId;
3422
4667
  let currentRel = "";
3423
4668
  for (const part of parts) {
3424
- currentRel = currentRel ? path8.join(currentRel, part) : part;
4669
+ currentRel = currentRel ? path10.join(currentRel, part) : part;
3425
4670
  if (remoteDirCache.has(currentRel)) {
3426
4671
  currentParent = remoteDirCache.get(currentRel);
3427
4672
  continue;
@@ -3450,8 +4695,8 @@ var DriveKit = class _DriveKit {
3450
4695
  };
3451
4696
  await pool.map(allFiles, async (fileItem) => {
3452
4697
  try {
3453
- const relDir = path8.dirname(fileItem.relPath);
3454
- const fileName = path8.basename(fileItem.relPath);
4698
+ const relDir = path10.dirname(fileItem.relPath);
4699
+ const fileName = path10.basename(fileItem.relPath);
3455
4700
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3456
4701
  if (options.onFileStart) {
3457
4702
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3594,8 +4839,8 @@ var DriveKit = class _DriveKit {
3594
4839
  rejectDone = reject;
3595
4840
  });
3596
4841
  passThrough.done = donePromise;
3597
- const remoteDir = path8.dirname(remotePath);
3598
- const fileName = options.name || options.filename || path8.basename(remotePath);
4842
+ const remoteDir = path10.dirname(remotePath);
4843
+ const fileName = options.name || options.filename || path10.basename(remotePath);
3599
4844
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3600
4845
  const mimeType = options.mimeType || "application/octet-stream";
3601
4846
  const raw = this.driveClient;
@@ -3828,6 +5073,47 @@ var DriveKit = class _DriveKit {
3828
5073
  const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3829
5074
  return await startWebDAVServer2(this, options);
3830
5075
  }
5076
+ /**
5077
+ * Performs an intelligent two-way bidirectional sync between local and Google Drive directories
5078
+ */
5079
+ async syncBiDirectional(options) {
5080
+ await this.init();
5081
+ const engine = new BidirectionalSyncEngine(this);
5082
+ return await engine.sync(options);
5083
+ }
5084
+ /**
5085
+ * Starts an embedded S3-compatible HTTP gateway server
5086
+ */
5087
+ async serveS3(options = {}) {
5088
+ await this.init();
5089
+ const gateway = new S3GatewayServer(this, options);
5090
+ await gateway.start();
5091
+ return gateway;
5092
+ }
5093
+ /**
5094
+ * Scans Google Drive files and generates a security & permission audit report
5095
+ */
5096
+ async auditPermissions(options = {}) {
5097
+ await this.init();
5098
+ const auditor = new SecurityAuditor(this.driveClient);
5099
+ return await auditor.audit(options);
5100
+ }
5101
+ /**
5102
+ * Revokes public 'anyone' link permissions from the given files
5103
+ */
5104
+ async revokePublicPermissions(fileIds) {
5105
+ await this.init();
5106
+ const auditor = new SecurityAuditor(this.driveClient);
5107
+ return await auditor.revokePublicAccess(fileIds);
5108
+ }
5109
+ /**
5110
+ * Multi-word fuzzy and semantic search across files
5111
+ */
5112
+ async searchSmart(query, options = {}) {
5113
+ await this.init();
5114
+ const engine = new SmartSearchEngine(this);
5115
+ return await engine.search(query, options);
5116
+ }
3831
5117
  /**
3832
5118
  * Calculates local file MD5 hash for integrity and deduplication checks
3833
5119
  */
@@ -4001,6 +5287,90 @@ ${chalk.cyan("\u{1F517} Getting shareable link for:")} ${chalk.bold(item.name)}.
4001
5287
  });
4002
5288
  }
4003
5289
 
5290
+ // src/integrations/middleware.ts
5291
+ init_esm_shims();
5292
+ import path11 from "path";
5293
+ import busboy from "busboy";
5294
+ function createDriveUploadMiddleware(drive2, options = {}) {
5295
+ const targetDir = options.destination || "/Uploads";
5296
+ return async (req, res, next) => {
5297
+ const contentType = req.headers["content-type"] || "";
5298
+ if (!contentType.includes("multipart/form-data")) {
5299
+ return next();
5300
+ }
5301
+ req.drivekitFiles = [];
5302
+ req.drivekitFields = {};
5303
+ const uploadPromises = [];
5304
+ try {
5305
+ const bb = busboy({
5306
+ headers: req.headers,
5307
+ limits: {
5308
+ fileSize: options.maxFileSize
5309
+ }
5310
+ });
5311
+ bb.on("file", (name, fileStream, info) => {
5312
+ const { filename, mimeType } = info;
5313
+ const rawName = filename || "upload.bin";
5314
+ const sanitizedName = path11.basename(rawName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5315
+ const rawFinalName = options.filenameGenerator ? options.filenameGenerator(sanitizedName, mimeType) : sanitizedName;
5316
+ const finalName = path11.basename(rawFinalName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5317
+ const remotePath = `${targetDir === "/" ? "" : targetDir}/${finalName}`;
5318
+ const uploadTask = (async () => {
5319
+ const driveStream = await drive2.createWriteStream(remotePath, {
5320
+ mimeType
5321
+ });
5322
+ fileStream.pipe(driveStream);
5323
+ const uploadedFile = await driveStream.done;
5324
+ req.drivekitFiles?.push(uploadedFile);
5325
+ return uploadedFile;
5326
+ })();
5327
+ uploadPromises.push(uploadTask);
5328
+ });
5329
+ bb.on("field", (name, val) => {
5330
+ if (req.drivekitFields) {
5331
+ req.drivekitFields[name] = val;
5332
+ }
5333
+ });
5334
+ bb.on("close", async () => {
5335
+ try {
5336
+ await Promise.all(uploadPromises);
5337
+ next();
5338
+ } catch (err) {
5339
+ next(err);
5340
+ }
5341
+ });
5342
+ bb.on("error", (err) => {
5343
+ next(err);
5344
+ });
5345
+ req.pipe(bb);
5346
+ } catch (err) {
5347
+ next(err);
5348
+ }
5349
+ };
5350
+ }
5351
+ async function handleNextJsUpload(formData, drive2, options = {}) {
5352
+ const targetDir = options.destination || "/Uploads";
5353
+ const results = [];
5354
+ for (const [key, value] of formData.entries()) {
5355
+ if (value && typeof value === "object" && "arrayBuffer" in value) {
5356
+ const file = value;
5357
+ const buffer = Buffer.from(await file.arrayBuffer());
5358
+ const rawName = file.name || "upload.bin";
5359
+ const sanitizedName = path11.basename(rawName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5360
+ const rawFinalName = options.filenameGenerator ? options.filenameGenerator(sanitizedName, file.type) : sanitizedName;
5361
+ const finalName = path11.basename(rawFinalName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5362
+ const uploaded = await drive2.upload({
5363
+ source: buffer,
5364
+ name: finalName,
5365
+ parent: targetDir,
5366
+ mimeType: file.type || "application/octet-stream"
5367
+ });
5368
+ results.push(uploaded);
5369
+ }
5370
+ }
5371
+ return results;
5372
+ }
5373
+
4004
5374
  // src/index.ts
4005
5375
  async function createDrive(options) {
4006
5376
  const instance = new DriveKit(options);
@@ -4009,6 +5379,7 @@ async function createDrive(options) {
4009
5379
  }
4010
5380
  var index_default = DriveKit;
4011
5381
  export {
5382
+ BidirectionalSyncEngine,
4012
5383
  ConcurrencyPool,
4013
5384
  DEFAULT_CHUNK_SIZE,
4014
5385
  DEFAULT_EXPORT_MIMES,
@@ -4017,8 +5388,10 @@ export {
4017
5388
  DriveAuthError,
4018
5389
  DriveAuthenticator,
4019
5390
  DriveFileRef,
5391
+ DriveFileRevisions,
4020
5392
  DriveFolderRef,
4021
5393
  DriveKit,
5394
+ DriveKitCrypto,
4022
5395
  DriveKitError,
4023
5396
  DriveNotFoundError,
4024
5397
  DriveQueryBuilder,
@@ -4026,20 +5399,36 @@ export {
4026
5399
  DriveUploadError,
4027
5400
  DriveWatcher,
4028
5401
  GOOGLE_WORKSPACE_MIME_TYPES,
5402
+ IV_LENGTH,
5403
+ MAGIC_HEADER,
5404
+ MAGIC_STREAM_HEADER,
4029
5405
  MIN_CHUNK_SIZE,
4030
5406
  MULTIPART_THRESHOLD,
4031
5407
  MemoryMetadataCache,
5408
+ PBKDF2_ROUNDS,
4032
5409
  PathResolver,
4033
5410
  PluginManager,
4034
5411
  ResumableUploader,
5412
+ S3GatewayServer,
5413
+ SALT_LENGTH,
5414
+ SecurityAuditor,
5415
+ SmartSearchEngine,
4035
5416
  SmartSyncEngine,
4036
5417
  SqliteMetadataCache,
4037
5418
  StorageCleaner,
5419
+ TAG_LENGTH,
4038
5420
  calculateFileMd5,
5421
+ compressBuffer,
5422
+ cosineSimilarity,
4039
5423
  createAutoNamePlugin,
5424
+ createCompressStream,
5425
+ createDecompressStream,
4040
5426
  createDrive,
5427
+ createDriveUploadMiddleware,
4041
5428
  createWebhookPlugin,
5429
+ decompressBuffer,
4042
5430
  index_default as default,
5431
+ deriveKey,
4043
5432
  escapeXml,
4044
5433
  formatBytes,
4045
5434
  formatDuration,
@@ -4048,7 +5437,9 @@ export {
4048
5437
  getFileIcon,
4049
5438
  getOptimizedHttpAgent,
4050
5439
  getOptimizedHttpsAgent,
5440
+ handleNextJsUpload,
4051
5441
  isGoogleWorkspaceDoc,
5442
+ isGzipBuffer,
4052
5443
  isRetryableError,
4053
5444
  loginWithBrowser,
4054
5445
  lookupMimeType,