drivekit 1.1.1 → 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/README.ar.md +52 -13
- package/README.md +19 -5
- package/dist/cli.cjs +2059 -282
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2048 -271
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1931 -237
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +401 -4
- package/dist/index.d.ts +401 -4
- package/dist/index.js +1900 -229
- package/dist/index.js.map +1 -1
- package/package.json +3 -1
package/dist/index.js
CHANGED
|
@@ -29,9 +29,9 @@ __export(webdav_exports, {
|
|
|
29
29
|
escapeXml: () => escapeXml,
|
|
30
30
|
startWebDAVServer: () => startWebDAVServer
|
|
31
31
|
});
|
|
32
|
-
import
|
|
32
|
+
import http4 from "http";
|
|
33
33
|
import url from "url";
|
|
34
|
-
import
|
|
34
|
+
import path9 from "path";
|
|
35
35
|
function escapeXml(unsafe) {
|
|
36
36
|
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
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 =
|
|
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,7 +64,14 @@ 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
|
|
67
|
+
const normalizedPath = path9.posix.normalize(decodedPath);
|
|
68
|
+
const virtualPath = normalizedPath.startsWith("/") ? normalizedPath : `/${normalizedPath}`;
|
|
69
|
+
const baseName = path9.basename(virtualPath);
|
|
70
|
+
if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
|
|
71
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
72
|
+
res.end("Not Found");
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
68
75
|
switch (req.method) {
|
|
69
76
|
case "OPTIONS": {
|
|
70
77
|
res.writeHead(200, {
|
|
@@ -79,6 +86,11 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
79
86
|
case "PROPFIND": {
|
|
80
87
|
const depth = req.headers["depth"] || "1";
|
|
81
88
|
const xml = await handlePropfind(drive2, virtualPath, depth);
|
|
89
|
+
if (xml === null) {
|
|
90
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
91
|
+
res.end("Not Found");
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
82
94
|
res.writeHead(207, {
|
|
83
95
|
"Content-Type": "application/xml; charset=utf-8"
|
|
84
96
|
});
|
|
@@ -143,7 +155,7 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
143
155
|
return;
|
|
144
156
|
}
|
|
145
157
|
case "PUT": {
|
|
146
|
-
const remoteDir =
|
|
158
|
+
const remoteDir = path9.dirname(virtualPath);
|
|
147
159
|
await drive2.mkdirp(remoteDir);
|
|
148
160
|
let existed = false;
|
|
149
161
|
try {
|
|
@@ -206,14 +218,14 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
206
218
|
}
|
|
207
219
|
const destUrl = url.parse(destination);
|
|
208
220
|
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
209
|
-
const newName =
|
|
210
|
-
const newParentDir =
|
|
221
|
+
const newName = path9.basename(destPath);
|
|
222
|
+
const newParentDir = path9.dirname(destPath);
|
|
211
223
|
const newParentFolderId = await drive2.mkdirp(newParentDir);
|
|
212
|
-
const currentParentDir =
|
|
224
|
+
const currentParentDir = path9.dirname(virtualPath);
|
|
213
225
|
if (newParentDir !== currentParentDir) {
|
|
214
226
|
await drive2.move(file.id, newParentFolderId);
|
|
215
227
|
}
|
|
216
|
-
if (newName !==
|
|
228
|
+
if (newName !== path9.basename(virtualPath)) {
|
|
217
229
|
await drive2.rename(file.id, newName);
|
|
218
230
|
}
|
|
219
231
|
res.writeHead(201);
|
|
@@ -240,8 +252,8 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
240
252
|
}
|
|
241
253
|
const destUrl = url.parse(destination);
|
|
242
254
|
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
243
|
-
const newName =
|
|
244
|
-
const newParentDir =
|
|
255
|
+
const newName = path9.basename(destPath);
|
|
256
|
+
const newParentDir = path9.dirname(destPath);
|
|
245
257
|
const newParentFolderId = await drive2.mkdirp(newParentDir);
|
|
246
258
|
await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
|
|
247
259
|
res.writeHead(201);
|
|
@@ -289,25 +301,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
|
|
|
289
301
|
virtualPath,
|
|
290
302
|
isFolder,
|
|
291
303
|
selfItem.size ? parseInt(selfItem.size, 10) : 0,
|
|
292
|
-
selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
304
|
+
selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
|
|
305
|
+
selfItem.mimeType || void 0
|
|
293
306
|
)
|
|
294
307
|
);
|
|
295
308
|
} catch {
|
|
296
|
-
return
|
|
309
|
+
return null;
|
|
297
310
|
}
|
|
298
311
|
}
|
|
299
312
|
if (isFolder && depth !== "0") {
|
|
300
313
|
try {
|
|
301
314
|
const children = await drive2.ls(virtualPath);
|
|
315
|
+
const seenNames = /* @__PURE__ */ new Map();
|
|
302
316
|
for (const child of children) {
|
|
317
|
+
let childName = child.name || "untitled";
|
|
318
|
+
if (seenNames.has(childName)) {
|
|
319
|
+
const count = seenNames.get(childName) + 1;
|
|
320
|
+
seenNames.set(childName, count);
|
|
321
|
+
const ext = path9.extname(childName);
|
|
322
|
+
const base = path9.basename(childName, ext);
|
|
323
|
+
childName = `${base} (${count})${ext}`;
|
|
324
|
+
} else {
|
|
325
|
+
seenNames.set(childName, 0);
|
|
326
|
+
}
|
|
303
327
|
const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
|
|
304
|
-
const childPath = virtualPath === "/" ? `/${
|
|
328
|
+
const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
|
|
305
329
|
responses.push(
|
|
306
330
|
renderWebDAVResponse(
|
|
307
331
|
childPath,
|
|
308
332
|
childIsFolder,
|
|
309
333
|
child.size ? parseInt(child.size, 10) : 0,
|
|
310
|
-
child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
334
|
+
child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
|
|
335
|
+
child.mimeType || void 0
|
|
311
336
|
)
|
|
312
337
|
);
|
|
313
338
|
}
|
|
@@ -319,11 +344,17 @@ async function handlePropfind(drive2, virtualPath, depth) {
|
|
|
319
344
|
${responses.join("\n")}
|
|
320
345
|
</D:multistatus>`;
|
|
321
346
|
}
|
|
322
|
-
function renderWebDAVResponse(href, isDir, size, modifiedTime) {
|
|
323
|
-
|
|
324
|
-
|
|
347
|
+
function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
|
|
348
|
+
let cleanHref = href;
|
|
349
|
+
if (isDir && !cleanHref.endsWith("/")) {
|
|
350
|
+
cleanHref += "/";
|
|
351
|
+
}
|
|
352
|
+
const encodedHref = encodeURI(cleanHref);
|
|
353
|
+
const displayName = escapeXml(path9.basename(href) || "root");
|
|
325
354
|
const resourceType = isDir ? "<D:collection/>" : "";
|
|
326
355
|
const dateFormatted = new Date(modifiedTime).toUTCString();
|
|
356
|
+
const contentTypeTag = !isDir && mimeType ? `
|
|
357
|
+
<D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
|
|
327
358
|
return ` <D:response>
|
|
328
359
|
<D:href>${encodedHref}</D:href>
|
|
329
360
|
<D:propstat>
|
|
@@ -331,8 +362,7 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
|
|
|
331
362
|
<D:displayname>${displayName}</D:displayname>
|
|
332
363
|
<D:resourcetype>${resourceType}</D:resourcetype>
|
|
333
364
|
<D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
|
|
334
|
-
<D:getlastmodified>${dateFormatted}</D:getlastmodified
|
|
335
|
-
<D:status>HTTP/1.1 200 OK</D:status>
|
|
365
|
+
<D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
|
|
336
366
|
</D:prop>
|
|
337
367
|
<D:status>HTTP/1.1 200 OK</D:status>
|
|
338
368
|
</D:propstat>
|
|
@@ -350,8 +380,9 @@ init_esm_shims();
|
|
|
350
380
|
|
|
351
381
|
// src/core/client.ts
|
|
352
382
|
init_esm_shims();
|
|
353
|
-
import
|
|
354
|
-
import
|
|
383
|
+
import fs7 from "fs";
|
|
384
|
+
import path10 from "path";
|
|
385
|
+
import crypto3 from "crypto";
|
|
355
386
|
import { drive } from "@googleapis/drive";
|
|
356
387
|
|
|
357
388
|
// src/auth/authenticator.ts
|
|
@@ -405,6 +436,39 @@ var DriveUploadError = class extends DriveKitError {
|
|
|
405
436
|
}
|
|
406
437
|
};
|
|
407
438
|
|
|
439
|
+
// src/utils/http-agent.ts
|
|
440
|
+
init_esm_shims();
|
|
441
|
+
import https from "https";
|
|
442
|
+
import http from "http";
|
|
443
|
+
var sharedHttpsAgent = null;
|
|
444
|
+
var sharedHttpAgent = null;
|
|
445
|
+
function getOptimizedHttpsAgent(options) {
|
|
446
|
+
if (!sharedHttpsAgent) {
|
|
447
|
+
sharedHttpsAgent = new https.Agent({
|
|
448
|
+
keepAlive: options?.keepAlive ?? true,
|
|
449
|
+
maxSockets: options?.maxSockets ?? 64,
|
|
450
|
+
maxFreeSockets: options?.maxFreeSockets ?? 32,
|
|
451
|
+
keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
|
|
452
|
+
timeout: options?.timeout ?? 3e4,
|
|
453
|
+
noDelay: true
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
return sharedHttpsAgent;
|
|
457
|
+
}
|
|
458
|
+
function getOptimizedHttpAgent(options) {
|
|
459
|
+
if (!sharedHttpAgent) {
|
|
460
|
+
sharedHttpAgent = new http.Agent({
|
|
461
|
+
keepAlive: options?.keepAlive ?? true,
|
|
462
|
+
maxSockets: options?.maxSockets ?? 64,
|
|
463
|
+
maxFreeSockets: options?.maxFreeSockets ?? 32,
|
|
464
|
+
keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
|
|
465
|
+
timeout: options?.timeout ?? 3e4,
|
|
466
|
+
noDelay: true
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
return sharedHttpAgent;
|
|
470
|
+
}
|
|
471
|
+
|
|
408
472
|
// src/auth/authenticator.ts
|
|
409
473
|
var DEFAULT_SCOPES = [
|
|
410
474
|
"https://www.googleapis.com/auth/drive"
|
|
@@ -428,44 +492,39 @@ var DriveAuthenticator = class {
|
|
|
428
492
|
const oauth2Client = new googleAuth.OAuth2();
|
|
429
493
|
oauth2Client.setCredentials({ access_token: this.config.accessToken });
|
|
430
494
|
this.authClient = oauth2Client;
|
|
431
|
-
|
|
432
|
-
}
|
|
433
|
-
if (this.config.oauth2Client) {
|
|
495
|
+
} else if (this.config.oauth2Client) {
|
|
434
496
|
this.authClient = this.config.oauth2Client;
|
|
435
|
-
|
|
436
|
-
}
|
|
437
|
-
if (this.config.oauth) {
|
|
497
|
+
} else if (this.config.oauth) {
|
|
438
498
|
const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
|
|
439
499
|
const oauth2Client = new googleAuth.OAuth2(clientId, clientSecret, redirectUri);
|
|
440
500
|
if (refreshToken) {
|
|
441
501
|
oauth2Client.setCredentials({ refresh_token: refreshToken });
|
|
442
502
|
}
|
|
443
503
|
this.authClient = oauth2Client;
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
if (keyFile) {
|
|
448
|
-
if (!fs.existsSync(keyFile)) {
|
|
504
|
+
} else if (this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS) {
|
|
505
|
+
const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
|
506
|
+
if (keyFile && !fs.existsSync(keyFile)) {
|
|
449
507
|
throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
|
|
450
508
|
}
|
|
451
|
-
const
|
|
509
|
+
const auth = new googleAuth.GoogleAuth({
|
|
452
510
|
keyFile,
|
|
453
511
|
scopes
|
|
454
512
|
});
|
|
455
|
-
this.authClient =
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
if (creds) {
|
|
460
|
-
const auth2 = new googleAuth.GoogleAuth({
|
|
513
|
+
this.authClient = auth;
|
|
514
|
+
} else if (this.config.credentials || process.env.GDRIVE_CREDENTIALS_JSON) {
|
|
515
|
+
const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
|
|
516
|
+
const auth = new googleAuth.GoogleAuth({
|
|
461
517
|
credentials: creds,
|
|
462
518
|
scopes
|
|
463
519
|
});
|
|
464
|
-
this.authClient =
|
|
465
|
-
|
|
520
|
+
this.authClient = auth;
|
|
521
|
+
} else {
|
|
522
|
+
const auth = new googleAuth.GoogleAuth({ scopes });
|
|
523
|
+
this.authClient = auth;
|
|
524
|
+
}
|
|
525
|
+
if (this.authClient?.transporter?.defaults) {
|
|
526
|
+
this.authClient.transporter.defaults.agent = getOptimizedHttpsAgent();
|
|
466
527
|
}
|
|
467
|
-
const auth = new googleAuth.GoogleAuth({ scopes });
|
|
468
|
-
this.authClient = auth;
|
|
469
528
|
return this.authClient;
|
|
470
529
|
} catch (err) {
|
|
471
530
|
if (err instanceof DriveAuthError) throw err;
|
|
@@ -604,6 +663,7 @@ var PathResolver = class {
|
|
|
604
663
|
drive;
|
|
605
664
|
rootFolderId;
|
|
606
665
|
cache = /* @__PURE__ */ new Map();
|
|
666
|
+
inFlightResolves = /* @__PURE__ */ new Map();
|
|
607
667
|
cacheTTL;
|
|
608
668
|
enableCache;
|
|
609
669
|
metadataCache;
|
|
@@ -627,8 +687,8 @@ var PathResolver = class {
|
|
|
627
687
|
/**
|
|
628
688
|
* Gets cache key for a path
|
|
629
689
|
*/
|
|
630
|
-
getCacheKey(
|
|
631
|
-
return `${this.rootFolderId}:${this.normalizePath(
|
|
690
|
+
getCacheKey(path12) {
|
|
691
|
+
return `${this.rootFolderId}:${this.normalizePath(path12)}`;
|
|
632
692
|
}
|
|
633
693
|
/**
|
|
634
694
|
* Clears the path cache
|
|
@@ -642,8 +702,8 @@ var PathResolver = class {
|
|
|
642
702
|
/**
|
|
643
703
|
* Invalidate a single path from cache
|
|
644
704
|
*/
|
|
645
|
-
invalidatePath(
|
|
646
|
-
const norm = this.normalizePath(
|
|
705
|
+
invalidatePath(path12) {
|
|
706
|
+
const norm = this.normalizePath(path12);
|
|
647
707
|
const key = this.getCacheKey(norm);
|
|
648
708
|
this.cache.delete(key);
|
|
649
709
|
if (this.metadataCache) {
|
|
@@ -656,6 +716,7 @@ var PathResolver = class {
|
|
|
656
716
|
/**
|
|
657
717
|
* Resolves a path to a Google Drive item (file or folder).
|
|
658
718
|
* If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
|
|
719
|
+
* Incorporates in-flight request coalescing to deduplicate concurrent resolutions of identical paths.
|
|
659
720
|
*/
|
|
660
721
|
async resolve(virtualPath, options = {}) {
|
|
661
722
|
const norm = this.normalizePath(virtualPath);
|
|
@@ -689,6 +750,20 @@ var PathResolver = class {
|
|
|
689
750
|
};
|
|
690
751
|
}
|
|
691
752
|
}
|
|
753
|
+
const flightKey = `${this.rootFolderId}:${norm}:${options.createIfMissing ? "create" : "read"}`;
|
|
754
|
+
const inFlight = this.inFlightResolves.get(flightKey);
|
|
755
|
+
if (inFlight) {
|
|
756
|
+
return await inFlight;
|
|
757
|
+
}
|
|
758
|
+
const task = this.doResolve(virtualPath, norm, options);
|
|
759
|
+
this.inFlightResolves.set(flightKey, task);
|
|
760
|
+
try {
|
|
761
|
+
return await task;
|
|
762
|
+
} finally {
|
|
763
|
+
this.inFlightResolves.delete(flightKey);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
async doResolve(virtualPath, norm, options) {
|
|
692
767
|
const segments = norm.split("/").filter(Boolean);
|
|
693
768
|
let currentParentId = this.rootFolderId;
|
|
694
769
|
let currentPath = "";
|
|
@@ -740,7 +815,7 @@ var PathResolver = class {
|
|
|
740
815
|
});
|
|
741
816
|
let file = response.data.files?.[0];
|
|
742
817
|
if (!file && currentParentId === this.rootFolderId) {
|
|
743
|
-
const sharedQ = `name = '${escapedName}' and trashed = false`;
|
|
818
|
+
const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
|
|
744
819
|
const sharedResponse = await withRetry(async () => {
|
|
745
820
|
return await this.drive.files.list({
|
|
746
821
|
q: sharedQ,
|
|
@@ -850,6 +925,7 @@ var PathResolver = class {
|
|
|
850
925
|
init_esm_shims();
|
|
851
926
|
import fs2 from "fs";
|
|
852
927
|
import path2 from "path";
|
|
928
|
+
import { Transform } from "stream";
|
|
853
929
|
|
|
854
930
|
// src/utils/format.ts
|
|
855
931
|
init_esm_shims();
|
|
@@ -914,6 +990,15 @@ var ResumableUploader = class {
|
|
|
914
990
|
const totalBytes = stat.size;
|
|
915
991
|
const fileName = options.name || path2.basename(filePath);
|
|
916
992
|
const mimeType = options.mimeType || lookupMimeType(filePath);
|
|
993
|
+
if (totalBytes <= MULTIPART_THRESHOLD) {
|
|
994
|
+
const readStream = fs2.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
|
|
995
|
+
const stream = options.onProgress ? this.wrapStreamWithProgress(readStream, totalBytes, options.onProgress) : readStream;
|
|
996
|
+
return await this.directUpload(stream, {
|
|
997
|
+
...options,
|
|
998
|
+
name: fileName,
|
|
999
|
+
mimeType
|
|
1000
|
+
});
|
|
1001
|
+
}
|
|
917
1002
|
return await this.chunkedUpload({
|
|
918
1003
|
filePath,
|
|
919
1004
|
totalBytes,
|
|
@@ -929,6 +1014,16 @@ var ResumableUploader = class {
|
|
|
929
1014
|
const totalBytes = buffer.length;
|
|
930
1015
|
const fileName = options.name || "untitled";
|
|
931
1016
|
const mimeType = options.mimeType || "application/octet-stream";
|
|
1017
|
+
if (totalBytes <= MULTIPART_THRESHOLD) {
|
|
1018
|
+
const { Readable } = await import("stream");
|
|
1019
|
+
const baseStream = Readable.from(totalBytes === 0 ? [] : [buffer]);
|
|
1020
|
+
const stream = options.onProgress ? this.wrapStreamWithProgress(baseStream, totalBytes, options.onProgress) : baseStream;
|
|
1021
|
+
return await this.directUpload(stream, {
|
|
1022
|
+
...options,
|
|
1023
|
+
name: fileName,
|
|
1024
|
+
mimeType
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
932
1027
|
return await this.chunkedUploadBuffer({
|
|
933
1028
|
buffer,
|
|
934
1029
|
totalBytes,
|
|
@@ -949,6 +1044,50 @@ var ResumableUploader = class {
|
|
|
949
1044
|
mimeType
|
|
950
1045
|
});
|
|
951
1046
|
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Calculates optimal chunk size based on file size for maximum throughput.
|
|
1049
|
+
*/
|
|
1050
|
+
computeAdaptiveChunkSize(totalBytes, explicitChunkSize) {
|
|
1051
|
+
if (explicitChunkSize) {
|
|
1052
|
+
return Math.max(MIN_CHUNK_SIZE, Math.floor(explicitChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE);
|
|
1053
|
+
}
|
|
1054
|
+
if (totalBytes > 128 * 1024 * 1024) {
|
|
1055
|
+
return 32 * 1024 * 1024;
|
|
1056
|
+
}
|
|
1057
|
+
if (totalBytes > 32 * 1024 * 1024) {
|
|
1058
|
+
return 16 * 1024 * 1024;
|
|
1059
|
+
}
|
|
1060
|
+
return this.defaultChunkSize;
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Attaches real-time progress monitoring to direct stream uploads.
|
|
1064
|
+
*/
|
|
1065
|
+
wrapStreamWithProgress(stream, totalBytes, onProgress) {
|
|
1066
|
+
let bytesSent = 0;
|
|
1067
|
+
const startTime = Date.now();
|
|
1068
|
+
const progressTransform = new Transform({
|
|
1069
|
+
transform(chunk, _encoding, callback) {
|
|
1070
|
+
bytesSent += chunk.length;
|
|
1071
|
+
const elapsedSecs = (Date.now() - startTime) / 1e3;
|
|
1072
|
+
const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
|
|
1073
|
+
const remainingBytes = Math.max(0, totalBytes - bytesSent);
|
|
1074
|
+
const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
|
|
1075
|
+
const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
|
|
1076
|
+
onProgress({
|
|
1077
|
+
bytesSent,
|
|
1078
|
+
totalBytes,
|
|
1079
|
+
percentage,
|
|
1080
|
+
bytesPerSecond,
|
|
1081
|
+
speedFormatted: formatSpeed(bytesPerSecond),
|
|
1082
|
+
estimatedTimeRemainingSeconds,
|
|
1083
|
+
chunkIndex: 1,
|
|
1084
|
+
totalChunks: 1
|
|
1085
|
+
});
|
|
1086
|
+
callback(null, chunk);
|
|
1087
|
+
}
|
|
1088
|
+
});
|
|
1089
|
+
return stream.pipe(progressTransform);
|
|
1090
|
+
}
|
|
952
1091
|
/**
|
|
953
1092
|
* Fast direct upload using googleapis multipart
|
|
954
1093
|
*/
|
|
@@ -981,7 +1120,7 @@ var ResumableUploader = class {
|
|
|
981
1120
|
*/
|
|
982
1121
|
async chunkedUpload(params) {
|
|
983
1122
|
const { filePath, totalBytes, fileName, mimeType, options } = params;
|
|
984
|
-
const chunkSize =
|
|
1123
|
+
const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
|
|
985
1124
|
const sessionUrl = await this.initiateResumableSession({
|
|
986
1125
|
fileName,
|
|
987
1126
|
mimeType,
|
|
@@ -1046,7 +1185,7 @@ var ResumableUploader = class {
|
|
|
1046
1185
|
*/
|
|
1047
1186
|
async chunkedUploadBuffer(params) {
|
|
1048
1187
|
const { buffer, totalBytes, fileName, mimeType, options } = params;
|
|
1049
|
-
const chunkSize =
|
|
1188
|
+
const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
|
|
1050
1189
|
const sessionUrl = await this.initiateResumableSession({
|
|
1051
1190
|
fileName,
|
|
1052
1191
|
mimeType,
|
|
@@ -1125,7 +1264,8 @@ var ResumableUploader = class {
|
|
|
1125
1264
|
url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
|
|
1126
1265
|
method: "POST",
|
|
1127
1266
|
headers,
|
|
1128
|
-
data: metadata
|
|
1267
|
+
data: metadata,
|
|
1268
|
+
agent: getOptimizedHttpsAgent()
|
|
1129
1269
|
});
|
|
1130
1270
|
});
|
|
1131
1271
|
const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
|
|
@@ -1151,6 +1291,7 @@ var ResumableUploader = class {
|
|
|
1151
1291
|
method: "PUT",
|
|
1152
1292
|
headers,
|
|
1153
1293
|
data: buffer,
|
|
1294
|
+
agent: getOptimizedHttpsAgent(),
|
|
1154
1295
|
validateStatus: (status) => status >= 200 && status < 300 || status === 308
|
|
1155
1296
|
});
|
|
1156
1297
|
if (res.status === 200 || res.status === 201) {
|
|
@@ -1184,7 +1325,7 @@ init_esm_shims();
|
|
|
1184
1325
|
import fs3 from "fs";
|
|
1185
1326
|
import path3 from "path";
|
|
1186
1327
|
import { pipeline } from "stream/promises";
|
|
1187
|
-
import { Transform } from "stream";
|
|
1328
|
+
import { Transform as Transform2 } from "stream";
|
|
1188
1329
|
var Downloader = class {
|
|
1189
1330
|
drive;
|
|
1190
1331
|
constructor(drive2) {
|
|
@@ -1194,17 +1335,22 @@ var Downloader = class {
|
|
|
1194
1335
|
* Downloads a file from Google Drive to local destination path or returns a readable stream.
|
|
1195
1336
|
*/
|
|
1196
1337
|
async download(fileId, options = {}) {
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1338
|
+
let name = options.metadata?.name;
|
|
1339
|
+
let mimeType = options.metadata?.mimeType;
|
|
1340
|
+
let totalBytes = options.metadata?.size;
|
|
1341
|
+
if (!name || !mimeType) {
|
|
1342
|
+
const metaRes = await withRetry(async () => {
|
|
1343
|
+
return await this.drive.files.get({
|
|
1344
|
+
fileId,
|
|
1345
|
+
fields: "id, name, mimeType, size",
|
|
1346
|
+
supportsAllDrives: true
|
|
1347
|
+
});
|
|
1202
1348
|
});
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1349
|
+
const file = metaRes.data;
|
|
1350
|
+
name = file.name || "downloaded-file";
|
|
1351
|
+
mimeType = file.mimeType || "application/octet-stream";
|
|
1352
|
+
totalBytes = file.size ? parseInt(file.size, 10) : void 0;
|
|
1353
|
+
}
|
|
1208
1354
|
let downloadStream;
|
|
1209
1355
|
let finalFileName = name;
|
|
1210
1356
|
if (isGoogleWorkspaceDoc(mimeType)) {
|
|
@@ -1235,7 +1381,7 @@ var Downloader = class {
|
|
|
1235
1381
|
}
|
|
1236
1382
|
let bytesRead = 0;
|
|
1237
1383
|
const startTime = Date.now();
|
|
1238
|
-
const progressTracker = new
|
|
1384
|
+
const progressTracker = new Transform2({
|
|
1239
1385
|
transform(chunk, encoding, callback) {
|
|
1240
1386
|
bytesRead += chunk.length;
|
|
1241
1387
|
if (options.onProgress) {
|
|
@@ -1260,7 +1406,7 @@ var Downloader = class {
|
|
|
1260
1406
|
destPath = path3.join(destPath, finalFileName);
|
|
1261
1407
|
}
|
|
1262
1408
|
await fs3.promises.mkdir(path3.dirname(destPath), { recursive: true });
|
|
1263
|
-
const writeStream = fs3.createWriteStream(destPath);
|
|
1409
|
+
const writeStream = fs3.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
|
|
1264
1410
|
await pipeline(monitoredStream, writeStream);
|
|
1265
1411
|
return {
|
|
1266
1412
|
filePath: destPath,
|
|
@@ -1503,6 +1649,7 @@ var DriveQueryBuilder = class {
|
|
|
1503
1649
|
const q = this.toQueryString();
|
|
1504
1650
|
const orderBy = this.orderClauses.join(", ");
|
|
1505
1651
|
let pageToken = void 0;
|
|
1652
|
+
const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
|
|
1506
1653
|
do {
|
|
1507
1654
|
const res = await withRetry(async () => {
|
|
1508
1655
|
return await this.drive.files.list({
|
|
@@ -1510,7 +1657,7 @@ var DriveQueryBuilder = class {
|
|
|
1510
1657
|
orderBy: orderBy || void 0,
|
|
1511
1658
|
pageSize: this.limitNumber,
|
|
1512
1659
|
pageToken,
|
|
1513
|
-
fields:
|
|
1660
|
+
fields: effectiveFields,
|
|
1514
1661
|
spaces: this.spaces,
|
|
1515
1662
|
supportsAllDrives: true,
|
|
1516
1663
|
includeItemsFromAllDrives: true
|
|
@@ -1634,7 +1781,7 @@ var DriveWatcher = class extends EventEmitter {
|
|
|
1634
1781
|
const res = await withRetry(async () => {
|
|
1635
1782
|
return await this.drive.changes.list({
|
|
1636
1783
|
pageToken: nextPageToken,
|
|
1637
|
-
fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
|
|
1784
|
+
fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, createdTime, modifiedTime, parents, trashed))",
|
|
1638
1785
|
supportsAllDrives: true,
|
|
1639
1786
|
includeItemsFromAllDrives: true
|
|
1640
1787
|
});
|
|
@@ -1725,16 +1872,24 @@ var StorageCleaner = class {
|
|
|
1725
1872
|
async findDuplicates(options = {}) {
|
|
1726
1873
|
const mode = options.by || "name";
|
|
1727
1874
|
const maxScan = options.maxScan || 1e3;
|
|
1728
|
-
const
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1875
|
+
const files = [];
|
|
1876
|
+
let pageToken = void 0;
|
|
1877
|
+
do {
|
|
1878
|
+
const remaining = maxScan - files.length;
|
|
1879
|
+
if (remaining <= 0) break;
|
|
1880
|
+
const res = await withRetry(async () => {
|
|
1881
|
+
return await this.drive.files.list({
|
|
1882
|
+
q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
|
|
1883
|
+
pageSize: Math.min(1e3, remaining),
|
|
1884
|
+
pageToken,
|
|
1885
|
+
fields: "nextPageToken, files(id, name, size, md5Checksum, modifiedTime)",
|
|
1886
|
+
supportsAllDrives: true,
|
|
1887
|
+
includeItemsFromAllDrives: true
|
|
1888
|
+
});
|
|
1735
1889
|
});
|
|
1736
|
-
|
|
1737
|
-
|
|
1890
|
+
files.push(...res.data.files || []);
|
|
1891
|
+
pageToken = res.data.nextPageToken || void 0;
|
|
1892
|
+
} while (pageToken && files.length < maxScan);
|
|
1738
1893
|
const map = /* @__PURE__ */ new Map();
|
|
1739
1894
|
for (const f of files) {
|
|
1740
1895
|
if (!f.id) continue;
|
|
@@ -1909,7 +2064,7 @@ var SmartSyncEngine = class {
|
|
|
1909
2064
|
|
|
1910
2065
|
// src/auth/browser-login.ts
|
|
1911
2066
|
init_esm_shims();
|
|
1912
|
-
import
|
|
2067
|
+
import http2 from "http";
|
|
1913
2068
|
import { exec } from "child_process";
|
|
1914
2069
|
import { auth as googleAuth2 } from "@googleapis/drive";
|
|
1915
2070
|
async function loginWithBrowser(options) {
|
|
@@ -1927,7 +2082,7 @@ async function loginWithBrowser(options) {
|
|
|
1927
2082
|
scope: scopes
|
|
1928
2083
|
});
|
|
1929
2084
|
return new Promise((resolve, reject) => {
|
|
1930
|
-
const server =
|
|
2085
|
+
const server = http2.createServer(async (req, res) => {
|
|
1931
2086
|
try {
|
|
1932
2087
|
const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
|
|
1933
2088
|
if (reqUrl.pathname === "/oauth2callback") {
|
|
@@ -2011,7 +2166,11 @@ ${authUrl}
|
|
|
2011
2166
|
});
|
|
2012
2167
|
});
|
|
2013
2168
|
server.on("error", (err) => {
|
|
2014
|
-
|
|
2169
|
+
if (err.code === "EADDRINUSE") {
|
|
2170
|
+
reject(new Error(`Port ${port} is already in use by another process. Please specify an alternate port with --port <number>.`));
|
|
2171
|
+
} else {
|
|
2172
|
+
reject(err);
|
|
2173
|
+
}
|
|
2015
2174
|
});
|
|
2016
2175
|
});
|
|
2017
2176
|
}
|
|
@@ -2078,6 +2237,10 @@ var DriveFileRef = class {
|
|
|
2078
2237
|
async getLink() {
|
|
2079
2238
|
return await this.drive.getShareableLink(this.pathOrId);
|
|
2080
2239
|
}
|
|
2240
|
+
/** Access historical revisions & version control for this file */
|
|
2241
|
+
get revisions() {
|
|
2242
|
+
return this.drive.getRevisions(this.pathOrId);
|
|
2243
|
+
}
|
|
2081
2244
|
/** Returns a ReadableStream for this file, optionally with byte Range requests */
|
|
2082
2245
|
async createReadStream(options) {
|
|
2083
2246
|
return await this.drive.createReadStream(this.pathOrId, options);
|
|
@@ -2283,7 +2446,7 @@ function createAutoNamePlugin(options) {
|
|
|
2283
2446
|
return {
|
|
2284
2447
|
name: "drivekit-official-autoname",
|
|
2285
2448
|
beforeUpload(opts) {
|
|
2286
|
-
let name = opts.filename;
|
|
2449
|
+
let name = opts.name || opts.filename;
|
|
2287
2450
|
if (!name && typeof opts.source === "string") {
|
|
2288
2451
|
name = path5.basename(opts.source);
|
|
2289
2452
|
}
|
|
@@ -2299,6 +2462,7 @@ function createAutoNamePlugin(options) {
|
|
|
2299
2462
|
finalName = `${finalName}${ext}`;
|
|
2300
2463
|
return {
|
|
2301
2464
|
...opts,
|
|
2465
|
+
name: finalName,
|
|
2302
2466
|
filename: finalName
|
|
2303
2467
|
};
|
|
2304
2468
|
}
|
|
@@ -2446,10 +2610,35 @@ var SqliteMetadataCache = class {
|
|
|
2446
2610
|
return;
|
|
2447
2611
|
}
|
|
2448
2612
|
if (!this.initialized || !this.db || entries.length === 0) return;
|
|
2613
|
+
const stmt = this.db.prepare(`
|
|
2614
|
+
INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
|
|
2615
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2616
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
2617
|
+
name = excluded.name,
|
|
2618
|
+
mimeType = excluded.mimeType,
|
|
2619
|
+
size = excluded.size,
|
|
2620
|
+
parentId = excluded.parentId,
|
|
2621
|
+
path = COALESCE(excluded.path, files.path),
|
|
2622
|
+
md5Checksum = excluded.md5Checksum,
|
|
2623
|
+
trashed = excluded.trashed,
|
|
2624
|
+
modifiedTime = excluded.modifiedTime,
|
|
2625
|
+
updatedAt = excluded.updatedAt
|
|
2626
|
+
`);
|
|
2449
2627
|
this.db.exec("BEGIN TRANSACTION;");
|
|
2450
2628
|
try {
|
|
2451
2629
|
for (const entry of entries) {
|
|
2452
|
-
|
|
2630
|
+
stmt.run(
|
|
2631
|
+
entry.id,
|
|
2632
|
+
entry.name,
|
|
2633
|
+
entry.mimeType ?? null,
|
|
2634
|
+
entry.size ?? null,
|
|
2635
|
+
entry.parentId ?? null,
|
|
2636
|
+
entry.path ?? null,
|
|
2637
|
+
entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
|
|
2638
|
+
entry.trashed ? 1 : 0,
|
|
2639
|
+
entry.modifiedTime ?? null,
|
|
2640
|
+
entry.updatedAt ?? Date.now()
|
|
2641
|
+
);
|
|
2453
2642
|
}
|
|
2454
2643
|
this.db.exec("COMMIT;");
|
|
2455
2644
|
} catch (e) {
|
|
@@ -2666,119 +2855,1333 @@ var MemoryMetadataCache = class {
|
|
|
2666
2855
|
}
|
|
2667
2856
|
};
|
|
2668
2857
|
|
|
2669
|
-
// src/
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
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;
|
|
2684
2881
|
}
|
|
2685
2882
|
/**
|
|
2686
|
-
*
|
|
2883
|
+
* Encrypts a Buffer using AES-256-GCM.
|
|
2884
|
+
* Format: [MAGIC (6B)][SALT (16B)][IV (12B)][TAG (16B)][CIPHERTEXT]
|
|
2687
2885
|
*/
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
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]);
|
|
2691
2894
|
}
|
|
2692
2895
|
/**
|
|
2693
|
-
*
|
|
2896
|
+
* Decrypts a Buffer previously encrypted with encryptBuffer or createEncryptStream.
|
|
2694
2897
|
*/
|
|
2695
|
-
|
|
2696
|
-
|
|
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()]);
|
|
2697
2923
|
}
|
|
2698
2924
|
/**
|
|
2699
|
-
*
|
|
2925
|
+
* Creates an encryption Transform stream that prepends stream header and appends GCM auth tag
|
|
2700
2926
|
*/
|
|
2701
|
-
|
|
2702
|
-
|
|
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
|
+
});
|
|
2703
2956
|
}
|
|
2704
2957
|
/**
|
|
2705
|
-
*
|
|
2958
|
+
* Creates a decryption Transform stream that verifies magic header and validates GCM authentication tag
|
|
2706
2959
|
*/
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
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
|
+
}
|
|
2714
3041
|
}
|
|
2715
|
-
|
|
2716
|
-
enableCache: this.options.enablePathCache ?? true,
|
|
2717
|
-
cacheTTL: this.options.pathCacheTTL,
|
|
2718
|
-
metadataCache: this.metadataCacheInstance || void 0
|
|
2719
|
-
});
|
|
2720
|
-
this.uploaderInstance = new ResumableUploader(
|
|
2721
|
-
this.driveClient,
|
|
2722
|
-
this.options.uploadChunkSize || DEFAULT_CHUNK_SIZE
|
|
2723
|
-
);
|
|
2724
|
-
this.downloaderInstance = new Downloader(this.driveClient);
|
|
2725
|
-
}
|
|
2726
|
-
return this;
|
|
3042
|
+
});
|
|
2727
3043
|
}
|
|
2728
3044
|
/**
|
|
2729
|
-
*
|
|
3045
|
+
* Encrypts a filename into a safe base64url string
|
|
2730
3046
|
*/
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
await this.init();
|
|
2741
|
-
return this.uploaderInstance;
|
|
2742
|
-
}
|
|
2743
|
-
async getDownloader() {
|
|
2744
|
-
await this.init();
|
|
2745
|
-
return this.downloaderInstance;
|
|
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`;
|
|
2746
3056
|
}
|
|
2747
3057
|
/**
|
|
2748
|
-
*
|
|
3058
|
+
* Decrypts a filename generated by encryptFilename
|
|
2749
3059
|
*/
|
|
2750
|
-
|
|
2751
|
-
if (
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
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;
|
|
2755
3079
|
}
|
|
2756
|
-
return idOrPath;
|
|
2757
3080
|
}
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
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
|
+
}
|
|
2761
3100
|
/**
|
|
2762
|
-
*
|
|
2763
|
-
* @param virtualPath Path like "/Documents/Projects/2026"
|
|
2764
|
-
* @returns Folder ID of the created or existing directory
|
|
3101
|
+
* Lists all historical revisions of the file
|
|
2765
3102
|
*/
|
|
2766
|
-
async
|
|
2767
|
-
const
|
|
2768
|
-
|
|
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
|
+
}));
|
|
2769
3120
|
}
|
|
2770
3121
|
/**
|
|
2771
|
-
*
|
|
3122
|
+
* Gets metadata for a specific revision
|
|
2772
3123
|
*/
|
|
2773
|
-
async
|
|
2774
|
-
const
|
|
2775
|
-
|
|
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
|
+
};
|
|
2776
3142
|
}
|
|
2777
3143
|
/**
|
|
2778
|
-
*
|
|
3144
|
+
* Pins or unpins a revision so Google Drive never automatically purges it after 30 days
|
|
2779
3145
|
*/
|
|
2780
|
-
async
|
|
2781
|
-
|
|
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 "<";
|
|
3708
|
+
case ">":
|
|
3709
|
+
return ">";
|
|
3710
|
+
case "&":
|
|
3711
|
+
return "&";
|
|
3712
|
+
case "'":
|
|
3713
|
+
return "'";
|
|
3714
|
+
case '"':
|
|
3715
|
+
return """;
|
|
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
|
+
|
|
4037
|
+
// src/core/client.ts
|
|
4038
|
+
var DriveKit = class _DriveKit {
|
|
4039
|
+
options;
|
|
4040
|
+
authenticator;
|
|
4041
|
+
driveClient = null;
|
|
4042
|
+
pathResolverInstance = null;
|
|
4043
|
+
uploaderInstance = null;
|
|
4044
|
+
downloaderInstance = null;
|
|
4045
|
+
metadataCacheInstance = null;
|
|
4046
|
+
cryptoInstance = null;
|
|
4047
|
+
rootFolderId;
|
|
4048
|
+
pluginManager = new PluginManager();
|
|
4049
|
+
constructor(options = {}) {
|
|
4050
|
+
this.options = options;
|
|
4051
|
+
this.rootFolderId = options.rootFolderId || "root";
|
|
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));
|
|
4074
|
+
}
|
|
4075
|
+
/**
|
|
4076
|
+
* Registers a middleware plugin into DriveKit lifecycle
|
|
4077
|
+
*/
|
|
4078
|
+
use(plugin) {
|
|
4079
|
+
this.pluginManager.use(plugin);
|
|
4080
|
+
return this;
|
|
4081
|
+
}
|
|
4082
|
+
/**
|
|
4083
|
+
* Unregisters a middleware plugin by name
|
|
4084
|
+
*/
|
|
4085
|
+
unuse(pluginName) {
|
|
4086
|
+
return this.pluginManager.unuse(pluginName);
|
|
4087
|
+
}
|
|
4088
|
+
/**
|
|
4089
|
+
* Access the underlying plugin manager instance
|
|
4090
|
+
*/
|
|
4091
|
+
get plugins() {
|
|
4092
|
+
return this.pluginManager;
|
|
4093
|
+
}
|
|
4094
|
+
/**
|
|
4095
|
+
* Returns a fluent, chained reference to a specific file
|
|
4096
|
+
*/
|
|
4097
|
+
file(pathOrId) {
|
|
4098
|
+
return new DriveFileRef(this, pathOrId);
|
|
4099
|
+
}
|
|
4100
|
+
/**
|
|
4101
|
+
* Returns a fluent, chained reference to a specific folder
|
|
4102
|
+
*/
|
|
4103
|
+
folder(pathOrId) {
|
|
4104
|
+
return new DriveFolderRef(this, pathOrId);
|
|
4105
|
+
}
|
|
4106
|
+
/**
|
|
4107
|
+
* Initializes the Google Drive API client (lazy-loaded if not called explicitly)
|
|
4108
|
+
*/
|
|
4109
|
+
async init() {
|
|
4110
|
+
if (!this.driveClient) {
|
|
4111
|
+
const auth = await this.authenticator.getAuthClient();
|
|
4112
|
+
const agent = getOptimizedHttpsAgent();
|
|
4113
|
+
this.driveClient = drive({ version: "v3", auth, agent });
|
|
4114
|
+
if (this.options.enablePersistentCache !== false) {
|
|
4115
|
+
this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
|
|
4116
|
+
this.metadataCacheInstance.init();
|
|
4117
|
+
}
|
|
4118
|
+
this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
|
|
4119
|
+
enableCache: this.options.enablePathCache ?? true,
|
|
4120
|
+
cacheTTL: this.options.pathCacheTTL,
|
|
4121
|
+
metadataCache: this.metadataCacheInstance || void 0
|
|
4122
|
+
});
|
|
4123
|
+
this.uploaderInstance = new ResumableUploader(
|
|
4124
|
+
this.driveClient,
|
|
4125
|
+
this.options.uploadChunkSize || DEFAULT_CHUNK_SIZE
|
|
4126
|
+
);
|
|
4127
|
+
this.downloaderInstance = new Downloader(this.driveClient);
|
|
4128
|
+
}
|
|
4129
|
+
return this;
|
|
4130
|
+
}
|
|
4131
|
+
/**
|
|
4132
|
+
* Access the underlying official `@googleapis/drive` instance for raw API calls
|
|
4133
|
+
*/
|
|
4134
|
+
async getRawClient() {
|
|
4135
|
+
await this.init();
|
|
4136
|
+
return this.driveClient;
|
|
4137
|
+
}
|
|
4138
|
+
async getResolver() {
|
|
4139
|
+
await this.init();
|
|
4140
|
+
return this.pathResolverInstance;
|
|
4141
|
+
}
|
|
4142
|
+
async getUploader() {
|
|
4143
|
+
await this.init();
|
|
4144
|
+
return this.uploaderInstance;
|
|
4145
|
+
}
|
|
4146
|
+
async getDownloader() {
|
|
4147
|
+
await this.init();
|
|
4148
|
+
return this.downloaderInstance;
|
|
4149
|
+
}
|
|
4150
|
+
/**
|
|
4151
|
+
* Resolves a target string that could be either an ID or a virtual path (starting with '/')
|
|
4152
|
+
*/
|
|
4153
|
+
async resolveId(idOrPath, autoCreateDir = false) {
|
|
4154
|
+
if (idOrPath.startsWith("/")) {
|
|
4155
|
+
const resolver = await this.getResolver();
|
|
4156
|
+
const res = await resolver.resolve(idOrPath, { createIfMissing: autoCreateDir });
|
|
4157
|
+
return res.id;
|
|
4158
|
+
}
|
|
4159
|
+
return idOrPath;
|
|
4160
|
+
}
|
|
4161
|
+
// ==========================================
|
|
4162
|
+
// DIRECTORY & PATH OPERATIONS
|
|
4163
|
+
// ==========================================
|
|
4164
|
+
/**
|
|
4165
|
+
* Creates a folder structure recursively, similar to `mkdir -p`.
|
|
4166
|
+
* @param virtualPath Path like "/Documents/Projects/2026"
|
|
4167
|
+
* @returns Folder ID of the created or existing directory
|
|
4168
|
+
*/
|
|
4169
|
+
async mkdirp(virtualPath) {
|
|
4170
|
+
const resolver = await this.getResolver();
|
|
4171
|
+
return await resolver.mkdirp(virtualPath);
|
|
4172
|
+
}
|
|
4173
|
+
/**
|
|
4174
|
+
* Resolves a virtual path to its Drive metadata
|
|
4175
|
+
*/
|
|
4176
|
+
async resolvePath(virtualPath) {
|
|
4177
|
+
const resolver = await this.getResolver();
|
|
4178
|
+
return await resolver.resolve(virtualPath);
|
|
4179
|
+
}
|
|
4180
|
+
/**
|
|
4181
|
+
* Check if a file or folder exists (by ID or virtual path)
|
|
4182
|
+
*/
|
|
4183
|
+
async exists(idOrPath) {
|
|
4184
|
+
try {
|
|
2782
4185
|
if (idOrPath.startsWith("/")) {
|
|
2783
4186
|
await this.resolvePath(idOrPath);
|
|
2784
4187
|
return true;
|
|
@@ -2794,15 +4197,41 @@ var DriveKit = class _DriveKit {
|
|
|
2794
4197
|
}
|
|
2795
4198
|
}
|
|
2796
4199
|
/**
|
|
2797
|
-
* Lists contents of a folder (by folder ID or path)
|
|
4200
|
+
* Lists contents of a folder (by folder ID or path) with opportunistic tree caching
|
|
2798
4201
|
*/
|
|
2799
4202
|
async ls(folderIdOrPath = "/") {
|
|
4203
|
+
let parentFolderId;
|
|
4204
|
+
let normalizedPath = null;
|
|
4205
|
+
let files;
|
|
2800
4206
|
if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
|
|
4207
|
+
parentFolderId = this.rootFolderId;
|
|
4208
|
+
normalizedPath = "/";
|
|
2801
4209
|
const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
|
|
2802
|
-
|
|
4210
|
+
files = await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
|
|
4211
|
+
} else {
|
|
4212
|
+
if (folderIdOrPath.startsWith("/")) {
|
|
4213
|
+
normalizedPath = folderIdOrPath.replace(/\/+$/, "") || "/";
|
|
4214
|
+
parentFolderId = await this.resolveId(normalizedPath);
|
|
4215
|
+
} else {
|
|
4216
|
+
parentFolderId = folderIdOrPath;
|
|
4217
|
+
}
|
|
4218
|
+
files = await this.query().inFolder(parentFolderId).notTrashed().orderBy("folder,name").list();
|
|
2803
4219
|
}
|
|
2804
|
-
|
|
2805
|
-
|
|
4220
|
+
if (this.metadataCacheInstance && files.length > 0) {
|
|
4221
|
+
const cacheEntries = files.filter((f) => !!f.id).map((f) => ({
|
|
4222
|
+
id: f.id,
|
|
4223
|
+
name: f.name || "untitled",
|
|
4224
|
+
mimeType: f.mimeType || "",
|
|
4225
|
+
size: f.size ? parseInt(f.size, 10) : void 0,
|
|
4226
|
+
parentId: parentFolderId,
|
|
4227
|
+
path: normalizedPath ? `${normalizedPath === "/" ? "" : normalizedPath}/${f.name}` : void 0,
|
|
4228
|
+
md5Checksum: f.md5Checksum || void 0,
|
|
4229
|
+
modifiedTime: f.modifiedTime || void 0,
|
|
4230
|
+
trashed: false
|
|
4231
|
+
}));
|
|
4232
|
+
this.metadataCacheInstance.upsertFiles(cacheEntries);
|
|
4233
|
+
}
|
|
4234
|
+
return files;
|
|
2806
4235
|
}
|
|
2807
4236
|
// ==========================================
|
|
2808
4237
|
// FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
|
|
@@ -2821,68 +4250,101 @@ var DriveKit = class _DriveKit {
|
|
|
2821
4250
|
if (parentId && parentId.startsWith("/")) {
|
|
2822
4251
|
parentId = await this.mkdirp(parentId);
|
|
2823
4252
|
}
|
|
2824
|
-
|
|
2825
|
-
if (
|
|
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) {
|
|
2826
4279
|
const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
|
|
2827
4280
|
if (existing?.id) {
|
|
2828
4281
|
await this.delete(existing.id, true);
|
|
2829
4282
|
}
|
|
2830
4283
|
}
|
|
2831
|
-
if (
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
}
|
|
2838
|
-
if (
|
|
2839
|
-
|
|
2840
|
-
if (
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
mimeType: file.mimeType || "",
|
|
2865
|
-
size: file.size ? parseInt(file.size, 10) : void 0,
|
|
2866
|
-
parentId,
|
|
2867
|
-
md5Checksum: localMd5,
|
|
2868
|
-
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
|
+
});
|
|
2869
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);
|
|
2870
4331
|
}
|
|
2871
|
-
return await this.pluginManager.runAfterUpload(file);
|
|
2872
4332
|
}
|
|
2873
4333
|
}
|
|
2874
4334
|
const uploaded = await uploader.upload({
|
|
2875
|
-
...
|
|
4335
|
+
...uploadOpts,
|
|
2876
4336
|
name: targetName,
|
|
2877
4337
|
parent: parentId
|
|
2878
4338
|
});
|
|
2879
4339
|
if (this.metadataCacheInstance && uploaded.id) {
|
|
4340
|
+
const virtualPath = typeof opts.parent === "string" && opts.parent.startsWith("/") ? `${opts.parent === "/" ? "" : opts.parent}/${uploaded.name || targetName || "untitled"}` : void 0;
|
|
2880
4341
|
this.metadataCacheInstance.upsertFile({
|
|
2881
4342
|
id: uploaded.id,
|
|
2882
4343
|
name: uploaded.name || targetName || "untitled",
|
|
2883
4344
|
mimeType: uploaded.mimeType || "",
|
|
2884
4345
|
size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
|
|
2885
4346
|
parentId,
|
|
4347
|
+
path: virtualPath,
|
|
2886
4348
|
trashed: false
|
|
2887
4349
|
});
|
|
2888
4350
|
}
|
|
@@ -2893,16 +4355,35 @@ var DriveKit = class _DriveKit {
|
|
|
2893
4355
|
* - Automatic conversion for Google Docs, Sheets, and Slides
|
|
2894
4356
|
* - Progress events
|
|
2895
4357
|
* - Saves directly to file or returns Readable Stream
|
|
4358
|
+
* - Leverages local metadata cache to bypass redundant Google API roundtrips
|
|
2896
4359
|
*/
|
|
2897
4360
|
async download(fileIdOrPath, options = {}) {
|
|
2898
4361
|
const fileId = await this.resolveId(fileIdOrPath);
|
|
2899
|
-
|
|
4362
|
+
let cachedMeta = options.metadata;
|
|
4363
|
+
if (!cachedMeta && this.metadataCacheInstance) {
|
|
4364
|
+
const cached = this.metadataCacheInstance.getById(fileId);
|
|
4365
|
+
if (cached && cached.name && cached.mimeType) {
|
|
4366
|
+
cachedMeta = { name: cached.name, mimeType: cached.mimeType, size: cached.size };
|
|
4367
|
+
}
|
|
4368
|
+
}
|
|
4369
|
+
const mergedOpts = cachedMeta ? { ...options, metadata: cachedMeta } : options;
|
|
4370
|
+
const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
|
|
2900
4371
|
const downloader = await this.getDownloader();
|
|
2901
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
|
+
}
|
|
2902
4383
|
return await this.pluginManager.runAfterDownload(result);
|
|
2903
4384
|
}
|
|
2904
4385
|
/**
|
|
2905
|
-
* Gets file metadata
|
|
4386
|
+
* Gets file metadata and updates the local metadata cache
|
|
2906
4387
|
*/
|
|
2907
4388
|
async getFile(fileIdOrPath) {
|
|
2908
4389
|
const fileId = await this.resolveId(fileIdOrPath);
|
|
@@ -2914,7 +4395,20 @@ var DriveKit = class _DriveKit {
|
|
|
2914
4395
|
supportsAllDrives: true
|
|
2915
4396
|
});
|
|
2916
4397
|
});
|
|
2917
|
-
|
|
4398
|
+
const file = res.data;
|
|
4399
|
+
if (this.metadataCacheInstance && file.id) {
|
|
4400
|
+
this.metadataCacheInstance.upsertFile({
|
|
4401
|
+
id: file.id,
|
|
4402
|
+
name: file.name || "",
|
|
4403
|
+
mimeType: file.mimeType || "",
|
|
4404
|
+
size: file.size ? parseInt(file.size, 10) : void 0,
|
|
4405
|
+
parentId: file.parents?.[0],
|
|
4406
|
+
path: fileIdOrPath.startsWith("/") ? fileIdOrPath : void 0,
|
|
4407
|
+
modifiedTime: file.modifiedTime || void 0,
|
|
4408
|
+
trashed: file.trashed || false
|
|
4409
|
+
});
|
|
4410
|
+
}
|
|
4411
|
+
return file;
|
|
2918
4412
|
}
|
|
2919
4413
|
/**
|
|
2920
4414
|
* Reads file content as UTF-8 string
|
|
@@ -2957,6 +4451,9 @@ var DriveKit = class _DriveKit {
|
|
|
2957
4451
|
if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
|
|
2958
4452
|
this.pathResolverInstance.invalidatePath(fileIdOrPath);
|
|
2959
4453
|
}
|
|
4454
|
+
if (this.metadataCacheInstance) {
|
|
4455
|
+
this.metadataCacheInstance.deleteFile(fileId);
|
|
4456
|
+
}
|
|
2960
4457
|
}
|
|
2961
4458
|
/**
|
|
2962
4459
|
* Move item to trash
|
|
@@ -2998,6 +4495,16 @@ var DriveKit = class _DriveKit {
|
|
|
2998
4495
|
if (this.pathResolverInstance) {
|
|
2999
4496
|
this.pathResolverInstance.clearCache();
|
|
3000
4497
|
}
|
|
4498
|
+
if (this.metadataCacheInstance) {
|
|
4499
|
+
const cached = this.metadataCacheInstance.getById(fileId);
|
|
4500
|
+
if (cached) {
|
|
4501
|
+
this.metadataCacheInstance.upsertFile({
|
|
4502
|
+
...cached,
|
|
4503
|
+
parentId: newParentId,
|
|
4504
|
+
path: void 0
|
|
4505
|
+
});
|
|
4506
|
+
}
|
|
4507
|
+
}
|
|
3001
4508
|
return res.data;
|
|
3002
4509
|
}
|
|
3003
4510
|
/**
|
|
@@ -3006,10 +4513,7 @@ var DriveKit = class _DriveKit {
|
|
|
3006
4513
|
async copy(fileIdOrPath, options = {}) {
|
|
3007
4514
|
const fileId = await this.resolveId(fileIdOrPath);
|
|
3008
4515
|
const raw = await this.getRawClient();
|
|
3009
|
-
|
|
3010
|
-
if (parentId && parentId.startsWith("/")) {
|
|
3011
|
-
parentId = await this.mkdirp(parentId);
|
|
3012
|
-
}
|
|
4516
|
+
const parentId = options.parent ? await this.resolveId(options.parent, true) : void 0;
|
|
3013
4517
|
const requestBody = {};
|
|
3014
4518
|
if (options.name) requestBody.name = options.name;
|
|
3015
4519
|
if (parentId) requestBody.parents = [parentId];
|
|
@@ -3040,6 +4544,16 @@ var DriveKit = class _DriveKit {
|
|
|
3040
4544
|
if (this.pathResolverInstance) {
|
|
3041
4545
|
this.pathResolverInstance.clearCache();
|
|
3042
4546
|
}
|
|
4547
|
+
if (this.metadataCacheInstance) {
|
|
4548
|
+
const cached = this.metadataCacheInstance.getById(fileId);
|
|
4549
|
+
if (cached) {
|
|
4550
|
+
this.metadataCacheInstance.upsertFile({
|
|
4551
|
+
...cached,
|
|
4552
|
+
name: newName,
|
|
4553
|
+
path: void 0
|
|
4554
|
+
});
|
|
4555
|
+
}
|
|
4556
|
+
}
|
|
3043
4557
|
return res.data;
|
|
3044
4558
|
}
|
|
3045
4559
|
// ==========================================
|
|
@@ -3126,16 +4640,16 @@ var DriveKit = class _DriveKit {
|
|
|
3126
4640
|
durationMs: 0
|
|
3127
4641
|
};
|
|
3128
4642
|
const collectFiles = async (dir, base) => {
|
|
3129
|
-
const entries = await
|
|
4643
|
+
const entries = await fs7.promises.readdir(dir, { withFileTypes: true });
|
|
3130
4644
|
const files = [];
|
|
3131
4645
|
for (const entry of entries) {
|
|
3132
|
-
const fullPath =
|
|
3133
|
-
const relPath =
|
|
4646
|
+
const fullPath = path10.join(dir, entry.name);
|
|
4647
|
+
const relPath = path10.join(base, entry.name);
|
|
3134
4648
|
if (entry.isDirectory()) {
|
|
3135
4649
|
const sub = await collectFiles(fullPath, relPath);
|
|
3136
4650
|
files.push(...sub);
|
|
3137
4651
|
} else if (entry.isFile()) {
|
|
3138
|
-
const stat = await
|
|
4652
|
+
const stat = await fs7.promises.stat(fullPath);
|
|
3139
4653
|
files.push({ fullPath, relPath, size: stat.size });
|
|
3140
4654
|
}
|
|
3141
4655
|
}
|
|
@@ -3148,11 +4662,11 @@ var DriveKit = class _DriveKit {
|
|
|
3148
4662
|
if (remoteDirCache.has(relDir)) {
|
|
3149
4663
|
return remoteDirCache.get(relDir);
|
|
3150
4664
|
}
|
|
3151
|
-
const parts = relDir.split(
|
|
4665
|
+
const parts = relDir.split(path10.sep).filter(Boolean);
|
|
3152
4666
|
let currentParent = targetFolderId;
|
|
3153
4667
|
let currentRel = "";
|
|
3154
4668
|
for (const part of parts) {
|
|
3155
|
-
currentRel = currentRel ?
|
|
4669
|
+
currentRel = currentRel ? path10.join(currentRel, part) : part;
|
|
3156
4670
|
if (remoteDirCache.has(currentRel)) {
|
|
3157
4671
|
currentParent = remoteDirCache.get(currentRel);
|
|
3158
4672
|
continue;
|
|
@@ -3181,8 +4695,8 @@ var DriveKit = class _DriveKit {
|
|
|
3181
4695
|
};
|
|
3182
4696
|
await pool.map(allFiles, async (fileItem) => {
|
|
3183
4697
|
try {
|
|
3184
|
-
const relDir =
|
|
3185
|
-
const fileName =
|
|
4698
|
+
const relDir = path10.dirname(fileItem.relPath);
|
|
4699
|
+
const fileName = path10.basename(fileItem.relPath);
|
|
3186
4700
|
const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
|
|
3187
4701
|
if (options.onFileStart) {
|
|
3188
4702
|
options.onFileStart(fileItem.fullPath, fileItem.relPath);
|
|
@@ -3317,7 +4831,7 @@ var DriveKit = class _DriveKit {
|
|
|
3317
4831
|
async createWriteStream(remotePath, options = {}) {
|
|
3318
4832
|
await this.init();
|
|
3319
4833
|
const { PassThrough } = await import("stream");
|
|
3320
|
-
const passThrough = new PassThrough();
|
|
4834
|
+
const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
|
|
3321
4835
|
let resolveDone;
|
|
3322
4836
|
let rejectDone;
|
|
3323
4837
|
const donePromise = new Promise((resolve, reject) => {
|
|
@@ -3325,8 +4839,8 @@ var DriveKit = class _DriveKit {
|
|
|
3325
4839
|
rejectDone = reject;
|
|
3326
4840
|
});
|
|
3327
4841
|
passThrough.done = donePromise;
|
|
3328
|
-
const remoteDir =
|
|
3329
|
-
const fileName = options.name || options.filename ||
|
|
4842
|
+
const remoteDir = path10.dirname(remotePath);
|
|
4843
|
+
const fileName = options.name || options.filename || path10.basename(remotePath);
|
|
3330
4844
|
const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
|
|
3331
4845
|
const mimeType = options.mimeType || "application/octet-stream";
|
|
3332
4846
|
const raw = this.driveClient;
|
|
@@ -3364,6 +4878,12 @@ var DriveKit = class _DriveKit {
|
|
|
3364
4878
|
// ==========================================
|
|
3365
4879
|
// METADATA CACHE OPERATIONS
|
|
3366
4880
|
// ==========================================
|
|
4881
|
+
/**
|
|
4882
|
+
* Synchronous getter for the active metadata cache instance
|
|
4883
|
+
*/
|
|
4884
|
+
get cache() {
|
|
4885
|
+
return this.metadataCacheInstance;
|
|
4886
|
+
}
|
|
3367
4887
|
/**
|
|
3368
4888
|
* Returns the active persistent metadata cache instance (SQLite/Memory)
|
|
3369
4889
|
*/
|
|
@@ -3386,6 +4906,9 @@ var DriveKit = class _DriveKit {
|
|
|
3386
4906
|
if (this.pathResolverInstance) {
|
|
3387
4907
|
this.pathResolverInstance.clearCache();
|
|
3388
4908
|
}
|
|
4909
|
+
if (this.metadataCacheInstance) {
|
|
4910
|
+
this.metadataCacheInstance.clear();
|
|
4911
|
+
}
|
|
3389
4912
|
}
|
|
3390
4913
|
/**
|
|
3391
4914
|
* Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
|
|
@@ -3550,6 +5073,47 @@ var DriveKit = class _DriveKit {
|
|
|
3550
5073
|
const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
|
|
3551
5074
|
return await startWebDAVServer2(this, options);
|
|
3552
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
|
+
}
|
|
3553
5117
|
/**
|
|
3554
5118
|
* Calculates local file MD5 hash for integrity and deduplication checks
|
|
3555
5119
|
*/
|
|
@@ -3723,6 +5287,90 @@ ${chalk.cyan("\u{1F517} Getting shareable link for:")} ${chalk.bold(item.name)}.
|
|
|
3723
5287
|
});
|
|
3724
5288
|
}
|
|
3725
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
|
+
|
|
3726
5374
|
// src/index.ts
|
|
3727
5375
|
async function createDrive(options) {
|
|
3728
5376
|
const instance = new DriveKit(options);
|
|
@@ -3731,6 +5379,7 @@ async function createDrive(options) {
|
|
|
3731
5379
|
}
|
|
3732
5380
|
var index_default = DriveKit;
|
|
3733
5381
|
export {
|
|
5382
|
+
BidirectionalSyncEngine,
|
|
3734
5383
|
ConcurrencyPool,
|
|
3735
5384
|
DEFAULT_CHUNK_SIZE,
|
|
3736
5385
|
DEFAULT_EXPORT_MIMES,
|
|
@@ -3739,8 +5388,10 @@ export {
|
|
|
3739
5388
|
DriveAuthError,
|
|
3740
5389
|
DriveAuthenticator,
|
|
3741
5390
|
DriveFileRef,
|
|
5391
|
+
DriveFileRevisions,
|
|
3742
5392
|
DriveFolderRef,
|
|
3743
5393
|
DriveKit,
|
|
5394
|
+
DriveKitCrypto,
|
|
3744
5395
|
DriveKitError,
|
|
3745
5396
|
DriveNotFoundError,
|
|
3746
5397
|
DriveQueryBuilder,
|
|
@@ -3748,27 +5399,47 @@ export {
|
|
|
3748
5399
|
DriveUploadError,
|
|
3749
5400
|
DriveWatcher,
|
|
3750
5401
|
GOOGLE_WORKSPACE_MIME_TYPES,
|
|
5402
|
+
IV_LENGTH,
|
|
5403
|
+
MAGIC_HEADER,
|
|
5404
|
+
MAGIC_STREAM_HEADER,
|
|
3751
5405
|
MIN_CHUNK_SIZE,
|
|
3752
5406
|
MULTIPART_THRESHOLD,
|
|
3753
5407
|
MemoryMetadataCache,
|
|
5408
|
+
PBKDF2_ROUNDS,
|
|
3754
5409
|
PathResolver,
|
|
3755
5410
|
PluginManager,
|
|
3756
5411
|
ResumableUploader,
|
|
5412
|
+
S3GatewayServer,
|
|
5413
|
+
SALT_LENGTH,
|
|
5414
|
+
SecurityAuditor,
|
|
5415
|
+
SmartSearchEngine,
|
|
3757
5416
|
SmartSyncEngine,
|
|
3758
5417
|
SqliteMetadataCache,
|
|
3759
5418
|
StorageCleaner,
|
|
5419
|
+
TAG_LENGTH,
|
|
3760
5420
|
calculateFileMd5,
|
|
5421
|
+
compressBuffer,
|
|
5422
|
+
cosineSimilarity,
|
|
3761
5423
|
createAutoNamePlugin,
|
|
5424
|
+
createCompressStream,
|
|
5425
|
+
createDecompressStream,
|
|
3762
5426
|
createDrive,
|
|
5427
|
+
createDriveUploadMiddleware,
|
|
3763
5428
|
createWebhookPlugin,
|
|
5429
|
+
decompressBuffer,
|
|
3764
5430
|
index_default as default,
|
|
5431
|
+
deriveKey,
|
|
3765
5432
|
escapeXml,
|
|
3766
5433
|
formatBytes,
|
|
3767
5434
|
formatDuration,
|
|
3768
5435
|
formatSpeed,
|
|
3769
5436
|
getExtensionForMime,
|
|
3770
5437
|
getFileIcon,
|
|
5438
|
+
getOptimizedHttpAgent,
|
|
5439
|
+
getOptimizedHttpsAgent,
|
|
5440
|
+
handleNextJsUpload,
|
|
3771
5441
|
isGoogleWorkspaceDoc,
|
|
5442
|
+
isGzipBuffer,
|
|
3772
5443
|
isRetryableError,
|
|
3773
5444
|
loginWithBrowser,
|
|
3774
5445
|
lookupMimeType,
|