@lobehub/lobehub 2.0.0-next.191 → 2.0.0-next.193

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.
@@ -1,53 +1,24 @@
1
- import {
2
- type ClientDBLoadingProgress,
3
- DatabaseLoadingState,
4
- type MigrationSQL,
5
- type MigrationTableItem,
6
- } from '@lobechat/types';
1
+ import { PGlite } from '@electric-sql/pglite';
2
+ import { vector } from '@electric-sql/pglite/vector';
7
3
  import { sql } from 'drizzle-orm';
8
4
  import { PgliteDatabase, drizzle } from 'drizzle-orm/pglite';
9
5
  import { Md5 } from 'ts-md5';
10
6
 
11
- import { sleep } from '@/utils/sleep';
12
-
13
7
  import migrations from '../core/migrations.json';
14
8
  import { DrizzleMigrationModel } from '../models/drizzleMigration';
15
9
  import * as schema from '../schemas';
16
10
 
17
11
  const pgliteSchemaHashCache = 'LOBE_CHAT_PGLITE_SCHEMA_HASH';
18
-
19
12
  const DB_NAME = 'lobechat';
20
- type DrizzleInstance = PgliteDatabase<typeof schema>;
21
13
 
22
- interface onErrorState {
23
- error: Error;
24
- migrationTableItems: MigrationTableItem[];
25
- migrationsSQL: MigrationSQL[];
26
- }
27
-
28
- export interface DatabaseLoadingCallbacks {
29
- onError?: (error: onErrorState) => void;
30
- onProgress?: (progress: ClientDBLoadingProgress) => void;
31
- onStateChange?: (state: DatabaseLoadingState) => void;
32
- }
14
+ type DrizzleInstance = PgliteDatabase<typeof schema>;
33
15
 
