@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.d.cts CHANGED
@@ -16,8 +16,9 @@ interface CompareResult$1 {
16
16
  }
17
17
  /**
18
18
  * Compare two PNG images and return the difference
19
- * @param image1 - First image (file path or Buffer)
20
- * @param image2 - Second image (file path or Buffer)
19
+ * @param image1 - Baseline (expected) image (file path or Buffer)
20
+ * @param image2 - Current (actual) image (file path or Buffer). Order matters
21
+ * for `interpret`: content only in `image2` is reported as an addition.
21
22
  * @param withDiff - Whether to create a diff image
22
23
  * @param options - Comparison options
23
24
  * @returns Comparison result
@@ -25,8 +26,9 @@ interface CompareResult$1 {
25
26
  export declare function compareImages(image1: string | Buffer, image2: string | Buffer, withDiff?: boolean, options?: DiffConfig): Promise<CompareResult$1>;
26
27
  /**
27
28
  * Quick comparison function that returns only pass/fail
28
- * @param image1 - First image (file path or Buffer)
29
- * @param image2 - Second image (file path or Buffer)
29
+ * @param image1 - Baseline (expected) image (file path or Buffer)
30
+ * @param image2 - Current (actual) image (file path or Buffer). Order matters
31
+ * for `interpret`: content only in `image2` is reported as an addition.
30
32
  * @param options - Comparison options
31
33
  * @returns Whether the images match
32
34
  */
