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/cli.cjs
CHANGED
|
@@ -92,6 +92,31 @@ var init_errors = __esm({
|
|
|
92
92
|
}
|
|
93
93
|
});
|
|
94
94
|
|
|
95
|
+
// src/utils/http-agent.ts
|
|
96
|
+
function getOptimizedHttpsAgent(options) {
|
|
97
|
+
if (!sharedHttpsAgent) {
|
|
98
|
+
sharedHttpsAgent = new import_node_https.default.Agent({
|
|
99
|
+
keepAlive: options?.keepAlive ?? true,
|
|
100
|
+
maxSockets: options?.maxSockets ?? 64,
|
|
101
|
+
maxFreeSockets: options?.maxFreeSockets ?? 32,
|
|
102
|
+
keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
|
|
103
|
+
timeout: options?.timeout ?? 3e4,
|
|
104
|
+
noDelay: true
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return sharedHttpsAgent;
|
|
108
|
+
}
|
|
109
|
+
var import_node_https, import_node_http, sharedHttpsAgent;
|
|
110
|
+
var init_http_agent = __esm({
|
|
111
|
+
"src/utils/http-agent.ts"() {
|
|
112
|
+
"use strict";
|
|
113
|
+
init_cjs_shims();
|
|
114
|
+
import_node_https = __toESM(require("https"), 1);
|
|
115
|
+
import_node_http = __toESM(require("http"), 1);
|
|
116
|
+
sharedHttpsAgent = null;
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
95
120
|
// src/auth/authenticator.ts
|
|
96
121
|
var import_node_fs, import_drive, DEFAULT_SCOPES, DriveAuthenticator;
|
|
97
122
|
var init_authenticator = __esm({
|
|
@@ -101,6 +126,7 @@ var init_authenticator = __esm({
|
|
|
101
126
|
import_node_fs = __toESM(require("fs"), 1);
|
|
102
127
|
import_drive = require("@googleapis/drive");
|
|
103
128
|
init_errors();
|
|
129
|
+
init_http_agent();
|
|
104
130
|
DEFAULT_SCOPES = [
|
|
105
131
|
"https://www.googleapis.com/auth/drive"
|
|
106
132
|
];
|
|
@@ -123,44 +149,39 @@ var init_authenticator = __esm({
|
|
|
123
149
|
const oauth2Client = new import_drive.auth.OAuth2();
|
|
124
150
|
oauth2Client.setCredentials({ access_token: this.config.accessToken });
|
|
125
151
|
this.authClient = oauth2Client;
|
|
126
|
-
|
|
127
|
-
}
|
|
128
|
-
if (this.config.oauth2Client) {
|
|
152
|
+
} else if (this.config.oauth2Client) {
|
|
129
153
|
this.authClient = this.config.oauth2Client;
|
|
130
|
-
|
|
131
|
-
}
|
|
132
|
-
if (this.config.oauth) {
|
|
154
|
+
} else if (this.config.oauth) {
|
|
133
155
|
const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
|
|
134
156
|
const oauth2Client = new import_drive.auth.OAuth2(clientId, clientSecret, redirectUri);
|
|
135
157
|
if (refreshToken) {
|
|
136
158
|
oauth2Client.setCredentials({ refresh_token: refreshToken });
|
|
137
159
|
}
|
|
138
160
|
this.authClient = oauth2Client;
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
if (keyFile) {
|
|
143
|
-
if (!import_node_fs.default.existsSync(keyFile)) {
|
|
161
|
+
} else if (this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS) {
|
|
162
|
+
const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
|
163
|
+
if (keyFile && !import_node_fs.default.existsSync(keyFile)) {
|
|
144
164
|
throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
|
|
145
165
|
}
|
|
146
|
-
const
|
|
166
|
+
const auth = new import_drive.auth.GoogleAuth({
|
|
147
167
|
keyFile,
|
|
148
168
|
scopes
|
|
149
169
|
});
|
|
150
|
-
this.authClient =
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
if (creds) {
|
|
155
|
-
const auth2 = new import_drive.auth.GoogleAuth({
|
|
170
|
+
this.authClient = auth;
|
|
171
|
+
} else if (this.config.credentials || process.env.GDRIVE_CREDENTIALS_JSON) {
|
|
172
|
+
const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
|
|
173
|
+
const auth = new import_drive.auth.GoogleAuth({
|
|
156
174
|
credentials: creds,
|
|
157
175
|
scopes
|
|
158
176
|
});
|
|
159
|
-
this.authClient =
|
|
160
|
-
|
|
177
|
+
this.authClient = auth;
|
|
178
|
+
} else {
|
|
179
|
+
const auth = new import_drive.auth.GoogleAuth({ scopes });
|
|
180
|
+
this.authClient = auth;
|
|
181
|
+
}
|
|
182
|
+
if (this.authClient?.transporter?.defaults) {
|
|
183
|
+
this.authClient.transporter.defaults.agent = getOptimizedHttpsAgent();
|
|
161
184
|
}
|
|
162
|
-
const auth = new import_drive.auth.GoogleAuth({ scopes });
|
|
163
|
-
this.authClient = auth;
|
|
164
185
|
return this.authClient;
|
|
165
186
|
} catch (err) {
|
|
166
187
|
if (err instanceof DriveAuthError) throw err;
|
|
@@ -319,6 +340,7 @@ var init_path_resolver = __esm({
|
|
|
319
340
|
drive;
|
|
320
341
|
rootFolderId;
|
|
321
342
|
cache = /* @__PURE__ */ new Map();
|
|
343
|
+
inFlightResolves = /* @__PURE__ */ new Map();
|
|
322
344
|
cacheTTL;
|
|
323
345
|
enableCache;
|
|
324
346
|
metadataCache;
|
|
@@ -342,8 +364,8 @@ var init_path_resolver = __esm({
|
|
|
342
364
|
/**
|
|
343
365
|
* Gets cache key for a path
|
|
344
366
|
*/
|
|
345
|
-
getCacheKey(
|
|
346
|
-
return `${this.rootFolderId}:${this.normalizePath(
|
|
367
|
+
getCacheKey(path11) {
|
|
368
|
+
return `${this.rootFolderId}:${this.normalizePath(path11)}`;
|
|
347
369
|
}
|
|
348
370
|
/**
|
|
349
371
|
* Clears the path cache
|
|
@@ -357,8 +379,8 @@ var init_path_resolver = __esm({
|
|
|
357
379
|
/**
|
|
358
380
|
* Invalidate a single path from cache
|
|
359
381
|
*/
|
|
360
|
-
invalidatePath(
|
|
361
|
-
const norm = this.normalizePath(
|
|
382
|
+
invalidatePath(path11) {
|
|
383
|
+
const norm = this.normalizePath(path11);
|
|
362
384
|
const key = this.getCacheKey(norm);
|
|
363
385
|
this.cache.delete(key);
|
|
364
386
|
if (this.metadataCache) {
|
|
@@ -371,6 +393,7 @@ var init_path_resolver = __esm({
|
|
|
371
393
|
/**
|
|
372
394
|
* Resolves a path to a Google Drive item (file or folder).
|
|
373
395
|
* If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
|
|
396
|
+
* Incorporates in-flight request coalescing to deduplicate concurrent resolutions of identical paths.
|
|
374
397
|
*/
|
|
375
398
|
async resolve(virtualPath, options = {}) {
|
|
376
399
|
const norm = this.normalizePath(virtualPath);
|
|
@@ -404,6 +427,20 @@ var init_path_resolver = __esm({
|
|
|
404
427
|
};
|
|
405
428
|
}
|
|
406
429
|
}
|
|
430
|
+
const flightKey = `${this.rootFolderId}:${norm}:${options.createIfMissing ? "create" : "read"}`;
|
|
431
|
+
const inFlight = this.inFlightResolves.get(flightKey);
|
|
432
|
+
if (inFlight) {
|
|
433
|
+
return await inFlight;
|
|
434
|
+
}
|
|
435
|
+
const task = this.doResolve(virtualPath, norm, options);
|
|
436
|
+
this.inFlightResolves.set(flightKey, task);
|
|
437
|
+
try {
|
|
438
|
+
return await task;
|
|
439
|
+
} finally {
|
|
440
|
+
this.inFlightResolves.delete(flightKey);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
async doResolve(virtualPath, norm, options) {
|
|
407
444
|
const segments = norm.split("/").filter(Boolean);
|
|
408
445
|
let currentParentId = this.rootFolderId;
|
|
409
446
|
let currentPath = "";
|
|
@@ -455,7 +492,7 @@ var init_path_resolver = __esm({
|
|
|
455
492
|
});
|
|
456
493
|
let file = response.data.files?.[0];
|
|
457
494
|
if (!file && currentParentId === this.rootFolderId) {
|
|
458
|
-
const sharedQ = `name = '${escapedName}' and trashed = false`;
|
|
495
|
+
const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
|
|
459
496
|
const sharedResponse = await withRetry(async () => {
|
|
460
497
|
return await this.drive.files.list({
|
|
461
498
|
q: sharedQ,
|
|
@@ -583,17 +620,19 @@ var init_format = __esm({
|
|
|
583
620
|
});
|
|
584
621
|
|
|
585
622
|
// src/core/resumable-uploader.ts
|
|
586
|
-
var import_node_fs2, import_node_path, MIN_CHUNK_SIZE, DEFAULT_CHUNK_SIZE, MULTIPART_THRESHOLD, ResumableUploader;
|
|
623
|
+
var import_node_fs2, import_node_path, import_node_stream, MIN_CHUNK_SIZE, DEFAULT_CHUNK_SIZE, MULTIPART_THRESHOLD, ResumableUploader;
|
|
587
624
|
var init_resumable_uploader = __esm({
|
|
588
625
|
"src/core/resumable-uploader.ts"() {
|
|
589
626
|
"use strict";
|
|
590
627
|
init_cjs_shims();
|
|
591
628
|
import_node_fs2 = __toESM(require("fs"), 1);
|
|
592
629
|
import_node_path = __toESM(require("path"), 1);
|
|
630
|
+
import_node_stream = require("stream");
|
|
593
631
|
init_errors();
|
|
594
632
|
init_format();
|
|
595
633
|
init_mime();
|
|
596
634
|
init_retry();
|
|
635
|
+
init_http_agent();
|
|
597
636
|
MIN_CHUNK_SIZE = 256 * 1024;
|
|
598
637
|
DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
|
|
599
638
|
MULTIPART_THRESHOLD = 5 * 1024 * 1024;
|
|
@@ -631,6 +670,15 @@ var init_resumable_uploader = __esm({
|
|
|
631
670
|
const totalBytes = stat.size;
|
|
632
671
|
const fileName = options.name || import_node_path.default.basename(filePath);
|
|
633
672
|
const mimeType = options.mimeType || lookupMimeType(filePath);
|
|
673
|
+
if (totalBytes <= MULTIPART_THRESHOLD) {
|
|
674
|
+
const readStream = import_node_fs2.default.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
|
|
675
|
+
const stream = options.onProgress ? this.wrapStreamWithProgress(readStream, totalBytes, options.onProgress) : readStream;
|
|
676
|
+
return await this.directUpload(stream, {
|
|
677
|
+
...options,
|
|
678
|
+
name: fileName,
|
|
679
|
+
mimeType
|
|
680
|
+
});
|
|
681
|
+
}
|
|
634
682
|
return await this.chunkedUpload({
|
|
635
683
|
filePath,
|
|
636
684
|
totalBytes,
|
|
@@ -646,6 +694,16 @@ var init_resumable_uploader = __esm({
|
|
|
646
694
|
const totalBytes = buffer.length;
|
|
647
695
|
const fileName = options.name || "untitled";
|
|
648
696
|
const mimeType = options.mimeType || "application/octet-stream";
|
|
697
|
+
if (totalBytes <= MULTIPART_THRESHOLD) {
|
|
698
|
+
const { Readable } = await import("stream");
|
|
699
|
+
const baseStream = Readable.from(totalBytes === 0 ? [] : [buffer]);
|
|
700
|
+
const stream = options.onProgress ? this.wrapStreamWithProgress(baseStream, totalBytes, options.onProgress) : baseStream;
|
|
701
|
+
return await this.directUpload(stream, {
|
|
702
|
+
...options,
|
|
703
|
+
name: fileName,
|
|
704
|
+
mimeType
|
|
705
|
+
});
|
|
706
|
+
}
|
|
649
707
|
return await this.chunkedUploadBuffer({
|
|
650
708
|
buffer,
|
|
651
709
|
totalBytes,
|
|
@@ -666,6 +724,50 @@ var init_resumable_uploader = __esm({
|
|
|
666
724
|
mimeType
|
|
667
725
|
});
|
|
668
726
|
}
|
|
727
|
+
/**
|
|
728
|
+
* Calculates optimal chunk size based on file size for maximum throughput.
|
|
729
|
+
*/
|
|
730
|
+
computeAdaptiveChunkSize(totalBytes, explicitChunkSize) {
|
|
731
|
+
if (explicitChunkSize) {
|
|
732
|
+
return Math.max(MIN_CHUNK_SIZE, Math.floor(explicitChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE);
|
|
733
|
+
}
|
|
734
|
+
if (totalBytes > 128 * 1024 * 1024) {
|
|
735
|
+
return 32 * 1024 * 1024;
|
|
736
|
+
}
|
|
737
|
+
if (totalBytes > 32 * 1024 * 1024) {
|
|
738
|
+
return 16 * 1024 * 1024;
|
|
739
|
+
}
|
|
740
|
+
return this.defaultChunkSize;
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* Attaches real-time progress monitoring to direct stream uploads.
|
|
744
|
+
*/
|
|
745
|
+
wrapStreamWithProgress(stream, totalBytes, onProgress) {
|
|
746
|
+
let bytesSent = 0;
|
|
747
|
+
const startTime = Date.now();
|
|
748
|
+
const progressTransform = new import_node_stream.Transform({
|
|
749
|
+
transform(chunk, _encoding, callback) {
|
|
750
|
+
bytesSent += chunk.length;
|
|
751
|
+
const elapsedSecs = (Date.now() - startTime) / 1e3;
|
|
752
|
+
const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
|
|
753
|
+
const remainingBytes = Math.max(0, totalBytes - bytesSent);
|
|
754
|
+
const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
|
|
755
|
+
const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
|
|
756
|
+
onProgress({
|
|
757
|
+
bytesSent,
|
|
758
|
+
totalBytes,
|
|
759
|
+
percentage,
|
|
760
|
+
bytesPerSecond,
|
|
761
|
+
speedFormatted: formatSpeed(bytesPerSecond),
|
|
762
|
+
estimatedTimeRemainingSeconds,
|
|
763
|
+
chunkIndex: 1,
|
|
764
|
+
totalChunks: 1
|
|
765
|
+
});
|
|
766
|
+
callback(null, chunk);
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
return stream.pipe(progressTransform);
|
|
770
|
+
}
|
|
669
771
|
/**
|
|
670
772
|
* Fast direct upload using googleapis multipart
|
|
671
773
|
*/
|
|
@@ -698,7 +800,7 @@ var init_resumable_uploader = __esm({
|
|
|
698
800
|
*/
|
|
699
801
|
async chunkedUpload(params) {
|
|
700
802
|
const { filePath, totalBytes, fileName, mimeType, options } = params;
|
|
701
|
-
const chunkSize =
|
|
803
|
+
const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
|
|
702
804
|
const sessionUrl = await this.initiateResumableSession({
|
|
703
805
|
fileName,
|
|
704
806
|
mimeType,
|
|
@@ -763,7 +865,7 @@ var init_resumable_uploader = __esm({
|
|
|
763
865
|
*/
|
|
764
866
|
async chunkedUploadBuffer(params) {
|
|
765
867
|
const { buffer, totalBytes, fileName, mimeType, options } = params;
|
|
766
|
-
const chunkSize =
|
|
868
|
+
const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
|
|
767
869
|
const sessionUrl = await this.initiateResumableSession({
|
|
768
870
|
fileName,
|
|
769
871
|
mimeType,
|
|
@@ -842,7 +944,8 @@ var init_resumable_uploader = __esm({
|
|
|
842
944
|
url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
|
|
843
945
|
method: "POST",
|
|
844
946
|
headers,
|
|
845
|
-
data: metadata
|
|
947
|
+
data: metadata,
|
|
948
|
+
agent: getOptimizedHttpsAgent()
|
|
846
949
|
});
|
|
847
950
|
});
|
|
848
951
|
const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
|
|
@@ -868,6 +971,7 @@ var init_resumable_uploader = __esm({
|
|
|
868
971
|
method: "PUT",
|
|
869
972
|
headers,
|
|
870
973
|
data: buffer,
|
|
974
|
+
agent: getOptimizedHttpsAgent(),
|
|
871
975
|
validateStatus: (status) => status >= 200 && status < 300 || status === 308
|
|
872
976
|
});
|
|
873
977
|
if (res.status === 200 || res.status === 201) {
|
|
@@ -899,7 +1003,7 @@ var init_resumable_uploader = __esm({
|
|
|
899
1003
|
});
|
|
900
1004
|
|
|
901
1005
|
// src/core/downloader.ts
|
|
902
|
-
var import_node_fs3, import_node_path2, import_promises,
|
|
1006
|
+
var import_node_fs3, import_node_path2, import_promises, import_node_stream2, Downloader;
|
|
903
1007
|
var init_downloader = __esm({
|
|
904
1008
|
"src/core/downloader.ts"() {
|
|
905
1009
|
"use strict";
|
|
@@ -907,7 +1011,7 @@ var init_downloader = __esm({
|
|
|
907
1011
|
import_node_fs3 = __toESM(require("fs"), 1);
|
|
908
1012
|
import_node_path2 = __toESM(require("path"), 1);
|
|
909
1013
|
import_promises = require("stream/promises");
|
|
910
|
-
|
|
1014
|
+
import_node_stream2 = require("stream");
|
|
911
1015
|
init_mime();
|
|
912
1016
|
init_format();
|
|
913
1017
|
init_retry();
|
|
@@ -920,17 +1024,22 @@ var init_downloader = __esm({
|
|
|
920
1024
|
* Downloads a file from Google Drive to local destination path or returns a readable stream.
|
|
921
1025
|
*/
|
|
922
1026
|
async download(fileId, options = {}) {
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
1027
|
+
let name = options.metadata?.name;
|
|
1028
|
+
let mimeType = options.metadata?.mimeType;
|
|
1029
|
+
let totalBytes = options.metadata?.size;
|
|
1030
|
+
if (!name || !mimeType) {
|
|
1031
|
+
const metaRes = await withRetry(async () => {
|
|
1032
|
+
return await this.drive.files.get({
|
|
1033
|
+
fileId,
|
|
1034
|
+
fields: "id, name, mimeType, size",
|
|
1035
|
+
supportsAllDrives: true
|
|
1036
|
+
});
|
|
928
1037
|
});
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
1038
|
+
const file = metaRes.data;
|
|
1039
|
+
name = file.name || "downloaded-file";
|
|
1040
|
+
mimeType = file.mimeType || "application/octet-stream";
|
|
1041
|
+
totalBytes = file.size ? parseInt(file.size, 10) : void 0;
|
|
1042
|
+
}
|
|
934
1043
|
let downloadStream;
|
|
935
1044
|
let finalFileName = name;
|
|
936
1045
|
if (isGoogleWorkspaceDoc(mimeType)) {
|
|
@@ -961,7 +1070,7 @@ var init_downloader = __esm({
|
|
|
961
1070
|
}
|
|
962
1071
|
let bytesRead = 0;
|
|
963
1072
|
const startTime = Date.now();
|
|
964
|
-
const progressTracker = new
|
|
1073
|
+
const progressTracker = new import_node_stream2.Transform({
|
|
965
1074
|
transform(chunk, encoding, callback) {
|
|
966
1075
|
bytesRead += chunk.length;
|
|
967
1076
|
if (options.onProgress) {
|
|
@@ -986,7 +1095,7 @@ var init_downloader = __esm({
|
|
|
986
1095
|
destPath = import_node_path2.default.join(destPath, finalFileName);
|
|
987
1096
|
}
|
|
988
1097
|
await import_node_fs3.default.promises.mkdir(import_node_path2.default.dirname(destPath), { recursive: true });
|
|
989
|
-
const writeStream = import_node_fs3.default.createWriteStream(destPath);
|
|
1098
|
+
const writeStream = import_node_fs3.default.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
|
|
990
1099
|
await (0, import_promises.pipeline)(monitoredStream, writeStream);
|
|
991
1100
|
return {
|
|
992
1101
|
filePath: destPath,
|
|
@@ -1237,6 +1346,7 @@ var init_query_builder = __esm({
|
|
|
1237
1346
|
const q = this.toQueryString();
|
|
1238
1347
|
const orderBy = this.orderClauses.join(", ");
|
|
1239
1348
|
let pageToken = void 0;
|
|
1349
|
+
const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
|
|
1240
1350
|
do {
|
|
1241
1351
|
const res = await withRetry(async () => {
|
|
1242
1352
|
return await this.drive.files.list({
|
|
@@ -1244,7 +1354,7 @@ var init_query_builder = __esm({
|
|
|
1244
1354
|
orderBy: orderBy || void 0,
|
|
1245
1355
|
pageSize: this.limitNumber,
|
|
1246
1356
|
pageToken,
|
|
1247
|
-
fields:
|
|
1357
|
+
fields: effectiveFields,
|
|
1248
1358
|
spaces: this.spaces,
|
|
1249
1359
|
supportsAllDrives: true,
|
|
1250
1360
|
includeItemsFromAllDrives: true
|
|
@@ -1381,7 +1491,7 @@ var init_watcher = __esm({
|
|
|
1381
1491
|
const res = await withRetry(async () => {
|
|
1382
1492
|
return await this.drive.changes.list({
|
|
1383
1493
|
pageToken: nextPageToken,
|
|
1384
|
-
fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
|
|
1494
|
+
fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, createdTime, modifiedTime, parents, trashed))",
|
|
1385
1495
|
supportsAllDrives: true,
|
|
1386
1496
|
includeItemsFromAllDrives: true
|
|
1387
1497
|
});
|
|
@@ -1480,16 +1590,24 @@ var init_storage_cleaner = __esm({
|
|
|
1480
1590
|
async findDuplicates(options = {}) {
|
|
1481
1591
|
const mode = options.by || "name";
|
|
1482
1592
|
const maxScan = options.maxScan || 1e3;
|
|
1483
|
-
const
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1593
|
+
const files = [];
|
|
1594
|
+
let pageToken = void 0;
|
|
1595
|
+
do {
|
|
1596
|
+
const remaining = maxScan - files.length;
|
|
1597
|
+
if (remaining <= 0) break;
|
|
1598
|
+
const res = await withRetry(async () => {
|
|
1599
|
+
return await this.drive.files.list({
|
|
1600
|
+
q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
|
|
1601
|
+
pageSize: Math.min(1e3, remaining),
|
|
1602
|
+
pageToken,
|
|
1603
|
+
fields: "nextPageToken, files(id, name, size, md5Checksum, modifiedTime)",
|
|
1604
|
+
supportsAllDrives: true,
|
|
1605
|
+
includeItemsFromAllDrives: true
|
|
1606
|
+
});
|
|
1490
1607
|
});
|
|
1491
|
-
|
|
1492
|
-
|
|
1608
|
+
files.push(...res.data.files || []);
|
|
1609
|
+
pageToken = res.data.nextPageToken || void 0;
|
|
1610
|
+
} while (pageToken && files.length < maxScan);
|
|
1493
1611
|
const map = /* @__PURE__ */ new Map();
|
|
1494
1612
|
for (const f of files) {
|
|
1495
1613
|
if (!f.id) continue;
|
|
@@ -1689,7 +1807,7 @@ async function loginWithBrowser(options) {
|
|
|
1689
1807
|
scope: scopes
|
|
1690
1808
|
});
|
|
1691
1809
|
return new Promise((resolve, reject) => {
|
|
1692
|
-
const server =
|
|
1810
|
+
const server = import_node_http2.default.createServer(async (req, res) => {
|
|
1693
1811
|
try {
|
|
1694
1812
|
const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
|
|
1695
1813
|
if (reqUrl.pathname === "/oauth2callback") {
|
|
@@ -1773,16 +1891,20 @@ ${authUrl}
|
|
|
1773
1891
|
});
|
|
1774
1892
|
});
|
|
1775
1893
|
server.on("error", (err) => {
|
|
1776
|
-
|
|
1894
|
+
if (err.code === "EADDRINUSE") {
|
|
1895
|
+
reject(new Error(`Port ${port} is already in use by another process. Please specify an alternate port with --port <number>.`));
|
|
1896
|
+
} else {
|
|
1897
|
+
reject(err);
|
|
1898
|
+
}
|
|
1777
1899
|
});
|
|
1778
1900
|
});
|
|
1779
1901
|
}
|
|
1780
|
-
var
|
|
1902
|
+
var import_node_http2, import_node_child_process, import_drive2;
|
|
1781
1903
|
var init_browser_login = __esm({
|
|
1782
1904
|
"src/auth/browser-login.ts"() {
|
|
1783
1905
|
"use strict";
|
|
1784
1906
|
init_cjs_shims();
|
|
1785
|
-
|
|
1907
|
+
import_node_http2 = __toESM(require("http"), 1);
|
|
1786
1908
|
import_node_child_process = require("child_process");
|
|
1787
1909
|
import_drive2 = require("@googleapis/drive");
|
|
1788
1910
|
init_authenticator();
|
|
@@ -1855,6 +1977,10 @@ var init_resource_refs = __esm({
|
|
|
1855
1977
|
async getLink() {
|
|
1856
1978
|
return await this.drive.getShareableLink(this.pathOrId);
|
|
1857
1979
|
}
|
|
1980
|
+
/** Access historical revisions & version control for this file */
|
|
1981
|
+
get revisions() {
|
|
1982
|
+
return this.drive.getRevisions(this.pathOrId);
|
|
1983
|
+
}
|
|
1858
1984
|
/** Returns a ReadableStream for this file, optionally with byte Range requests */
|
|
1859
1985
|
async createReadStream(options) {
|
|
1860
1986
|
return await this.drive.createReadStream(this.pathOrId, options);
|
|
@@ -2149,10 +2275,35 @@ var init_cache = __esm({
|
|
|
2149
2275
|
return;
|
|
2150
2276
|
}
|
|
2151
2277
|
if (!this.initialized || !this.db || entries.length === 0) return;
|
|
2278
|
+
const stmt = this.db.prepare(`
|
|
2279
|
+
INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
|
|
2280
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2281
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
2282
|
+
name = excluded.name,
|
|
2283
|
+
mimeType = excluded.mimeType,
|
|
2284
|
+
size = excluded.size,
|
|
2285
|
+
parentId = excluded.parentId,
|
|
2286
|
+
path = COALESCE(excluded.path, files.path),
|
|
2287
|
+
md5Checksum = excluded.md5Checksum,
|
|
2288
|
+
trashed = excluded.trashed,
|
|
2289
|
+
modifiedTime = excluded.modifiedTime,
|
|
2290
|
+
updatedAt = excluded.updatedAt
|
|
2291
|
+
`);
|
|
2152
2292
|
this.db.exec("BEGIN TRANSACTION;");
|
|
2153
2293
|
try {
|
|
2154
2294
|
for (const entry of entries) {
|
|
2155
|
-
|
|
2295
|
+
stmt.run(
|
|
2296
|
+
entry.id,
|
|
2297
|
+
entry.name,
|
|
2298
|
+
entry.mimeType ?? null,
|
|
2299
|
+
entry.size ?? null,
|
|
2300
|
+
entry.parentId ?? null,
|
|
2301
|
+
entry.path ?? null,
|
|
2302
|
+
entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
|
|
2303
|
+
entry.trashed ? 1 : 0,
|
|
2304
|
+
entry.modifiedTime ?? null,
|
|
2305
|
+
entry.updatedAt ?? Date.now()
|
|
2306
|
+
);
|
|
2156
2307
|
}
|
|
2157
2308
|
this.db.exec("COMMIT;");
|
|
2158
2309
|
} catch (e) {
|
|
@@ -2371,144 +2522,1355 @@ var init_cache = __esm({
|
|
|
2371
2522
|
}
|
|
2372
2523
|
});
|
|
2373
2524
|
|
|
2374
|
-
// src/
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
escapeXml: () => escapeXml,
|
|
2378
|
-
startWebDAVServer: () => startWebDAVServer
|
|
2379
|
-
});
|
|
2380
|
-
function escapeXml(unsafe) {
|
|
2381
|
-
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2525
|
+
// src/crypto/encryption.ts
|
|
2526
|
+
function deriveKey(password, salt) {
|
|
2527
|
+
return import_node_crypto2.default.pbkdf2Sync(password, salt, PBKDF2_ROUNDS, 32, "sha512");
|
|
2382
2528
|
}
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2529
|
+
var import_node_crypto2, import_node_stream3, MAGIC_HEADER, MAGIC_STREAM_HEADER, SALT_LENGTH, IV_LENGTH, TAG_LENGTH, PBKDF2_ROUNDS, DriveKitCrypto;
|
|
2530
|
+
var init_encryption = __esm({
|
|
2531
|
+
"src/crypto/encryption.ts"() {
|
|
2532
|
+
"use strict";
|
|
2533
|
+
init_cjs_shims();
|
|
2534
|
+
import_node_crypto2 = __toESM(require("crypto"), 1);
|
|
2535
|
+
import_node_stream3 = require("stream");
|
|
2536
|
+
MAGIC_HEADER = Buffer.from("DKENC1", "utf8");
|
|
2537
|
+
MAGIC_STREAM_HEADER = Buffer.from("DKENCS", "utf8");
|
|
2538
|
+
SALT_LENGTH = 16;
|
|
2539
|
+
IV_LENGTH = 12;
|
|
2540
|
+
TAG_LENGTH = 16;
|
|
2541
|
+
PBKDF2_ROUNDS = 1e5;
|
|
2542
|
+
DriveKitCrypto = class {
|
|
2543
|
+
config;
|
|
2544
|
+
constructor(config) {
|
|
2545
|
+
if (!config.password && !config.key) {
|
|
2546
|
+
throw new Error("DriveKitCrypto requires either a password or a 32-byte key.");
|
|
2398
2547
|
}
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
if (user !== options.auth.username || pass !== options.auth.password) {
|
|
2402
|
-
res.writeHead(401, {
|
|
2403
|
-
"WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
|
|
2404
|
-
"Content-Type": "text/plain"
|
|
2405
|
-
});
|
|
2406
|
-
res.end("Invalid credentials");
|
|
2407
|
-
return;
|
|
2548
|
+
if (config.key && config.key.length !== 32) {
|
|
2549
|
+
throw new Error(`DriveKitCrypto raw key must be exactly 32 bytes, got ${config.key.length} bytes.`);
|
|
2408
2550
|
}
|
|
2551
|
+
this.config = config;
|
|
2409
2552
|
}
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2553
|
+
/**
|
|
2554
|
+
* Encrypts a Buffer using AES-256-GCM.
|
|
2555
|
+
* Format: [MAGIC (6B)][SALT (16B)][IV (12B)][TAG (16B)][CIPHERTEXT]
|
|
2556
|
+
*/
|
|
2557
|
+
encryptBuffer(data) {
|
|
2558
|
+
const salt = import_node_crypto2.default.randomBytes(SALT_LENGTH);
|
|
2559
|
+
const iv = import_node_crypto2.default.randomBytes(IV_LENGTH);
|
|
2560
|
+
const key = this.config.key || deriveKey(this.config.password, salt);
|
|
2561
|
+
const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
|
|
2562
|
+
const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
|
|
2563
|
+
const tag = cipher.getAuthTag();
|
|
2564
|
+
return Buffer.concat([MAGIC_HEADER, salt, iv, tag, ciphertext]);
|
|
2565
|
+
}
|
|
2566
|
+
/**
|
|
2567
|
+
* Decrypts a Buffer previously encrypted with encryptBuffer or createEncryptStream.
|
|
2568
|
+
*/
|
|
2569
|
+
decryptBuffer(encryptedData) {
|
|
2570
|
+
if (encryptedData.length < MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH + TAG_LENGTH) {
|
|
2571
|
+
throw new Error("Encrypted payload is too short to be valid DriveKit ciphertext.");
|
|
2423
2572
|
}
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
});
|
|
2430
|
-
res.end(xml);
|
|
2431
|
-
return;
|
|
2573
|
+
const magic = encryptedData.subarray(0, MAGIC_HEADER.length);
|
|
2574
|
+
const isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
|
|
2575
|
+
const isBufferFormat = magic.equals(MAGIC_HEADER);
|
|
2576
|
+
if (!isStreamFormat && !isBufferFormat) {
|
|
2577
|
+
throw new Error("Invalid magic header: file was not encrypted by DriveKit or is corrupted.");
|
|
2432
2578
|
}
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2579
|
+
const salt = encryptedData.subarray(6, 6 + SALT_LENGTH);
|
|
2580
|
+
const iv = encryptedData.subarray(6 + SALT_LENGTH, 6 + SALT_LENGTH + IV_LENGTH);
|
|
2581
|
+
const key = this.config.key || deriveKey(this.config.password, salt);
|
|
2582
|
+
let tag;
|
|
2583
|
+
let ciphertext;
|
|
2584
|
+
if (isStreamFormat) {
|
|
2585
|
+
tag = encryptedData.subarray(encryptedData.length - TAG_LENGTH);
|
|
2586
|
+
ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, encryptedData.length - TAG_LENGTH);
|
|
2587
|
+
} else {
|
|
2588
|
+
tag = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, 6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
|
|
2589
|
+
ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
|
|
2590
|
+
}
|
|
2591
|
+
const decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
|
|
2592
|
+
decipher.setAuthTag(tag);
|
|
2593
|
+
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
2594
|
+
}
|
|
2595
|
+
/**
|
|
2596
|
+
* Creates an encryption Transform stream that prepends stream header and appends GCM auth tag
|
|
2597
|
+
*/
|
|
2598
|
+
createEncryptStream() {
|
|
2599
|
+
const salt = import_node_crypto2.default.randomBytes(SALT_LENGTH);
|
|
2600
|
+
const iv = import_node_crypto2.default.randomBytes(IV_LENGTH);
|
|
2601
|
+
const key = this.config.key || deriveKey(this.config.password, salt);
|
|
2602
|
+
const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
|
|
2603
|
+
let headerPushed = false;
|
|
2604
|
+
return new import_node_stream3.Transform({
|
|
2605
|
+
transform(chunk, _encoding, callback) {
|
|
2606
|
+
if (!headerPushed) {
|
|
2607
|
+
this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
|
|
2608
|
+
headerPushed = true;
|
|
2609
|
+
}
|
|
2610
|
+
const encrypted = cipher.update(chunk);
|
|
2611
|
+
if (encrypted.length > 0) {
|
|
2612
|
+
this.push(encrypted);
|
|
2613
|
+
}
|
|
2614
|
+
callback();
|
|
2615
|
+
},
|
|
2616
|
+
flush(callback) {
|
|
2617
|
+
if (!headerPushed) {
|
|
2618
|
+
this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
|
|
2619
|
+
headerPushed = true;
|
|
2620
|
+
}
|
|
2621
|
+
const finalChunk = cipher.final();
|
|
2622
|
+
const tag = cipher.getAuthTag();
|
|
2623
|
+
this.push(Buffer.concat([finalChunk, tag]));
|
|
2624
|
+
callback();
|
|
2439
2625
|
}
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2626
|
+
});
|
|
2627
|
+
}
|
|
2628
|
+
/**
|
|
2629
|
+
* Creates a decryption Transform stream that verifies magic header and validates GCM authentication tag
|
|
2630
|
+
*/
|
|
2631
|
+
createDecryptStream() {
|
|
2632
|
+
const HEADER_BASE_LEN = MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH;
|
|
2633
|
+
let headerBuffer = Buffer.alloc(0);
|
|
2634
|
+
let decipher = null;
|
|
2635
|
+
let isStreamFormat = false;
|
|
2636
|
+
let pendingTail = Buffer.alloc(0);
|
|
2637
|
+
const self = this;
|
|
2638
|
+
return new import_node_stream3.Transform({
|
|
2639
|
+
transform(chunk, _encoding, callback) {
|
|
2640
|
+
try {
|
|
2641
|
+
let data = chunk;
|
|
2642
|
+
if (!decipher) {
|
|
2643
|
+
headerBuffer = Buffer.concat([headerBuffer, data]);
|
|
2644
|
+
if (headerBuffer.length < HEADER_BASE_LEN) {
|
|
2645
|
+
return callback();
|
|
2646
|
+
}
|
|
2647
|
+
const magic = headerBuffer.subarray(0, MAGIC_HEADER.length);
|
|
2648
|
+
isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
|
|
2649
|
+
const isBufferFormat = magic.equals(MAGIC_HEADER);
|
|
2650
|
+
if (!isStreamFormat && !isBufferFormat) {
|
|
2651
|
+
return callback(new Error("Invalid magic header: stream was not encrypted by DriveKit or is corrupted."));
|
|
2652
|
+
}
|
|
2653
|
+
const salt = headerBuffer.subarray(MAGIC_HEADER.length, MAGIC_HEADER.length + SALT_LENGTH);
|
|
2654
|
+
const iv = headerBuffer.subarray(MAGIC_HEADER.length + SALT_LENGTH, HEADER_BASE_LEN);
|
|
2655
|
+
const key = self.config.key || deriveKey(self.config.password, salt);
|
|
2656
|
+
decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
|
|
2657
|
+
if (isBufferFormat) {
|
|
2658
|
+
if (headerBuffer.length < HEADER_BASE_LEN + TAG_LENGTH) {
|
|
2659
|
+
return callback();
|
|
2660
|
+
}
|
|
2661
|
+
const tag = headerBuffer.subarray(HEADER_BASE_LEN, HEADER_BASE_LEN + TAG_LENGTH);
|
|
2662
|
+
decipher.setAuthTag(tag);
|
|
2663
|
+
data = headerBuffer.subarray(HEADER_BASE_LEN + TAG_LENGTH);
|
|
2664
|
+
headerBuffer = Buffer.alloc(0);
|
|
2665
|
+
} else {
|
|
2666
|
+
data = headerBuffer.subarray(HEADER_BASE_LEN);
|
|
2667
|
+
headerBuffer = Buffer.alloc(0);
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
if (data.length > 0) {
|
|
2671
|
+
if (isStreamFormat) {
|
|
2672
|
+
pendingTail = Buffer.concat([pendingTail, data]);
|
|
2673
|
+
if (pendingTail.length > TAG_LENGTH) {
|
|
2674
|
+
const toProcess = pendingTail.subarray(0, pendingTail.length - TAG_LENGTH);
|
|
2675
|
+
pendingTail = pendingTail.subarray(pendingTail.length - TAG_LENGTH);
|
|
2676
|
+
const decryptedChunk = decipher.update(toProcess);
|
|
2677
|
+
if (decryptedChunk.length > 0) {
|
|
2678
|
+
this.push(decryptedChunk);
|
|
2679
|
+
}
|
|
2680
|
+
}
|
|
2681
|
+
} else {
|
|
2682
|
+
const decryptedChunk = decipher.update(data);
|
|
2683
|
+
if (decryptedChunk.length > 0) {
|
|
2684
|
+
this.push(decryptedChunk);
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
callback();
|
|
2689
|
+
} catch (err) {
|
|
2690
|
+
callback(err);
|
|
2446
2691
|
}
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
|
|
2453
|
-
if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
|
|
2454
|
-
res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
|
|
2455
|
-
res.end();
|
|
2456
|
-
return;
|
|
2692
|
+
},
|
|
2693
|
+
flush(callback) {
|
|
2694
|
+
try {
|
|
2695
|
+
if (!decipher) {
|
|
2696
|
+
return callback(new Error("Encrypted stream is too short: missing header."));
|
|
2457
2697
|
}
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
"Content-Length": chunkLength,
|
|
2464
|
-
"Accept-Ranges": "bytes"
|
|
2465
|
-
});
|
|
2466
|
-
if (req.method === "HEAD") {
|
|
2467
|
-
res.end();
|
|
2468
|
-
} else {
|
|
2469
|
-
stream.pipe(res);
|
|
2698
|
+
if (isStreamFormat) {
|
|
2699
|
+
if (pendingTail.length !== TAG_LENGTH) {
|
|
2700
|
+
return callback(new Error("Encrypted stream is truncated: missing authentication tag."));
|
|
2701
|
+
}
|
|
2702
|
+
decipher.setAuthTag(pendingTail);
|
|
2470
2703
|
}
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
"Content-Type": file.mimeType || "application/octet-stream",
|
|
2475
|
-
"Content-Length": file.size || void 0,
|
|
2476
|
-
"Accept-Ranges": "bytes"
|
|
2477
|
-
});
|
|
2478
|
-
if (req.method === "HEAD") {
|
|
2479
|
-
res.end();
|
|
2480
|
-
} else {
|
|
2481
|
-
stream.pipe(res);
|
|
2704
|
+
const finalChunk = decipher.final();
|
|
2705
|
+
if (finalChunk.length > 0) {
|
|
2706
|
+
this.push(finalChunk);
|
|
2482
2707
|
}
|
|
2708
|
+
callback();
|
|
2709
|
+
} catch (err) {
|
|
2710
|
+
callback(new Error(`Authentication failed: corrupted data or invalid authentication tag (${err.message})`));
|
|
2483
2711
|
}
|
|
2484
|
-
} catch (e) {
|
|
2485
|
-
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2486
|
-
res.end("File Not Found");
|
|
2487
2712
|
}
|
|
2488
|
-
|
|
2713
|
+
});
|
|
2714
|
+
}
|
|
2715
|
+
/**
|
|
2716
|
+
* Encrypts a filename into a safe base64url string
|
|
2717
|
+
*/
|
|
2718
|
+
encryptFilename(plainName) {
|
|
2719
|
+
const iv = import_node_crypto2.default.randomBytes(12);
|
|
2720
|
+
const salt = import_node_crypto2.default.randomBytes(8);
|
|
2721
|
+
const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
|
|
2722
|
+
const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
|
|
2723
|
+
const encrypted = Buffer.concat([cipher.update(Buffer.from(plainName, "utf8")), cipher.final()]);
|
|
2724
|
+
const tag = cipher.getAuthTag();
|
|
2725
|
+
const payload = Buffer.concat([salt, iv, tag, encrypted]);
|
|
2726
|
+
return `dk_${payload.toString("base64url")}.enc`;
|
|
2727
|
+
}
|
|
2728
|
+
/**
|
|
2729
|
+
* Decrypts a filename generated by encryptFilename
|
|
2730
|
+
*/
|
|
2731
|
+
decryptFilename(encryptedName) {
|
|
2732
|
+
if (!encryptedName.startsWith("dk_") || !encryptedName.endsWith(".enc")) {
|
|
2733
|
+
return encryptedName;
|
|
2489
2734
|
}
|
|
2490
|
-
|
|
2491
|
-
const
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2735
|
+
try {
|
|
2736
|
+
const raw = encryptedName.slice(3, -4);
|
|
2737
|
+
const payload = Buffer.from(raw, "base64url");
|
|
2738
|
+
if (payload.length < 8 + 12 + 16) return encryptedName;
|
|
2739
|
+
const salt = payload.subarray(0, 8);
|
|
2740
|
+
const iv = payload.subarray(8, 20);
|
|
2741
|
+
const tag = payload.subarray(20, 36);
|
|
2742
|
+
const ciphertext = payload.subarray(36);
|
|
2743
|
+
const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
|
|
2744
|
+
const decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
|
|
2745
|
+
decipher.setAuthTag(tag);
|
|
2746
|
+
const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
2747
|
+
return decrypted.toString("utf8");
|
|
2748
|
+
} catch {
|
|
2749
|
+
return encryptedName;
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
};
|
|
2753
|
+
}
|
|
2754
|
+
});
|
|
2755
|
+
|
|
2756
|
+
// src/core/revisions.ts
|
|
2757
|
+
var DriveFileRevisions;
|
|
2758
|
+
var init_revisions = __esm({
|
|
2759
|
+
"src/core/revisions.ts"() {
|
|
2760
|
+
"use strict";
|
|
2761
|
+
init_cjs_shims();
|
|
2762
|
+
init_retry();
|
|
2763
|
+
DriveFileRevisions = class {
|
|
2764
|
+
drive;
|
|
2765
|
+
pathOrId;
|
|
2766
|
+
idResolver;
|
|
2767
|
+
constructor(drive2, pathOrId, idResolver) {
|
|
2768
|
+
this.drive = drive2;
|
|
2769
|
+
this.pathOrId = pathOrId;
|
|
2770
|
+
this.idResolver = idResolver;
|
|
2771
|
+
}
|
|
2772
|
+
async getId() {
|
|
2773
|
+
if (this.idResolver && (this.pathOrId.startsWith("/") || this.pathOrId.includes("/"))) {
|
|
2774
|
+
return await this.idResolver(this.pathOrId);
|
|
2775
|
+
}
|
|
2776
|
+
return this.pathOrId;
|
|
2777
|
+
}
|
|
2778
|
+
/**
|
|
2779
|
+
* Lists all historical revisions of the file
|
|
2780
|
+
*/
|
|
2781
|
+
async list() {
|
|
2782
|
+
const fileId = await this.getId();
|
|
2783
|
+
const res = await withRetry(async () => {
|
|
2784
|
+
return await this.drive.revisions.list({
|
|
2785
|
+
fileId,
|
|
2786
|
+
fields: "revisions(id, mimeType, modifiedTime, keepForever, size, originalFilename)"
|
|
2787
|
+
});
|
|
2788
|
+
});
|
|
2789
|
+
const revs = res.data.revisions || [];
|
|
2790
|
+
return revs.map((r) => ({
|
|
2791
|
+
id: r.id,
|
|
2792
|
+
mimeType: r.mimeType || void 0,
|
|
2793
|
+
modifiedTime: r.modifiedTime || void 0,
|
|
2794
|
+
keepForever: r.keepForever ?? false,
|
|
2795
|
+
size: r.size ? parseInt(r.size, 10) : void 0,
|
|
2796
|
+
originalFilename: r.originalFilename || void 0
|
|
2797
|
+
}));
|
|
2798
|
+
}
|
|
2799
|
+
/**
|
|
2800
|
+
* Gets metadata for a specific revision
|
|
2801
|
+
*/
|
|
2802
|
+
async get(revisionId) {
|
|
2803
|
+
const fileId = await this.getId();
|
|
2804
|
+
const res = await withRetry(async () => {
|
|
2805
|
+
return await this.drive.revisions.get({
|
|
2806
|
+
fileId,
|
|
2807
|
+
revisionId,
|
|
2808
|
+
fields: "id, mimeType, modifiedTime, keepForever, size, originalFilename"
|
|
2809
|
+
});
|
|
2810
|
+
});
|
|
2811
|
+
const r = res.data;
|
|
2812
|
+
return {
|
|
2813
|
+
id: r.id,
|
|
2814
|
+
mimeType: r.mimeType || void 0,
|
|
2815
|
+
modifiedTime: r.modifiedTime || void 0,
|
|
2816
|
+
keepForever: r.keepForever ?? false,
|
|
2817
|
+
size: r.size ? parseInt(r.size, 10) : void 0,
|
|
2818
|
+
originalFilename: r.originalFilename || void 0
|
|
2819
|
+
};
|
|
2820
|
+
}
|
|
2821
|
+
/**
|
|
2822
|
+
* Pins or unpins a revision so Google Drive never automatically purges it after 30 days
|
|
2823
|
+
*/
|
|
2824
|
+
async keepForever(revisionId, keep = true) {
|
|
2825
|
+
const fileId = await this.getId();
|
|
2826
|
+
const res = await withRetry(async () => {
|
|
2827
|
+
return await this.drive.revisions.update({
|
|
2828
|
+
fileId,
|
|
2829
|
+
revisionId,
|
|
2830
|
+
requestBody: {
|
|
2831
|
+
keepForever: keep
|
|
2832
|
+
},
|
|
2833
|
+
fields: "id, keepForever, modifiedTime"
|
|
2834
|
+
});
|
|
2835
|
+
});
|
|
2836
|
+
return {
|
|
2837
|
+
id: res.data.id,
|
|
2838
|
+
keepForever: res.data.keepForever ?? keep,
|
|
2839
|
+
modifiedTime: res.data.modifiedTime || void 0
|
|
2840
|
+
};
|
|
2841
|
+
}
|
|
2842
|
+
/**
|
|
2843
|
+
* Deletes a specific historical revision
|
|
2844
|
+
*/
|
|
2845
|
+
async delete(revisionId) {
|
|
2846
|
+
const fileId = await this.getId();
|
|
2847
|
+
await withRetry(async () => {
|
|
2848
|
+
return await this.drive.revisions.delete({
|
|
2849
|
+
fileId,
|
|
2850
|
+
revisionId
|
|
2851
|
+
});
|
|
2852
|
+
});
|
|
2853
|
+
}
|
|
2854
|
+
/**
|
|
2855
|
+
* Gets a readable stream of a specific historical revision
|
|
2856
|
+
*/
|
|
2857
|
+
async getStream(revisionId) {
|
|
2858
|
+
const fileId = await this.getId();
|
|
2859
|
+
const res = await withRetry(async () => {
|
|
2860
|
+
return await this.drive.revisions.get(
|
|
2861
|
+
{ fileId, revisionId, alt: "media" },
|
|
2862
|
+
{ responseType: "stream" }
|
|
2863
|
+
);
|
|
2864
|
+
});
|
|
2865
|
+
return res.data;
|
|
2866
|
+
}
|
|
2867
|
+
/**
|
|
2868
|
+
* Restores the file content to a specific previous revision
|
|
2869
|
+
*/
|
|
2870
|
+
async restore(revisionId) {
|
|
2871
|
+
const fileId = await this.getId();
|
|
2872
|
+
const stream = await this.getStream(revisionId);
|
|
2873
|
+
const meta = await this.get(revisionId);
|
|
2874
|
+
await withRetry(async () => {
|
|
2875
|
+
return await this.drive.files.update({
|
|
2876
|
+
fileId,
|
|
2877
|
+
media: {
|
|
2878
|
+
mimeType: meta.mimeType || "application/octet-stream",
|
|
2879
|
+
body: stream
|
|
2880
|
+
}
|
|
2881
|
+
});
|
|
2882
|
+
});
|
|
2883
|
+
}
|
|
2884
|
+
};
|
|
2885
|
+
}
|
|
2886
|
+
});
|
|
2887
|
+
|
|
2888
|
+
// src/core/bidirectional-sync.ts
|
|
2889
|
+
var import_node_fs6, import_node_path6, BidirectionalSyncEngine;
|
|
2890
|
+
var init_bidirectional_sync = __esm({
|
|
2891
|
+
"src/core/bidirectional-sync.ts"() {
|
|
2892
|
+
"use strict";
|
|
2893
|
+
init_cjs_shims();
|
|
2894
|
+
import_node_fs6 = __toESM(require("fs"), 1);
|
|
2895
|
+
import_node_path6 = __toESM(require("path"), 1);
|
|
2896
|
+
init_smart_sync();
|
|
2897
|
+
BidirectionalSyncEngine = class {
|
|
2898
|
+
drive;
|
|
2899
|
+
ledger = /* @__PURE__ */ new Map();
|
|
2900
|
+
constructor(drive2) {
|
|
2901
|
+
this.drive = drive2;
|
|
2902
|
+
}
|
|
2903
|
+
/**
|
|
2904
|
+
* Performs a two-way synchronization cycle between local and remote directories
|
|
2905
|
+
*/
|
|
2906
|
+
async sync(options) {
|
|
2907
|
+
const startTime = Date.now();
|
|
2908
|
+
const {
|
|
2909
|
+
localDir,
|
|
2910
|
+
remoteDir,
|
|
2911
|
+
conflictStrategy = "rename-conflict",
|
|
2912
|
+
deleteMissing = false,
|
|
2913
|
+
dryRun = false,
|
|
2914
|
+
onProgress
|
|
2915
|
+
} = options;
|
|
2916
|
+
const result = {
|
|
2917
|
+
uploaded: [],
|
|
2918
|
+
downloaded: [],
|
|
2919
|
+
deletedLocal: [],
|
|
2920
|
+
deletedRemote: [],
|
|
2921
|
+
conflicts: [],
|
|
2922
|
+
skipped: [],
|
|
2923
|
+
durationMs: 0
|
|
2924
|
+
};
|
|
2925
|
+
if (!import_node_fs6.default.existsSync(localDir)) {
|
|
2926
|
+
await import_node_fs6.default.promises.mkdir(localDir, { recursive: true });
|
|
2927
|
+
}
|
|
2928
|
+
const remoteFolderId = await this.drive.mkdirp(remoteDir);
|
|
2929
|
+
const localFiles = await this.scanLocalDir(localDir);
|
|
2930
|
+
const remoteFiles = await this.scanRemoteDir(remoteFolderId, "");
|
|
2931
|
+
const allPaths = /* @__PURE__ */ new Set([
|
|
2932
|
+
...localFiles.keys(),
|
|
2933
|
+
...remoteFiles.keys(),
|
|
2934
|
+
...this.ledger.keys()
|
|
2935
|
+
]);
|
|
2936
|
+
for (const relPath of allPaths) {
|
|
2937
|
+
const resolvedLocal = import_node_path6.default.resolve(localDir, relPath);
|
|
2938
|
+
const resolvedRoot = import_node_path6.default.resolve(localDir);
|
|
2939
|
+
if (!resolvedLocal.startsWith(resolvedRoot + import_node_path6.default.sep) && resolvedLocal !== resolvedRoot) {
|
|
2940
|
+
throw new Error(`Security Violation: Path traversal detected in sync path: "${relPath}"`);
|
|
2941
|
+
}
|
|
2942
|
+
const local = localFiles.get(relPath);
|
|
2943
|
+
const remote = remoteFiles.get(relPath);
|
|
2944
|
+
const prev = this.ledger.get(relPath);
|
|
2945
|
+
if (local && remote) {
|
|
2946
|
+
const localChanged = !prev || local.md5 !== prev.localMd5 || Math.abs(local.mtime - prev.localMtime) > 1e3;
|
|
2947
|
+
const remoteChanged = !prev || remote.md5 !== prev.remoteMd5 || Math.abs(remote.mtime - prev.remoteMtime) > 1e3;
|
|
2948
|
+
if (local.md5 === remote.md5) {
|
|
2949
|
+
result.skipped.push(relPath);
|
|
2950
|
+
onProgress?.({ action: "skip-identical", relPath });
|
|
2951
|
+
this.ledger.set(relPath, {
|
|
2952
|
+
relPath,
|
|
2953
|
+
localMtime: local.mtime,
|
|
2954
|
+
remoteMtime: remote.mtime,
|
|
2955
|
+
localMd5: local.md5,
|
|
2956
|
+
remoteMd5: remote.md5,
|
|
2957
|
+
remoteId: remote.id
|
|
2958
|
+
});
|
|
2959
|
+
continue;
|
|
2960
|
+
}
|
|
2961
|
+
if (localChanged && !remoteChanged) {
|
|
2962
|
+
if (!dryRun) {
|
|
2963
|
+
await this.uploadFile(local.fullPath, remoteDir, relPath);
|
|
2964
|
+
const freshRemote = await this.drive.getFile(remote.id);
|
|
2965
|
+
this.updateLedger(relPath, local, freshRemote);
|
|
2966
|
+
}
|
|
2967
|
+
result.uploaded.push(relPath);
|
|
2968
|
+
onProgress?.({ action: "upload", relPath, details: "Local modification propagated" });
|
|
2969
|
+
continue;
|
|
2970
|
+
}
|
|
2971
|
+
if (remoteChanged && !localChanged) {
|
|
2972
|
+
if (!dryRun) {
|
|
2973
|
+
await this.downloadFile(remote.id, local.fullPath);
|
|
2974
|
+
const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
|
|
2975
|
+
this.ledger.set(relPath, {
|
|
2976
|
+
relPath,
|
|
2977
|
+
localMtime: freshStat.mtimeMs,
|
|
2978
|
+
remoteMtime: remote.mtime,
|
|
2979
|
+
localMd5: remote.md5,
|
|
2980
|
+
remoteMd5: remote.md5,
|
|
2981
|
+
remoteId: remote.id
|
|
2982
|
+
});
|
|
2983
|
+
}
|
|
2984
|
+
result.downloaded.push(relPath);
|
|
2985
|
+
onProgress?.({ action: "download", relPath, details: "Remote modification propagated" });
|
|
2986
|
+
continue;
|
|
2987
|
+
}
|
|
2988
|
+
result.conflicts.push(relPath);
|
|
2989
|
+
onProgress?.({ action: "conflict-resolved", relPath, details: `Strategy: ${conflictStrategy}` });
|
|
2990
|
+
if (!dryRun) {
|
|
2991
|
+
if (conflictStrategy === "prefer-local") {
|
|
2992
|
+
await this.uploadFile(local.fullPath, remoteDir, relPath);
|
|
2993
|
+
const freshRemote = await this.drive.getFile(remote.id);
|
|
2994
|
+
this.updateLedger(relPath, local, freshRemote);
|
|
2995
|
+
result.uploaded.push(relPath);
|
|
2996
|
+
} else if (conflictStrategy === "prefer-cloud") {
|
|
2997
|
+
await this.downloadFile(remote.id, local.fullPath);
|
|
2998
|
+
const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
|
|
2999
|
+
this.ledger.set(relPath, {
|
|
3000
|
+
relPath,
|
|
3001
|
+
localMtime: freshStat.mtimeMs,
|
|
3002
|
+
remoteMtime: remote.mtime,
|
|
3003
|
+
localMd5: remote.md5,
|
|
3004
|
+
remoteMd5: remote.md5,
|
|
3005
|
+
remoteId: remote.id
|
|
3006
|
+
});
|
|
3007
|
+
result.downloaded.push(relPath);
|
|
3008
|
+
} else if (conflictStrategy === "keep-newer") {
|
|
3009
|
+
if (local.mtime >= remote.mtime) {
|
|
3010
|
+
await this.uploadFile(local.fullPath, remoteDir, relPath);
|
|
3011
|
+
const freshRemote = await this.drive.getFile(remote.id);
|
|
3012
|
+
this.updateLedger(relPath, local, freshRemote);
|
|
3013
|
+
result.uploaded.push(relPath);
|
|
3014
|
+
} else {
|
|
3015
|
+
await this.downloadFile(remote.id, local.fullPath);
|
|
3016
|
+
const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
|
|
3017
|
+
this.ledger.set(relPath, {
|
|
3018
|
+
relPath,
|
|
3019
|
+
localMtime: freshStat.mtimeMs,
|
|
3020
|
+
remoteMtime: remote.mtime,
|
|
3021
|
+
localMd5: remote.md5,
|
|
3022
|
+
remoteMd5: remote.md5,
|
|
3023
|
+
remoteId: remote.id
|
|
3024
|
+
});
|
|
3025
|
+
result.downloaded.push(relPath);
|
|
3026
|
+
}
|
|
3027
|
+
} else {
|
|
3028
|
+
const ext = import_node_path6.default.extname(relPath);
|
|
3029
|
+
const base = relPath.slice(0, relPath.length - ext.length);
|
|
3030
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
3031
|
+
const conflictRelPath = `${base} (Conflict ${timestamp})${ext}`;
|
|
3032
|
+
const conflictFullPath = import_node_path6.default.join(localDir, conflictRelPath);
|
|
3033
|
+
await this.downloadFile(remote.id, conflictFullPath);
|
|
3034
|
+
await this.uploadFile(local.fullPath, remoteDir, relPath);
|
|
3035
|
+
const freshRemote = await this.drive.getFile(remote.id);
|
|
3036
|
+
this.updateLedger(relPath, local, freshRemote);
|
|
3037
|
+
}
|
|
3038
|
+
}
|
|
3039
|
+
continue;
|
|
3040
|
+
}
|
|
3041
|
+
if (local && !remote) {
|
|
3042
|
+
if (prev && deleteMissing) {
|
|
3043
|
+
if (!dryRun) {
|
|
3044
|
+
await import_node_fs6.default.promises.unlink(local.fullPath);
|
|
3045
|
+
this.ledger.delete(relPath);
|
|
3046
|
+
}
|
|
3047
|
+
result.deletedLocal.push(relPath);
|
|
3048
|
+
onProgress?.({ action: "delete-local", relPath, details: "Deleted remotely" });
|
|
3049
|
+
} else {
|
|
3050
|
+
if (!dryRun) {
|
|
3051
|
+
const uploadedFile = await this.uploadFile(local.fullPath, remoteDir, relPath);
|
|
3052
|
+
this.updateLedger(relPath, local, uploadedFile);
|
|
3053
|
+
}
|
|
3054
|
+
result.uploaded.push(relPath);
|
|
3055
|
+
onProgress?.({ action: "upload", relPath, details: "New local file" });
|
|
3056
|
+
}
|
|
3057
|
+
continue;
|
|
3058
|
+
}
|
|
3059
|
+
if (!local && remote) {
|
|
3060
|
+
if (prev && deleteMissing) {
|
|
3061
|
+
if (!dryRun) {
|
|
3062
|
+
await this.drive.delete(remote.id, true);
|
|
3063
|
+
this.ledger.delete(relPath);
|
|
3064
|
+
}
|
|
3065
|
+
result.deletedRemote.push(relPath);
|
|
3066
|
+
onProgress?.({ action: "delete-remote", relPath, details: "Deleted locally" });
|
|
3067
|
+
} else {
|
|
3068
|
+
if (!dryRun) {
|
|
3069
|
+
const localDest = import_node_path6.default.join(localDir, relPath);
|
|
3070
|
+
await import_node_fs6.default.promises.mkdir(import_node_path6.default.dirname(localDest), { recursive: true });
|
|
3071
|
+
await this.downloadFile(remote.id, localDest);
|
|
3072
|
+
const stat = await import_node_fs6.default.promises.stat(localDest);
|
|
3073
|
+
this.ledger.set(relPath, {
|
|
3074
|
+
relPath,
|
|
3075
|
+
localMtime: stat.mtimeMs,
|
|
3076
|
+
remoteMtime: remote.mtime,
|
|
3077
|
+
localMd5: remote.md5,
|
|
3078
|
+
remoteMd5: remote.md5,
|
|
3079
|
+
remoteId: remote.id
|
|
3080
|
+
});
|
|
3081
|
+
}
|
|
3082
|
+
result.downloaded.push(relPath);
|
|
3083
|
+
onProgress?.({ action: "download", relPath, details: "New remote file" });
|
|
3084
|
+
}
|
|
3085
|
+
continue;
|
|
3086
|
+
}
|
|
3087
|
+
if (prev && !local && !remote) {
|
|
3088
|
+
this.ledger.delete(relPath);
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
3091
|
+
result.durationMs = Date.now() - startTime;
|
|
3092
|
+
return result;
|
|
3093
|
+
}
|
|
3094
|
+
async scanLocalDir(dir, baseDir = dir) {
|
|
3095
|
+
const map = /* @__PURE__ */ new Map();
|
|
3096
|
+
if (!import_node_fs6.default.existsSync(dir)) return map;
|
|
3097
|
+
const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
|
|
3098
|
+
for (const entry of entries) {
|
|
3099
|
+
const fullPath = import_node_path6.default.join(dir, entry.name);
|
|
3100
|
+
if (entry.isDirectory()) {
|
|
3101
|
+
const sub = await this.scanLocalDir(fullPath, baseDir);
|
|
3102
|
+
for (const [k, v] of sub) map.set(k, v);
|
|
3103
|
+
} else if (entry.isFile()) {
|
|
3104
|
+
const rel = import_node_path6.default.relative(baseDir, fullPath).replace(/\\/g, "/");
|
|
3105
|
+
const stat = await import_node_fs6.default.promises.stat(fullPath);
|
|
3106
|
+
const md5 = await calculateFileMd5(fullPath);
|
|
3107
|
+
map.set(rel, { fullPath, mtime: stat.mtimeMs, md5 });
|
|
3108
|
+
}
|
|
3109
|
+
}
|
|
3110
|
+
return map;
|
|
3111
|
+
}
|
|
3112
|
+
async scanRemoteDir(folderId, relPrefix) {
|
|
3113
|
+
const map = /* @__PURE__ */ new Map();
|
|
3114
|
+
const items = await this.drive.query().inFolder(folderId).notTrashed().list();
|
|
3115
|
+
for (const item of items) {
|
|
3116
|
+
if (!item.id || !item.name) continue;
|
|
3117
|
+
const cleanName = import_node_path6.default.basename(item.name.replace(/\\/g, "/")).replace(/\0/g, "");
|
|
3118
|
+
if (!cleanName || cleanName === "." || cleanName === "..") continue;
|
|
3119
|
+
const relPath = relPrefix ? `${relPrefix}/${cleanName}` : cleanName;
|
|
3120
|
+
if (item.mimeType === "application/vnd.google-apps.folder") {
|
|
3121
|
+
const sub = await this.scanRemoteDir(item.id, relPath);
|
|
3122
|
+
for (const [k, v] of sub) map.set(k, v);
|
|
3123
|
+
} else {
|
|
3124
|
+
const mtime = item.modifiedTime ? new Date(item.modifiedTime).getTime() : 0;
|
|
3125
|
+
map.set(relPath, {
|
|
3126
|
+
id: item.id,
|
|
3127
|
+
name: item.name,
|
|
3128
|
+
mtime,
|
|
3129
|
+
md5: item.md5Checksum || ""
|
|
3130
|
+
});
|
|
3131
|
+
}
|
|
3132
|
+
}
|
|
3133
|
+
return map;
|
|
3134
|
+
}
|
|
3135
|
+
async uploadFile(localPath, remoteDir, relPath) {
|
|
3136
|
+
const remoteSubDir = import_node_path6.default.dirname(relPath);
|
|
3137
|
+
const targetFolder = remoteSubDir === "." ? remoteDir : `${remoteDir}/${remoteSubDir}`;
|
|
3138
|
+
return await this.drive.upload({
|
|
3139
|
+
source: localPath,
|
|
3140
|
+
name: import_node_path6.default.basename(relPath),
|
|
3141
|
+
parent: targetFolder,
|
|
3142
|
+
overwrite: true
|
|
3143
|
+
});
|
|
3144
|
+
}
|
|
3145
|
+
async downloadFile(fileId, destPath) {
|
|
3146
|
+
await import_node_fs6.default.promises.mkdir(import_node_path6.default.dirname(destPath), { recursive: true });
|
|
3147
|
+
await this.drive.download(fileId, { destination: destPath });
|
|
3148
|
+
}
|
|
3149
|
+
updateLedger(relPath, local, remote) {
|
|
3150
|
+
this.ledger.set(relPath, {
|
|
3151
|
+
relPath,
|
|
3152
|
+
localMtime: local.mtime,
|
|
3153
|
+
remoteMtime: remote.modifiedTime ? new Date(remote.modifiedTime).getTime() : Date.now(),
|
|
3154
|
+
localMd5: local.md5,
|
|
3155
|
+
remoteMd5: remote.md5Checksum || local.md5,
|
|
3156
|
+
remoteId: remote.id
|
|
3157
|
+
});
|
|
3158
|
+
}
|
|
3159
|
+
};
|
|
3160
|
+
}
|
|
3161
|
+
});
|
|
3162
|
+
|
|
3163
|
+
// src/server/s3-gateway.ts
|
|
3164
|
+
var import_node_http3, import_node_path7, import_node_url, S3GatewayServer;
|
|
3165
|
+
var init_s3_gateway = __esm({
|
|
3166
|
+
"src/server/s3-gateway.ts"() {
|
|
3167
|
+
"use strict";
|
|
3168
|
+
init_cjs_shims();
|
|
3169
|
+
import_node_http3 = __toESM(require("http"), 1);
|
|
3170
|
+
import_node_path7 = __toESM(require("path"), 1);
|
|
3171
|
+
import_node_url = require("url");
|
|
3172
|
+
S3GatewayServer = class {
|
|
3173
|
+
drive;
|
|
3174
|
+
options;
|
|
3175
|
+
server = null;
|
|
3176
|
+
constructor(drive2, options = {}) {
|
|
3177
|
+
this.drive = drive2;
|
|
3178
|
+
this.options = {
|
|
3179
|
+
port: options.port || 9e3,
|
|
3180
|
+
host: options.host || "127.0.0.1",
|
|
3181
|
+
bucketRoot: options.bucketRoot || "/",
|
|
3182
|
+
...options
|
|
3183
|
+
};
|
|
3184
|
+
}
|
|
3185
|
+
/**
|
|
3186
|
+
* Starts the S3 gateway HTTP server
|
|
3187
|
+
*/
|
|
3188
|
+
async start() {
|
|
3189
|
+
return new Promise((resolve, reject) => {
|
|
3190
|
+
this.server = import_node_http3.default.createServer(async (req, res) => {
|
|
3191
|
+
try {
|
|
3192
|
+
await this.handleRequest(req, res);
|
|
3193
|
+
} catch (err) {
|
|
3194
|
+
this.sendXmlError(res, 500, "InternalError", err.message || "Internal S3 Gateway Error");
|
|
3195
|
+
}
|
|
3196
|
+
});
|
|
3197
|
+
this.server.on("error", reject);
|
|
3198
|
+
this.server.listen(this.options.port, this.options.host, () => {
|
|
3199
|
+
resolve({ port: this.options.port, host: this.options.host });
|
|
3200
|
+
});
|
|
3201
|
+
});
|
|
3202
|
+
}
|
|
3203
|
+
/**
|
|
3204
|
+
* Stops the S3 gateway HTTP server
|
|
3205
|
+
*/
|
|
3206
|
+
async stop() {
|
|
3207
|
+
return new Promise((resolve) => {
|
|
3208
|
+
if (this.server) {
|
|
3209
|
+
this.server.close(() => resolve());
|
|
3210
|
+
} else {
|
|
3211
|
+
resolve();
|
|
3212
|
+
}
|
|
3213
|
+
});
|
|
3214
|
+
}
|
|
3215
|
+
async handleRequest(req, res) {
|
|
3216
|
+
const parsed = (0, import_node_url.parse)(req.url || "/", true);
|
|
3217
|
+
const rawPathname = decodeURIComponent(parsed.pathname || "/");
|
|
3218
|
+
const pathname = import_node_path7.default.posix.normalize(rawPathname);
|
|
3219
|
+
if (rawPathname.includes("..") || pathname.includes("..") || pathname === ".") {
|
|
3220
|
+
this.sendXmlError(res, 400, "InvalidURI", "Path traversal characters are not permitted");
|
|
3221
|
+
return;
|
|
3222
|
+
}
|
|
3223
|
+
const method = req.method?.toUpperCase() || "GET";
|
|
3224
|
+
if (this.options.accessKeyId) {
|
|
3225
|
+
const authHeader = req.headers["authorization"];
|
|
3226
|
+
if (!authHeader || !authHeader.includes(this.options.accessKeyId)) {
|
|
3227
|
+
res.setHeader("WWW-Authenticate", "AWS4-HMAC-SHA256");
|
|
3228
|
+
this.sendXmlError(res, 403, "AccessDenied", "Invalid or missing AWS credentials");
|
|
3229
|
+
return;
|
|
3230
|
+
}
|
|
3231
|
+
}
|
|
3232
|
+
const segments = pathname.split("/").filter(Boolean);
|
|
3233
|
+
if (segments.some((s) => s === ".." || s === ".")) {
|
|
3234
|
+
this.sendXmlError(res, 400, "InvalidURI", "Invalid path segment");
|
|
3235
|
+
return;
|
|
3236
|
+
}
|
|
3237
|
+
if (segments.length === 0) {
|
|
3238
|
+
if (method === "GET") {
|
|
3239
|
+
await this.handleListBuckets(res);
|
|
3240
|
+
return;
|
|
3241
|
+
}
|
|
3242
|
+
this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on root");
|
|
3243
|
+
return;
|
|
3244
|
+
}
|
|
3245
|
+
const bucket = segments[0];
|
|
3246
|
+
const key = segments.slice(1).join("/");
|
|
3247
|
+
if (!key) {
|
|
3248
|
+
if (method === "GET") {
|
|
3249
|
+
const prefix = parsed.query.prefix || "";
|
|
3250
|
+
await this.handleListObjects(bucket, prefix, res);
|
|
3251
|
+
return;
|
|
3252
|
+
}
|
|
3253
|
+
if (method === "PUT") {
|
|
3254
|
+
await this.drive.mkdirp(`/${bucket}`);
|
|
3255
|
+
res.statusCode = 200;
|
|
3256
|
+
res.end();
|
|
3257
|
+
return;
|
|
3258
|
+
}
|
|
3259
|
+
this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on bucket");
|
|
3260
|
+
return;
|
|
3261
|
+
}
|
|
3262
|
+
const remotePath = `/${bucket}/${key}`;
|
|
3263
|
+
if (method === "HEAD") {
|
|
3264
|
+
try {
|
|
3265
|
+
const file = await this.drive.getFile(remotePath);
|
|
3266
|
+
res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
|
|
3267
|
+
res.setHeader("Content-Length", file.size || "0");
|
|
3268
|
+
res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
|
|
3269
|
+
if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
|
|
3270
|
+
res.statusCode = 200;
|
|
3271
|
+
res.end();
|
|
3272
|
+
} catch {
|
|
3273
|
+
this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
|
|
3274
|
+
}
|
|
3275
|
+
return;
|
|
3276
|
+
}
|
|
3277
|
+
if (method === "GET") {
|
|
3278
|
+
try {
|
|
3279
|
+
const file = await this.drive.getFile(remotePath);
|
|
3280
|
+
const range = req.headers["range"];
|
|
3281
|
+
let options = void 0;
|
|
3282
|
+
if (range && range.startsWith("bytes=")) {
|
|
3283
|
+
const parts = range.replace("bytes=", "").split("-");
|
|
3284
|
+
options = {
|
|
3285
|
+
start: parts[0] ? parseInt(parts[0], 10) : 0,
|
|
3286
|
+
end: parts[1] ? parseInt(parts[1], 10) : void 0
|
|
3287
|
+
};
|
|
3288
|
+
res.statusCode = 206;
|
|
3289
|
+
const end = options.end !== void 0 ? options.end : parseInt(file.size || "0", 10) - 1;
|
|
3290
|
+
res.setHeader("Content-Range", `bytes ${options.start}-${end}/${file.size}`);
|
|
3291
|
+
} else {
|
|
3292
|
+
res.statusCode = 200;
|
|
3293
|
+
}
|
|
3294
|
+
res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
|
|
3295
|
+
res.setHeader("Content-Length", file.size || "0");
|
|
3296
|
+
res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
|
|
3297
|
+
if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
|
|
3298
|
+
const stream = await this.drive.createReadStream(remotePath, options);
|
|
3299
|
+
stream.pipe(res);
|
|
3300
|
+
} catch {
|
|
3301
|
+
this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
|
|
3302
|
+
}
|
|
3303
|
+
return;
|
|
3304
|
+
}
|
|
3305
|
+
if (method === "PUT") {
|
|
3306
|
+
const upload = await this.drive.createWriteStream(remotePath);
|
|
3307
|
+
req.pipe(upload);
|
|
3308
|
+
try {
|
|
3309
|
+
const file = await upload.done;
|
|
3310
|
+
res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
|
|
3311
|
+
res.statusCode = 200;
|
|
3312
|
+
res.end();
|
|
3313
|
+
} catch (err) {
|
|
3314
|
+
this.sendXmlError(res, 500, "InternalError", err.message);
|
|
3315
|
+
}
|
|
3316
|
+
return;
|
|
3317
|
+
}
|
|
3318
|
+
if (method === "DELETE") {
|
|
3319
|
+
try {
|
|
3320
|
+
const file = await this.drive.resolvePath(remotePath);
|
|
3321
|
+
await this.drive.delete(file.id, true);
|
|
3322
|
+
res.statusCode = 204;
|
|
3323
|
+
res.end();
|
|
3324
|
+
} catch {
|
|
3325
|
+
res.statusCode = 204;
|
|
3326
|
+
res.end();
|
|
3327
|
+
}
|
|
3328
|
+
return;
|
|
3329
|
+
}
|
|
3330
|
+
this.sendXmlError(res, 405, "MethodNotAllowed", `HTTP method ${method} not allowed`);
|
|
3331
|
+
}
|
|
3332
|
+
async handleListBuckets(res) {
|
|
3333
|
+
const items = await this.drive.ls("/");
|
|
3334
|
+
const folders = items.filter((i) => i.mimeType === "application/vnd.google-apps.folder");
|
|
3335
|
+
let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
|
|
3336
|
+
xml += " <Buckets>\n";
|
|
3337
|
+
for (const f of folders) {
|
|
3338
|
+
xml += " <Bucket>\n";
|
|
3339
|
+
xml += ` <Name>${this.escapeXml(f.name || "bucket")}</Name>
|
|
3340
|
+
`;
|
|
3341
|
+
xml += ` <CreationDate>${f.createdTime || (/* @__PURE__ */ new Date()).toISOString()}</CreationDate>
|
|
3342
|
+
`;
|
|
3343
|
+
xml += " </Bucket>\n";
|
|
3344
|
+
}
|
|
3345
|
+
xml += " </Buckets>\n</ListAllMyBucketsResult>";
|
|
3346
|
+
res.setHeader("Content-Type", "application/xml");
|
|
3347
|
+
res.statusCode = 200;
|
|
3348
|
+
res.end(xml);
|
|
3349
|
+
}
|
|
3350
|
+
async handleListObjects(bucket, prefix, res) {
|
|
3351
|
+
const targetPath = `/${bucket}${prefix ? `/${prefix}` : ""}`;
|
|
3352
|
+
let items = [];
|
|
3353
|
+
try {
|
|
3354
|
+
items = await this.drive.ls(targetPath);
|
|
3355
|
+
} catch {
|
|
3356
|
+
items = [];
|
|
3357
|
+
}
|
|
3358
|
+
let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
|
|
3359
|
+
xml += ` <Name>${this.escapeXml(bucket)}</Name>
|
|
3360
|
+
`;
|
|
3361
|
+
xml += ` <Prefix>${this.escapeXml(prefix)}</Prefix>
|
|
3362
|
+
`;
|
|
3363
|
+
xml += " <IsTruncated>false</IsTruncated>\n";
|
|
3364
|
+
for (const item of items) {
|
|
3365
|
+
if (item.mimeType === "application/vnd.google-apps.folder") continue;
|
|
3366
|
+
const key = prefix ? `${prefix}/${item.name}` : item.name;
|
|
3367
|
+
xml += " <Contents>\n";
|
|
3368
|
+
xml += ` <Key>${this.escapeXml(key)}</Key>
|
|
3369
|
+
`;
|
|
3370
|
+
xml += ` <LastModified>${item.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()}</LastModified>
|
|
3371
|
+
`;
|
|
3372
|
+
xml += ` <ETag>"${item.md5Checksum || item.id}"</ETag>
|
|
3373
|
+
`;
|
|
3374
|
+
xml += ` <Size>${item.size || 0}</Size>
|
|
3375
|
+
`;
|
|
3376
|
+
xml += " <StorageClass>STANDARD</StorageClass>\n";
|
|
3377
|
+
xml += " </Contents>\n";
|
|
3378
|
+
}
|
|
3379
|
+
xml += "</ListBucketResult>";
|
|
3380
|
+
res.setHeader("Content-Type", "application/xml");
|
|
3381
|
+
res.statusCode = 200;
|
|
3382
|
+
res.end(xml);
|
|
3383
|
+
}
|
|
3384
|
+
sendXmlError(res, status, code, message) {
|
|
3385
|
+
const xml = `<?xml version="1.0" encoding="UTF-8"?>
|
|
3386
|
+
<Error>
|
|
3387
|
+
<Code>${this.escapeXml(code)}</Code>
|
|
3388
|
+
<Message>${this.escapeXml(message)}</Message>
|
|
3389
|
+
</Error>`;
|
|
3390
|
+
res.setHeader("Content-Type", "application/xml");
|
|
3391
|
+
res.statusCode = status;
|
|
3392
|
+
res.end(xml);
|
|
3393
|
+
}
|
|
3394
|
+
escapeXml(unsafe) {
|
|
3395
|
+
return unsafe.replace(/[<>&'"]/g, (c) => {
|
|
3396
|
+
switch (c) {
|
|
3397
|
+
case "<":
|
|
3398
|
+
return "<";
|
|
3399
|
+
case ">":
|
|
3400
|
+
return ">";
|
|
3401
|
+
case "&":
|
|
3402
|
+
return "&";
|
|
3403
|
+
case "'":
|
|
3404
|
+
return "'";
|
|
3405
|
+
case '"':
|
|
3406
|
+
return """;
|
|
3407
|
+
default:
|
|
3408
|
+
return c;
|
|
3409
|
+
}
|
|
3410
|
+
});
|
|
3411
|
+
}
|
|
3412
|
+
};
|
|
3413
|
+
}
|
|
3414
|
+
});
|
|
3415
|
+
|
|
3416
|
+
// src/core/security-auditor.ts
|
|
3417
|
+
var SecurityAuditor;
|
|
3418
|
+
var init_security_auditor = __esm({
|
|
3419
|
+
"src/core/security-auditor.ts"() {
|
|
3420
|
+
"use strict";
|
|
3421
|
+
init_cjs_shims();
|
|
3422
|
+
init_retry();
|
|
3423
|
+
SecurityAuditor = class {
|
|
3424
|
+
drive;
|
|
3425
|
+
constructor(drive2) {
|
|
3426
|
+
this.drive = drive2;
|
|
3427
|
+
}
|
|
3428
|
+
/**
|
|
3429
|
+
* Scans Google Drive files and audits their permission grants
|
|
3430
|
+
*/
|
|
3431
|
+
async audit(options = {}) {
|
|
3432
|
+
const limit = options.scanLimit || 500;
|
|
3433
|
+
const allowedDomains = new Set((options.allowedDomains || []).map((d) => d.toLowerCase()));
|
|
3434
|
+
const issues = [];
|
|
3435
|
+
let publicCount = 0;
|
|
3436
|
+
let domainCount = 0;
|
|
3437
|
+
let externalCount = 0;
|
|
3438
|
+
let scannedTotal = 0;
|
|
3439
|
+
let pageToken = void 0;
|
|
3440
|
+
do {
|
|
3441
|
+
const res = await withRetry(async () => {
|
|
3442
|
+
return await this.drive.files.list({
|
|
3443
|
+
q: "trashed = false",
|
|
3444
|
+
fields: "nextPageToken, files(id, name, mimeType, webViewLink, shared, permissions(id, type, role, emailAddress, domain))",
|
|
3445
|
+
pageSize: Math.min(100, limit - scannedTotal),
|
|
3446
|
+
supportsAllDrives: true,
|
|
3447
|
+
includeItemsFromAllDrives: true,
|
|
3448
|
+
pageToken
|
|
3449
|
+
});
|
|
3450
|
+
});
|
|
3451
|
+
const files = res.data.files || [];
|
|
3452
|
+
for (const file of files) {
|
|
3453
|
+
if (!file.id || !file.name) continue;
|
|
3454
|
+
scannedTotal++;
|
|
3455
|
+
const perms = file.permissions || [];
|
|
3456
|
+
for (const p of perms) {
|
|
3457
|
+
if (p.type === "anyone") {
|
|
3458
|
+
publicCount++;
|
|
3459
|
+
const isCritical = ["writer", "owner", "organizer", "fileOrganizer"].includes(p.role || "");
|
|
3460
|
+
issues.push({
|
|
3461
|
+
fileId: file.id,
|
|
3462
|
+
fileName: file.name,
|
|
3463
|
+
risk: isCritical ? "CRITICAL" : "HIGH",
|
|
3464
|
+
reason: `Publicly accessible to anyone (${p.role} access)`,
|
|
3465
|
+
permissionId: p.id,
|
|
3466
|
+
type: p.type,
|
|
3467
|
+
role: p.role || "reader",
|
|
3468
|
+
webViewLink: file.webViewLink || void 0
|
|
3469
|
+
});
|
|
3470
|
+
continue;
|
|
3471
|
+
}
|
|
3472
|
+
if (p.type === "domain") {
|
|
3473
|
+
domainCount++;
|
|
3474
|
+
issues.push({
|
|
3475
|
+
fileId: file.id,
|
|
3476
|
+
fileName: file.name,
|
|
3477
|
+
risk: "MEDIUM",
|
|
3478
|
+
reason: `Shared with entire organization domain (${p.domain})`,
|
|
3479
|
+
permissionId: p.id,
|
|
3480
|
+
type: p.type,
|
|
3481
|
+
role: p.role || "reader",
|
|
3482
|
+
domain: p.domain || void 0,
|
|
3483
|
+
webViewLink: file.webViewLink || void 0
|
|
3484
|
+
});
|
|
3485
|
+
continue;
|
|
3486
|
+
}
|
|
3487
|
+
if (p.type === "user" && p.emailAddress && allowedDomains.size > 0) {
|
|
3488
|
+
const userDomain = p.emailAddress.split("@")[1]?.toLowerCase();
|
|
3489
|
+
if (userDomain && !allowedDomains.has(userDomain)) {
|
|
3490
|
+
externalCount++;
|
|
3491
|
+
issues.push({
|
|
3492
|
+
fileId: file.id,
|
|
3493
|
+
fileName: file.name,
|
|
3494
|
+
risk: "HIGH",
|
|
3495
|
+
reason: `Shared with external user outside allowed domains: ${p.emailAddress}`,
|
|
3496
|
+
permissionId: p.id,
|
|
3497
|
+
type: p.type,
|
|
3498
|
+
role: p.role || "reader",
|
|
3499
|
+
emailAddress: p.emailAddress,
|
|
3500
|
+
webViewLink: file.webViewLink || void 0
|
|
3501
|
+
});
|
|
3502
|
+
}
|
|
3503
|
+
}
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
pageToken = res.data.nextPageToken || void 0;
|
|
3507
|
+
} while (pageToken && scannedTotal < limit);
|
|
3508
|
+
return {
|
|
3509
|
+
totalScanned: scannedTotal,
|
|
3510
|
+
publicFilesCount: publicCount,
|
|
3511
|
+
domainSharedCount: domainCount,
|
|
3512
|
+
externalSharesCount: externalCount,
|
|
3513
|
+
issues,
|
|
3514
|
+
scannedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3515
|
+
};
|
|
3516
|
+
}
|
|
3517
|
+
/**
|
|
3518
|
+
* Revokes public 'anyone' permissions on specified files
|
|
3519
|
+
*/
|
|
3520
|
+
async revokePublicAccess(fileIds) {
|
|
3521
|
+
const revoked = [];
|
|
3522
|
+
const errors = [];
|
|
3523
|
+
for (const fileId of fileIds) {
|
|
3524
|
+
try {
|
|
3525
|
+
const fileRes = await withRetry(async () => {
|
|
3526
|
+
return await this.drive.files.get({
|
|
3527
|
+
fileId,
|
|
3528
|
+
fields: "id, permissions(id, type)",
|
|
3529
|
+
supportsAllDrives: true
|
|
3530
|
+
});
|
|
3531
|
+
});
|
|
3532
|
+
const publicPerms = (fileRes.data.permissions || []).filter((p) => p.type === "anyone");
|
|
3533
|
+
for (const p of publicPerms) {
|
|
3534
|
+
if (p.id) {
|
|
3535
|
+
await withRetry(async () => {
|
|
3536
|
+
return await this.drive.permissions.delete({
|
|
3537
|
+
fileId,
|
|
3538
|
+
permissionId: p.id,
|
|
3539
|
+
supportsAllDrives: true
|
|
3540
|
+
});
|
|
3541
|
+
});
|
|
3542
|
+
}
|
|
3543
|
+
}
|
|
3544
|
+
revoked.push(fileId);
|
|
3545
|
+
} catch (err) {
|
|
3546
|
+
errors.push({ fileId, error: err.message });
|
|
3547
|
+
}
|
|
3548
|
+
}
|
|
3549
|
+
return { revoked, errors };
|
|
3550
|
+
}
|
|
3551
|
+
};
|
|
3552
|
+
}
|
|
3553
|
+
});
|
|
3554
|
+
|
|
3555
|
+
// src/core/semantic-search.ts
|
|
3556
|
+
function levenshtein(a, b) {
|
|
3557
|
+
const an = a.length;
|
|
3558
|
+
const bn = b.length;
|
|
3559
|
+
if (an === 0) return bn;
|
|
3560
|
+
if (bn === 0) return an;
|
|
3561
|
+
const matrix = Array.from({ length: bn + 1 }, (_, i) => [i]);
|
|
3562
|
+
for (let j = 0; j <= an; j++) matrix[0][j] = j;
|
|
3563
|
+
for (let i = 1; i <= bn; i++) {
|
|
3564
|
+
for (let j = 1; j <= an; j++) {
|
|
3565
|
+
if (b.charAt(i - 1) === a.charAt(j - 1)) {
|
|
3566
|
+
matrix[i][j] = matrix[i - 1][j - 1];
|
|
3567
|
+
} else {
|
|
3568
|
+
matrix[i][j] = Math.min(
|
|
3569
|
+
matrix[i - 1][j - 1] + 1,
|
|
3570
|
+
// substitution
|
|
3571
|
+
matrix[i][j - 1] + 1,
|
|
3572
|
+
// insertion
|
|
3573
|
+
matrix[i - 1][j] + 1
|
|
3574
|
+
// deletion
|
|
3575
|
+
);
|
|
3576
|
+
}
|
|
3577
|
+
}
|
|
3578
|
+
}
|
|
3579
|
+
return matrix[bn][an];
|
|
3580
|
+
}
|
|
3581
|
+
function cosineSimilarity(vecA, vecB) {
|
|
3582
|
+
if (vecA.length !== vecB.length || vecA.length === 0) return 0;
|
|
3583
|
+
let dot = 0;
|
|
3584
|
+
let normA = 0;
|
|
3585
|
+
let normB = 0;
|
|
3586
|
+
for (let i = 0; i < vecA.length; i++) {
|
|
3587
|
+
dot += vecA[i] * vecB[i];
|
|
3588
|
+
normA += vecA[i] * vecA[i];
|
|
3589
|
+
normB += vecB[i] * vecB[i];
|
|
3590
|
+
}
|
|
3591
|
+
if (normA === 0 || normB === 0) return 0;
|
|
3592
|
+
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
3593
|
+
}
|
|
3594
|
+
var SmartSearchEngine;
|
|
3595
|
+
var init_semantic_search = __esm({
|
|
3596
|
+
"src/core/semantic-search.ts"() {
|
|
3597
|
+
"use strict";
|
|
3598
|
+
init_cjs_shims();
|
|
3599
|
+
SmartSearchEngine = class {
|
|
3600
|
+
drive;
|
|
3601
|
+
constructor(drive2) {
|
|
3602
|
+
this.drive = drive2;
|
|
3603
|
+
}
|
|
3604
|
+
/**
|
|
3605
|
+
* Searches Drive using tokenized fuzzy matching and optional semantic embeddings
|
|
3606
|
+
*/
|
|
3607
|
+
async search(query, options = {}) {
|
|
3608
|
+
const limit = options.limit || 20;
|
|
3609
|
+
const minScore = options.minScore ?? 0.3;
|
|
3610
|
+
const queryTokens = query.toLowerCase().split(/\s+/).filter(Boolean);
|
|
3611
|
+
if (queryTokens.length === 0) return [];
|
|
3612
|
+
let candidates = [];
|
|
3613
|
+
if (options.parent) {
|
|
3614
|
+
candidates = await this.drive.ls(options.parent);
|
|
3615
|
+
} else {
|
|
3616
|
+
candidates = await this.drive.query().notTrashed().pageSize(100).list();
|
|
3617
|
+
}
|
|
3618
|
+
let queryVector = null;
|
|
3619
|
+
if (options.embedder) {
|
|
3620
|
+
try {
|
|
3621
|
+
queryVector = await options.embedder(query);
|
|
3622
|
+
} catch {
|
|
3623
|
+
queryVector = null;
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
const scored = [];
|
|
3627
|
+
for (const file of candidates) {
|
|
3628
|
+
const fileName = (file.name || "").toLowerCase();
|
|
3629
|
+
const desc = (file.description || "").toLowerCase();
|
|
3630
|
+
const matchedOn = [];
|
|
3631
|
+
let nameScore = 0;
|
|
3632
|
+
let descScore = 0;
|
|
3633
|
+
let semanticScore = 0;
|
|
3634
|
+
if (fileName.includes(query.toLowerCase())) {
|
|
3635
|
+
nameScore = 0.95;
|
|
3636
|
+
matchedOn.push("name");
|
|
3637
|
+
} else {
|
|
3638
|
+
let tokensMatched = 0;
|
|
3639
|
+
for (const token of queryTokens) {
|
|
3640
|
+
if (fileName.includes(token)) {
|
|
3641
|
+
tokensMatched += 1;
|
|
3642
|
+
continue;
|
|
3643
|
+
}
|
|
3644
|
+
const words = fileName.split(/[\s._-]+/);
|
|
3645
|
+
for (const word of words) {
|
|
3646
|
+
const dist = levenshtein(token, word);
|
|
3647
|
+
const maxLen = Math.max(token.length, word.length);
|
|
3648
|
+
if (maxLen > 3 && dist <= 2) {
|
|
3649
|
+
tokensMatched += 1 - dist / maxLen;
|
|
3650
|
+
break;
|
|
3651
|
+
}
|
|
3652
|
+
}
|
|
3653
|
+
}
|
|
3654
|
+
nameScore = tokensMatched / queryTokens.length;
|
|
3655
|
+
if (nameScore > 0.4) matchedOn.push("name");
|
|
3656
|
+
}
|
|
3657
|
+
if (desc) {
|
|
3658
|
+
if (desc.includes(query.toLowerCase())) {
|
|
3659
|
+
descScore = 0.8;
|
|
3660
|
+
matchedOn.push("description");
|
|
3661
|
+
}
|
|
3662
|
+
}
|
|
3663
|
+
if (queryVector && options.embedder) {
|
|
3664
|
+
try {
|
|
3665
|
+
const fileVector = await options.embedder(`${file.name} ${file.description || ""}`);
|
|
3666
|
+
semanticScore = cosineSimilarity(queryVector, fileVector);
|
|
3667
|
+
if (semanticScore > 0.6) matchedOn.push("semantic");
|
|
3668
|
+
} catch {
|
|
3669
|
+
}
|
|
3670
|
+
}
|
|
3671
|
+
const totalScore = Math.min(1, nameScore * 0.7 + descScore * 0.15 + semanticScore * 0.15);
|
|
3672
|
+
if (totalScore >= minScore) {
|
|
3673
|
+
scored.push({
|
|
3674
|
+
file,
|
|
3675
|
+
score: Math.round(totalScore * 100) / 100,
|
|
3676
|
+
matchedOn: matchedOn.length > 0 ? matchedOn : ["name"]
|
|
3677
|
+
});
|
|
3678
|
+
}
|
|
3679
|
+
}
|
|
3680
|
+
scored.sort((a, b) => b.score - a.score);
|
|
3681
|
+
return scored.slice(0, limit);
|
|
3682
|
+
}
|
|
3683
|
+
};
|
|
3684
|
+
}
|
|
3685
|
+
});
|
|
3686
|
+
|
|
3687
|
+
// src/utils/compression.ts
|
|
3688
|
+
async function compressBuffer(buffer, algorithm = "gzip") {
|
|
3689
|
+
switch (algorithm) {
|
|
3690
|
+
case "brotli":
|
|
3691
|
+
return await brotliCompressAsync(buffer);
|
|
3692
|
+
case "deflate":
|
|
3693
|
+
return await (0, import_node_util.promisify)(import_node_zlib.default.deflate)(buffer);
|
|
3694
|
+
case "gzip":
|
|
3695
|
+
default:
|
|
3696
|
+
return await gzipAsync(buffer);
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
3699
|
+
async function decompressBuffer(buffer, algorithm = "gzip") {
|
|
3700
|
+
switch (algorithm) {
|
|
3701
|
+
case "brotli":
|
|
3702
|
+
return await brotliDecompressAsync(buffer);
|
|
3703
|
+
case "deflate":
|
|
3704
|
+
return await (0, import_node_util.promisify)(import_node_zlib.default.inflate)(buffer);
|
|
3705
|
+
case "gzip":
|
|
3706
|
+
default:
|
|
3707
|
+
return await gunzipAsync(buffer);
|
|
3708
|
+
}
|
|
3709
|
+
}
|
|
3710
|
+
var import_node_zlib, import_node_util, gzipAsync, gunzipAsync, brotliCompressAsync, brotliDecompressAsync;
|
|
3711
|
+
var init_compression = __esm({
|
|
3712
|
+
"src/utils/compression.ts"() {
|
|
3713
|
+
"use strict";
|
|
3714
|
+
init_cjs_shims();
|
|
3715
|
+
import_node_zlib = __toESM(require("zlib"), 1);
|
|
3716
|
+
import_node_util = require("util");
|
|
3717
|
+
gzipAsync = (0, import_node_util.promisify)(import_node_zlib.default.gzip);
|
|
3718
|
+
gunzipAsync = (0, import_node_util.promisify)(import_node_zlib.default.gunzip);
|
|
3719
|
+
brotliCompressAsync = (0, import_node_util.promisify)(import_node_zlib.default.brotliCompress);
|
|
3720
|
+
brotliDecompressAsync = (0, import_node_util.promisify)(import_node_zlib.default.brotliDecompress);
|
|
3721
|
+
}
|
|
3722
|
+
});
|
|
3723
|
+
|
|
3724
|
+
// src/server/webdav.ts
|
|
3725
|
+
var webdav_exports = {};
|
|
3726
|
+
__export(webdav_exports, {
|
|
3727
|
+
escapeXml: () => escapeXml,
|
|
3728
|
+
startWebDAVServer: () => startWebDAVServer
|
|
3729
|
+
});
|
|
3730
|
+
function escapeXml(unsafe) {
|
|
3731
|
+
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
3732
|
+
}
|
|
3733
|
+
async function startWebDAVServer(drive2, options = {}) {
|
|
3734
|
+
const port = options.port || 8080;
|
|
3735
|
+
const host = options.host || "127.0.0.1";
|
|
3736
|
+
await drive2.init();
|
|
3737
|
+
const server = import_node_http4.default.createServer(async (req, res) => {
|
|
3738
|
+
try {
|
|
3739
|
+
if (options.auth?.username && options.auth?.password) {
|
|
3740
|
+
const authHeader = req.headers["authorization"];
|
|
3741
|
+
if (!authHeader || !authHeader.startsWith("Basic ")) {
|
|
3742
|
+
res.writeHead(401, {
|
|
3743
|
+
"WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
|
|
3744
|
+
"Content-Type": "text/plain"
|
|
3745
|
+
});
|
|
3746
|
+
res.end("Authentication required");
|
|
3747
|
+
return;
|
|
3748
|
+
}
|
|
3749
|
+
const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
|
|
3750
|
+
const [user, pass] = credentials.split(":");
|
|
3751
|
+
if (user !== options.auth.username || pass !== options.auth.password) {
|
|
3752
|
+
res.writeHead(401, {
|
|
3753
|
+
"WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
|
|
3754
|
+
"Content-Type": "text/plain"
|
|
3755
|
+
});
|
|
3756
|
+
res.end("Invalid credentials");
|
|
3757
|
+
return;
|
|
3758
|
+
}
|
|
3759
|
+
}
|
|
3760
|
+
const parsedUrl = import_node_url2.default.parse(req.url || "/", true);
|
|
3761
|
+
const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
|
|
3762
|
+
const normalizedPath = import_node_path8.default.posix.normalize(decodedPath);
|
|
3763
|
+
const virtualPath = normalizedPath.startsWith("/") ? normalizedPath : `/${normalizedPath}`;
|
|
3764
|
+
const baseName = import_node_path8.default.basename(virtualPath);
|
|
3765
|
+
if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
|
|
3766
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
3767
|
+
res.end("Not Found");
|
|
3768
|
+
return;
|
|
3769
|
+
}
|
|
3770
|
+
switch (req.method) {
|
|
3771
|
+
case "OPTIONS": {
|
|
3772
|
+
res.writeHead(200, {
|
|
3773
|
+
DAV: "1, 2",
|
|
3774
|
+
Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
|
|
3775
|
+
"MS-Author-Via": "DAV",
|
|
3776
|
+
"Accept-Ranges": "bytes"
|
|
3777
|
+
});
|
|
3778
|
+
res.end();
|
|
3779
|
+
return;
|
|
3780
|
+
}
|
|
3781
|
+
case "PROPFIND": {
|
|
3782
|
+
const depth = req.headers["depth"] || "1";
|
|
3783
|
+
const xml = await handlePropfind(drive2, virtualPath, depth);
|
|
3784
|
+
if (xml === null) {
|
|
3785
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
3786
|
+
res.end("Not Found");
|
|
3787
|
+
return;
|
|
3788
|
+
}
|
|
3789
|
+
res.writeHead(207, {
|
|
3790
|
+
"Content-Type": "application/xml; charset=utf-8"
|
|
3791
|
+
});
|
|
3792
|
+
res.end(xml);
|
|
3793
|
+
return;
|
|
3794
|
+
}
|
|
3795
|
+
case "GET":
|
|
3796
|
+
case "HEAD": {
|
|
3797
|
+
if (virtualPath === "/" || virtualPath === "") {
|
|
3798
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
3799
|
+
res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
|
|
3800
|
+
return;
|
|
3801
|
+
}
|
|
3802
|
+
try {
|
|
3803
|
+
const file = await drive2.getFile(virtualPath);
|
|
3804
|
+
if (file.mimeType === "application/vnd.google-apps.folder") {
|
|
3805
|
+
res.writeHead(405, { "Content-Type": "text/plain" });
|
|
3806
|
+
res.end("Cannot GET a directory");
|
|
3807
|
+
return;
|
|
3808
|
+
}
|
|
3809
|
+
const fileSize = file.size ? parseInt(file.size, 10) : void 0;
|
|
3810
|
+
const rangeHeader = req.headers["range"];
|
|
3811
|
+
if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
|
|
3812
|
+
const parts = rangeHeader.replace("bytes=", "").split("-");
|
|
3813
|
+
const start = parseInt(parts[0], 10);
|
|
3814
|
+
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
|
|
3815
|
+
if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
|
|
3816
|
+
res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
|
|
3817
|
+
res.end();
|
|
3818
|
+
return;
|
|
3819
|
+
}
|
|
3820
|
+
const stream = await drive2.createReadStream(virtualPath, { start, end });
|
|
3821
|
+
const chunkLength = end - start + 1;
|
|
3822
|
+
res.writeHead(206, {
|
|
3823
|
+
"Content-Type": file.mimeType || "application/octet-stream",
|
|
3824
|
+
"Content-Range": `bytes ${start}-${end}/${fileSize}`,
|
|
3825
|
+
"Content-Length": chunkLength,
|
|
3826
|
+
"Accept-Ranges": "bytes"
|
|
3827
|
+
});
|
|
3828
|
+
if (req.method === "HEAD") {
|
|
3829
|
+
res.end();
|
|
3830
|
+
} else {
|
|
3831
|
+
stream.pipe(res);
|
|
3832
|
+
}
|
|
3833
|
+
} else {
|
|
3834
|
+
const stream = await drive2.createReadStream(virtualPath);
|
|
3835
|
+
res.writeHead(200, {
|
|
3836
|
+
"Content-Type": file.mimeType || "application/octet-stream",
|
|
3837
|
+
"Content-Length": file.size || void 0,
|
|
3838
|
+
"Accept-Ranges": "bytes"
|
|
3839
|
+
});
|
|
3840
|
+
if (req.method === "HEAD") {
|
|
3841
|
+
res.end();
|
|
3842
|
+
} else {
|
|
3843
|
+
stream.pipe(res);
|
|
3844
|
+
}
|
|
3845
|
+
}
|
|
3846
|
+
} catch (e) {
|
|
3847
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
3848
|
+
res.end("File Not Found");
|
|
3849
|
+
}
|
|
3850
|
+
return;
|
|
3851
|
+
}
|
|
3852
|
+
case "PUT": {
|
|
3853
|
+
const remoteDir = import_node_path8.default.dirname(virtualPath);
|
|
3854
|
+
await drive2.mkdirp(remoteDir);
|
|
3855
|
+
let existed = false;
|
|
3856
|
+
try {
|
|
3857
|
+
const existingFile = await drive2.getFile(virtualPath);
|
|
3858
|
+
if (existingFile && existingFile.id) {
|
|
3859
|
+
existed = true;
|
|
3860
|
+
}
|
|
3861
|
+
} catch {
|
|
3862
|
+
existed = false;
|
|
3863
|
+
}
|
|
3864
|
+
try {
|
|
3865
|
+
const uploadStream = await drive2.createWriteStream(virtualPath, {
|
|
3866
|
+
overwrite: true
|
|
3867
|
+
});
|
|
3868
|
+
req.pipe(uploadStream);
|
|
3869
|
+
await uploadStream.done;
|
|
3870
|
+
res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
|
|
3871
|
+
res.end(existed ? "" : "Created");
|
|
3872
|
+
} catch (err) {
|
|
3873
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2512
3874
|
res.end(err.message || "Upload failed");
|
|
2513
3875
|
}
|
|
2514
3876
|
return;
|
|
@@ -2549,16 +3911,16 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
2549
3911
|
res.end("Source file not found");
|
|
2550
3912
|
return;
|
|
2551
3913
|
}
|
|
2552
|
-
const destUrl =
|
|
3914
|
+
const destUrl = import_node_url2.default.parse(destination);
|
|
2553
3915
|
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
2554
|
-
const newName =
|
|
2555
|
-
const newParentDir =
|
|
3916
|
+
const newName = import_node_path8.default.basename(destPath);
|
|
3917
|
+
const newParentDir = import_node_path8.default.dirname(destPath);
|
|
2556
3918
|
const newParentFolderId = await drive2.mkdirp(newParentDir);
|
|
2557
|
-
const currentParentDir =
|
|
3919
|
+
const currentParentDir = import_node_path8.default.dirname(virtualPath);
|
|
2558
3920
|
if (newParentDir !== currentParentDir) {
|
|
2559
3921
|
await drive2.move(file.id, newParentFolderId);
|
|
2560
3922
|
}
|
|
2561
|
-
if (newName !==
|
|
3923
|
+
if (newName !== import_node_path8.default.basename(virtualPath)) {
|
|
2562
3924
|
await drive2.rename(file.id, newName);
|
|
2563
3925
|
}
|
|
2564
3926
|
res.writeHead(201);
|
|
@@ -2583,10 +3945,10 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
2583
3945
|
res.end("Source file not found");
|
|
2584
3946
|
return;
|
|
2585
3947
|
}
|
|
2586
|
-
const destUrl =
|
|
3948
|
+
const destUrl = import_node_url2.default.parse(destination);
|
|
2587
3949
|
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
2588
|
-
const newName =
|
|
2589
|
-
const newParentDir =
|
|
3950
|
+
const newName = import_node_path8.default.basename(destPath);
|
|
3951
|
+
const newParentDir = import_node_path8.default.dirname(destPath);
|
|
2590
3952
|
const newParentFolderId = await drive2.mkdirp(newParentDir);
|
|
2591
3953
|
await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
|
|
2592
3954
|
res.writeHead(201);
|
|
@@ -2634,25 +3996,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
|
|
|
2634
3996
|
virtualPath,
|
|
2635
3997
|
isFolder,
|
|
2636
3998
|
selfItem.size ? parseInt(selfItem.size, 10) : 0,
|
|
2637
|
-
selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
3999
|
+
selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
|
|
4000
|
+
selfItem.mimeType || void 0
|
|
2638
4001
|
)
|
|
2639
4002
|
);
|
|
2640
4003
|
} catch {
|
|
2641
|
-
return
|
|
4004
|
+
return null;
|
|
2642
4005
|
}
|
|
2643
4006
|
}
|
|
2644
4007
|
if (isFolder && depth !== "0") {
|
|
2645
4008
|
try {
|
|
2646
4009
|
const children = await drive2.ls(virtualPath);
|
|
4010
|
+
const seenNames = /* @__PURE__ */ new Map();
|
|
2647
4011
|
for (const child of children) {
|
|
4012
|
+
let childName = child.name || "untitled";
|
|
4013
|
+
if (seenNames.has(childName)) {
|
|
4014
|
+
const count = seenNames.get(childName) + 1;
|
|
4015
|
+
seenNames.set(childName, count);
|
|
4016
|
+
const ext = import_node_path8.default.extname(childName);
|
|
4017
|
+
const base = import_node_path8.default.basename(childName, ext);
|
|
4018
|
+
childName = `${base} (${count})${ext}`;
|
|
4019
|
+
} else {
|
|
4020
|
+
seenNames.set(childName, 0);
|
|
4021
|
+
}
|
|
2648
4022
|
const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
|
|
2649
|
-
const childPath = virtualPath === "/" ? `/${
|
|
4023
|
+
const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
|
|
2650
4024
|
responses.push(
|
|
2651
4025
|
renderWebDAVResponse(
|
|
2652
4026
|
childPath,
|
|
2653
4027
|
childIsFolder,
|
|
2654
4028
|
child.size ? parseInt(child.size, 10) : 0,
|
|
2655
|
-
child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
4029
|
+
child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
|
|
4030
|
+
child.mimeType || void 0
|
|
2656
4031
|
)
|
|
2657
4032
|
);
|
|
2658
4033
|
}
|
|
@@ -2664,11 +4039,17 @@ async function handlePropfind(drive2, virtualPath, depth) {
|
|
|
2664
4039
|
${responses.join("\n")}
|
|
2665
4040
|
</D:multistatus>`;
|
|
2666
4041
|
}
|
|
2667
|
-
function renderWebDAVResponse(href, isDir, size, modifiedTime) {
|
|
2668
|
-
|
|
2669
|
-
|
|
4042
|
+
function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
|
|
4043
|
+
let cleanHref = href;
|
|
4044
|
+
if (isDir && !cleanHref.endsWith("/")) {
|
|
4045
|
+
cleanHref += "/";
|
|
4046
|
+
}
|
|
4047
|
+
const encodedHref = encodeURI(cleanHref);
|
|
4048
|
+
const displayName = escapeXml(import_node_path8.default.basename(href) || "root");
|
|
2670
4049
|
const resourceType = isDir ? "<D:collection/>" : "";
|
|
2671
4050
|
const dateFormatted = new Date(modifiedTime).toUTCString();
|
|
4051
|
+
const contentTypeTag = !isDir && mimeType ? `
|
|
4052
|
+
<D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
|
|
2672
4053
|
return ` <D:response>
|
|
2673
4054
|
<D:href>${encodedHref}</D:href>
|
|
2674
4055
|
<D:propstat>
|
|
@@ -2676,21 +4057,20 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
|
|
|
2676
4057
|
<D:displayname>${displayName}</D:displayname>
|
|
2677
4058
|
<D:resourcetype>${resourceType}</D:resourcetype>
|
|
2678
4059
|
<D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
|
|
2679
|
-
<D:getlastmodified>${dateFormatted}</D:getlastmodified
|
|
2680
|
-
<D:status>HTTP/1.1 200 OK</D:status>
|
|
4060
|
+
<D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
|
|
2681
4061
|
</D:prop>
|
|
2682
4062
|
<D:status>HTTP/1.1 200 OK</D:status>
|
|
2683
4063
|
</D:propstat>
|
|
2684
4064
|
</D:response>`;
|
|
2685
4065
|
}
|
|
2686
|
-
var
|
|
4066
|
+
var import_node_http4, import_node_url2, import_node_path8;
|
|
2687
4067
|
var init_webdav = __esm({
|
|
2688
4068
|
"src/server/webdav.ts"() {
|
|
2689
4069
|
"use strict";
|
|
2690
4070
|
init_cjs_shims();
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
4071
|
+
import_node_http4 = __toESM(require("http"), 1);
|
|
4072
|
+
import_node_url2 = __toESM(require("url"), 1);
|
|
4073
|
+
import_node_path8 = __toESM(require("path"), 1);
|
|
2694
4074
|
}
|
|
2695
4075
|
});
|
|
2696
4076
|
|
|
@@ -2699,13 +4079,14 @@ var client_exports = {};
|
|
|
2699
4079
|
__export(client_exports, {
|
|
2700
4080
|
DriveKit: () => DriveKit
|
|
2701
4081
|
});
|
|
2702
|
-
var
|
|
4082
|
+
var import_node_fs7, import_node_path9, import_node_crypto3, import_drive3, DriveKit;
|
|
2703
4083
|
var init_client = __esm({
|
|
2704
4084
|
"src/core/client.ts"() {
|
|
2705
4085
|
"use strict";
|
|
2706
4086
|
init_cjs_shims();
|
|
2707
|
-
|
|
2708
|
-
|
|
4087
|
+
import_node_fs7 = __toESM(require("fs"), 1);
|
|
4088
|
+
import_node_path9 = __toESM(require("path"), 1);
|
|
4089
|
+
import_node_crypto3 = __toESM(require("crypto"), 1);
|
|
2709
4090
|
import_drive3 = require("@googleapis/drive");
|
|
2710
4091
|
init_authenticator();
|
|
2711
4092
|
init_path_resolver();
|
|
@@ -2723,6 +4104,14 @@ var init_client = __esm({
|
|
|
2723
4104
|
init_format();
|
|
2724
4105
|
init_mime();
|
|
2725
4106
|
init_cache();
|
|
4107
|
+
init_http_agent();
|
|
4108
|
+
init_encryption();
|
|
4109
|
+
init_revisions();
|
|
4110
|
+
init_bidirectional_sync();
|
|
4111
|
+
init_s3_gateway();
|
|
4112
|
+
init_security_auditor();
|
|
4113
|
+
init_semantic_search();
|
|
4114
|
+
init_compression();
|
|
2726
4115
|
DriveKit = class _DriveKit {
|
|
2727
4116
|
options;
|
|
2728
4117
|
authenticator;
|
|
@@ -2731,12 +4120,34 @@ var init_client = __esm({
|
|
|
2731
4120
|
uploaderInstance = null;
|
|
2732
4121
|
downloaderInstance = null;
|
|
2733
4122
|
metadataCacheInstance = null;
|
|
4123
|
+
cryptoInstance = null;
|
|
2734
4124
|
rootFolderId;
|
|
2735
4125
|
pluginManager = new PluginManager();
|
|
2736
4126
|
constructor(options = {}) {
|
|
2737
4127
|
this.options = options;
|
|
2738
4128
|
this.rootFolderId = options.rootFolderId || "root";
|
|
2739
4129
|
this.authenticator = new DriveAuthenticator(options.auth);
|
|
4130
|
+
if (options.encryption) {
|
|
4131
|
+
this.cryptoInstance = new DriveKitCrypto(options.encryption);
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4134
|
+
/**
|
|
4135
|
+
* Access the client-side AES-256-GCM encryption engine
|
|
4136
|
+
*/
|
|
4137
|
+
get crypto() {
|
|
4138
|
+
if (!this.cryptoInstance) {
|
|
4139
|
+
throw new Error("Encryption is not configured on this DriveKit instance. Pass { encryption: { password: ... } } in options.");
|
|
4140
|
+
}
|
|
4141
|
+
return this.cryptoInstance;
|
|
4142
|
+
}
|
|
4143
|
+
/**
|
|
4144
|
+
* Access historical revisions & version control for a file
|
|
4145
|
+
*/
|
|
4146
|
+
getRevisions(fileIdOrPath) {
|
|
4147
|
+
if (!this.driveClient) {
|
|
4148
|
+
throw new Error("DriveKit is not initialized. Call await drive.init() first.");
|
|
4149
|
+
}
|
|
4150
|
+
return new DriveFileRevisions(this.driveClient, fileIdOrPath, (p) => this.resolveId(p));
|
|
2740
4151
|
}
|
|
2741
4152
|
/**
|
|
2742
4153
|
* Registers a middleware plugin into DriveKit lifecycle
|
|
@@ -2745,6 +4156,18 @@ var init_client = __esm({
|
|
|
2745
4156
|
this.pluginManager.use(plugin);
|
|
2746
4157
|
return this;
|
|
2747
4158
|
}
|
|
4159
|
+
/**
|
|
4160
|
+
* Unregisters a middleware plugin by name
|
|
4161
|
+
*/
|
|
4162
|
+
unuse(pluginName) {
|
|
4163
|
+
return this.pluginManager.unuse(pluginName);
|
|
4164
|
+
}
|
|
4165
|
+
/**
|
|
4166
|
+
* Access the underlying plugin manager instance
|
|
4167
|
+
*/
|
|
4168
|
+
get plugins() {
|
|
4169
|
+
return this.pluginManager;
|
|
4170
|
+
}
|
|
2748
4171
|
/**
|
|
2749
4172
|
* Returns a fluent, chained reference to a specific file
|
|
2750
4173
|
*/
|
|
@@ -2763,7 +4186,8 @@ var init_client = __esm({
|
|
|
2763
4186
|
async init() {
|
|
2764
4187
|
if (!this.driveClient) {
|
|
2765
4188
|
const auth = await this.authenticator.getAuthClient();
|
|
2766
|
-
|
|
4189
|
+
const agent = getOptimizedHttpsAgent();
|
|
4190
|
+
this.driveClient = (0, import_drive3.drive)({ version: "v3", auth, agent });
|
|
2767
4191
|
if (this.options.enablePersistentCache !== false) {
|
|
2768
4192
|
this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
|
|
2769
4193
|
this.metadataCacheInstance.init();
|
|
@@ -2850,15 +4274,41 @@ var init_client = __esm({
|
|
|
2850
4274
|
}
|
|
2851
4275
|
}
|
|
2852
4276
|
/**
|
|
2853
|
-
* Lists contents of a folder (by folder ID or path)
|
|
4277
|
+
* Lists contents of a folder (by folder ID or path) with opportunistic tree caching
|
|
2854
4278
|
*/
|
|
2855
4279
|
async ls(folderIdOrPath = "/") {
|
|
4280
|
+
let parentFolderId;
|
|
4281
|
+
let normalizedPath = null;
|
|
4282
|
+
let files;
|
|
2856
4283
|
if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
|
|
4284
|
+
parentFolderId = this.rootFolderId;
|
|
4285
|
+
normalizedPath = "/";
|
|
2857
4286
|
const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
|
|
2858
|
-
|
|
4287
|
+
files = await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
|
|
4288
|
+
} else {
|
|
4289
|
+
if (folderIdOrPath.startsWith("/")) {
|
|
4290
|
+
normalizedPath = folderIdOrPath.replace(/\/+$/, "") || "/";
|
|
4291
|
+
parentFolderId = await this.resolveId(normalizedPath);
|
|
4292
|
+
} else {
|
|
4293
|
+
parentFolderId = folderIdOrPath;
|
|
4294
|
+
}
|
|
4295
|
+
files = await this.query().inFolder(parentFolderId).notTrashed().orderBy("folder,name").list();
|
|
4296
|
+
}
|
|
4297
|
+
if (this.metadataCacheInstance && files.length > 0) {
|
|
4298
|
+
const cacheEntries = files.filter((f) => !!f.id).map((f) => ({
|
|
4299
|
+
id: f.id,
|
|
4300
|
+
name: f.name || "untitled",
|
|
4301
|
+
mimeType: f.mimeType || "",
|
|
4302
|
+
size: f.size ? parseInt(f.size, 10) : void 0,
|
|
4303
|
+
parentId: parentFolderId,
|
|
4304
|
+
path: normalizedPath ? `${normalizedPath === "/" ? "" : normalizedPath}/${f.name}` : void 0,
|
|
4305
|
+
md5Checksum: f.md5Checksum || void 0,
|
|
4306
|
+
modifiedTime: f.modifiedTime || void 0,
|
|
4307
|
+
trashed: false
|
|
4308
|
+
}));
|
|
4309
|
+
this.metadataCacheInstance.upsertFiles(cacheEntries);
|
|
2859
4310
|
}
|
|
2860
|
-
|
|
2861
|
-
return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
|
|
4311
|
+
return files;
|
|
2862
4312
|
}
|
|
2863
4313
|
// ==========================================
|
|
2864
4314
|
// FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
|
|
@@ -2877,68 +4327,101 @@ var init_client = __esm({
|
|
|
2877
4327
|
if (parentId && parentId.startsWith("/")) {
|
|
2878
4328
|
parentId = await this.mkdirp(parentId);
|
|
2879
4329
|
}
|
|
2880
|
-
|
|
2881
|
-
if (
|
|
4330
|
+
let uploadOpts = { ...opts };
|
|
4331
|
+
if (uploadOpts.compress) {
|
|
4332
|
+
const algo = typeof uploadOpts.compress === "string" ? uploadOpts.compress : "gzip";
|
|
4333
|
+
if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
|
|
4334
|
+
const plainBuf = await import_node_fs7.default.promises.readFile(uploadOpts.source);
|
|
4335
|
+
uploadOpts.source = await compressBuffer(plainBuf, algo);
|
|
4336
|
+
} else if (Buffer.isBuffer(uploadOpts.source)) {
|
|
4337
|
+
uploadOpts.source = await compressBuffer(uploadOpts.source, algo);
|
|
4338
|
+
}
|
|
4339
|
+
uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_compressed: algo };
|
|
4340
|
+
}
|
|
4341
|
+
if ((uploadOpts.encrypt || this.options.encryption) && this.cryptoInstance) {
|
|
4342
|
+
const origName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : "encrypted.bin");
|
|
4343
|
+
if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
|
|
4344
|
+
const plainBuf = await import_node_fs7.default.promises.readFile(uploadOpts.source);
|
|
4345
|
+
uploadOpts.source = this.cryptoInstance.encryptBuffer(plainBuf);
|
|
4346
|
+
} else if (Buffer.isBuffer(uploadOpts.source)) {
|
|
4347
|
+
uploadOpts.source = this.cryptoInstance.encryptBuffer(uploadOpts.source);
|
|
4348
|
+
}
|
|
4349
|
+
if (this.options.encryption?.encryptFilenames) {
|
|
4350
|
+
uploadOpts.name = this.cryptoInstance.encryptFilename(origName);
|
|
4351
|
+
}
|
|
4352
|
+
uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_encrypted: "true" };
|
|
4353
|
+
}
|
|
4354
|
+
const targetName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : void 0);
|
|
4355
|
+
if (uploadOpts.overwrite && targetName && parentId) {
|
|
2882
4356
|
const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
|
|
2883
4357
|
if (existing?.id) {
|
|
2884
4358
|
await this.delete(existing.id, true);
|
|
2885
4359
|
}
|
|
2886
4360
|
}
|
|
2887
|
-
if (
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
4361
|
+
if (uploadOpts.deduplicate) {
|
|
4362
|
+
let localMd5;
|
|
4363
|
+
if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
|
|
4364
|
+
localMd5 = await calculateFileMd5(uploadOpts.source);
|
|
4365
|
+
} else if (Buffer.isBuffer(uploadOpts.source)) {
|
|
4366
|
+
localMd5 = import_node_crypto3.default.createHash("md5").update(uploadOpts.source).digest("hex");
|
|
2893
4367
|
}
|
|
2894
|
-
if (
|
|
2895
|
-
|
|
2896
|
-
if (
|
|
2897
|
-
|
|
4368
|
+
if (localMd5) {
|
|
4369
|
+
let existingId;
|
|
4370
|
+
if (this.metadataCacheInstance) {
|
|
4371
|
+
const cached = this.metadataCacheInstance.findByMd5(localMd5);
|
|
4372
|
+
if (cached) existingId = cached.id;
|
|
2898
4373
|
}
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
name: file.name || fileName,
|
|
2920
|
-
mimeType: file.mimeType || "",
|
|
2921
|
-
size: file.size ? parseInt(file.size, 10) : void 0,
|
|
2922
|
-
parentId,
|
|
2923
|
-
md5Checksum: localMd5,
|
|
2924
|
-
trashed: false
|
|
4374
|
+
if (!existingId) {
|
|
4375
|
+
const found = await this.query().md5(localMd5).notTrashed().first();
|
|
4376
|
+
if (found?.id) {
|
|
4377
|
+
existingId = found.id;
|
|
4378
|
+
}
|
|
4379
|
+
}
|
|
4380
|
+
if (existingId) {
|
|
4381
|
+
const fileName = targetName || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : "file.bin");
|
|
4382
|
+
const raw = await this.getRawClient();
|
|
4383
|
+
const copyRes = await withRetry(async () => {
|
|
4384
|
+
return await raw.files.copy({
|
|
4385
|
+
fileId: existingId,
|
|
4386
|
+
requestBody: {
|
|
4387
|
+
name: fileName,
|
|
4388
|
+
parents: parentId ? [parentId] : void 0,
|
|
4389
|
+
description: uploadOpts.description
|
|
4390
|
+
},
|
|
4391
|
+
fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
|
|
4392
|
+
supportsAllDrives: true
|
|
4393
|
+
});
|
|
2925
4394
|
});
|
|
4395
|
+
const file = copyRes.data;
|
|
4396
|
+
if (this.metadataCacheInstance && file.id) {
|
|
4397
|
+
this.metadataCacheInstance.upsertFile({
|
|
4398
|
+
id: file.id,
|
|
4399
|
+
name: file.name || fileName,
|
|
4400
|
+
mimeType: file.mimeType || "",
|
|
4401
|
+
size: file.size ? parseInt(file.size, 10) : void 0,
|
|
4402
|
+
parentId,
|
|
4403
|
+
md5Checksum: localMd5,
|
|
4404
|
+
trashed: false
|
|
4405
|
+
});
|
|
4406
|
+
}
|
|
4407
|
+
return await this.pluginManager.runAfterUpload(file);
|
|
2926
4408
|
}
|
|
2927
|
-
return await this.pluginManager.runAfterUpload(file);
|
|
2928
4409
|
}
|
|
2929
4410
|
}
|
|
2930
4411
|
const uploaded = await uploader.upload({
|
|
2931
|
-
...
|
|
4412
|
+
...uploadOpts,
|
|
2932
4413
|
name: targetName,
|
|
2933
4414
|
parent: parentId
|
|
2934
4415
|
});
|
|
2935
4416
|
if (this.metadataCacheInstance && uploaded.id) {
|
|
4417
|
+
const virtualPath = typeof opts.parent === "string" && opts.parent.startsWith("/") ? `${opts.parent === "/" ? "" : opts.parent}/${uploaded.name || targetName || "untitled"}` : void 0;
|
|
2936
4418
|
this.metadataCacheInstance.upsertFile({
|
|
2937
4419
|
id: uploaded.id,
|
|
2938
4420
|
name: uploaded.name || targetName || "untitled",
|
|
2939
4421
|
mimeType: uploaded.mimeType || "",
|
|
2940
4422
|
size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
|
|
2941
4423
|
parentId,
|
|
4424
|
+
path: virtualPath,
|
|
2942
4425
|
trashed: false
|
|
2943
4426
|
});
|
|
2944
4427
|
}
|
|
@@ -2949,16 +4432,35 @@ var init_client = __esm({
|
|
|
2949
4432
|
* - Automatic conversion for Google Docs, Sheets, and Slides
|
|
2950
4433
|
* - Progress events
|
|
2951
4434
|
* - Saves directly to file or returns Readable Stream
|
|
4435
|
+
* - Leverages local metadata cache to bypass redundant Google API roundtrips
|
|
2952
4436
|
*/
|
|
2953
4437
|
async download(fileIdOrPath, options = {}) {
|
|
2954
4438
|
const fileId = await this.resolveId(fileIdOrPath);
|
|
2955
|
-
|
|
4439
|
+
let cachedMeta = options.metadata;
|
|
4440
|
+
if (!cachedMeta && this.metadataCacheInstance) {
|
|
4441
|
+
const cached = this.metadataCacheInstance.getById(fileId);
|
|
4442
|
+
if (cached && cached.name && cached.mimeType) {
|
|
4443
|
+
cachedMeta = { name: cached.name, mimeType: cached.mimeType, size: cached.size };
|
|
4444
|
+
}
|
|
4445
|
+
}
|
|
4446
|
+
const mergedOpts = cachedMeta ? { ...options, metadata: cachedMeta } : options;
|
|
4447
|
+
const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
|
|
2956
4448
|
const downloader = await this.getDownloader();
|
|
2957
4449
|
const result = await downloader.download(fileId, processedOpts);
|
|
4450
|
+
if (processedOpts.decrypt && this.cryptoInstance && result.filePath && import_node_fs7.default.existsSync(result.filePath)) {
|
|
4451
|
+
const encrypted = await import_node_fs7.default.promises.readFile(result.filePath);
|
|
4452
|
+
const decrypted = this.cryptoInstance.decryptBuffer(encrypted);
|
|
4453
|
+
await import_node_fs7.default.promises.writeFile(result.filePath, decrypted);
|
|
4454
|
+
}
|
|
4455
|
+
if (processedOpts.decompress && result.filePath && import_node_fs7.default.existsSync(result.filePath)) {
|
|
4456
|
+
const comp = await import_node_fs7.default.promises.readFile(result.filePath);
|
|
4457
|
+
const decomp = await decompressBuffer(comp);
|
|
4458
|
+
await import_node_fs7.default.promises.writeFile(result.filePath, decomp);
|
|
4459
|
+
}
|
|
2958
4460
|
return await this.pluginManager.runAfterDownload(result);
|
|
2959
4461
|
}
|
|
2960
4462
|
/**
|
|
2961
|
-
* Gets file metadata
|
|
4463
|
+
* Gets file metadata and updates the local metadata cache
|
|
2962
4464
|
*/
|
|
2963
4465
|
async getFile(fileIdOrPath) {
|
|
2964
4466
|
const fileId = await this.resolveId(fileIdOrPath);
|
|
@@ -2970,7 +4472,20 @@ var init_client = __esm({
|
|
|
2970
4472
|
supportsAllDrives: true
|
|
2971
4473
|
});
|
|
2972
4474
|
});
|
|
2973
|
-
|
|
4475
|
+
const file = res.data;
|
|
4476
|
+
if (this.metadataCacheInstance && file.id) {
|
|
4477
|
+
this.metadataCacheInstance.upsertFile({
|
|
4478
|
+
id: file.id,
|
|
4479
|
+
name: file.name || "",
|
|
4480
|
+
mimeType: file.mimeType || "",
|
|
4481
|
+
size: file.size ? parseInt(file.size, 10) : void 0,
|
|
4482
|
+
parentId: file.parents?.[0],
|
|
4483
|
+
path: fileIdOrPath.startsWith("/") ? fileIdOrPath : void 0,
|
|
4484
|
+
modifiedTime: file.modifiedTime || void 0,
|
|
4485
|
+
trashed: file.trashed || false
|
|
4486
|
+
});
|
|
4487
|
+
}
|
|
4488
|
+
return file;
|
|
2974
4489
|
}
|
|
2975
4490
|
/**
|
|
2976
4491
|
* Reads file content as UTF-8 string
|
|
@@ -3013,6 +4528,9 @@ var init_client = __esm({
|
|
|
3013
4528
|
if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
|
|
3014
4529
|
this.pathResolverInstance.invalidatePath(fileIdOrPath);
|
|
3015
4530
|
}
|
|
4531
|
+
if (this.metadataCacheInstance) {
|
|
4532
|
+
this.metadataCacheInstance.deleteFile(fileId);
|
|
4533
|
+
}
|
|
3016
4534
|
}
|
|
3017
4535
|
/**
|
|
3018
4536
|
* Move item to trash
|
|
@@ -3054,6 +4572,16 @@ var init_client = __esm({
|
|
|
3054
4572
|
if (this.pathResolverInstance) {
|
|
3055
4573
|
this.pathResolverInstance.clearCache();
|
|
3056
4574
|
}
|
|
4575
|
+
if (this.metadataCacheInstance) {
|
|
4576
|
+
const cached = this.metadataCacheInstance.getById(fileId);
|
|
4577
|
+
if (cached) {
|
|
4578
|
+
this.metadataCacheInstance.upsertFile({
|
|
4579
|
+
...cached,
|
|
4580
|
+
parentId: newParentId,
|
|
4581
|
+
path: void 0
|
|
4582
|
+
});
|
|
4583
|
+
}
|
|
4584
|
+
}
|
|
3057
4585
|
return res.data;
|
|
3058
4586
|
}
|
|
3059
4587
|
/**
|
|
@@ -3062,10 +4590,7 @@ var init_client = __esm({
|
|
|
3062
4590
|
async copy(fileIdOrPath, options = {}) {
|
|
3063
4591
|
const fileId = await this.resolveId(fileIdOrPath);
|
|
3064
4592
|
const raw = await this.getRawClient();
|
|
3065
|
-
|
|
3066
|
-
if (parentId && parentId.startsWith("/")) {
|
|
3067
|
-
parentId = await this.mkdirp(parentId);
|
|
3068
|
-
}
|
|
4593
|
+
const parentId = options.parent ? await this.resolveId(options.parent, true) : void 0;
|
|
3069
4594
|
const requestBody = {};
|
|
3070
4595
|
if (options.name) requestBody.name = options.name;
|
|
3071
4596
|
if (parentId) requestBody.parents = [parentId];
|
|
@@ -3096,6 +4621,16 @@ var init_client = __esm({
|
|
|
3096
4621
|
if (this.pathResolverInstance) {
|
|
3097
4622
|
this.pathResolverInstance.clearCache();
|
|
3098
4623
|
}
|
|
4624
|
+
if (this.metadataCacheInstance) {
|
|
4625
|
+
const cached = this.metadataCacheInstance.getById(fileId);
|
|
4626
|
+
if (cached) {
|
|
4627
|
+
this.metadataCacheInstance.upsertFile({
|
|
4628
|
+
...cached,
|
|
4629
|
+
name: newName,
|
|
4630
|
+
path: void 0
|
|
4631
|
+
});
|
|
4632
|
+
}
|
|
4633
|
+
}
|
|
3099
4634
|
return res.data;
|
|
3100
4635
|
}
|
|
3101
4636
|
// ==========================================
|
|
@@ -3182,16 +4717,16 @@ var init_client = __esm({
|
|
|
3182
4717
|
durationMs: 0
|
|
3183
4718
|
};
|
|
3184
4719
|
const collectFiles = async (dir, base) => {
|
|
3185
|
-
const entries = await
|
|
4720
|
+
const entries = await import_node_fs7.default.promises.readdir(dir, { withFileTypes: true });
|
|
3186
4721
|
const files = [];
|
|
3187
4722
|
for (const entry of entries) {
|
|
3188
|
-
const fullPath =
|
|
3189
|
-
const relPath =
|
|
4723
|
+
const fullPath = import_node_path9.default.join(dir, entry.name);
|
|
4724
|
+
const relPath = import_node_path9.default.join(base, entry.name);
|
|
3190
4725
|
if (entry.isDirectory()) {
|
|
3191
4726
|
const sub = await collectFiles(fullPath, relPath);
|
|
3192
4727
|
files.push(...sub);
|
|
3193
4728
|
} else if (entry.isFile()) {
|
|
3194
|
-
const stat = await
|
|
4729
|
+
const stat = await import_node_fs7.default.promises.stat(fullPath);
|
|
3195
4730
|
files.push({ fullPath, relPath, size: stat.size });
|
|
3196
4731
|
}
|
|
3197
4732
|
}
|
|
@@ -3204,11 +4739,11 @@ var init_client = __esm({
|
|
|
3204
4739
|
if (remoteDirCache.has(relDir)) {
|
|
3205
4740
|
return remoteDirCache.get(relDir);
|
|
3206
4741
|
}
|
|
3207
|
-
const parts = relDir.split(
|
|
4742
|
+
const parts = relDir.split(import_node_path9.default.sep).filter(Boolean);
|
|
3208
4743
|
let currentParent = targetFolderId;
|
|
3209
4744
|
let currentRel = "";
|
|
3210
4745
|
for (const part of parts) {
|
|
3211
|
-
currentRel = currentRel ?
|
|
4746
|
+
currentRel = currentRel ? import_node_path9.default.join(currentRel, part) : part;
|
|
3212
4747
|
if (remoteDirCache.has(currentRel)) {
|
|
3213
4748
|
currentParent = remoteDirCache.get(currentRel);
|
|
3214
4749
|
continue;
|
|
@@ -3237,8 +4772,8 @@ var init_client = __esm({
|
|
|
3237
4772
|
};
|
|
3238
4773
|
await pool.map(allFiles, async (fileItem) => {
|
|
3239
4774
|
try {
|
|
3240
|
-
const relDir =
|
|
3241
|
-
const fileName =
|
|
4775
|
+
const relDir = import_node_path9.default.dirname(fileItem.relPath);
|
|
4776
|
+
const fileName = import_node_path9.default.basename(fileItem.relPath);
|
|
3242
4777
|
const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
|
|
3243
4778
|
if (options.onFileStart) {
|
|
3244
4779
|
options.onFileStart(fileItem.fullPath, fileItem.relPath);
|
|
@@ -3373,7 +4908,7 @@ var init_client = __esm({
|
|
|
3373
4908
|
async createWriteStream(remotePath, options = {}) {
|
|
3374
4909
|
await this.init();
|
|
3375
4910
|
const { PassThrough } = await import("stream");
|
|
3376
|
-
const passThrough = new PassThrough();
|
|
4911
|
+
const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
|
|
3377
4912
|
let resolveDone;
|
|
3378
4913
|
let rejectDone;
|
|
3379
4914
|
const donePromise = new Promise((resolve, reject) => {
|
|
@@ -3381,8 +4916,8 @@ var init_client = __esm({
|
|
|
3381
4916
|
rejectDone = reject;
|
|
3382
4917
|
});
|
|
3383
4918
|
passThrough.done = donePromise;
|
|
3384
|
-
const remoteDir =
|
|
3385
|
-
const fileName = options.name || options.filename ||
|
|
4919
|
+
const remoteDir = import_node_path9.default.dirname(remotePath);
|
|
4920
|
+
const fileName = options.name || options.filename || import_node_path9.default.basename(remotePath);
|
|
3386
4921
|
const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
|
|
3387
4922
|
const mimeType = options.mimeType || "application/octet-stream";
|
|
3388
4923
|
const raw = this.driveClient;
|
|
@@ -3420,6 +4955,12 @@ var init_client = __esm({
|
|
|
3420
4955
|
// ==========================================
|
|
3421
4956
|
// METADATA CACHE OPERATIONS
|
|
3422
4957
|
// ==========================================
|
|
4958
|
+
/**
|
|
4959
|
+
* Synchronous getter for the active metadata cache instance
|
|
4960
|
+
*/
|
|
4961
|
+
get cache() {
|
|
4962
|
+
return this.metadataCacheInstance;
|
|
4963
|
+
}
|
|
3423
4964
|
/**
|
|
3424
4965
|
* Returns the active persistent metadata cache instance (SQLite/Memory)
|
|
3425
4966
|
*/
|
|
@@ -3442,6 +4983,9 @@ var init_client = __esm({
|
|
|
3442
4983
|
if (this.pathResolverInstance) {
|
|
3443
4984
|
this.pathResolverInstance.clearCache();
|
|
3444
4985
|
}
|
|
4986
|
+
if (this.metadataCacheInstance) {
|
|
4987
|
+
this.metadataCacheInstance.clear();
|
|
4988
|
+
}
|
|
3445
4989
|
}
|
|
3446
4990
|
/**
|
|
3447
4991
|
* Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
|
|
@@ -3606,6 +5150,47 @@ var init_client = __esm({
|
|
|
3606
5150
|
const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
|
|
3607
5151
|
return await startWebDAVServer2(this, options);
|
|
3608
5152
|
}
|
|
5153
|
+
/**
|
|
5154
|
+
* Performs an intelligent two-way bidirectional sync between local and Google Drive directories
|
|
5155
|
+
*/
|
|
5156
|
+
async syncBiDirectional(options) {
|
|
5157
|
+
await this.init();
|
|
5158
|
+
const engine = new BidirectionalSyncEngine(this);
|
|
5159
|
+
return await engine.sync(options);
|
|
5160
|
+
}
|
|
5161
|
+
/**
|
|
5162
|
+
* Starts an embedded S3-compatible HTTP gateway server
|
|
5163
|
+
*/
|
|
5164
|
+
async serveS3(options = {}) {
|
|
5165
|
+
await this.init();
|
|
5166
|
+
const gateway = new S3GatewayServer(this, options);
|
|
5167
|
+
await gateway.start();
|
|
5168
|
+
return gateway;
|
|
5169
|
+
}
|
|
5170
|
+
/**
|
|
5171
|
+
* Scans Google Drive files and generates a security & permission audit report
|
|
5172
|
+
*/
|
|
5173
|
+
async auditPermissions(options = {}) {
|
|
5174
|
+
await this.init();
|
|
5175
|
+
const auditor = new SecurityAuditor(this.driveClient);
|
|
5176
|
+
return await auditor.audit(options);
|
|
5177
|
+
}
|
|
5178
|
+
/**
|
|
5179
|
+
* Revokes public 'anyone' link permissions from the given files
|
|
5180
|
+
*/
|
|
5181
|
+
async revokePublicPermissions(fileIds) {
|
|
5182
|
+
await this.init();
|
|
5183
|
+
const auditor = new SecurityAuditor(this.driveClient);
|
|
5184
|
+
return await auditor.revokePublicAccess(fileIds);
|
|
5185
|
+
}
|
|
5186
|
+
/**
|
|
5187
|
+
* Multi-word fuzzy and semantic search across files
|
|
5188
|
+
*/
|
|
5189
|
+
async searchSmart(query, options = {}) {
|
|
5190
|
+
await this.init();
|
|
5191
|
+
const engine = new SmartSearchEngine(this);
|
|
5192
|
+
return await engine.search(query, options);
|
|
5193
|
+
}
|
|
3609
5194
|
/**
|
|
3610
5195
|
* Calculates local file MD5 hash for integrity and deduplication checks
|
|
3611
5196
|
*/
|
|
@@ -3629,8 +5214,8 @@ __export(cli_exports, {
|
|
|
3629
5214
|
});
|
|
3630
5215
|
module.exports = __toCommonJS(cli_exports);
|
|
3631
5216
|
init_cjs_shims();
|
|
3632
|
-
var
|
|
3633
|
-
var
|
|
5217
|
+
var import_node_fs8 = __toESM(require("fs"), 1);
|
|
5218
|
+
var import_node_path10 = __toESM(require("path"), 1);
|
|
3634
5219
|
var import_commander = require("commander");
|
|
3635
5220
|
var import_chalk2 = __toESM(require("chalk"), 1);
|
|
3636
5221
|
var import_ora = __toESM(require("ora"), 1);
|
|
@@ -3793,17 +5378,29 @@ ${import_chalk.default.cyan("\u{1F517} Getting shareable link for:")} ${import_c
|
|
|
3793
5378
|
|
|
3794
5379
|
// src/cli.ts
|
|
3795
5380
|
var program = new import_commander.Command();
|
|
3796
|
-
var pkgVersion = "1.
|
|
5381
|
+
var pkgVersion = "1.2.0";
|
|
3797
5382
|
try {
|
|
3798
5383
|
const pkgPath = new URL("../package.json", importMetaUrl);
|
|
3799
|
-
const pkg = JSON.parse(
|
|
5384
|
+
const pkg = JSON.parse(import_node_fs8.default.readFileSync(pkgPath, "utf8"));
|
|
3800
5385
|
if (pkg.version) pkgVersion = pkg.version;
|
|
3801
5386
|
} catch {
|
|
3802
5387
|
}
|
|
3803
5388
|
program.name("drivekit").description(import_chalk2.default.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version(pkgVersion).option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
|
|
3804
5389
|
function getAuthConfig(cmdOptions) {
|
|
3805
5390
|
const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
|
|
3806
|
-
|
|
5391
|
+
let accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
|
|
5392
|
+
if (!keyFilePath && !accessToken) {
|
|
5393
|
+
const tokensFile = import_node_path10.default.resolve(process.cwd(), "gdrive-tokens.json");
|
|
5394
|
+
if (import_node_fs8.default.existsSync(tokensFile)) {
|
|
5395
|
+
try {
|
|
5396
|
+
const tokens = JSON.parse(import_node_fs8.default.readFileSync(tokensFile, "utf8"));
|
|
5397
|
+
if (tokens.access_token) {
|
|
5398
|
+
accessToken = tokens.access_token;
|
|
5399
|
+
}
|
|
5400
|
+
} catch {
|
|
5401
|
+
}
|
|
5402
|
+
}
|
|
5403
|
+
}
|
|
3807
5404
|
return {
|
|
3808
5405
|
keyFilePath,
|
|
3809
5406
|
accessToken
|
|
@@ -3873,11 +5470,11 @@ program.command("explore [folder]").description("Interactive terminal keyboard f
|
|
|
3873
5470
|
}
|
|
3874
5471
|
});
|
|
3875
5472
|
program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").option("-d, --dedup", "Enable instant cloud deduplication via MD5 hash check").action(async (localFile, remotePath = "/", options) => {
|
|
3876
|
-
if (!
|
|
5473
|
+
if (!import_node_fs8.default.existsSync(localFile)) {
|
|
3877
5474
|
console.error(import_chalk2.default.red(`\u274C Local file not found: ${localFile}`));
|
|
3878
5475
|
process.exit(1);
|
|
3879
5476
|
}
|
|
3880
|
-
const fileName =
|
|
5477
|
+
const fileName = import_node_path10.default.basename(localFile);
|
|
3881
5478
|
const spinner = (0, import_ora.default)(`Preparing upload: ${fileName}...`).start();
|
|
3882
5479
|
try {
|
|
3883
5480
|
const client = await getClient(options);
|
|
@@ -3973,7 +5570,7 @@ program.command("delete <fileIdOrPath>").description("Move a file/folder to tras
|
|
|
3973
5570
|
}
|
|
3974
5571
|
});
|
|
3975
5572
|
program.command("sync <localDir> <remoteFolder>").description("Sync a local directory to Google Drive recursively with high concurrency").option("-c, --concurrency <number>", "Number of parallel uploads", "4").option("-o, --overwrite", "Overwrite files if they already exist").action(async (localDir, remoteFolder, options) => {
|
|
3976
|
-
if (!
|
|
5573
|
+
if (!import_node_fs8.default.existsSync(localDir)) {
|
|
3977
5574
|
console.error(import_chalk2.default.red(`\u274C Local directory not found: ${localDir}`));
|
|
3978
5575
|
process.exit(1);
|
|
3979
5576
|
}
|
|
@@ -4141,8 +5738,8 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
|
|
|
4141
5738
|
if (result.tokens.refresh_token) {
|
|
4142
5739
|
console.log(`Refresh Token: ${import_chalk2.default.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
|
|
4143
5740
|
}
|
|
4144
|
-
const outPath =
|
|
4145
|
-
|
|
5741
|
+
const outPath = import_node_path10.default.resolve("./gdrive-tokens.json");
|
|
5742
|
+
import_node_fs8.default.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
|
|
4146
5743
|
console.log(`\u{1F4BE} Saved tokens to: ${import_chalk2.default.bold(outPath)}
|
|
4147
5744
|
`);
|
|
4148
5745
|
} catch (err) {
|
|
@@ -4254,6 +5851,186 @@ program.command("serve").description("Start embedded WebDAV server to mount Driv
|
|
|
4254
5851
|
process.exit(1);
|
|
4255
5852
|
}
|
|
4256
5853
|
});
|
|
5854
|
+
program.command("sync-2way <localDir> <remoteDir>").description("Two-way bidirectional synchronization with conflict resolution").option("-s, --strategy <strategy>", "Conflict strategy: rename-conflict, keep-newer, prefer-cloud, prefer-local", "rename-conflict").option("--delete-missing", "Propagate deletions in both directions").option("--dry-run", "Preview changes without modifying any files").action(async (localDir, remoteDir, options) => {
|
|
5855
|
+
console.log(import_chalk2.default.bold.cyan(`
|
|
5856
|
+
\u{1F504} Two-Way Sync: "${localDir}" \u21C4 "${remoteDir}"`));
|
|
5857
|
+
console.log(`Conflict Strategy: ${import_chalk2.default.yellow(options.strategy)} | Delete Missing: ${options.deleteMissing ? import_chalk2.default.red("YES") : import_chalk2.default.dim("NO")}
|
|
5858
|
+
`);
|
|
5859
|
+
try {
|
|
5860
|
+
const client = await getClient(options);
|
|
5861
|
+
const res = await client.syncBiDirectional({
|
|
5862
|
+
localDir: import_node_path10.default.resolve(localDir),
|
|
5863
|
+
remoteDir,
|
|
5864
|
+
conflictStrategy: options.strategy,
|
|
5865
|
+
deleteMissing: !!options.deleteMissing,
|
|
5866
|
+
dryRun: !!options.dryRun,
|
|
5867
|
+
onProgress: (ev) => {
|
|
5868
|
+
const actionColors = {
|
|
5869
|
+
upload: import_chalk2.default.green("[UPLOAD]"),
|
|
5870
|
+
download: import_chalk2.default.blue("[DOWNLOAD]"),
|
|
5871
|
+
"delete-local": import_chalk2.default.red("[DELETE LOCAL]"),
|
|
5872
|
+
"delete-remote": import_chalk2.default.red("[DELETE REMOTE]"),
|
|
5873
|
+
"conflict-resolved": import_chalk2.default.yellow("[CONFLICT]"),
|
|
5874
|
+
"skip-identical": import_chalk2.default.dim("[IDENTICAL]")
|
|
5875
|
+
};
|
|
5876
|
+
const prefix = actionColors[ev.action] || `[${ev.action}]`;
|
|
5877
|
+
console.log(` ${prefix} ${import_chalk2.default.white(ev.relPath)} ${ev.details ? import_chalk2.default.dim(`(${ev.details})`) : ""}`);
|
|
5878
|
+
}
|
|
5879
|
+
});
|
|
5880
|
+
console.log(import_chalk2.default.bold.green(`
|
|
5881
|
+
\u2705 Two-Way Sync Completed in ${(res.durationMs / 1e3).toFixed(2)}s!`));
|
|
5882
|
+
console.log(` \u2B06\uFE0F Uploaded: ${import_chalk2.default.bold(res.uploaded.length)}`);
|
|
5883
|
+
console.log(` \u2B07\uFE0F Downloaded: ${import_chalk2.default.bold(res.downloaded.length)}`);
|
|
5884
|
+
console.log(` \u{1F5D1}\uFE0F Deleted Local: ${import_chalk2.default.bold(res.deletedLocal.length)}`);
|
|
5885
|
+
console.log(` \u{1F5D1}\uFE0F Deleted Remote:${import_chalk2.default.bold(res.deletedRemote.length)}`);
|
|
5886
|
+
console.log(` \u26A1 Conflicts: ${import_chalk2.default.bold(res.conflicts.length)}`);
|
|
5887
|
+
console.log(` \u23ED\uFE0F Identical: ${import_chalk2.default.bold(res.skipped.length)}
|
|
5888
|
+
`);
|
|
5889
|
+
} catch (err) {
|
|
5890
|
+
console.error(import_chalk2.default.red(`
|
|
5891
|
+
Two-Way sync failed: ${err.message}`));
|
|
5892
|
+
process.exit(1);
|
|
5893
|
+
}
|
|
5894
|
+
});
|
|
5895
|
+
program.command("serve-s3").description("Start S3-compatible HTTP gateway server to treat Drive as an S3 Bucket").option("-p, --port <port>", "Port number to listen on", "9000").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").option("-b, --bucket-root <path>", "Virtual path root for S3 buckets", "/").option("--key <accessKey>", "Optional S3 access key ID").option("--secret <secretKey>", "Optional S3 secret access key").action(async (options) => {
|
|
5896
|
+
try {
|
|
5897
|
+
const client = await getClient(options);
|
|
5898
|
+
const port = parseInt(options.port, 10) || 9e3;
|
|
5899
|
+
const host = options.host || "127.0.0.1";
|
|
5900
|
+
console.log(import_chalk2.default.bold.cyan("\n\u{1F4E6} DriveKit S3-Compatible Gateway"));
|
|
5901
|
+
console.log("Starting S3 REST API bridge to Google Drive...\n");
|
|
5902
|
+
const gateway = await client.serveS3({
|
|
5903
|
+
port,
|
|
5904
|
+
host,
|
|
5905
|
+
bucketRoot: options.bucketRoot,
|
|
5906
|
+
accessKeyId: options.key,
|
|
5907
|
+
secretAccessKey: options.secret
|
|
5908
|
+
});
|
|
5909
|
+
console.log(import_chalk2.default.bold.green(`\u{1F680} S3 Gateway active at: ${import_chalk2.default.underline(`http://${host}:${port}`)}`));
|
|
5910
|
+
console.log(import_chalk2.default.white("\n\u{1F4CC} Connect with AWS CLI:"));
|
|
5911
|
+
console.log(import_chalk2.default.yellow(` aws s3 ls --endpoint-url http://${host}:${port}`));
|
|
5912
|
+
console.log(import_chalk2.default.white("\u{1F4CC} Connect with MinIO client:"));
|
|
5913
|
+
console.log(import_chalk2.default.yellow(` mc alias set drivekit http://${host}:${port} ${options.key || "dummy"} ${options.secret || "dummy"}
|
|
5914
|
+
`));
|
|
5915
|
+
console.log(import_chalk2.default.dim("Press Ctrl+C to stop the S3 Gateway.\n"));
|
|
5916
|
+
process.on("SIGINT", async () => {
|
|
5917
|
+
await gateway.stop();
|
|
5918
|
+
console.log(import_chalk2.default.yellow("\nS3 Gateway stopped. Goodbye!"));
|
|
5919
|
+
process.exit(0);
|
|
5920
|
+
});
|
|
5921
|
+
} catch (err) {
|
|
5922
|
+
console.error(import_chalk2.default.red(`Failed to start S3 gateway: ${err.message}`));
|
|
5923
|
+
process.exit(1);
|
|
5924
|
+
}
|
|
5925
|
+
});
|
|
5926
|
+
program.command("audit").description("Audit Drive security & permissions: detect public leaks and external shares").option("-l, --limit <count>", "Maximum files to scan", "200").option("--allowed-domains <domains>", "Comma-separated allowed organization domains").option("--revoke-public", 'Automatically revoke public "anyone" links').action(async (options) => {
|
|
5927
|
+
const spinner = (0, import_ora.default)("Auditing Google Drive permissions...").start();
|
|
5928
|
+
try {
|
|
5929
|
+
const client = await getClient(options);
|
|
5930
|
+
const limit = parseInt(options.limit, 10) || 200;
|
|
5931
|
+
const allowedDomains = options.allowedDomains ? options.allowedDomains.split(",").map((d) => d.trim()) : [];
|
|
5932
|
+
const report = await client.auditPermissions({ scanLimit: limit, allowedDomains });
|
|
5933
|
+
spinner.stop();
|
|
5934
|
+
console.log(import_chalk2.default.bold.cyan("\n\u{1F6E1}\uFE0F Google Drive Security & Permission Audit Report"));
|
|
5935
|
+
console.log(`Scanned files: ${import_chalk2.default.bold(report.totalScanned)} | Audit time: ${import_chalk2.default.dim(report.scannedAt)}
|
|
5936
|
+
`);
|
|
5937
|
+
console.log(`\u{1F310} Publicly Accessible (Anyone with Link): ${report.publicFilesCount > 0 ? import_chalk2.default.bold.red(report.publicFilesCount) : import_chalk2.default.green("0")}`);
|
|
5938
|
+
console.log(`\u{1F3E2} Organization Domain Shares: ${import_chalk2.default.yellow(report.domainSharedCount)}`);
|
|
5939
|
+
console.log(`\u{1F464} External Collaborators: ${report.externalSharesCount > 0 ? import_chalk2.default.bold.yellow(report.externalSharesCount) : import_chalk2.default.green("0")}
|
|
5940
|
+
`);
|
|
5941
|
+
if (report.issues.length > 0) {
|
|
5942
|
+
console.log(import_chalk2.default.bold.yellow("\u26A0\uFE0F Detected Security Issues:"));
|
|
5943
|
+
for (const issue of report.issues.slice(0, 30)) {
|
|
5944
|
+
const riskColor = issue.risk === "CRITICAL" ? import_chalk2.default.bold.bgRed : issue.risk === "HIGH" ? import_chalk2.default.red : import_chalk2.default.yellow;
|
|
5945
|
+
console.log(` ${riskColor(`[${issue.risk}]`)} ${import_chalk2.default.bold(issue.fileName)}`);
|
|
5946
|
+
console.log(` \u21B3 Reason: ${issue.reason}`);
|
|
5947
|
+
if (issue.webViewLink) console.log(` \u21B3 URL: ${import_chalk2.default.dim(issue.webViewLink)}`);
|
|
5948
|
+
}
|
|
5949
|
+
if (report.issues.length > 30) {
|
|
5950
|
+
console.log(import_chalk2.default.dim(`
|
|
5951
|
+
... and ${report.issues.length - 30} more issues.`));
|
|
5952
|
+
}
|
|
5953
|
+
console.log("");
|
|
5954
|
+
} else {
|
|
5955
|
+
console.log(import_chalk2.default.green("\u2728 No critical security leaks detected!\n"));
|
|
5956
|
+
}
|
|
5957
|
+
if (options.revokePublic && report.publicFilesCount > 0) {
|
|
5958
|
+
const publicFileIds = Array.from(new Set(report.issues.filter((i) => i.type === "anyone").map((i) => i.fileId)));
|
|
5959
|
+
const revSpinner = (0, import_ora.default)(`Revoking public access on ${publicFileIds.length} files...`).start();
|
|
5960
|
+
const revRes = await client.revokePublicPermissions(publicFileIds);
|
|
5961
|
+
revSpinner.succeed(import_chalk2.default.green(`Successfully revoked public access on ${revRes.revoked.length} files!`));
|
|
5962
|
+
}
|
|
5963
|
+
} catch (err) {
|
|
5964
|
+
spinner.fail(import_chalk2.default.red(`Security audit failed: ${err.message}`));
|
|
5965
|
+
process.exit(1);
|
|
5966
|
+
}
|
|
5967
|
+
});
|
|
5968
|
+
program.command("revisions <fileIdOrPath>").description("List and manage historical file revisions").option("--keep-forever <revId>", "Pin a revision to prevent automatic purging after 30 days").option("--restore <revId>", "Restore file to a specific previous revision").action(async (fileIdOrPath, options) => {
|
|
5969
|
+
try {
|
|
5970
|
+
const client = await getClient(options);
|
|
5971
|
+
const revsManager = client.getRevisions(fileIdOrPath);
|
|
5972
|
+
if (options.keepForever) {
|
|
5973
|
+
const spinner2 = (0, import_ora.default)(`Pinning revision ${options.keepForever}...`).start();
|
|
5974
|
+
await revsManager.keepForever(options.keepForever, true);
|
|
5975
|
+
spinner2.succeed(import_chalk2.default.green(`Revision ${options.keepForever} is now pinned forever!`));
|
|
5976
|
+
return;
|
|
5977
|
+
}
|
|
5978
|
+
if (options.restore) {
|
|
5979
|
+
const spinner2 = (0, import_ora.default)(`Restoring file to revision ${options.restore}...`).start();
|
|
5980
|
+
await revsManager.restore(options.restore);
|
|
5981
|
+
spinner2.succeed(import_chalk2.default.green(`File content successfully restored to revision ${options.restore}!`));
|
|
5982
|
+
return;
|
|
5983
|
+
}
|
|
5984
|
+
const spinner = (0, import_ora.default)("Fetching revision history...").start();
|
|
5985
|
+
const revisions = await revsManager.list();
|
|
5986
|
+
spinner.stop();
|
|
5987
|
+
console.log(import_chalk2.default.bold.cyan(`
|
|
5988
|
+
\u{1F4DC} Revision History for "${fileIdOrPath}" (${revisions.length} versions):
|
|
5989
|
+
`));
|
|
5990
|
+
for (const r of revisions) {
|
|
5991
|
+
const pinned = r.keepForever ? import_chalk2.default.green("\u{1F4CC} [PINNED]") : import_chalk2.default.dim("[EXPIRABLE]");
|
|
5992
|
+
console.log(` ID: ${import_chalk2.default.bold.yellow(r.id.padEnd(20))} Modified: ${import_chalk2.default.white(r.modifiedTime || "unknown")} ${pinned} ${r.size ? formatBytes(r.size) : ""}`);
|
|
5993
|
+
}
|
|
5994
|
+
console.log("");
|
|
5995
|
+
} catch (err) {
|
|
5996
|
+
console.error(import_chalk2.default.red(`Failed to manage revisions: ${err.message}`));
|
|
5997
|
+
process.exit(1);
|
|
5998
|
+
}
|
|
5999
|
+
});
|
|
6000
|
+
program.command("search <query>").description("Search Google Drive files by name, description, or fuzzy matching").option("--smart", "Use multi-word fuzzy relevance scoring").option("-l, --limit <count>", "Maximum results to return", "20").action(async (query, options) => {
|
|
6001
|
+
const spinner = (0, import_ora.default)(`Searching for "${query}"...`).start();
|
|
6002
|
+
try {
|
|
6003
|
+
const client = await getClient(options);
|
|
6004
|
+
const limit = parseInt(options.limit, 10) || 20;
|
|
6005
|
+
if (options.smart) {
|
|
6006
|
+
const results = await client.searchSmart(query, { limit });
|
|
6007
|
+
spinner.stop();
|
|
6008
|
+
console.log(import_chalk2.default.bold.cyan(`
|
|
6009
|
+
\u{1F50D} Smart Search Results for "${query}" (${results.length}):
|
|
6010
|
+
`));
|
|
6011
|
+
for (const res of results) {
|
|
6012
|
+
const scorePercent = Math.round(res.score * 100);
|
|
6013
|
+
const scoreColor = scorePercent >= 80 ? import_chalk2.default.green : scorePercent >= 50 ? import_chalk2.default.yellow : import_chalk2.default.dim;
|
|
6014
|
+
console.log(` ${scoreColor(`[${scorePercent}%]`)} ${import_chalk2.default.bold(res.file.name)} ${import_chalk2.default.dim(`(Matched on: ${res.matchedOn.join(", ")})`)}`);
|
|
6015
|
+
console.log(` \u21B3 ID: ${import_chalk2.default.dim(res.file.id)} | Size: ${formatBytes(res.file.size ? parseInt(res.file.size, 10) : 0)}`);
|
|
6016
|
+
}
|
|
6017
|
+
console.log("");
|
|
6018
|
+
return;
|
|
6019
|
+
}
|
|
6020
|
+
const files = await client.query().nameContains(query).notTrashed().pageSize(limit).list();
|
|
6021
|
+
spinner.stop();
|
|
6022
|
+
console.log(import_chalk2.default.bold.cyan(`
|
|
6023
|
+
\u{1F50D} Found ${files.length} matching files:
|
|
6024
|
+
`));
|
|
6025
|
+
for (const f of files) {
|
|
6026
|
+
console.log(` \u{1F4C4} ${import_chalk2.default.white((f.name || "untitled").padEnd(35))} ${import_chalk2.default.dim(`ID: ${f.id}`)} [${formatBytes(f.size ? parseInt(f.size, 10) : 0)}]`);
|
|
6027
|
+
}
|
|
6028
|
+
console.log("");
|
|
6029
|
+
} catch (err) {
|
|
6030
|
+
spinner.fail(import_chalk2.default.red(`Search failed: ${err.message}`));
|
|
6031
|
+
process.exit(1);
|
|
6032
|
+
}
|
|
6033
|
+
});
|
|
4257
6034
|
function runCLI() {
|
|
4258
6035
|
program.parse(process.argv);
|
|
4259
6036
|
}
|