drivekit 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2,7 +2,8 @@ import * as http from 'http';
2
2
  import { drive_v3 } from '@googleapis/drive';
3
3
  import { OAuth2Client } from 'google-auth-library';
4
4
  import { EventEmitter } from 'node:events';
5
- import http$1 from 'node:http';
5
+ import { Transform } from 'node:stream';
6
+ import http$1, { IncomingMessage, ServerResponse } from 'node:http';
6
7
  import https from 'node:https';
7
8
 
8
9
  interface BrowserLoginOptions {
@@ -81,6 +82,12 @@ interface DriveKitOptions {
81
82
  maxRetries?: number;
82
83
  /** Base delay for exponential backoff in ms (default: 1000) */
83
84
  retryBaseDelayMs?: number;
85
+ /** Zero-knowledge client-side AES-256-GCM encryption configuration */
86
+ encryption?: {
87
+ password?: string;
88
+ key?: Buffer;
89
+ encryptFilenames?: boolean;
90
+ };
84
91
  }
85
92
  /**
86
93
  * Upload progress event payload
@@ -140,6 +147,10 @@ interface UploadOptions {
140
147
  /** Custom properties / metadata */
141
148
  properties?: Record<string, string>;
142
149
  appProperties?: Record<string, string>;
150
+ /** Client-side zero-knowledge encryption with AES-256-GCM */
151
+ encrypt?: boolean;
152
+ /** Real-time on-the-fly stream compression algorithm */
153
+ compress?: 'gzip' | 'brotli' | 'deflate';
143
154
  /** Optional AbortSignal for instant operation cancellation */
144
155
  signal?: AbortSignal;
145
156
  }
@@ -159,6 +170,10 @@ interface DownloadOptions {
159
170
  mimeType?: string;
160
171
  size?: number;
161
172
  };
173
+ /** Automatically decrypt client-side encrypted files */
174
+ decrypt?: boolean;
175
+ /** Automatically decompress compressed stream */
176
+ decompress?: boolean;
162
177
  /** Optional AbortSignal for instant operation cancellation */
163
178
  signal?: AbortSignal;
164
179
  }
@@ -452,6 +467,46 @@ declare class SmartSyncEngine {
452
467
  }): Promise<PullResult>;
453
468
  }
454
469
 
470
+ interface DriveRevision {
471
+ id: string;
472
+ mimeType?: string;
473
+ modifiedTime?: string;
474
+ keepForever?: boolean;
475
+ size?: number;
476
+ originalFilename?: string;
477
+ }
478
+ declare class DriveFileRevisions {
479
+ private drive;
480
+ private pathOrId;
481
+ private idResolver?;
482
+ constructor(drive: drive_v3.Drive, pathOrId: string, idResolver?: (idOrPath: string) => Promise<string>);
483
+ private getId;
484
+ /**
485
+ * Lists all historical revisions of the file
486
+ */
487
+ list(): Promise<DriveRevision[]>;
488
+ /**
489
+ * Gets metadata for a specific revision
490
+ */
491
+ get(revisionId: string): Promise<DriveRevision>;
492
+ /**
493
+ * Pins or unpins a revision so Google Drive never automatically purges it after 30 days
494
+ */
495
+ keepForever(revisionId: string, keep?: boolean): Promise<DriveRevision>;
496
+ /**
497
+ * Deletes a specific historical revision
498
+ */
499
+ delete(revisionId: string): Promise<void>;
500
+ /**
501
+ * Gets a readable stream of a specific historical revision
502
+ */
503
+ getStream(revisionId: string): Promise<NodeJS.ReadableStream>;
504
+ /**
505
+ * Restores the file content to a specific previous revision
506
+ */
507
+ restore(revisionId: string): Promise<void>;
508
+ }
509
+
455
510
  /**
456
511
  * Fluent reference to a specific file in Google Drive
457
512
  */
@@ -492,6 +547,8 @@ declare class DriveFileRef {
492
547
  previewLink: string;
493
548
  directDownloadLink: string;
494
549
  }>;
550
+ /** Access historical revisions & version control for this file */
551
+ get revisions(): DriveFileRevisions;
495
552
  /** Returns a ReadableStream for this file, optionally with byte Range requests */
