tero 0.0.9 → 0.0.12

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.
@@ -27,12 +27,13 @@ export declare class DataRecovery {
27
27
  private config;
28
28
  constructor(config: RecoveryConfig);
29
29
  private initializeCloudStorage;
30
+ private getDbName;
30
31
  private getCloudKey;
31
32
  private isNotFound;
32
33
  checkFileInCloud(key: string): Promise<FileRecoveryInfo>;
33
34
  recoverSingleFile(key: string): Promise<boolean>;
34
35
  recoverFromArchive(archiveName?: string): Promise<RecoveryResult>;
35
- recoverIndividualFiles(keys?: string[]): Promise<RecoveryResult>;
36
+ recoverIndividualFiles(keys?: string[], isCancelled?: () => boolean): Promise<RecoveryResult>;
36
37
  listAvailableArchives(): Promise<string[]>;
37
38
  listAvailableFiles(): Promise<string[]>;
38
39
  /**
@@ -44,7 +45,7 @@ export declare class DataRecovery {
44
45
  * Recover only files that exist in the cloud but are missing locally.
45
46
  * Returns the standard RecoveryResult. Used by v2 hydrate-on-startup (mode='missing').
46
47
  */
47
- recoverMissingFiles(): Promise<RecoveryResult>;
48
+ recoverMissingFiles(isCancelled?: () => boolean): Promise<RecoveryResult>;
48
49
  private downloadFile;
49
50
  private extractArchive;
50
51
  testCloudConnection(): Promise<{
package/dist/recovery.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { S3Client, GetObjectCommand, ListObjectsV2Command, HeadObjectCommand } from "@aws-sdk/client-s3";
2
- import { createWriteStream, existsSync, mkdirSync } from "fs";
3
- import { join, dirname } from "path";
2
+ import { createWriteStream, existsSync, mkdirSync, openSync, fsyncSync, closeSync } from "fs";
3
+ import { join, dirname, resolve as pathResolve } from "path";
4
4
  import { pipeline } from "stream/promises";
5
5
  import { partitionedPath } from "./acid-engine.js";
6
6
  export class DataRecovery {
@@ -27,13 +27,30 @@ export class DataRecovery {
27
27
  this.s3Client = new S3Client(clientConfig);
28
28
  }
29
29
  catch (error) {
30
- throw new Error(`Failed to initialize cloud storage for recovery: ${error instanceof Error ? error.message : 'Unknown error'}`);
30
+ throw new Error(`Failed to initialize cloud storage for recovery: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
31
31
  }
32
32
  }
33
+ getDbName() {
34
+ const override = this.config.cloudStorage?.dbName || this.config?.bucketPrefix;
35
+ if (typeof override === 'string' && override.trim()) {
36
+ return override.trim().replace(/^\/+|\/+$/g, '').replace(/[^a-zA-Z0-9_\-]/g, '_').slice(0, 128);
37
+ }
38
+ const raw = this.config.localPath;
39
+ const base = raw.split('/').pop() || 'database';
40
+ let h = 0x811c9dc5;
41
+ for (let i = 0; i < raw.length; i++) {
42
+ h ^= raw.charCodeAt(i);
43
+ h = Math.imul(h, 0x01000193) >>> 0;
44
+ }
45
+ const suffix = h.toString(16).padStart(8, '0').slice(0, 6);
46
+ return `${base}-${suffix}`;
47
+ }
33
48
  getCloudKey(filename) {
34
49
  const prefix = this.config.cloudStorage.pathPrefix || 'tero-backups';
35
- const dbName = this.config.localPath.split('/').pop() || 'database';
36
- return `${prefix}/${dbName}/${filename}`;
50
+ const dbName = this.getDbName();
51
+ if (!filename)
52
+ return `${prefix}/${dbName}/`;
53
+ return `${prefix}/${dbName}/${filename.replace(/^\/+/, '')}`;
37
54
  }
38
55
  isNotFound(error) {
39
56
  return (error?.name === 'NotFound' ||
@@ -147,7 +164,7 @@ export class DataRecovery {
147
164
  };
148
165
  }
149
166
  }
150
- async recoverIndividualFiles(keys) {
167
+ async recoverIndividualFiles(keys, isCancelled) {
151
168
  const startTime = Date.now();
152
169
  const recovered = [];
153
170
  const failed = [];
@@ -169,6 +186,8 @@ export class DataRecovery {
169
186
  // ~25ms × (50,000 / 10) ≈ 125 seconds (~2 min) and can be tuned higher.
170
187
  const concurrency = this.config.concurrency ?? 10;
171
188
  for (let i = 0; i < keys.length; i += concurrency) {
189
+ if (isCancelled?.())
190
+ break;
172
191
  const batch = keys.slice(i, i + concurrency);
173
192
  const results = await Promise.allSettled(batch.map(async (key) => {
174
193
  try {
@@ -215,17 +234,27 @@ export class DataRecovery {
215
234
  async listAvailableArchives() {
216
235
  try {
217
236
  const prefix = this.getCloudKey('');
218
- const listCommand = new ListObjectsV2Command({
219
- Bucket: this.config.cloudStorage.bucket,
220
- Prefix: prefix,
221
- MaxKeys: 100
222
- });
223
- const response = await this.s3Client.send(listCommand);
224
- if (!response.Contents) {
237
+ // Paginated listing — a bucket with >1000 objects would otherwise
238
+ // silently truncate the archive list (hydrate 'snapshot' mode would
239
+ // miss the newest archive sitting past the first page).
240
+ const objects = [];
241
+ let token;
242
+ do {
243
+ const response = await this.s3Client.send(new ListObjectsV2Command({
244
+ Bucket: this.config.cloudStorage.bucket,
245
+ Prefix: prefix,
246
+ MaxKeys: 1000,
247
+ ContinuationToken: token
248
+ }));
249
+ if (response.Contents)
250
+ objects.push(...response.Contents);
251
+ token = response.IsTruncated ? response.NextContinuationToken : undefined;
252
+ } while (token);
253
+ if (objects.length === 0) {
225
254
  return [];
226
255
  }
227
256
  // Filter for archive files and sort by date (newest first)
228
- const archives = response.Contents
257
+ const archives = objects
229
258
  .filter((obj) => obj.Key && obj.Key.endsWith('.tar.gz'))
230
259
  .sort((a, b) => {
231
260
  const dateA = a.LastModified?.getTime() || 0;
@@ -243,18 +272,31 @@ export class DataRecovery {
243
272
  async listAvailableFiles() {
244
273
  try {
245
274
  const prefix = this.getCloudKey('');
246
- const listCommand = new ListObjectsV2Command({
247
- Bucket: this.config.cloudStorage.bucket,
248
- Prefix: prefix,
249
- MaxKeys: 1000
250
- });
251
- const response = await this.s3Client.send(listCommand);
252
- if (!response.Contents) {
275
+ // Paginated listing — restores from buckets with >1000 objects
276
+ // previously saw a silently truncated file list.
277
+ const objects = [];
278
+ let token;
279
+ do {
280
+ const response = await this.s3Client.send(new ListObjectsV2Command({
281
+ Bucket: this.config.cloudStorage.bucket,
282
+ Prefix: prefix,
283
+ MaxKeys: 1000,
284
+ ContinuationToken: token
285
+ }));
286
+ if (response.Contents)
287
+ objects.push(...response.Contents);
288
+ token = response.IsTruncated ? response.NextContinuationToken : undefined;
289
+ } while (token);
290
+ if (objects.length === 0) {
253
291
  return [];
254
292
  }
255
- // Filter for JSON files and extract keys
256
- const files = response.Contents
257
- .filter((obj) => obj.Key && obj.Key.endsWith('.json'))
293
+ // Filter for JSON files and extract keys (excluding metadata manifests)
294
+ const files = objects
295
+ .filter((obj) => obj.Key &&
296
+ obj.Key.endsWith('.json') &&
297
+ !obj.Key.endsWith('MANIFEST.json') &&
298
+ !obj.Key.endsWith('latest.json') &&
299
+ !obj.Key.endsWith('index.json'))
258
300
  .map((obj) => {
259
301
  const filename = obj.Key.split('/').pop();
260
302
  return filename.replace('.json', '');
@@ -290,7 +332,7 @@ export class DataRecovery {
290
332
  * Recover only files that exist in the cloud but are missing locally.
291
333
  * Returns the standard RecoveryResult. Used by v2 hydrate-on-startup (mode='missing').
292
334
  */
293
- async recoverMissingFiles() {
335
+ async recoverMissingFiles(isCancelled) {
294
336
  const startTime = Date.now();
295
337
  try {
296
338
  const missing = await this.listMissingLocally();
@@ -303,7 +345,7 @@ export class DataRecovery {
303
345
  duration: Date.now() - startTime,
304
346
  };
305
347
  }
306
- const result = await this.recoverIndividualFiles(missing);
348
+ const result = await this.recoverIndividualFiles(missing, isCancelled);
307
349
  result.duration = Date.now() - startTime;
308
350
  return result;
309
351
  }
@@ -346,11 +388,44 @@ export class DataRecovery {
346
388
  async extractArchive(archivePath) {
347
389
  try {
348
390
  const tar = await import('tar');
391
+ const targetDir = pathResolve(this.config.localPath);
349
392
  await tar.extract({
350
393
  file: archivePath,
351
- cwd: this.config.localPath,
352
- strip: 1 // Remove the top-level directory from the archive
394
+ cwd: targetDir,
395
+ strip: 1, // Remove the top-level directory from the archive
396
+ // Hardened: block ZipSlip + symlink escape. Tar entries can be symlinks
397
+ // that point outside targetDir; the filter below rejects any path that
398
+ // resolves outside, and we additionally reject symlink/hardlink types.
399
+ filter: (path, entry) => {
400
+ // Reject symlink and hardlink entries entirely — they can escape even if path looks safe
401
+ const type = entry?.type?.toLowerCase?.();
402
+ if (type === 'symlink' || type === 'symboliclink' || type === 'link')
403
+ return false;
404
+ if (entry?.linkpath)
405
+ return false;
406
+ // Prevent path traversal (Zip Slip / Tar Slip)
407
+ const resolved = pathResolve(targetDir, path);
408
+ if (!(resolved === targetDir || resolved.startsWith(targetDir + '/')))
409
+ return false;
410
+ if (path.includes('..'))
411
+ return false;
412
+ // Also reject entries with absolute paths
413
+ if (path.startsWith('/'))
414
+ return false;
415
+ return true;
416
+ }
353
417
  });
418
+ // Fsync directory to ensure dentries are durable
419
+ try {
420
+ const fd = openSync(targetDir, 'r');
421
+ try {
422
+ fsyncSync(fd);
423
+ }
424
+ finally {
425
+ closeSync(fd);
426
+ }
427
+ }
428
+ catch { }
354
429
  return true;
355
430
  }
356
431
  catch (error) {
package/package.json CHANGED
@@ -1,10 +1,32 @@
1
1
  {
2
2
  "name": "tero",
3
- "version": "0.0.9",
3
+ "version": "0.0.12",
4
4
  "description": "Tero is a JSON database that provides ACID transactions, schema validation, automated cloud backup, and automatic cloud recovery",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
7
7
  "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./acid-engine": {
14
+ "types": "./dist/acid-engine.d.ts",
15
+ "import": "./dist/acid-engine.js"
16
+ },
17
+ "./backup": {
18
+ "types": "./dist/backup.d.ts",
19
+ "import": "./dist/backup.js"
20
+ },
21
+ "./recovery": {
22
+ "types": "./dist/recovery.d.ts",
23
+ "import": "./dist/recovery.js"
24
+ },
25
+ "./schema": {
26
+ "types": "./dist/schema.d.ts",
27
+ "import": "./dist/schema.js"
28
+ }
29
+ },
8
30
  "repository": {
9
31
  "type": "git",
10
32
  "url": "git+https://github.com/codedynasty-dev/tero.git"
@@ -14,26 +36,24 @@
14
36
  "url": "https://github.com/codedynasty-dev/tero/issues"
15
37
  },
16
38
  "homepage": "https://github.com/codedynasty-dev/tero.git",
39
+ "engines": {
40
+ "node": ">=18.0.0"
41
+ },
17
42
  "scripts": {
18
- "build": "tsc && npm run test",
43
+ "build": "tsc",
19
44
  "dev": "tsc --watch",
20
45
  "test": "node run-tests.js",
21
- "test:production": "node local_tests/production-test.js",
22
- "test:legacy": "node local_tests/test.js",
23
- "test:backup": "node local_tests/backup-test.js",
46
+ "test:production": "node local_tests/prod-test-suite.js",
24
47
  "test:s3": "node local_tests/s3-live-backup-test.js",
25
- "test:schema": "node local_tests/schema-test.js",
26
- "test:all": "npm run test",
48
+ "test:all": "npm run test && npm run test:production",
27
49
  "test:watch": "npm run test",
28
- "prebuild": "echo 'Building Tero...'",
29
- "postbuild": "echo 'Build completed successfully!'",
30
- "pretest": "echo 'Running Tero test suite...'",
31
- "posttest": "echo 'Test suite completed!'",
32
- "verify": "node verify-build.js && npm run test",
33
- "ci": "npm run verify",
50
+ "verify": "node local_tests/prod-test-suite.js && npm run test",
51
+ "ci": "npm run test && node local_tests/prod-test-suite.js",
34
52
  "bench": "node bench/run-bench.js --synchronous normal",
35
53
  "bench:full": "node bench/run-bench.js --synchronous full",
36
- "bench:quick": "node bench/run-bench.js --quick --synchronous normal"
54
+ "bench:quick": "node bench/run-bench.js --quick --synchronous normal",
55
+ "bench:live": "node bench/run-live-bench.js",
56
+ "bench:live:quick": "node bench/run-live-bench.js --quick"
37
57
  },
38
58
  "files": [
39
59
  "dist/**/*"
@@ -45,21 +65,16 @@
45
65
  ],
46
66
  "license": "MIT",
47
67
  "dependencies": {
48
- "@aws-sdk/client-s3": "^3.0.0",
49
- "@aws-sdk/lib-storage": "^3.0.0",
68
+ "@aws-sdk/client-s3": "^3.1120.0",
69
+ "@aws-sdk/lib-storage": "^3.1120.0",
50
70
  "cron": "^4.3.2",
51
- "fs-ext": "^2.0.0",
52
- "glob": "^9.3.4",
53
71
  "quick-lru": "^7.0.1",
54
- "tar": "^6.1.13"
72
+ "tar": "^7.5.22"
55
73
  },
56
74
  "devDependencies": {
57
75
  "@types/cron": "^2.0.1",
58
- "@types/fs-ext": "^2.0.3",
59
- "@types/glob": "^8.1.0",
60
76
  "@types/node": "^24.0.14",
61
77
  "@types/quick-lru": "^2.0.0",
62
- "@types/tar": "^6.1.13",
63
78
  "typescript": "^5.8.3"
64
79
  }
65
80
  }