@cappa/core 0.13.0 → 0.13.1

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
@@ -114,6 +114,15 @@ export declare class ScreenshotFileSystem {
114
114
  * Get the diff directory path
115
115
  */
116
116
  getDiffDir(): string;
117
+ /**
118
+ * Resolve a screenshot filename inside one of the buckets.
119
+ *
120
+ * This is the single sink every read and write funnels through, so it is also
121
+ * where an untrusted filename is stopped: plugin-supplied names (Storybook
122
+ * variant filenames come straight from story code) must never escape the
123
+ * bucket they belong to.
124
+ */
125
+ private resolveBucketPath;
117
126
  /**
118
127
  * Get the path to an actual screenshot file
119
128
  */
@@ -574,6 +583,15 @@ declare class ScreenshotTool {
574
583
  comparisonResult: null;
575
584
  passed: boolean;
576
585
  }>;
586
+ /**
587
+ * Resolve the filename a variant is written under.
588
+ *
589
+ * An explicit `variant.filename` wins, but it is sanitized first: for
590
+ * `@cappa/plugin-storybook` it arrives from the browser as a story parameter,
591
+ * so it is story-author input and could otherwise carry `../` or an absolute
592
+ * path into the write sink. A name left empty by sanitization falls back to
593
+ * the derived one.
594
+ */
577
595
  getVariantFilename(filename: string, variant: ScreenshotVariant): string;
578
596
  /**
579
597
  * Captures a single screenshot with the given options
@@ -1692,6 +1710,17 @@ export declare class WarmBrowser {
1692
1710
  */
1693
1711
  export declare function mapWithConcurrency<T, R = void>(concurrency: number, items: readonly T[], fn: (item: T, workerIndex: number) => Promise<R>): Promise<R[]>;
1694
1712
  //#endregion
1713
+ //#region src/paths.d.ts
1714
+ /**
1715
+ * Turn a screenshot filename into a relative path that stays inside its bucket.
1716
+ *
1717
+ * Path separators are kept — they are how plugins express folders — but
1718
+ * traversal (`..`), no-op (`.`) and empty segments are dropped, backslashes are
1719
+ * normalised to `/`, and a Windows drive prefix is removed. Returns an empty
1720
+ * string when nothing usable is left, which callers treat as "no name given".
1721
+ */
1722
+ export declare function sanitizeScreenshotFilename(filename: string): string;
1723
+ //#endregion
1695
1724
  //#region src/runner/tasks.d.ts
1696
1725
  /**
1697
1726
  * Decide whether a plugin's `execute` result represents a failed screenshot.
package/dist/index.d.mts CHANGED
@@ -114,6 +114,15 @@ export declare class ScreenshotFileSystem {
114
114
  * Get the diff directory path
115
115
  */
116
116
  getDiffDir(): string;
117
+ /**
118
+ * Resolve a screenshot filename inside one of the buckets.
119
+ *
120
+ * This is the single sink every read and write funnels through, so it is also
121
+ * where an untrusted filename is stopped: plugin-supplied names (Storybook
122
+ * variant filenames come straight from story code) must never escape the
123
+ * bucket they belong to.
124
+ */
125
+ private resolveBucketPath;
117
126
  /**
118
127
  * Get the path to an actual screenshot file
119
128
  */
@@ -574,6 +583,15 @@ declare class ScreenshotTool {
574
583
  comparisonResult: null;
575
584
  passed: boolean;
576
585
  }>;
586
+ /**
587
+ * Resolve the filename a variant is written under.
588
+ *
589
+ * An explicit `variant.filename` wins, but it is sanitized first: for
590
+ * `@cappa/plugin-storybook` it arrives from the browser as a story parameter,
591
+ * so it is story-author input and could otherwise carry `../` or an absolute
592
+ * path into the write sink. A name left empty by sanitization falls back to
593
+ * the derived one.
594
+ */
577
595
  getVariantFilename(filename: string, variant: ScreenshotVariant): string;
578
596
  /**
579
597
  * Captures a single screenshot with the given options
@@ -1692,6 +1710,17 @@ export declare class WarmBrowser {
1692
1710
  */
1693
1711
  export declare function mapWithConcurrency<T, R = void>(concurrency: number, items: readonly T[], fn: (item: T, workerIndex: number) => Promise<R>): Promise<R[]>;
1694
1712
  //#endregion
1713
+ //#region src/paths.d.ts
1714
+ /**
1715
+ * Turn a screenshot filename into a relative path that stays inside its bucket.
1716
+ *
1717
+ * Path separators are kept — they are how plugins express folders — but
1718
+ * traversal (`..`), no-op (`.`) and empty segments are dropped, backslashes are
1719
+ * normalised to `/`, and a Windows drive prefix is removed. Returns an empty
1720
+ * string when nothing usable is left, which callers treat as "no name given".
1721
+ */
1722
+ export declare function sanitizeScreenshotFilename(filename: string): string;
1723
+ //#endregion
1695
1724
  //#region src/runner/tasks.d.ts
1696
1725
  /**
1697
1726
  * Decide whether a plugin's `execute` result represents a failed screenshot.
package/dist/index.mjs CHANGED
@@ -478,6 +478,57 @@ async function mapWithConcurrency(concurrency, items, fn) {
478
478
  return results;
479
479
  }
480
480
  //#endregion
481
+ //#region src/paths.ts
482
+ /**
483
+ * Screenshot filenames are not a trusted input.
484
+ *
485
+ * A name is whatever a plugin chose, and a plugin may derive it from something
486
+ * it does not control either: `@cappa/plugin-storybook` reads
487
+ * `parameters.cappa.variants[].filename` out of the browser, so the string
488
+ * originates in story-author code. Every name eventually lands in
489
+ * `path.resolve(<bucket dir>, name)`, which honours both absolute paths and
490
+ * `../`, so without a guard a single story could write a PNG anywhere the
491
+ * process can write.
492
+ *
493
+ * Two layers live here: `sanitizeScreenshotFilename` turns a name into a
494
+ * relative path that cannot escape (used where a bad name should degrade rather
495
+ * than fail a run), and `resolveInside` is the hard backstop at the write sink.
496
+ */
497
+ /**
498
+ * Whether `target` resolves to something strictly inside `base`.
499
+ *
500
+ * Note this is deliberately stricter than a `startsWith("..")` check on the
501
+ * relative path, which also rejects legitimate names such as `..foo.png`.
502
+ */
503
+ function isPathInside(base, target) {
504
+ const relative = path.relative(base, target);
505
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
506
+ }
507
+ /**
508
+ * Resolve `filename` inside `base`, rejecting absolute paths and any name that
509
+ * escapes `base`.
510
+ *
511
+ * @param label - The bucket name used in the error message (`actual`, `diff`, …)
512
+ */
513
+ function resolveInside(base, filename, label) {
514
+ const resolved = path.resolve(base, filename);
515
+ if (path.isAbsolute(filename) || !isPathInside(base, resolved)) throw new Error(`Refusing to resolve screenshot path outside of the ${label} directory: ${filename}`);
516
+ return resolved;
517
+ }
518
+ /**
519
+ * Turn a screenshot filename into a relative path that stays inside its bucket.
520
+ *
521
+ * Path separators are kept — they are how plugins express folders — but
522
+ * traversal (`..`), no-op (`.`) and empty segments are dropped, backslashes are
523
+ * normalised to `/`, and a Windows drive prefix is removed. Returns an empty
524
+ * string when nothing usable is left, which callers treat as "no name given".
525
+ */
526
+ function sanitizeScreenshotFilename(filename) {
527
+ const segments = filename.replace(/\\/g, "/").split("/").map((segment) => segment.replace(/\0/g, "").trim()).filter((segment) => segment !== "" && segment !== "." && segment !== "..");
528
+ if (segments[0] && /^[a-zA-Z]:$/.test(segments[0])) segments.shift();
529
+ return segments.join("/");
530
+ }
531
+ //#endregion
481
532
  //#region src/filesystem.ts
482
533
  var filesystem_exports = /* @__PURE__ */ __exportAll({
483
534
  ScreenshotFileSystem: () => ScreenshotFileSystem,
@@ -545,9 +596,8 @@ var ScreenshotFileSystem = class {
545
596
  */
546
597
  async approveFromActualPath(actualFilePath) {
547
598
  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);
599
+ if (!isPathInside(this.actual, actualAbsolute)) throw new Error(`Cannot approve screenshot outside of actual directory: ${actualFilePath}`);
600
+ return this.approveRelative(path.relative(this.actual, actualAbsolute));
551
601
  }
552
602
  /**
553
603
  * Apply baseline updates for grouped screenshots (same rules as `cappa approve`).
@@ -679,22 +729,33 @@ var ScreenshotFileSystem = class {
679
729
  return this.diff;
680
730
  }
681
731
  /**
732
+ * Resolve a screenshot filename inside one of the buckets.
733
+ *
734
+ * This is the single sink every read and write funnels through, so it is also
735
+ * where an untrusted filename is stopped: plugin-supplied names (Storybook
736
+ * variant filenames come straight from story code) must never escape the
737
+ * bucket they belong to.
738
+ */
739
+ resolveBucketPath(directory, filename) {
740
+ return resolveInside(this[directory], filename, directory);
741
+ }
742
+ /**
682
743
  * Get the path to an actual screenshot file
683
744
  */
684
745
  getActualFilePath(filename) {
685
- return path.resolve(this.actual, filename);
746
+ return this.resolveBucketPath("actual", filename);
686
747
  }
687
748
  /**
688
749
  * Get the path to an expected screenshot file
689
750
  */
690
751
  getExpectedFilePath(filename) {
691
- return path.resolve(this.expected, filename);
752
+ return this.resolveBucketPath("expected", filename);
692
753
  }
693
754
  /**
694
755
  * Get the path to a diff screenshot file
695
756
  */
696
757
  getDiffFilePath(filename) {
697
- return path.resolve(this.diff, filename);
758
+ return this.resolveBucketPath("diff", filename);
698
759
  }
699
760
  /**
700
761
  * Write a file to the actual directory
@@ -759,9 +820,8 @@ var ScreenshotFileSystem = class {
759
820
  return path.resolve(this.actual, filePath);
760
821
  }
761
822
  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;
823
+ if (!isPathInside(this[directory], filePath)) throw new Error(`Cannot resolve relative path outside of ${directory} directory: ${filePath}`);
824
+ return path.relative(this[directory], filePath);
765
825
  }
766
826
  };
767
827
  //#endregion
@@ -1693,8 +1753,21 @@ var ScreenshotTool = class {
1693
1753
  passed: false
1694
1754
  };
1695
1755
  }
1756
+ /**
1757
+ * Resolve the filename a variant is written under.
1758
+ *
1759
+ * An explicit `variant.filename` wins, but it is sanitized first: for
1760
+ * `@cappa/plugin-storybook` it arrives from the browser as a story parameter,
1761
+ * so it is story-author input and could otherwise carry `../` or an absolute
1762
+ * path into the write sink. A name left empty by sanitization falls back to
1763
+ * the derived one.
1764
+ */
1696
1765
  getVariantFilename(filename, variant) {
1697
- if (variant.filename) return variant.filename;
1766
+ if (variant.filename) {
1767
+ const safeFilename = sanitizeScreenshotFilename(variant.filename);
1768
+ if (safeFilename !== variant.filename) this.logger.warn(`Variant filename "${variant.filename}" is not a valid screenshot path, using "${safeFilename || "the derived name"}" instead`);
1769
+ if (safeFilename) return safeFilename;
1770
+ }
1698
1771
  const parsed = path.parse(filename);
1699
1772
  const suffix = variant.id.trim().replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "variant";
1700
1773
  const ext = parsed.ext || ".png";
@@ -1855,7 +1928,7 @@ var ScreenshotTool = class {
1855
1928
  baseResult.diffImagePath = baseCaptureResult.diffImagePath;
1856
1929
  baseResult.skipped = baseCaptureResult.skipped;
1857
1930
  for (const variant of variants) {
1858
- const variantFilename = variant.filename || this.getVariantFilename(baseFilename, variant);
1931
+ const variantFilename = this.getVariantFilename(baseFilename, variant);
1859
1932
  const variantOptions = {
1860
1933
  ...baseOptions,
1861
1934
  ...variant.options
@@ -3039,6 +3112,6 @@ var FsScreenshotStore = class {
3039
3112
  }
3040
3113
  };
3041
3114
  //#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 };
3115
+ 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
3116
 
3044
3117
  //# sourceMappingURL=index.mjs.map