@@ -114,6 +116,15 @@ export declare class ScreenshotFileSystem {
114
116
  * Get the diff directory path
115
117
  */
116
118
  getDiffDir(): string;
119
+ /**
120
+ * Resolve a screenshot filename inside one of the buckets.
121
+ *
122
+ * This is the single sink every read and write funnels through, so it is also
123
+ * where an untrusted filename is stopped: plugin-supplied names (Storybook
124
+ * variant filenames come straight from story code) must never escape the
125
+ * bucket they belong to.
126
+ */
127
+ private resolveBucketPath;
117
128
  /**
118
129
  * Get the path to an actual screenshot file
119
130
  */
@@ -574,6 +585,15 @@ declare class ScreenshotTool {
574
585
  comparisonResult: null;
575
586
  passed: boolean;
576
587
  }>;
588
+ /**
589
+ * Resolve the filename a variant is written under.
590
+ *
591
+ * An explicit `variant.filename` wins, but it is sanitized first: for
592
+ * `@cappa/plugin-storybook` it arrives from the browser as a story parameter,
593
+ * so it is story-author input and could otherwise carry `../` or an absolute
594
+ * path into the write sink. A name left empty by sanitization falls back to
595
+ * the derived one.
596
+ */
577
597
  getVariantFilename(filename: string, variant: ScreenshotVariant): string;
578
598
  /**
579
599
  * Captures a single screenshot with the given options
@@ -970,8 +990,8 @@ interface CompareResult {
970
990
  }
971
991
  /**
972
992
  * Compare two PNG images and return the difference
973
- * @param image1 - First image (file path or Buffer)
974
- * @param image2 - Second image (file path or Buffer)
993
+ * @param image1 - Baseline (expected) image (file path or Buffer)
994
+ * @param image2 - Current (actual) image (file path or Buffer)
975
995
  * @param withDiff - Whether to create a diff image
976
996
  * @param options - Comparison options
977
997
  * @returns Comparison result
@@ -979,8 +999,8 @@ interface CompareResult {
979
999
  export declare function compareImagesGMSD(image1: string | Buffer, image2: string | Buffer, withDiff?: boolean, options?: DiffConfigGMSD): Promise<CompareResult>;
980
1000
  /**
981
1001
  * Quick comparison function that returns only pass/fail
982
- * @param image1 - First image (file path or Buffer)
983
- * @param image2 - Second image (file path or Buffer)
1002
+ * @param image1 - Baseline (expected) image (file path or Buffer)
1003
+ * @param image2 - Current (actual) image (file path or Buffer)
984
1004
  * @param options - Comparison options
985
1005
  * @returns Whether the images match
986
1006
  */
@@ -1692,6 +1712,17 @@ export declare class WarmBrowser {
1692
1712
  */
1693
1713
  export declare function mapWithConcurrency<T, R = void>(concurrency: number, items: readonly T[], fn: (item: T, workerIndex: number) => Promise<R>): Promise<R[]>;
1694
1714
  //#endregion
1715
+ //#region src/paths.d.ts
1716
+ /**
1717
+ * Turn a screenshot filename into a relative path that stays inside its bucket.
1718
+ *
1719
+ * Path separators are kept — they are how plugins express folders — but
1720
+ * traversal (`..`), no-op (`.`) and empty segments are dropped, backslashes are
1721
+ * normalised to `/`, and a Windows drive prefix is removed. Returns an empty
1722
+ * string when nothing usable is left, which callers treat as "no name given".
1723
+ */
1724
+ export declare function sanitizeScreenshotFilename(filename: string): string;
1725
+ //#endregion
1695
1726
  //#region src/runner/tasks.d.ts
1696
1727
  /**
1697
1728
  * Decide whether a plugin's `execute` result represents a failed screenshot.
package/dist/index.d.mts CHANGED
@@ -16,8 +16,9 @@ interface CompareResult$1 {
16
16
  }
17
17
  /**
18
18
  * Compare two PNG images and return the difference
19
- * @param image1 - First image (file path or Buffer)
20
- * @param image2 - Second image (file path or Buffer)
19
+ * @param image1 - Baseline (expected) image (file path or Buffer)
20
+ * @param image2 - Current (actual) image (file path or Buffer). Order matters
21
+ * for `interpret`: content only in `image2` is reported as an addition.
21
22
  * @param withDiff - Whether to create a diff image
22
23
  * @param options - Comparison options
23
24
  * @returns Comparison result
@@ -25,8 +26,9 @@ interface CompareResult$1 {
25
26
  export declare function compareImages(image1: string | Buffer, image2: string | Buffer, withDiff?: boolean, options?: DiffConfig): Promise<CompareResult$1>;
26
27
  /**
27
28
  * Quick comparison function that returns only pass/fail
28
- * @param image1 - First image (file path or Buffer)
29
- * @param image2 - Second image (file path or Buffer)
29
+ * @param image1 - Baseline (expected) image (file path or Buffer)
30
+ * @param image2 - Current (actual) image (file path or Buffer). Order matters
31
+ * for `interpret`: content only in `image2` is reported as an addition.
30
32
  * @param options - Comparison options
31
33
  * @returns Whether the images match
32
34
  */
@@ -114,6 +116,15 @@ export declare class ScreenshotFileSystem {
114
116
  * Get the diff directory path
115
117
  */
116
118
  getDiffDir(): string;
119
+ /**
120
+ * Resolve a screenshot filename inside one of the buckets.
121
+ *
122
+ * This is the single sink every read and write funnels through, so it is also
123
+ * where an untrusted filename is stopped: plugin-supplied names (Storybook
124
+ * variant filenames come straight from story code) must never escape the
125
+ * bucket they belong to.
126
+ */
127
+ private resolveBucketPath;
117
128
  /**
118
129
  * Get the path to an actual screenshot file
119
130
  */
@@ -574,6 +585,15 @@ declare class ScreenshotTool {
574
585
  comparisonResult: null;
575
586
  passed: boolean;
576
587
  }>;
588
+ /**
589
+ * Resolve the filename a variant is written under.
590
+ *
591
+ * An explicit `variant.filename` wins, but it is sanitized first: for
592
+ * `@cappa/plugin-storybook` it arrives from the browser as a story parameter,
593
+ * so it is story-author input and could otherwise carry `../` or an absolute
594
+ * path into the write sink. A name left empty by sanitization falls back to
595
+ * the derived one.
596
+ */
577
597
  getVariantFilename(filename: string, variant: ScreenshotVariant): string;
578
598
  /**
579
599
  * Captures a single screenshot with the given options
@@ -970,8 +990,8 @@ interface CompareResult {
970
990
  }
971
991
  /**
972
992
  * Compare two PNG images and return the difference
973
- * @param image1 - First image (file path or Buffer)
974
- * @param image2 - Second image (file path or Buffer)
993
+ * @param image1 - Baseline (expected) image (file path or Buffer)
994
+ * @param image2 - Current (actual) image (file path or Buffer)
975
995
  * @param withDiff - Whether to create a diff image
976
996
  * @param options - Comparison options
977
997
  * @returns Comparison result
@@ -979,8 +999,8 @@ interface CompareResult {
979
999
  export declare function compareImagesGMSD(image1: string | Buffer, image2: string | Buffer, withDiff?: boolean, options?: DiffConfigGMSD): Promise<CompareResult>;
980
1000
  /**
981
1001
  * Quick comparison function that returns only pass/fail
982
- * @param image1 - First image (file path or Buffer)
983
- * @param image2 - Second image (file path or Buffer)
1002
+ * @param image1 - Baseline (expected) image (file path or Buffer)
1003
+ * @param image2 - Current (actual) image (file path or Buffer)
984
1004
  * @param options - Comparison options
985
1005
  * @returns Whether the images match
986
1006
  */
@@ -1692,6 +1712,17 @@ export declare class WarmBrowser {
1692
1712
  */
1693
1713
  export declare function mapWithConcurrency<T, R = void>(concurrency: number, items: readonly T[], fn: (item: T, workerIndex: number) => Promise<R>): Promise<R[]>;
1694
1714
  //#endregion
1715
+ //#region src/paths.d.ts
1716
+ /**
1717
+ * Turn a screenshot filename into a relative path that stays inside its bucket.
1718
+ *
1719
+ * Path separators are kept — they are how plugins express folders — but
1720
+ * traversal (`..`), no-op (`.`) and empty segments are dropped, backslashes are
1721
+ * normalised to `/`, and a Windows drive prefix is removed. Returns an empty
1722
+ * string when nothing usable is left, which callers treat as "no name given".
1723
+ */
1724
+ export declare function sanitizeScreenshotFilename(filename: string): string;
1725
+ //#endregion
1695
1726
  //#region src/runner/tasks.d.ts
1696
1727
  /**
1697
1728
  * Decide whether a plugin's `execute` result represents a failed screenshot.
package/dist/index.mjs CHANGED
@@ -236,8 +236,8 @@ const compare$1 = (image1, image2, diff, width, height, options) => {
236
236
  };
237
237
  /**
238
238
  * Compare two PNG images and return the difference
239
- * @param image1 - First image (file path or Buffer)
240
- * @param image2 - Second image (file path or Buffer)
239
+ * @param image1 - Baseline (expected) image (file path or Buffer)
240
+ * @param image2 - Current (actual) image (file path or Buffer)
241
241
  * @param withDiff - Whether to create a diff image
242
242
  * @param options - Comparison options
243
243
  * @returns Comparison result
@@ -285,8 +285,8 @@ function annotateDiffImage(image, options) {
285
285
  }
286
286
  /**
287
287
  * Quick comparison function that returns only pass/fail
288
- * @param image1 - First image (file path or Buffer)
289
- * @param image2 - Second image (file path or Buffer)
288
+ * @param image1 - Baseline (expected) image (file path or Buffer)
289
+ * @param image2 - Current (actual) image (file path or Buffer)
290
290
  * @param options - Comparison options
291
291
  * @returns Whether the images match
292
292
  */
@@ -323,8 +323,9 @@ function toNativeOptions(config) {
323
323
  }
324
324
  /**
325
325
  * Compare two PNG images and return the difference
326
- * @param image1 - First image (file path or Buffer)
327
- * @param image2 - Second image (file path or Buffer)
326
+ * @param image1 - Baseline (expected) image (file path or Buffer)
327
+ * @param image2 - Current (actual) image (file path or Buffer). Order matters
328
+ * for `interpret`: content only in `image2` is reported as an addition.
328
329
  * @param withDiff - Whether to create a diff image
329
330
  * @param options - Comparison options
330
331
  * @returns Comparison result
@@ -409,8 +410,9 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
409
410
  }
410
411
  /**
411
412
  * Quick comparison function that returns only pass/fail
412
- * @param image1 - First image (file path or Buffer)
413
- * @param image2 - Second image (file path or Buffer)
413
+ * @param image1 - Baseline (expected) image (file path or Buffer)
414
+ * @param image2 - Current (actual) image (file path or Buffer). Order matters
415
+ * for `interpret`: content only in `image2` is reported as an addition.
414
416
  * @param options - Comparison options
415
417
  * @returns Whether the images match
416
418
  */
@@ -478,6 +480,57 @@ async function mapWithConcurrency(concurrency, items, fn) {
478
480
  return results;
479
481
  }
480
482
  //#endregion
483
+ //#region src/paths.ts
484
+ /**
485
+ * Screenshot filenames are not a trusted input.
486
+ *
487
+ * A name is whatever a plugin chose, and a plugin may derive it from something
488
+ * it does not control either: `@cappa/plugin-storybook` reads
489
+ * `parameters.cappa.variants[].filename` out of the browser, so the string
490
+ * originates in story-author code. Every name eventually lands in
491
+ * `path.resolve(<bucket dir>, name)`, which honours both absolute paths and
492
+ * `../`, so without a guard a single story could write a PNG anywhere the
493
+ * process can write.
494
+ *
495
+ * Two layers live here: `sanitizeScreenshotFilename` turns a name into a
496
+ * relative path that cannot escape (used where a bad name should degrade rather
497
+ * than fail a run), and `resolveInside` is the hard backstop at the write sink.
498
+ */
499
+ /**
500
+ * Whether `target` resolves to something strictly inside `base`.
501
+ *
502
+ * Note this is deliberately stricter than a `startsWith("..")` check on the
503
+ * relative path, which also rejects legitimate names such as `..foo.png`.
504
+ */
505
+ function isPathInside(base, target) {
506
+ const relative = path.relative(base, target);
507
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
508
+ }
509
+ /**
510
+ * Resolve `filename` inside `base`, rejecting absolute paths and any name that
511
+ * escapes `base`.
512
+ *
513
+ * @param label - The bucket name used in the error message (`actual`, `diff`, …)
514
+ */
515
+ function resolveInside(base, filename, label) {
516
+ const resolved = path.resolve(base, filename);
517
+ if (path.isAbsolute(filename) || !isPathInside(base, resolved)) throw new Error(`Refusing to resolve screenshot path outside of the ${label} directory: ${filename}`);
518
+ return resolved;
519
+ }
520
+ /**
521
+ * Turn a screenshot filename into a relative path that stays inside its bucket.
522
+ *
523
+ * Path separators are kept — they are how plugins express folders — but
524
+ * traversal (`..`), no-op (`.`) and empty segments are dropped, backslashes are
525
+ * normalised to `/`, and a Windows drive prefix is removed. Returns an empty
526
+ * string when nothing usable is left, which callers treat as "no name given".
527
+ */
528
+ function sanitizeScreenshotFilename(filename) {
529
+ const segments = filename.replace(/\\/g, "/").split("/").map((segment) => segment.replace(/\0/g, "").trim()).filter((segment) => segment !== "" && segment !== "." && segment !== "..");
530
+ if (segments[0] && /^[a-zA-Z]:$/.test(segments[0])) segments.shift();
531
+ return segments.join("/");
532
+ }
533
+ //#endregion
481
534
  //#region src/filesystem.ts
482
535
  var filesystem_exports = /* @__PURE__ */ __exportAll({
483
536
  ScreenshotFileSystem: () => ScreenshotFileSystem,
@@ -545,9 +598,8 @@ var ScreenshotFileSystem = class {
545
598
  */
546
599
  async approveFromActualPath(actualFilePath) {
547
600
  const actualAbsolute = this.resolveActualPath(actualFilePath);
548
- const relativePath = path.relative(this.actual, actualAbsolute);
549
- if (relativePath.startsWith("..")) throw new Error(`Cannot approve screenshot outside of actual directory: ${actualFilePath}`);
550
- return this.approveRelative(relativePath);
601
+ if (!isPathInside(this.actual, actualAbsolute)) throw new Error(`Cannot approve screenshot outside of actual directory: ${actualFilePath}`);
602
+ return this.approveRelative(path.relative(this.actual, actualAbsolute));
551
603
  }
552
604
  /**
553
605
  * Apply baseline updates for grouped screenshots (same rules as `cappa approve`).
@@ -579,7 +631,7 @@ var ScreenshotFileSystem = class {
579
631
  }
580
632
  if (screenshot.category === "passed") {
581
633
  if (!screenshot.expectedPath) throw new Error("Expected path is required for passed screenshots");
582
- if (!await imagesMatch(path.resolve(outputDir, screenshot.actualPath), path.resolve(outputDir, screenshot.expectedPath), diff.type === "gmsd" ? { threshold: diff.threshold } : diff)) await this.approveFromActualPath(path.resolve(outputDir, screenshot.actualPath));
634
+ if (!await imagesMatch(path.resolve(outputDir, screenshot.expectedPath), path.resolve(outputDir, screenshot.actualPath), diff.type === "gmsd" ? { threshold: diff.threshold } : diff)) await this.approveFromActualPath(path.resolve(outputDir, screenshot.actualPath));
583
635
  }
584
636
  }
585
637
  /**
@@ -679,22 +731,33 @@ var ScreenshotFileSystem = class {
679
731
  return this.diff;
680
732
  }
681
733
  /**
734
+ * Resolve a screenshot filename inside one of the buckets.
735
+ *
736
+ * This is the single sink every read and write funnels through, so it is also
737
+ * where an untrusted filename is stopped: plugin-supplied names (Storybook
738
+ * variant filenames come straight from story code) must never escape the
739
+ * bucket they belong to.
740
+ */
741
+ resolveBucketPath(directory, filename) {
742
+ return resolveInside(this[directory], filename, directory);
743
+ }
744
+ /**
682
745
  * Get the path to an actual screenshot file
683
746
  */
684
747
  getActualFilePath(filename) {
685
- return path.resolve(this.actual, filename);
748
+ return this.resolveBucketPath("actual", filename);
686
749
  }
687
750
  /**
688
751
  * Get the path to an expected screenshot file
689
752
  */
690
753
  getExpectedFilePath(filename) {
691
- return path.resolve(this.expected, filename);
754
+ return this.resolveBucketPath("expected", filename);
692
755
  }
693
756
  /**
694
757
  * Get the path to a diff screenshot file
695
758
  */
696
759
  getDiffFilePath(filename) {
697
- return path.resolve(this.diff, filename);
760
+ return this.resolveBucketPath("diff", filename);
698
761
  }
699
762
  /**
700
763
  * Write a file to the actual directory
@@ -759,9 +822,8 @@ var ScreenshotFileSystem = class {
759
822
  return path.resolve(this.actual, filePath);
760
823
  }
761
824
  getRelativePath(directory, filePath) {
762
- const relativePath = path.relative(this[directory], filePath);
763
- if (relativePath.startsWith("..")) throw new Error(`Cannot resolve relative path outside of ${directory} directory: ${filePath}`);
764
- return relativePath;
825
+ if (!isPathInside(this[directory], filePath)) throw new Error(`Cannot resolve relative path outside of ${directory} directory: ${filePath}`);
826
+ return path.relative(this[directory], filePath);
765
827
  }
766
828
  };
767
829
  //#endregion
@@ -1666,7 +1728,7 @@ var ScreenshotTool = class {
1666
1728
  delay: this.getIncBackoffDelay(i, options.delay || 0)
1667
1729
  });
1668
1730
  if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
1669
- const comparisonResult = diffConfig.type === "gmsd" ? await compareImagesGMSD(screenshotBuffer, referenceImage, true, diffConfig) : await compareImages(screenshotBuffer, referenceImage, true, diffConfig);
1731
+ const comparisonResult = diffConfig.type === "gmsd" ? await compareImagesGMSD(referenceImage, screenshotBuffer, true, diffConfig) : await compareImages(referenceImage, screenshotBuffer, true, diffConfig);
1670
1732
  if (i === this.retries - 1 && !comparisonResult.passed) {
1671
1733
  this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
1672
1734
  return {
@@ -1693,8 +1755,21 @@ var ScreenshotTool = class {
1693
1755
  passed: false
1694
1756
  };
1695
1757
  }
1758
+ /**
1759
+ * Resolve the filename a variant is written under.
1760
+ *
1761
+ * An explicit `variant.filename` wins, but it is sanitized first: for
1762
+ * `@cappa/plugin-storybook` it arrives from the browser as a story parameter,
1763
+ * so it is story-author input and could otherwise carry `../` or an absolute
1764
+ * path into the write sink. A name left empty by sanitization falls back to
1765
+ * the derived one.
1766
+ */
1696
1767
  getVariantFilename(filename, variant) {
1697
- if (variant.filename) return variant.filename;
1768
+ if (variant.filename) {
1769
+ const safeFilename = sanitizeScreenshotFilename(variant.filename);
1770
+ if (safeFilename !== variant.filename) this.logger.warn(`Variant filename "${variant.filename}" is not a valid screenshot path, using "${safeFilename || "the derived name"}" instead`);
1771
+ if (safeFilename) return safeFilename;
1772
+ }
1698
1773
  const parsed = path.parse(filename);
1699
1774
  const suffix = variant.id.trim().replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "variant";
1700
1775
  const ext = parsed.ext || ".png";
@@ -1855,7 +1930,7 @@ var ScreenshotTool = class {
1855
1930
  baseResult.diffImagePath = baseCaptureResult.diffImagePath;
1856
1931
  baseResult.skipped = baseCaptureResult.skipped;
1857
1932
  for (const variant of variants) {
1858
- const variantFilename = variant.filename || this.getVariantFilename(baseFilename, variant);
1933
+ const variantFilename = this.getVariantFilename(baseFilename, variant);
1859
1934
  const variantOptions = {
1860
1935
  ...baseOptions,
1861
1936
  ...variant.options
@@ -3039,6 +3114,6 @@ var FsScreenshotStore = class {
3039
3114
  }
3040
3115
  };
3041
3116
  //#endregion
3042
- export { CaptureRunner, DEFAULT_DEBOUNCE_MS, DEFAULT_IGNORED_DIRS, DEFAULT_MAX_TASKS, ENGINE_ERROR_CODES, FsScreenshotStore, LocalEngine, MANIFEST_FILENAME, MANIFEST_VERSION, RunInProgressError, RunStore, ScreenshotFileSystem, ScreenshotTool, UnknownTargetsError, WarmBrowser, WatchInProgressError, WatchSession, collectScreenshots, compareImages, compareImagesGMSD, defineConfig, didScreenshotFail, filterTasks, getDeletedScreenshots, groupScreenshots, imagesMatch, imagesMatchGMSD, isRunInProgressError, isUnknownTargetsError, isWatchInProgressError, mapWithConcurrency, mergeCaptureManifest, readCaptureManifest, readDiffMeta, recordCaptureOrigins, selectTasks, toDiffMetaPath, toManifestKey, toSerializedError, toTaskStatus };
3117
+ export { CaptureRunner, DEFAULT_DEBOUNCE_MS, DEFAULT_IGNORED_DIRS, DEFAULT_MAX_TASKS, ENGINE_ERROR_CODES, FsScreenshotStore, LocalEngine, MANIFEST_FILENAME, MANIFEST_VERSION, RunInProgressError, RunStore, ScreenshotFileSystem, ScreenshotTool, UnknownTargetsError, WarmBrowser, WatchInProgressError, WatchSession, collectScreenshots, compareImages, compareImagesGMSD, defineConfig, didScreenshotFail, filterTasks, getDeletedScreenshots, groupScreenshots, imagesMatch, imagesMatchGMSD, isRunInProgressError, isUnknownTargetsError, isWatchInProgressError, mapWithConcurrency, mergeCaptureManifest, readCaptureManifest, readDiffMeta, recordCaptureOrigins, sanitizeScreenshotFilename, selectTasks, toDiffMetaPath, toManifestKey, toSerializedError, toTaskStatus };
3043
3118
 
3044
3119
  //# sourceMappingURL=index.mjs.map