@cappa/core 0.13.0 → 0.13.2

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.cjs CHANGED
@@ -262,8 +262,8 @@ const compare = (image1, image2, diff, width, height, options) => {
262
262
  };
263
263
  /**
264
264
  * Compare two PNG images and return the difference
265
- * @param image1 - First image (file path or Buffer)
266
- * @param image2 - Second image (file path or Buffer)
265
+ * @param image1 - Baseline (expected) image (file path or Buffer)
266
+ * @param image2 - Current (actual) image (file path or Buffer)
267
267
  * @param withDiff - Whether to create a diff image
268
268
  * @param options - Comparison options
269
269
  * @returns Comparison result
@@ -311,8 +311,8 @@ function annotateDiffImage(image, options) {
311
311
  }
312
312
  /**
313
313
  * Quick comparison function that returns only pass/fail
314
- * @param image1 - First image (file path or Buffer)
315
- * @param image2 - Second image (file path or Buffer)
314
+ * @param image1 - Baseline (expected) image (file path or Buffer)
315
+ * @param image2 - Current (actual) image (file path or Buffer)
316
316
  * @param options - Comparison options
317
317
  * @returns Whether the images match
318
318
  */
@@ -349,8 +349,9 @@ function toNativeOptions(config) {
349
349
  }
350
350
  /**
351
351
  * Compare two PNG images and return the difference
352
- * @param image1 - First image (file path or Buffer)
353
- * @param image2 - Second image (file path or Buffer)
352
+ * @param image1 - Baseline (expected) image (file path or Buffer)
353
+ * @param image2 - Current (actual) image (file path or Buffer). Order matters
354
+ * for `interpret`: content only in `image2` is reported as an addition.
354
355
  * @param withDiff - Whether to create a diff image
355
356
  * @param options - Comparison options
356
357
  * @returns Comparison result
@@ -435,8 +436,9 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
435
436
  }
436
437
  /**
437
438
  * Quick comparison function that returns only pass/fail
438
- * @param image1 - First image (file path or Buffer)
439
- * @param image2 - Second image (file path or Buffer)
439
+ * @param image1 - Baseline (expected) image (file path or Buffer)
440
+ * @param image2 - Current (actual) image (file path or Buffer). Order matters
441
+ * for `interpret`: content only in `image2` is reported as an addition.
440
442
  * @param options - Comparison options
441
443
  * @returns Whether the images match
442
444
  */
@@ -504,6 +506,57 @@ async function mapWithConcurrency(concurrency, items, fn) {
504
506
  return results;
505
507
  }
506
508
  //#endregion