34
- export class DatabaseManager {
16
+ class DatabaseManager {
35
17
  private static instance: DatabaseManager;
36
18
  private dbInstance: DrizzleInstance | null = null;
37
19
  private initPromise: Promise<DrizzleInstance> | null = null;
38
- private callbacks?: DatabaseLoadingCallbacks;
39
20
  private isLocalDBSchemaSynced = false;
40
21
 
41
- // CDN configuration
42
- private static WASM_CDN_URL =
43
- 'https://registry.npmmirror.com/@electric-sql/pglite/0.2.17/files/dist/postgres.wasm';
44
-
45
- private static FSBUNDLER_CDN_URL =
46
- 'https://registry.npmmirror.com/@electric-sql/pglite/0.2.17/files/dist/postgres.data';
47
-
48
- private static VECTOR_CDN_URL =
49
- 'https://registry.npmmirror.com/@electric-sql/pglite/0.2.17/files/dist/vector.tar.gz';
50
-
51
22
  private constructor() {}
52
23
 
53
24
  static getInstance() {
@@ -57,108 +28,8 @@ export class DatabaseManager {
57
28
  return DatabaseManager.instance;
58
29
  }
59
30
 
60
- // Load and compile WASM module
61
- private async loadWasmModule(): Promise<WebAssembly.Module> {
62
- const start = Date.now();
63
- this.callbacks?.onStateChange?.(DatabaseLoadingState.LoadingWasm);
64
-
65
- const response = await fetch(DatabaseManager.WASM_CDN_URL);
66
-
67
- const contentLength = Number(response.headers.get('Content-Length')) || 0;
68
- const reader = response.body?.getReader();
69
-
70
- if (!reader) throw new Error('Failed to start WASM download');
71
-
72
- let receivedLength = 0;
73
- const chunks: Uint8Array[] = [];
74
-
75
- // Read data stream
76
- // eslint-disable-next-line no-constant-condition
77
- while (true) {
78
- const { done, value } = await reader.read();
79
-
80
- if (done) break;
81
-
82
- chunks.push(value);
83
- receivedLength += value.length;
84
-
85
- // Calculate and report progress
86
- const progress = Math.min(Math.round((receivedLength / contentLength) * 100), 100);
87
- this.callbacks?.onProgress?.({
88
- phase: 'wasm',
89
- progress,
90
- });
91
- }
92
-
93
- // Merge data chunks
94
- const wasmBytes = new Uint8Array(receivedLength);
95
- let position = 0;
96
- for (const chunk of chunks) {
97
- wasmBytes.set(chunk, position);
98
- position += chunk.length;
99
- }
100
-
101
- this.callbacks?.onProgress?.({
102
- costTime: Date.now() - start,
103
- phase: 'wasm',
104
- progress: 100,
105
- });
106
-
107
- // Compile WASM module
108
- return WebAssembly.compile(wasmBytes);
109
- }
110
-
111
- private fetchFsBundle = async () => {
112
- const res = await fetch(DatabaseManager.FSBUNDLER_CDN_URL);
113
-
114
- return await res.blob();
115
- };
116
-
117
- // Asynchronously load PGlite related dependencies
118
- private async loadDependencies() {
119
- const start = Date.now();
120
- this.callbacks?.onStateChange?.(DatabaseLoadingState.LoadingDependencies);
121
-
122
- const imports = [
123
- import('@electric-sql/pglite').then((m) => ({
124
- IdbFs: m.IdbFs,
125
- MemoryFS: m.MemoryFS,
126
- PGlite: m.PGlite,
127
- })),
128
- import('@electric-sql/pglite/vector'),
129
- this.fetchFsBundle(),
130
- ];
131
-
132
- let loaded = 0;
133
- const results = await Promise.all(
134
- imports.map(async (importPromise) => {
135
- const result = await importPromise;
136
- loaded += 1;
137
-
138
- // Calculate loading progress
139
- this.callbacks?.onProgress?.({
140
- phase: 'dependencies',
141
- progress: Math.min(Math.round((loaded / imports.length) * 100), 100),
142
- });
143
- return result;
144
- }),
145
- );
146
-
147
- this.callbacks?.onProgress?.({
148
- costTime: Date.now() - start,
149
- phase: 'dependencies',
150
- progress: 100,
151
- });
152
-
153
- // @ts-ignore
154
- const [{ PGlite, IdbFs, MemoryFS }, { vector }, fsBundle] = results;
155
-
156
- return { IdbFs, MemoryFS, PGlite, fsBundle, vector };
157
- }
158
-
159
- // Database migration method
160
- private async migrate(skipMultiRun = false): Promise<DrizzleInstance> {
161
- if (this.isLocalDBSchemaSynced && skipMultiRun) return this.db;
31
+ private async migrate(): Promise<DrizzleInstance> {
32
+ if (this.isLocalDBSchemaSynced) return this.db;
162
33
 
163
34
  let hash: string | undefined;
164
35
  if (typeof localStorage !== 'undefined') {
@@ -179,17 +50,13 @@ export class DatabaseManager {
179
50
  }
180
51
  } catch (error) {
181
52
  console.warn('Error checking table existence, proceeding with migration', error);
182
- // If query fails, continue migration to ensure safety
183
53
  }
184
54
  }
185
55
  }
186
56
 
187
57
  const start = Date.now();
188
58
  try {
189
- this.callbacks?.onStateChange?.(DatabaseLoadingState.Migrating);
190
-
191
- // refs: https://github.com/drizzle-team/drizzle-orm/discussions/2532
192
- // @ts-expect-error
59
+ // @ts-expect-error - migrate internal API
193
60
  await this.db.dialect.migrate(migrations, this.db.session, {});
194
61
 
195
62
  if (typeof localStorage !== 'undefined' && hash) {
@@ -197,7 +64,6 @@ export class DatabaseManager {
197
64
  }
198
65
 
199
66
  this.isLocalDBSchemaSynced = true;
200
-
201
67
  console.info(`🗂 Migration success, take ${Date.now() - start}ms`);
202
68
  } catch (cause) {
203
69
  console.error('❌ Local database schema migration failed', cause);
@@ -207,95 +73,32 @@ export class DatabaseManager {
207
73
  return this.db;
208
74
  }
209
75
 
210
- // Initialize database
211
- async initialize(callbacks?: DatabaseLoadingCallbacks): Promise<DrizzleInstance> {
76
+ async initialize(): Promise<DrizzleInstance> {
212
77
  if (this.initPromise) return this.initPromise;
213
78
 
214
- this.callbacks = callbacks;
215
-
216
79
  this.initPromise = (async () => {
217
- try {
218
- if (this.dbInstance) return this.dbInstance;
219
-
220
- const time = Date.now();
221
- // Initialize database
222
- this.callbacks?.onStateChange?.(DatabaseLoadingState.Initializing);
223
-
224
- // Load dependencies
225
- const { fsBundle, PGlite, MemoryFS, IdbFs, vector } = await this.loadDependencies();
226
-
227
- // Load and compile WASM module
228
- const wasmModule = await this.loadWasmModule();
229
-
230
- const { initPgliteWorker } = await import('./pglite');
231
-
232
- let db: typeof PGlite;
233
-
234
- // make db as web worker if worker is available
235
- // https://github.com/lobehub/lobe-chat/issues/5785
236
- if (typeof Worker !== 'undefined' && typeof navigator.locks !== 'undefined') {
237
- db = await initPgliteWorker({
238
- dbName: DB_NAME,
239
- fsBundle: fsBundle as Blob,
240
- vectorBundlePath: DatabaseManager.VECTOR_CDN_URL,
241
- wasmModule,
242
- });
243
- } else {
244
- // in edge runtime or test runtime, we don't have worker
245
- db = new PGlite({
246
- extensions: { vector },
247
- fs: typeof window === 'undefined' ? new MemoryFS(DB_NAME) : new IdbFs(DB_NAME),
248
- relaxedDurability: true,
249
- wasmModule,
250
- });
251
- }
252
-
253
- this.dbInstance = drizzle({ client: db, schema });
80
+ if (this.dbInstance) return this.dbInstance;
254
81
 
255
- await this.migrate(true);
82
+ const time = Date.now();
256
83
 
257
- this.callbacks?.onStateChange?.(DatabaseLoadingState.Finished);
258
- console.log(`✅ Database initialized in ${Date.now() - time}ms`);
259
-
260
- await sleep(50);
84
+ // 直接使用 pglite,自动处理 wasm 加载
85
+ const pglite = new PGlite(`idb://${DB_NAME}`, {
86
+ extensions: { vector },
87
+ relaxedDurability: true,
88
+ });
261
89
 
262
- this.callbacks?.onStateChange?.(DatabaseLoadingState.Ready);
90
+ this.dbInstance = drizzle({ client: pglite, schema });
263
91
 
264
- return this.dbInstance as DrizzleInstance;
265
- } catch (e) {
266
- this.initPromise = null;
267
- this.callbacks?.onStateChange?.(DatabaseLoadingState.Error);
268
- const error = e as Error;
92
+ await this.migrate();
269
93
 
270
- // Query migration table data
271
- let migrationsTableData: MigrationTableItem[] = [];
272
- try {
273
- // Attempt to query migration table
274
- const drizzleMigration = new DrizzleMigrationModel(this.db as any);
275
- migrationsTableData = await drizzleMigration.getMigrationList();
276
- } catch (queryError) {
277
- console.error('Failed to query migrations table:', queryError);
278
- }
94
+ console.log(`✅ Database initialized in ${Date.now() - time}ms`);
279
95
 
280
- this.callbacks?.onError?.({
281
- error: {
282
- message: error.message,
283
- name: error.name,
284
- stack: error.stack,
285
- },
286
- migrationTableItems: migrationsTableData,
287
- migrationsSQL: migrations,
288
- });
289
-
290
- console.error(error);
291
- throw error;
292
- }
96
+ return this.dbInstance;
293
97
  })();
294
98
 
295
99
  return this.initPromise;
296
100
  }
297
101
 
298
- // Get database instance
299
102
  get db(): DrizzleInstance {
300
103
  if (!this.dbInstance) {
301
104
  throw new Error('Database not initialized. Please call initialize() first.');
@@ -303,7 +106,6 @@ export class DatabaseManager {
303
106
  return this.dbInstance;
304
107
  }
305
108
 
306
- // Create proxy object
307
109
  createProxy(): DrizzleInstance {
308
110
  return new Proxy({} as DrizzleInstance, {
309
111
  get: (target, prop) => {
@@ -313,7 +115,7 @@ export class DatabaseManager {
313
115
  }
314
116
 
315
117
  async resetDatabase(): Promise<void> {
316
- // 1. Close existing PGlite connection (if exists)
118
+ // 1. Close existing PGlite connection
317
119
  if (this.dbInstance) {
318
120
  try {
319
121
  // @ts-ignore
@@ -321,31 +123,28 @@ export class DatabaseManager {
321
123
  console.log('PGlite instance closed successfully.');
322
124
  } catch (e) {
323
125
  console.error('Error closing PGlite instance:', e);
324
- // Even if closing fails, continue with deletion attempt; IndexedDB onblocked or onerror will handle subsequent issues
325
126
  }
326
127
  }
327
128
 
328
129
  // 2. Reset database instance and initialization state
329
130
  this.dbInstance = null;
330
131
  this.initPromise = null;
331
- this.isLocalDBSchemaSynced = false; // Reset sync state
132
+ this.isLocalDBSchemaSynced = false;
332
133
 
333
134
  // 3. Delete IndexedDB database
334
135
  return new Promise<void>((resolve, reject) => {
335
- // Check if IndexedDB is available
336
136
  if (typeof indexedDB === 'undefined') {
337
137
  console.warn('IndexedDB is not available, cannot delete database');
338
- resolve(); // Cannot delete in this environment, resolve directly
138
+ resolve();
339
139
  return;
340
140
  }
341
141
 
342
- const dbName = `/pglite/${DB_NAME}`; // Path used by PGlite IdbFs
142
+ const dbName = `/pglite/${DB_NAME}`;
343
143
  const request = indexedDB.deleteDatabase(dbName);
344
144
 
345
145
  request.onsuccess = () => {
346
146
  console.log(`✅ Database '${dbName}' reset successfully`);
347
147
 
348
- // Clear locally stored schema hash
349
148
  if (typeof localStorage !== 'undefined') {
350
149
  localStorage.removeItem(pgliteSchemaHashCache);
351
150
  }
@@ -365,14 +164,10 @@ export class DatabaseManager {
365
164
  };
366
165
 
367
166
  request.onblocked = (event) => {
368
- // This event is triggered when other open connections block database deletion
369
- console.warn(
370
- `Deletion of database '${dbName}' is blocked. This usually means other connections (e.g., in other tabs) are still open. Event:`,
371
- event,
372
- );
167
+ console.warn(`Deletion of database '${dbName}' is blocked.`, event);
373
168
  reject(
374
169
  new Error(
375
- `Failed to reset database '${dbName}' because it is blocked by other open connections. Please close other tabs or applications using this database and try again.`,
170
+ `Failed to reset database '${dbName}' because it is blocked by other open connections.`,
376
171
  ),
377
172
  );
378
173
  };
@@ -383,12 +178,9 @@ export class DatabaseManager {
383
178
  // Export singleton
384
179
  const dbManager = DatabaseManager.getInstance();
385
180
 
386
- // Keep original clientDB export unchanged
387
181
  export const clientDB = dbManager.createProxy();
388
182
 
389
- // Export initialization method for application startup
390
- export const initializeDB = (callbacks?: DatabaseLoadingCallbacks) =>
391
- dbManager.initialize(callbacks);
183
+ export const initializeDB = () => dbManager.initialize();
392
184
 
393
185
  export const resetClientDatabase = async () => {
394
186
  await dbManager.resetDatabase();
@@ -1,14 +1,30 @@
1
- import { clientDB, initializeDB } from '../../client/db';
1
+ import { PGlite } from '@electric-sql/pglite';
2
+ import { vector } from '@electric-sql/pglite/vector';
3
+ import { drizzle } from 'drizzle-orm/pglite';
4
+
5
+ import migrations from '../../core/migrations.json';
6
+ import * as schema from '../../schemas';
2
7
  import { LobeChatDatabase } from '../../type';
3
8
 
4
9
  const isServerDBMode = process.env.TEST_SERVER_DB === '1';
5
10
 
11
+ let testClientDB: ReturnType<typeof drizzle<typeof schema>> | null = null;
12
+
6
13
  export const getTestDB = async () => {
7
14
  if (isServerDBMode) {
8
15
  const { getTestDBInstance } = await import('../../core/dbForTest');
9
16
  return await getTestDBInstance();
10
17
  }
11
18
 
12
- await initializeDB();
13
- return clientDB as LobeChatDatabase;
19
+ if (testClientDB) return testClientDB as unknown as LobeChatDatabase;
20
+
21
+ // 直接使用 pglite 内置资源,不需要从 CDN 下载
22
+ const pglite = new PGlite({ extensions: { vector } });
23
+
24
+ testClientDB = drizzle({ client: pglite, schema });
25
+
26
+ // @ts-expect-error - migrate internal API
27
+ await testClientDB.dialect.migrate(migrations, testClientDB.session, {});
28
+
29
+ return testClientDB as unknown as LobeChatDatabase;
14
30
  };
@@ -2,7 +2,7 @@
2
2
  import { and, eq } from 'drizzle-orm';
3
3
  import { afterEach, beforeEach, describe, expect, it } from 'vitest';
4
4
 
5
- import { LobeChatDatabase } from '../../type';import { sleep } from '@/utils/sleep';
5
+ import { sleep } from '@/utils/sleep';
6
6
 
7
7
  import {
8
8
  NewKnowledgeBase,
@@ -12,6 +12,7 @@ import {
12
12
  knowledgeBases,
13
13
  users,
14
14
  } from '../../schemas';
15
+ import { LobeChatDatabase } from '../../type';
15
16
  import { KnowledgeBaseModel } from '../knowledgeBase';
16
17
  import { getTestDB } from './_util';
17
18
 
@@ -228,6 +229,34 @@ describe('KnowledgeBaseModel', () => {
228
229
  expect(remainingFiles).toHaveLength(1);
229
230
  expect(remainingFiles[0].fileId).toBe('file2');
230
231
  });
232
+
233
+ it('should not allow removing files from another user knowledge base', async () => {
234
+ await serverDB.insert(globalFiles).values([
235
+ {
236
+ hashId: 'hash1',
237
+ url: 'https://example.com/document.pdf',
238
+ size: 1000,
239
+ fileType: 'application/pdf',
240
+ creator: userId,
241
+ },
242
+ ]);
243
+
244
+ await serverDB.insert(files).values([fileList[0]]);
245
+
246
+ const { id: knowledgeBaseId } = await knowledgeBaseModel.create({ name: 'Test Group' });
247
+ await knowledgeBaseModel.addFilesToKnowledgeBase(knowledgeBaseId, ['file1']);
248
+
249
+ // Another user tries to remove files from this knowledge base
250
+ const attackerModel = new KnowledgeBaseModel(serverDB, 'user2');
251
+ await attackerModel.removeFilesFromKnowledgeBase(knowledgeBaseId, ['file1']);
252
+
253
+ // Files should still exist since the attacker doesn't own them
254
+ const remainingFiles = await serverDB.query.knowledgeBaseFiles.findMany({
255
+ where: eq(knowledgeBaseFiles.knowledgeBaseId, knowledgeBaseId),
256
+ });
257
+ expect(remainingFiles).toHaveLength(1);
258
+ expect(remainingFiles[0].fileId).toBe('file1');
259
+ });
231
260
  });
232
261
 
233
262
  describe('static findById', () => {
@@ -43,13 +43,15 @@ export class KnowledgeBaseModel {
43
43
  };
44
44
 
45
45
  removeFilesFromKnowledgeBase = async (knowledgeBaseId: string, ids: string[]) => {
46
- return this.db.delete(knowledgeBaseFiles).where(
47
- and(
48
- eq(knowledgeBaseFiles.knowledgeBaseId, knowledgeBaseId),
49
- inArray(knowledgeBaseFiles.fileId, ids),
50
- // eq(knowledgeBaseFiles.userId, this.userId),
51
- ),
52
- );
46
+ return this.db
47
+ .delete(knowledgeBaseFiles)
48
+ .where(
49
+ and(
50
+ eq(knowledgeBaseFiles.userId, this.userId),
51
+ eq(knowledgeBaseFiles.knowledgeBaseId, knowledgeBaseId),
52
+ inArray(knowledgeBaseFiles.fileId, ids),
53
+ ),
54
+ );
53
55
  };
54
56
  // query
55
57
  query = async () => {
@@ -22,13 +22,14 @@ import ModelConfigModal from './ModelConfigModal';
22
22
  import { ProviderSettingsContext } from './ProviderSettingsContext';
23
23
 
24
24
  const styles = createStaticStyles(({ css, cx }) => {
25
- const config = css`
26
- opacity: 0;
27
- transition: all 100ms ease-in-out;
28
- `;
29
-
30
25
  return {
31
- config,
26
+ config: cx(
27
+ 'model-item-config',
28
+ css`
29
+ opacity: 0;
30
+ transition: all 100ms ease-in-out;
31
+ `,
32
+ ),
32
33
  container: css`
33
34
  position: relative;
34
35
  border-radius: ${cssVar.borderRadiusLG}px;
@@ -37,7 +38,7 @@ const styles = createStaticStyles(({ css, cx }) => {
37
38
  &:hover {
38
39
  background-color: ${cssVar.colorFillTertiary};
39
40
 
40
- .${cx(config)} {
41
+ .model-item-config {
41
42
  opacity: 1;
42
43
  }
43
44
  }
@@ -311,7 +311,7 @@ export function defineConfig(config: CustomNextConfig) {
311
311
  ],
312
312
 
313
313
  // when external packages in dev mode with turbopack, this config will lead to bundle error
314
- serverExternalPackages: isProd ? ['@electric-sql/pglite', 'pdfkit'] : ['pdfkit'],
314
+ serverExternalPackages: ['pdfkit'],
315
315
 
316
316
  transpilePackages: ['pdfjs-dist', 'mermaid', 'better-auth-harmony'],
317
317
  turbopack: {
@@ -3,6 +3,7 @@ import {
3
3
  DeleteObjectCommand,
4
4
  DeleteObjectsCommand,
5
5
  GetObjectCommand,
6
+ HeadObjectCommand,
6
7
  PutObjectCommand,
7
8
  S3Client,
8
9
  } from '@aws-sdk/client-s3';
@@ -304,6 +305,63 @@ describe('FileS3', () => {
304
305
  });
305
306
  });
306
307
 
308
+ describe('getFileMetadata', () => {
309
+ it('should retrieve file metadata with content length and type', async () => {
310
+ const s3 = new FileS3();
311
+ mockS3ClientSend.mockResolvedValue({
312
+ ContentLength: 1024,
313
+ ContentType: 'image/png',
314
+ });
315
+
316
+ const result = await s3.getFileMetadata('test-file.png');
317
+
318
+ expect(HeadObjectCommand).toHaveBeenCalledWith({
319
+ Bucket: 'test-bucket',
320
+ Key: 'test-file.png',
321
+ });
322
+ expect(result).toEqual({
323
+ contentLength: 1024,
324
+ contentType: 'image/png',
325
+ });
326
+ });
327
+
328
+ it('should return 0 for content length when not provided', async () => {
329
+ const s3 = new FileS3();
330
+ mockS3ClientSend.mockResolvedValue({
331
+ ContentType: 'application/octet-stream',
332
+ });
333
+
334
+ const result = await s3.getFileMetadata('test-file.bin');
335
+
336
+ expect(result).toEqual({
337
+ contentLength: 0,
338
+ contentType: 'application/octet-stream',
339
+ });
340
+ });
341
+
342
+ it('should handle missing content type', async () => {
343
+ const s3 = new FileS3();
344
+ mockS3ClientSend.mockResolvedValue({
345
+ ContentLength: 2048,
346
+ });
347
+
348
+ const result = await s3.getFileMetadata('test-file.bin');
349
+
350
+ expect(result).toEqual({
351
+ contentLength: 2048,
352
+ contentType: undefined,
353
+ });
354
+ });
355
+
356
+ it('should handle S3 errors', async () => {
357
+ const s3 = new FileS3();
358
+ const error = new Error('File not found');
359
+ mockS3ClientSend.mockRejectedValue(error);
360
+
361
+ await expect(s3.getFileMetadata('non-existent-file.txt')).rejects.toThrow('File not found');
362
+ });
363
+ });
364
+
307
365
  describe('createPreSignedUrl', () => {
308
366
  it('should create presigned URL for upload with ACL', async () => {
309
367
  const s3 = new FileS3();
@@ -2,6 +2,7 @@ import {
2
2
  DeleteObjectCommand,
3
3
  DeleteObjectsCommand,
4
4
  GetObjectCommand,
5
+ HeadObjectCommand,
5
6
  PutObjectCommand,
6
7
  S3Client,
7
8
  } from '@aws-sdk/client-s3';
@@ -111,6 +112,26 @@ export class S3 {
111
112
  return response.Body.transformToByteArray();
112
113
  }
113
114
 
115
+ /**
116
+ * Get file metadata from S3 using HeadObject
117
+ * This is used to verify actual file size from S3 instead of trusting client-provided values
118
+ */
119
+ public async getFileMetadata(
120
+ key: string,
121
+ ): Promise<{ contentLength: number; contentType?: string }> {
122
+ const command = new HeadObjectCommand({
123
+ Bucket: this.bucket,
124
+ Key: key,
125
+ });
126
+
127
+ const response = await this.client.send(command);
128
+
129
+ return {
130
+ contentLength: response.ContentLength ?? 0,
131
+ contentType: response.ContentType,
132
+ };
133
+ }
134
+
114
135
  public async createPreSignedUrl(key: string): Promise<string> {
115
136
  const command = new PutObjectCommand({
116
137
  ACL: this.setAcl ? 'public-read' : undefined,