496
553
  createReadStream(options?: {
497
554
  start?: number;
@@ -679,6 +736,219 @@ declare class MemoryMetadataCache implements IMetadataCache {
679
736
  close(): void;
680
737
  }
681
738
 
739
+ declare const MAGIC_HEADER: Buffer<ArrayBuffer>;
740
+ declare const MAGIC_STREAM_HEADER: Buffer<ArrayBuffer>;
741
+ declare const SALT_LENGTH = 16;
742
+ declare const IV_LENGTH = 12;
743
+ declare const TAG_LENGTH = 16;
744
+ declare const PBKDF2_ROUNDS = 100000;
745
+ interface DriveKitCryptoConfig {
746
+ password?: string;
747
+ key?: Buffer;
748
+ encryptFilenames?: boolean;
749
+ }
750
+ /**
751
+ * Derives a 256-bit AES key from a password and salt using PBKDF2 (SHA-512)
752
+ */
753
+ declare function deriveKey(password: string, salt: Buffer): Buffer;
754
+ /**
755
+ * Zero-Knowledge Client-Side AES-256-GCM Encryption Engine for DriveKit.
756
+ */
757
+ declare class DriveKitCrypto {
758
+ private config;
759
+ constructor(config: DriveKitCryptoConfig);
760
+ /**
761
+ * Encrypts a Buffer using AES-256-GCM.
762
+ * Format: [MAGIC (6B)][SALT (16B)][IV (12B)][TAG (16B)][CIPHERTEXT]
763
+ */
764
+ encryptBuffer(data: Buffer): Buffer;
765
+ /**
766
+ * Decrypts a Buffer previously encrypted with encryptBuffer or createEncryptStream.
767
+ */
768
+ decryptBuffer(encryptedData: Buffer): Buffer;
769
+ /**
770
+ * Creates an encryption Transform stream that prepends stream header and appends GCM auth tag
771
+ */
772
+ createEncryptStream(): Transform;
773
+ /**
774
+ * Creates a decryption Transform stream that verifies magic header and validates GCM authentication tag
775
+ */
776
+ createDecryptStream(): Transform;
777
+ /**
778
+ * Encrypts a filename into a safe base64url string
779
+ */
780
+ encryptFilename(plainName: string): string;
781
+ /**
782
+ * Decrypts a filename generated by encryptFilename
783
+ */
784
+ decryptFilename(encryptedName: string): string;
785
+ }
786
+
787
+ type ConflictStrategy = 'rename-conflict' | 'keep-newer' | 'prefer-cloud' | 'prefer-local';
788
+ interface BidirectionalSyncOptions {
789
+ localDir: string;
790
+ remoteDir: string;
791
+ conflictStrategy?: ConflictStrategy;
792
+ deleteMissing?: boolean;
793
+ dryRun?: boolean;
794
+ onProgress?: (event: SyncProgressEvent) => void;
795
+ }
796
+ type SyncActionType = 'upload' | 'download' | 'delete-local' | 'delete-remote' | 'conflict-resolved' | 'skip-identical';
797
+ interface SyncProgressEvent {
798
+ action: SyncActionType;
799
+ relPath: string;
800
+ details?: string;
801
+ }
802
+ interface BidirectionalSyncResult {
803
+ uploaded: string[];
804
+ downloaded: string[];
805
+ deletedLocal: string[];
806
+ deletedRemote: string[];
807
+ conflicts: string[];
808
+ skipped: string[];
809
+ durationMs: number;
810
+ }
811
+ interface LedgerEntry {
812
+ relPath: string;
813
+ localMtime: number;
814
+ remoteMtime: number;
815
+ localMd5: string;
816
+ remoteMd5: string;
817
+ remoteId: string;
818
+ }
819
+ /**
820
+ * Intelligent Two-Way Bidirectional Synchronization Engine.
821
+ * Detects local and remote changes, handles additions, updates, deletions, and resolves conflicts.
822
+ */
823
+ declare class BidirectionalSyncEngine {
824
+ private drive;
825
+ private ledger;
826
+ constructor(drive: DriveKit);
827
+ /**
828
+ * Performs a two-way synchronization cycle between local and remote directories
829
+ */
830
+ sync(options: BidirectionalSyncOptions): Promise<BidirectionalSyncResult>;
831
+ private scanLocalDir;
832
+ private scanRemoteDir;
833
+ private uploadFile;
834
+ private downloadFile;
835
+ private updateLedger;
836
+ }
837
+
838
+ interface S3GatewayOptions {
839
+ port?: number;
840
+ host?: string;
841
+ bucketRoot?: string;
842
+ accessKeyId?: string;
843
+ secretAccessKey?: string;
844
+ }
845
+ /**
846
+ * Lightweight S3-Compatible HTTP Gateway for Google Drive.
847
+ * Allows AWS S3 CLI, MinIO client, and backup agents to read & write to Google Drive as an S3 Bucket.
848
+ */
849
+ declare class S3GatewayServer {
850
+ private drive;
851
+ private options;
852
+ private server;
853
+ constructor(drive: DriveKit, options?: S3GatewayOptions);
854
+ /**
855
+ * Starts the S3 gateway HTTP server
856
+ */
857
+ start(): Promise<{
858
+ port: number;
859
+ host: string;
860
+ }>;
861
+ /**
862
+ * Stops the S3 gateway HTTP server
863
+ */
864
+ stop(): Promise<void>;
865
+ private handleRequest;
866
+ private handleListBuckets;
867
+ private handleListObjects;
868
+ private sendXmlError;
869
+ private escapeXml;
870
+ }
871
+
872
+ type SecurityRiskLevel = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
873
+ interface AuditIssue {
874
+ fileId: string;
875
+ fileName: string;
876
+ risk: SecurityRiskLevel;
877
+ reason: string;
878
+ permissionId: string;
879
+ type: string;
880
+ role: string;
881
+ emailAddress?: string;
882
+ domain?: string;
883
+ webViewLink?: string;
884
+ }
885
+ interface SecurityAuditReport {
886
+ totalScanned: number;
887
+ publicFilesCount: number;
888
+ domainSharedCount: number;
889
+ externalSharesCount: number;
890
+ issues: AuditIssue[];
891
+ scannedAt: string;
892
+ }
893
+ interface AuditOptions {
894
+ scanLimit?: number;
895
+ allowedDomains?: string[];
896
+ }
897
+ /**
898
+ * Security & Permissions Auditor for Google Drive.
899
+ * Detects public leaks, unrestricted domain shares, and unauthorized external collaborators.
900
+ */
901
+ declare class SecurityAuditor {
902
+ private drive;
903
+ constructor(drive: drive_v3.Drive);
904
+ /**
905
+ * Scans Google Drive files and audits their permission grants
906
+ */
907
+ audit(options?: AuditOptions): Promise<SecurityAuditReport>;
908
+ /**
909
+ * Revokes public 'anyone' permissions on specified files
910
+ */
911
+ revokePublicAccess(fileIds: string[]): Promise<{
912
+ revoked: string[];
913
+ errors: {
914
+ fileId: string;
915
+ error: string;
916
+ }[];
917
+ }>;
918
+ }
919
+
920
+ interface SmartSearchResult {
921
+ file: DriveApiFile;
922
+ score: number;
923
+ matchedOn: ('name' | 'path' | 'description' | 'semantic')[];
924
+ }
925
+ interface SmartSearchOptions {
926
+ /** Maximum number of results to return */
927
+ limit?: number;
928
+ /** Minimum similarity score threshold (0.0 - 1.0) */
929
+ minScore?: number;
930
+ /** Optional custom vector embedding function for true semantic search */
931
+ embedder?: (text: string) => Promise<number[]>;
932
+ /** Restrict search to specific parent folder ID or virtual path */
933
+ parent?: string;
934
+ }
935
+ /**
936
+ * Calculates cosine similarity between two numerical vectors
937
+ */
938
+ declare function cosineSimilarity(vecA: number[], vecB: number[]): number;
939
+ /**
940
+ * Multi-layer Fuzzy & Semantic Search Engine for DriveKit.
941
+ * Matches multi-word queries, typos, and semantic concepts across Google Drive files.
942
+ */
943
+ declare class SmartSearchEngine {
944
+ private drive;
945
+ constructor(drive: DriveKit);
946
+ /**
947
+ * Searches Drive using tokenized fuzzy matching and optional semantic embeddings
948
+ */
949
+ search(query: string, options?: SmartSearchOptions): Promise<SmartSearchResult[]>;
950
+ }
951
+
682
952
  declare class DriveKit {
683
953
  private options;
684
954
  private authenticator;
@@ -687,9 +957,18 @@ declare class DriveKit {
687
957
  private uploaderInstance;
688
958
  private downloaderInstance;
689
959
  private metadataCacheInstance;
960
+ private cryptoInstance;
690
961
  private rootFolderId;
691
962
  private pluginManager;
692
963
  constructor(options?: DriveKitOptions);
964
+ /**
965
+ * Access the client-side AES-256-GCM encryption engine
966
+ */
967
+ get crypto(): DriveKitCrypto;
968
+ /**
969
+ * Access historical revisions & version control for a file
970
+ */
971
+ getRevisions(fileIdOrPath: string): DriveFileRevisions;
693
972
  /**
694
973
  * Registers a middleware plugin into DriveKit lifecycle
695
974
  */
@@ -964,6 +1243,32 @@ declare class DriveKit {
964
1243
  url: string;
965
1244
  close: () => Promise<void>;
966
1245
  }>;
1246
+ /**
1247
+ * Performs an intelligent two-way bidirectional sync between local and Google Drive directories
1248
+ */
1249
+ syncBiDirectional(options: BidirectionalSyncOptions): Promise<BidirectionalSyncResult>;
1250
+ /**
1251
+ * Starts an embedded S3-compatible HTTP gateway server
1252
+ */
1253
+ serveS3(options?: S3GatewayOptions): Promise<S3GatewayServer>;
1254
+ /**
1255
+ * Scans Google Drive files and generates a security & permission audit report
1256
+ */
1257
+ auditPermissions(options?: AuditOptions): Promise<SecurityAuditReport>;
1258
+ /**
1259
+ * Revokes public 'anyone' link permissions from the given files
1260
+ */
1261
+ revokePublicPermissions(fileIds: string[]): Promise<{
1262
+ revoked: string[];
1263
+ errors: {
1264
+ fileId: string;
1265
+ error: string;
1266
+ }[];
1267
+ }>;
1268
+ /**
1269
+ * Multi-word fuzzy and semantic search across files
1270
+ */
1271
+ searchSmart(query: string, options?: SmartSearchOptions): Promise<SmartSearchResult[]>;
967
1272
  /**
968
1273
  * Calculates local file MD5 hash for integrity and deduplication checks
969
1274
  */
@@ -1314,6 +1619,50 @@ declare function getOptimizedHttpsAgent(options?: HttpAgentOptions): https.Agent
1314
1619
  */
1315
1620
  declare function getOptimizedHttpAgent(options?: HttpAgentOptions): http$1.Agent;
1316
1621
 
1622
+ type CompressionAlgorithm = 'gzip' | 'brotli' | 'deflate';
1623
+ /**
1624
+ * Returns a Transform stream for real-time stream compression
1625
+ */
1626
+ declare function createCompressStream(algorithm?: CompressionAlgorithm): Transform;
1627
+ /**
1628
+ * Returns a Transform stream for real-time stream decompression
1629
+ */
1630
+ declare function createDecompressStream(algorithm?: CompressionAlgorithm): Transform;
1631
+ /**
1632
+ * Compresses an in-memory buffer using the specified algorithm
1633
+ */
1634
+ declare function compressBuffer(buffer: Buffer, algorithm?: CompressionAlgorithm): Promise<Buffer>;
1635
+ /**
1636
+ * Decompresses an in-memory buffer using the specified algorithm
1637
+ */
1638
+ declare function decompressBuffer(buffer: Buffer, algorithm?: CompressionAlgorithm): Promise<Buffer>;
1639
+ /**
1640
+ * Checks if a buffer starts with standard GZIP magic bytes (0x1f, 0x8b)
1641
+ */
1642
+ declare function isGzipBuffer(buffer: Buffer): boolean;
1643
+
1644
+ interface UploadMiddlewareOptions {
1645
+ /** Target virtual directory in Google Drive (e.g. '/UserUploads') */
1646
+ destination?: string;
1647
+ /** Max allowed file size in bytes */
1648
+ maxFileSize?: number;
1649
+ /** Custom file namer function */
1650
+ filenameGenerator?: (originalName: string, mimeType: string) => string;
1651
+ }
1652
+ interface DrivekitRequest extends IncomingMessage {
1653
+ drivekitFiles?: DriveApiFile[];
1654
+ drivekitFields?: Record<string, string>;
1655
+ }
1656
+ /**
1657
+ * Express / Connect / Node.js HTTP Streaming Multipart Middleware.
1658
+ * Directly streams files from browser form-data into Google Drive without touching server disk!
1659
+ */
1660
+ declare function createDriveUploadMiddleware(drive: DriveKit, options?: UploadMiddlewareOptions): (req: DrivekitRequest, res: ServerResponse, next: (err?: any) => void) => Promise<void>;
1661
+ /**
1662
+ * Next.js / Web Fetch API Multipart Upload Handler for App Router API routes
1663
+ */
1664
+ declare function handleNextJsUpload(formData: FormData, drive: DriveKit, options?: UploadMiddlewareOptions): Promise<DriveApiFile[]>;
1665
+
1317
1666
  /**
1318
1667
  * Creates and initializes a DriveKit instance
1319
1668
  *
@@ -1334,4 +1683,4 @@ declare function getOptimizedHttpAgent(options?: HttpAgentOptions): http$1.Agent
1334
1683
  */
1335
1684
  declare function createDrive(options?: DriveKitOptions): Promise<DriveKit>;
1336
1685
 
1337
- export { type BrowserLoginOptions, type CacheFileEntry, type CacheStats, ConcurrencyPool, DEFAULT_CHUNK_SIZE, DEFAULT_EXPORT_MIMES, DEFAULT_SCOPES, type DownloadOptions, type DownloadProgress, Downloader, type DriveApiFile, type DriveApiFileList, type DriveApiPermission, DriveAuthError, DriveAuthenticator, DriveFileRef, DriveFolderRef, DriveKit, type DriveKitAuthConfig, DriveKitError, type DriveKitOptions, type DriveKitPlugin, DriveNotFoundError, DriveQueryBuilder, DriveRateLimitError, DriveUploadError, DriveWatcher, type DriveWriteStream, type DuplicateGroup, type FileChangeEvent, GOOGLE_WORKSPACE_MIME_TYPES, type HttpAgentOptions, type IMetadataCache, type LoginResult, MIN_CHUNK_SIZE, MULTIPART_THRESHOLD, MemoryMetadataCache, PathResolver, type PermissionRole, type PermissionType, PluginManager, type PullResult, ResumableUploader, type RetryOptions, type ShareOptions, SmartSyncEngine, SqliteMetadataCache, StorageCleaner, type SyncResult, type UploadOptions, type UploadProgress, type WatcherOptions, type WebDAVServerOptions, type WebhookPluginOptions, calculateFileMd5, createAutoNamePlugin, createDrive, createWebhookPlugin, DriveKit as default, escapeXml, formatBytes, formatDuration, formatSpeed, getExtensionForMime, getFileIcon, getOptimizedHttpAgent, getOptimizedHttpsAgent, isGoogleWorkspaceDoc, isRetryableError, loginWithBrowser, lookupMimeType, renderFileRow, runInteractiveExplorer, startWebDAVServer, terminalLink, withRetry };
1686
+ export { type AuditIssue, type AuditOptions, BidirectionalSyncEngine, type BidirectionalSyncOptions, type BidirectionalSyncResult, type BrowserLoginOptions, type CacheFileEntry, type CacheStats, type CompressionAlgorithm, ConcurrencyPool, type ConflictStrategy, DEFAULT_CHUNK_SIZE, DEFAULT_EXPORT_MIMES, DEFAULT_SCOPES, type DownloadOptions, type DownloadProgress, Downloader, type DriveApiFile, type DriveApiFileList, type DriveApiPermission, DriveAuthError, DriveAuthenticator, DriveFileRef, DriveFileRevisions, DriveFolderRef, DriveKit, type DriveKitAuthConfig, DriveKitCrypto, type DriveKitCryptoConfig, DriveKitError, type DriveKitOptions, type DriveKitPlugin, DriveNotFoundError, DriveQueryBuilder, DriveRateLimitError, type DriveRevision, DriveUploadError, DriveWatcher, type DriveWriteStream, type DrivekitRequest, type DuplicateGroup, type FileChangeEvent, GOOGLE_WORKSPACE_MIME_TYPES, type HttpAgentOptions, type IMetadataCache, IV_LENGTH, type LedgerEntry, type LoginResult, MAGIC_HEADER, MAGIC_STREAM_HEADER, MIN_CHUNK_SIZE, MULTIPART_THRESHOLD, MemoryMetadataCache, PBKDF2_ROUNDS, PathResolver, type PermissionRole, type PermissionType, PluginManager, type PullResult, ResumableUploader, type RetryOptions, type S3GatewayOptions, S3GatewayServer, SALT_LENGTH, type SecurityAuditReport, SecurityAuditor, type SecurityRiskLevel, type ShareOptions, SmartSearchEngine, type SmartSearchOptions, type SmartSearchResult, SmartSyncEngine, SqliteMetadataCache, StorageCleaner, type SyncActionType, type SyncProgressEvent, type SyncResult, TAG_LENGTH, type UploadMiddlewareOptions, type UploadOptions, type UploadProgress, type WatcherOptions, type WebDAVServerOptions, type WebhookPluginOptions, calculateFileMd5, compressBuffer, cosineSimilarity, createAutoNamePlugin, createCompressStream, createDecompressStream, createDrive, createDriveUploadMiddleware, createWebhookPlugin, decompressBuffer, DriveKit as default, deriveKey, escapeXml, formatBytes, formatDuration, formatSpeed, getExtensionForMime, getFileIcon, getOptimizedHttpAgent, getOptimizedHttpsAgent, handleNextJsUpload, isGoogleWorkspaceDoc, isGzipBuffer, isRetryableError, loginWithBrowser, lookupMimeType, renderFileRow, runInteractiveExplorer, startWebDAVServer, terminalLink, withRetry };