509
+ //#region src/paths.ts
510
+ /**
511
+ * Screenshot filenames are not a trusted input.
512
+ *
513
+ * A name is whatever a plugin chose, and a plugin may derive it from something
514
+ * it does not control either: `@cappa/plugin-storybook` reads
515
+ * `parameters.cappa.variants[].filename` out of the browser, so the string
516
+ * originates in story-author code. Every name eventually lands in
517
+ * `path.resolve(<bucket dir>, name)`, which honours both absolute paths and
518
+ * `../`, so without a guard a single story could write a PNG anywhere the
519
+ * process can write.
520
+ *
521
+ * Two layers live here: `sanitizeScreenshotFilename` turns a name into a
522
+ * relative path that cannot escape (used where a bad name should degrade rather
523
+ * than fail a run), and `resolveInside` is the hard backstop at the write sink.
524
+ */
525
+ /**
526
+ * Whether `target` resolves to something strictly inside `base`.
527
+ *
528
+ * Note this is deliberately stricter than a `startsWith("..")` check on the
529
+ * relative path, which also rejects legitimate names such as `..foo.png`.
530
+ */
531
+ function isPathInside(base, target) {
532
+ const relative = node_path.default.relative(base, target);
533
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${node_path.default.sep}`) && !node_path.default.isAbsolute(relative);
534
+ }
535
+ /**
536
+ * Resolve `filename` inside `base`, rejecting absolute paths and any name that
537
+ * escapes `base`.
538
+ *
539
+ * @param label - The bucket name used in the error message (`actual`, `diff`, …)
540
+ */
541
+ function resolveInside(base, filename, label) {
542
+ const resolved = node_path.default.resolve(base, filename);
543
+ if (node_path.default.isAbsolute(filename) || !isPathInside(base, resolved)) throw new Error(`Refusing to resolve screenshot path outside of the ${label} directory: ${filename}`);
544
+ return resolved;
545
+ }
546
+ /**
547
+ * Turn a screenshot filename into a relative path that stays inside its bucket.
548
+ *
549
+ * Path separators are kept — they are how plugins express folders — but
550
+ * traversal (`..`), no-op (`.`) and empty segments are dropped, backslashes are
551
+ * normalised to `/`, and a Windows drive prefix is removed. Returns an empty
552
+ * string when nothing usable is left, which callers treat as "no name given".
553
+ */
554
+ function sanitizeScreenshotFilename(filename) {
555
+ const segments = filename.replace(/\\/g, "/").split("/").map((segment) => segment.replace(/\0/g, "").trim()).filter((segment) => segment !== "" && segment !== "." && segment !== "..");
556
+ if (segments[0] && /^[a-zA-Z]:$/.test(segments[0])) segments.shift();
557
+ return segments.join("/");
558
+ }
559
+ //#endregion
507
560
  //#region src/filesystem.ts
508
561
  var filesystem_exports = /* @__PURE__ */ __exportAll({
509
562
  ScreenshotFileSystem: () => ScreenshotFileSystem,
@@ -571,9 +624,8 @@ var ScreenshotFileSystem = class {
571
624
  */
572
625
  async approveFromActualPath(actualFilePath) {
573
626
  const actualAbsolute = this.resolveActualPath(actualFilePath);
574
- const relativePath = node_path.default.relative(this.actual, actualAbsolute);
575
- if (relativePath.startsWith("..")) throw new Error(`Cannot approve screenshot outside of actual directory: ${actualFilePath}`);
576
- return this.approveRelative(relativePath);
627
+ if (!isPathInside(this.actual, actualAbsolute)) throw new Error(`Cannot approve screenshot outside of actual directory: ${actualFilePath}`);
628
+ return this.approveRelative(node_path.default.relative(this.actual, actualAbsolute));
577
629
  }
578
630
  /**
579
631
  * Apply baseline updates for grouped screenshots (same rules as `cappa approve`).
@@ -605,7 +657,7 @@ var ScreenshotFileSystem = class {
605
657
  }
606
658
  if (screenshot.category === "passed") {
607
659
  if (!screenshot.expectedPath) throw new Error("Expected path is required for passed screenshots");
608
- if (!await imagesMatch(node_path.default.resolve(outputDir, screenshot.actualPath), node_path.default.resolve(outputDir, screenshot.expectedPath), diff.type === "gmsd" ? { threshold: diff.threshold } : diff)) await this.approveFromActualPath(node_path.default.resolve(outputDir, screenshot.actualPath));
660
+ if (!await imagesMatch(node_path.default.resolve(outputDir, screenshot.expectedPath), node_path.default.resolve(outputDir, screenshot.actualPath), diff.type === "gmsd" ? { threshold: diff.threshold } : diff)) await this.approveFromActualPath(node_path.default.resolve(outputDir, screenshot.actualPath));
609
661
  }
610
662
  }
611
663
  /**
@@ -705,22 +757,33 @@ var ScreenshotFileSystem = class {
705
757
  return this.diff;
706
758
  }
707
759
  /**
760
+ * Resolve a screenshot filename inside one of the buckets.
761
+ *
762
+ * This is the single sink every read and write funnels through, so it is also
763
+ * where an untrusted filename is stopped: plugin-supplied names (Storybook
764
+ * variant filenames come straight from story code) must never escape the
765
+ * bucket they belong to.
766
+ */
767
+ resolveBucketPath(directory, filename) {
768
+ return resolveInside(this[directory], filename, directory);
769
+ }
770
+ /**
708
771
  * Get the path to an actual screenshot file
709
772
  */
710
773
  getActualFilePath(filename) {
711
- return node_path.default.resolve(this.actual, filename);
774
+ return this.resolveBucketPath("actual", filename);
712
775
  }
713
776
  /**
714
777
  * Get the path to an expected screenshot file
715
778
  */
716
779
  getExpectedFilePath(filename) {
717
- return node_path.default.resolve(this.expected, filename);
780
+ return this.resolveBucketPath("expected", filename);
718
781
  }
719
782
  /**
720
783
  * Get the path to a diff screenshot file
721
784
  */
722
785
  getDiffFilePath(filename) {
723
- return node_path.default.resolve(this.diff, filename);
786
+ return this.resolveBucketPath("diff", filename);
724
787
  }
725
788
  /**
726
789
  * Write a file to the actual directory
@@ -785,9 +848,8 @@ var ScreenshotFileSystem = class {
785
848
  return node_path.default.resolve(this.actual, filePath);
786
849
  }
787
850
  getRelativePath(directory, filePath) {
788
- const relativePath = node_path.default.relative(this[directory], filePath);
789
- if (relativePath.startsWith("..")) throw new Error(`Cannot resolve relative path outside of ${directory} directory: ${filePath}`);
790
- return relativePath;
851
+ if (!isPathInside(this[directory], filePath)) throw new Error(`Cannot resolve relative path outside of ${directory} directory: ${filePath}`);
852
+ return node_path.default.relative(this[directory], filePath);
791
853
  }
792
854
  };
793
855
  //#endregion
@@ -1692,7 +1754,7 @@ var ScreenshotTool = class {
1692
1754
  delay: this.getIncBackoffDelay(i, options.delay || 0)
1693
1755
  });
1694
1756
  if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
1695
- const comparisonResult = diffConfig.type === "gmsd" ? await compareImagesGMSD(screenshotBuffer, referenceImage, true, diffConfig) : await compareImages(screenshotBuffer, referenceImage, true, diffConfig);
1757
+ const comparisonResult = diffConfig.type === "gmsd" ? await compareImagesGMSD(referenceImage, screenshotBuffer, true, diffConfig) : await compareImages(referenceImage, screenshotBuffer, true, diffConfig);
1696
1758
  if (i === this.retries - 1 && !comparisonResult.passed) {
1697
1759
  this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
1698
1760
  return {
@@ -1719,8 +1781,21 @@ var ScreenshotTool = class {
1719
1781
  passed: false
1720
1782
  };
1721
1783
  }
1784
+ /**
1785
+ * Resolve the filename a variant is written under.
1786
+ *
1787
+ * An explicit `variant.filename` wins, but it is sanitized first: for
1788
+ * `@cappa/plugin-storybook` it arrives from the browser as a story parameter,
1789
+ * so it is story-author input and could otherwise carry `../` or an absolute
1790
+ * path into the write sink. A name left empty by sanitization falls back to
1791
+ * the derived one.
1792
+ */
1722
1793
  getVariantFilename(filename, variant) {
1723
- if (variant.filename) return variant.filename;
1794
+ if (variant.filename) {
1795
+ const safeFilename = sanitizeScreenshotFilename(variant.filename);
1796
+ if (safeFilename !== variant.filename) this.logger.warn(`Variant filename "${variant.filename}" is not a valid screenshot path, using "${safeFilename || "the derived name"}" instead`);
1797
+ if (safeFilename) return safeFilename;
1798
+ }
1724
1799
  const parsed = node_path.default.parse(filename);
1725
1800
  const suffix = variant.id.trim().replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "variant";
1726
1801
  const ext = parsed.ext || ".png";
@@ -1881,7 +1956,7 @@ var ScreenshotTool = class {
1881
1956
  baseResult.diffImagePath = baseCaptureResult.diffImagePath;
1882
1957
  baseResult.skipped = baseCaptureResult.skipped;
1883
1958
  for (const variant of variants) {
1884
- const variantFilename = variant.filename || this.getVariantFilename(baseFilename, variant);
1959
+ const variantFilename = this.getVariantFilename(baseFilename, variant);
1885
1960
  const variantOptions = {
1886
1961
  ...baseOptions,
1887
1962
  ...variant.options
@@ -3100,6 +3175,7 @@ exports.mergeCaptureManifest = mergeCaptureManifest;
3100
3175
  exports.readCaptureManifest = readCaptureManifest;
3101
3176
  exports.readDiffMeta = readDiffMeta;
3102
3177
  exports.recordCaptureOrigins = recordCaptureOrigins;
3178
+ exports.sanitizeScreenshotFilename = sanitizeScreenshotFilename;
3103
3179
  exports.selectTasks = selectTasks;
3104
3180
  exports.toDiffMetaPath = toDiffMetaPath;
3105
3181
  exports.toManifestKey = toManifestKey;