From 6f8182db41a8fceddd9c42f3d7c4089c3f959ee9 Mon Sep 17 00:00:00 2001 From: LamGC Date: Thu, 15 Oct 2026 11:42:07 +0800 Subject: [PATCH] fix: bound recording resources and add security regressions (#41) - Bound recording bytes, JSON structure, events, markers, terminal dimensions and timestamp arithmetic before unsafe player allocation or scheduling. - Share validated playback data and metadata; cancel stale, failed and timed-out loads. - Add PHP 7.4-compatible predecode budgets and preserve supported v1/v2/v3 behavior. - Add localized errors, documented limits and 110 official/seeded recording fixtures. Verified 325 Node tests, native PHP 7.4/8.3 regression suites and 55 Chromium tests on each WordPress CI matrix. Preserve plugin version, vendor files and isolated package artifacts. --- README-zh.md | 27 +- README.md | 33 +- SOURCE.md | 18 + includes/uploads.php | 220 +- ...player-zh_CN-lamgc-asciiplayer-editor.json | 34 +- ...iiplayer-zh_CN-lamgc-asciiplayer-view.json | 34 +- languages/wp-asciiplayer-zh_CN.mo | Bin 8055 -> 9038 bytes languages/wp-asciiplayer-zh_CN.po | 65 +- languages/wp-asciiplayer.pot | 59 +- readme.txt | 4 + scripts/verify-build.mjs | 6 +- src/preview.js | 33 +- src/recording-errors.js | 22 + src/recording-loader.js | 353 ++ src/view.js | 95 +- tests/e2e/bounded-recording.spec.js | 341 ++ tests/e2e/i18n.spec.js | 4 +- tests/e2e/recording-source.spec.js | 2 +- tests/e2e/security-fixtures.spec.js | 320 ++ tests/fixtures/security/PROVENANCE.md | 69 + tests/fixtures/security/README.md | 169 + tests/fixtures/security/cells-v1-at.cast | 1 + tests/fixtures/security/cells-v1-over.cast | 1 + tests/fixtures/security/cells-v2-at.cast | 2 + tests/fixtures/security/cells-v2-over.cast | 2 + tests/fixtures/security/cells-v3-at.cast | 2 + tests/fixtures/security/cells-v3-over.cast | 2 + tests/fixtures/security/depth-v1-at.cast | 1 + tests/fixtures/security/depth-v1-over.cast | 1 + tests/fixtures/security/depth-v2-at.cast | 1 + tests/fixtures/security/depth-v2-over.cast | 1 + tests/fixtures/security/depth-v3-at.cast | 1 + tests/fixtures/security/depth-v3-over.cast | 1 + tests/fixtures/security/dimensions-v1-at.cast | 1 + .../fixtures/security/dimensions-v1-over.cast | 1 + tests/fixtures/security/dimensions-v2-at.cast | 2 + .../fixtures/security/dimensions-v2-over.cast | 2 + tests/fixtures/security/dimensions-v3-at.cast | 2 + .../fixtures/security/dimensions-v3-over.cast | 2 + tests/fixtures/security/duration-v1-at.cast | 1 + tests/fixtures/security/duration-v1-over.cast | 1 + tests/fixtures/security/duration-v1-zero.cast | 1 + tests/fixtures/security/duration-v2-at.cast | 2 + tests/fixtures/security/duration-v2-over.cast | 2 + tests/fixtures/security/duration-v2-zero.cast | 2 + tests/fixtures/security/duration-v3-at.cast | 2 + tests/fixtures/security/duration-v3-over.cast | 2 + tests/fixtures/security/duration-v3-zero.cast | 2 + tests/fixtures/security/generate.mjs | 88 + tests/fixtures/security/idle-limit-v1-at.cast | 1 + .../fixtures/security/idle-limit-v1-over.cast | 1 + .../fixtures/security/idle-limit-v1-zero.cast | 1 + tests/fixtures/security/idle-limit-v2-at.cast | 2 + .../fixtures/security/idle-limit-v2-over.cast | 2 + .../fixtures/security/idle-limit-v2-zero.cast | 2 + tests/fixtures/security/idle-limit-v3-at.cast | 2 + .../fixtures/security/idle-limit-v3-over.cast | 2 + .../fixtures/security/idle-limit-v3-zero.cast | 2 + .../security/interval-timeline-v1-at.cast | 1 + .../security/interval-timeline-v1-over.cast | 1 + .../security/interval-timeline-v3-at.cast | 3 + .../security/interval-timeline-v3-over.cast | 3 + .../fixtures/security/late-resize-v2-at.cast | 3 + .../late-resize-v2-dimensions-at.cast | 3 + .../late-resize-v2-dimensions-over.cast | 3 + .../security/late-resize-v2-over.cast | 3 + .../fixtures/security/late-resize-v3-at.cast | 3 + .../late-resize-v3-dimensions-at.cast | 3 + .../late-resize-v3-dimensions-over.cast | 3 + .../security/late-resize-v3-over.cast | 3 + .../fixtures/security/malformed-v1-json.cast | 1 + .../fixtures/security/malformed-v2-event.cast | 2 + .../fixtures/security/malformed-v3-event.cast | 2 + tests/fixtures/security/manifest.json | 2925 +++++++++++++++++ tests/fixtures/security/official-v1.cast | 38 + tests/fixtures/security/official-v2.cast | 8 + tests/fixtures/security/official-v3.cast | 8 + tests/fixtures/security/provenance.json | 148 + tests/fixtures/security/recipes.mjs | 212 ++ .../security/record-official-baselines.sh | 47 + tests/fixtures/security/seeded-v1-valid.cast | 25 + tests/fixtures/security/seeded-v2-valid.cast | 5 + tests/fixtures/security/seeded-v3-valid.cast | 5 + tests/fixtures/security/synthetic-output.py | 20 + .../security/time-v1-ms-rounding-over.cast | 1 + .../security/time-v1-ms-sum-overflow.cast | 1 + .../security/time-v2-output-nonprogress.cast | 2 + .../security/time-v3-ms-rounding-over.cast | 3 + .../security/time-v3-ms-sum-overflow.cast | 3 + tests/fixtures/security/timeline-v1-at.cast | 1 + tests/fixtures/security/timeline-v1-over.cast | 1 + tests/fixtures/security/timeline-v2-at.cast | 2 + tests/fixtures/security/timeline-v2-over.cast | 2 + tests/fixtures/security/timeline-v3-at.cast | 2 + tests/fixtures/security/timeline-v3-over.cast | 2 + .../security/valid-v1-duplicate-version.cast | 1 + .../security/valid-v1-escaped-version.cast | 1 + .../valid-v1-multiline-late-version.cast | 7 + tests/fixtures/security/valid-v1-zero.cast | 1 + .../security/valid-v2-filtered-lines.cast | 6 + tests/fixtures/security/valid-v2-zero.cast | 2 + .../security/valid-v3-filtered-lines.cast | 6 + tests/fixtures/security/valid-v3-zero.cast | 2 + tests/js/playback.test.js | 118 + tests/js/preview-lifecycle.test.js | 116 + tests/js/recording-loader.test.js | 357 ++ tests/js/security-fixtures.test.js | 256 ++ tests/js/security-loader-fixtures.test.js | 397 +++ tests/php/cast-budget-decoder.php | 11 + tests/php/cast-budget.php | 155 + tests/php/run.php | 3 + tests/php/security-fixtures.php | 236 ++ tests/php/uploads.php | 22 +- 113 files changed, 7121 insertions(+), 126 deletions(-) create mode 100644 src/recording-errors.js create mode 100644 src/recording-loader.js create mode 100644 tests/e2e/bounded-recording.spec.js create mode 100644 tests/e2e/security-fixtures.spec.js create mode 100644 tests/fixtures/security/PROVENANCE.md create mode 100644 tests/fixtures/security/README.md create mode 100644 tests/fixtures/security/cells-v1-at.cast create mode 100644 tests/fixtures/security/cells-v1-over.cast create mode 100644 tests/fixtures/security/cells-v2-at.cast create mode 100644 tests/fixtures/security/cells-v2-over.cast create mode 100644 tests/fixtures/security/cells-v3-at.cast create mode 100644 tests/fixtures/security/cells-v3-over.cast create mode 100644 tests/fixtures/security/depth-v1-at.cast create mode 100644 tests/fixtures/security/depth-v1-over.cast create mode 100644 tests/fixtures/security/depth-v2-at.cast create mode 100644 tests/fixtures/security/depth-v2-over.cast create mode 100644 tests/fixtures/security/depth-v3-at.cast create mode 100644 tests/fixtures/security/depth-v3-over.cast create mode 100644 tests/fixtures/security/dimensions-v1-at.cast create mode 100644 tests/fixtures/security/dimensions-v1-over.cast create mode 100644 tests/fixtures/security/dimensions-v2-at.cast create mode 100644 tests/fixtures/security/dimensions-v2-over.cast create mode 100644 tests/fixtures/security/dimensions-v3-at.cast create mode 100644 tests/fixtures/security/dimensions-v3-over.cast create mode 100644 tests/fixtures/security/duration-v1-at.cast create mode 100644 tests/fixtures/security/duration-v1-over.cast create mode 100644 tests/fixtures/security/duration-v1-zero.cast create mode 100644 tests/fixtures/security/duration-v2-at.cast create mode 100644 tests/fixtures/security/duration-v2-over.cast create mode 100644 tests/fixtures/security/duration-v2-zero.cast create mode 100644 tests/fixtures/security/duration-v3-at.cast create mode 100644 tests/fixtures/security/duration-v3-over.cast create mode 100644 tests/fixtures/security/duration-v3-zero.cast create mode 100644 tests/fixtures/security/generate.mjs create mode 100644 tests/fixtures/security/idle-limit-v1-at.cast create mode 100644 tests/fixtures/security/idle-limit-v1-over.cast create mode 100644 tests/fixtures/security/idle-limit-v1-zero.cast create mode 100644 tests/fixtures/security/idle-limit-v2-at.cast create mode 100644 tests/fixtures/security/idle-limit-v2-over.cast create mode 100644 tests/fixtures/security/idle-limit-v2-zero.cast create mode 100644 tests/fixtures/security/idle-limit-v3-at.cast create mode 100644 tests/fixtures/security/idle-limit-v3-over.cast create mode 100644 tests/fixtures/security/idle-limit-v3-zero.cast create mode 100644 tests/fixtures/security/interval-timeline-v1-at.cast create mode 100644 tests/fixtures/security/interval-timeline-v1-over.cast create mode 100644 tests/fixtures/security/interval-timeline-v3-at.cast create mode 100644 tests/fixtures/security/interval-timeline-v3-over.cast create mode 100644 tests/fixtures/security/late-resize-v2-at.cast create mode 100644 tests/fixtures/security/late-resize-v2-dimensions-at.cast create mode 100644 tests/fixtures/security/late-resize-v2-dimensions-over.cast create mode 100644 tests/fixtures/security/late-resize-v2-over.cast create mode 100644 tests/fixtures/security/late-resize-v3-at.cast create mode 100644 tests/fixtures/security/late-resize-v3-dimensions-at.cast create mode 100644 tests/fixtures/security/late-resize-v3-dimensions-over.cast create mode 100644 tests/fixtures/security/late-resize-v3-over.cast create mode 100644 tests/fixtures/security/malformed-v1-json.cast create mode 100644 tests/fixtures/security/malformed-v2-event.cast create mode 100644 tests/fixtures/security/malformed-v3-event.cast create mode 100644 tests/fixtures/security/manifest.json create mode 100644 tests/fixtures/security/official-v1.cast create mode 100644 tests/fixtures/security/official-v2.cast create mode 100644 tests/fixtures/security/official-v3.cast create mode 100644 tests/fixtures/security/provenance.json create mode 100644 tests/fixtures/security/recipes.mjs create mode 100755 tests/fixtures/security/record-official-baselines.sh create mode 100644 tests/fixtures/security/seeded-v1-valid.cast create mode 100644 tests/fixtures/security/seeded-v2-valid.cast create mode 100644 tests/fixtures/security/seeded-v3-valid.cast create mode 100644 tests/fixtures/security/synthetic-output.py create mode 100644 tests/fixtures/security/time-v1-ms-rounding-over.cast create mode 100644 tests/fixtures/security/time-v1-ms-sum-overflow.cast create mode 100644 tests/fixtures/security/time-v2-output-nonprogress.cast create mode 100644 tests/fixtures/security/time-v3-ms-rounding-over.cast create mode 100644 tests/fixtures/security/time-v3-ms-sum-overflow.cast create mode 100644 tests/fixtures/security/timeline-v1-at.cast create mode 100644 tests/fixtures/security/timeline-v1-over.cast create mode 100644 tests/fixtures/security/timeline-v2-at.cast create mode 100644 tests/fixtures/security/timeline-v2-over.cast create mode 100644 tests/fixtures/security/timeline-v3-at.cast create mode 100644 tests/fixtures/security/timeline-v3-over.cast create mode 100644 tests/fixtures/security/valid-v1-duplicate-version.cast create mode 100644 tests/fixtures/security/valid-v1-escaped-version.cast create mode 100644 tests/fixtures/security/valid-v1-multiline-late-version.cast create mode 100644 tests/fixtures/security/valid-v1-zero.cast create mode 100644 tests/fixtures/security/valid-v2-filtered-lines.cast create mode 100644 tests/fixtures/security/valid-v2-zero.cast create mode 100644 tests/fixtures/security/valid-v3-filtered-lines.cast create mode 100644 tests/fixtures/security/valid-v3-zero.cast create mode 100644 tests/js/playback.test.js create mode 100644 tests/js/preview-lifecycle.test.js create mode 100644 tests/js/recording-loader.test.js create mode 100644 tests/js/security-fixtures.test.js create mode 100644 tests/js/security-loader-fixtures.test.js create mode 100644 tests/php/cast-budget-decoder.php create mode 100644 tests/php/cast-budget.php create mode 100644 tests/php/security-fixtures.php diff --git a/README-zh.md b/README-zh.md index d0fa4dc..6c80993 100644 --- a/README-zh.md +++ b/README-zh.md @@ -70,17 +70,30 @@ URL 要直接指向录制文件,例如 `.cast` 文件,而不是 asciinema 已有 WordPress `upload_files` 权限的用户可以上传 `.cast` 文件。 多站点还需要网络管理员允许 `cast` 扩展名。插件不会增加用户的上传权限,也不会另建录屏管理文章类型。 -上传文件会完整校验,限制如下: +上传和浏览器播放(包括远程录屏)执行以下资源限制: -- 每个文件最多 **32 MiB**。 -- 最多 **100,000** 个事件或流内行。 -- 每条 JSONL 行最多 **256 KiB**。 -- 终端任一方向不超过 **1,000** 列或行。 +- 接收到的录屏数据最多 **32 MiB**;旧的 v1 格式最多 **2 MiB**。 +- 最多 **100,000** 个事件或流内行,忽略的行也计入。 +- 每条 JSONL 行最多 **256 KiB**,最多 **1,000** 个时间标记。 +- 终端每个方向不超过 **1,000** 列或行,列数 × 行数不超过 **40,000** 个单元格。 +- 录屏时间轴和支持的时间值最多 **2,147,483,647 毫秒**(约 **24.85 天**)。v1/v3 的相对时间按播放器的顺序以毫秒累加。浏览器播放还要求累计录屏时间除以播放速度后不超过此上限;因此在 **0.01×** 速度下,原始录屏时长最多约 **5.97 小时**。这一保守边界确保原生定时器延迟和输出批处理处于支持的数值范围内。起始时间、空闲时间与时间戳封面选项也会检查。 +- JSON 容器最多嵌套 **15** 层;v1 最多 **400,000** 个标量/键名与 **100,016** 个容器;每条 JSONL 行最多 **20,000** 个标量/键名。解码前检查,未知元数据与重复键名也计入。 +- 浏览器请求总时限为 **30 秒**,等待下个响应或数据块的时限为 **10 秒**;编辑器加载播放器资源与录屏合计也限 30 秒。 -旧的 asciicast v1 格式最多 **2 MiB**,需要格式化 JSON,并让起始 `{` 单独占一行; -内置播放器无法读取压成一行的 v1 文件。Asciicast v2、v3 使用标准 JSONL。 +单元格限制检查初始尺寸、每次尺寸变化,以及 Columns/Rows 覆盖后的实际尺寸。 +创建终端前,还会用播放器初始默认的 80×24 尺寸检查覆盖值;单独覆盖一个方向时,也须同时满足初始终端和录屏的预算。 +录屏头中的零尺寸使用播放器默认值;普通空行、注释和安全的未知事件类型仍兼容。 +Asciicast v2、v3 使用 JSONL,旧的 v1 在较小的数据上限内仍受支持。 站点或服务器更低的上传限制仍然生效。无效录屏会被拒绝,也不会因此开放普通 JSON、HTML 或 SVG 上传。 +这些限制也适用于旧文件和外部托管录屏的播放。此前能加载的超大终端或包含大量时间标记的录屏, +可能会显示明确的超限提示。建议拆分或简化录屏,而不是让浏览器处理无限数据。 +已有文件和文章不会被重写。 + +浏览器通过一次请求读取并校验录屏,通过后才交给播放器;不会增加服务器代理或额外元数据请求。 +超时或取消会停止加载,切换录屏或离开预览会取消旧请求。 +远程服务器仍须允许 CORS,浏览器的凭据和来源信息规则保持不变。 + ## 界面语言 插件界面包含英文和简体中文(`zh_CN`): diff --git a/README.md b/README.md index 1b6ab19..cec6c8c 100644 --- a/README.md +++ b/README.md @@ -85,19 +85,36 @@ permission. Multisite networks must also allow the `cast` extension. The plugin does not grant extra upload permissions or add a separate recording-management post type. -Uploads are checked against these limits: +Uploads and browser playback (including remote recordings) enforce these resource limits: -- **32 MiB** per file. -- **100,000** events or stream lines. -- **256 KiB** per JSONL line. -- **1,000** columns or rows in either direction. +- **32 MiB** of received recording data; **2 MiB** for legacy v1. +- **100,000** events or stream lines, including ignored lines. +- **256 KiB** per JSONL line and **1,000** marker events. +- **1,000** columns or rows per axis, and **40,000** terminal cells (columns × rows). +- **2,147,483,647 milliseconds** (about **24.85 days**) for recording timelines and supported time values. Relative v1/v3 intervals are accumulated in milliseconds, matching the player. Browser playback also requires cumulative recording time divided by playback speed to fit this ceiling; at **0.01×**, this permits about **5.97 hours** of source time. This conservative bound keeps native timer delays and output batching within their supported numeric range. Playback start, idle-time and timestamp-poster options are checked too. +- At most **15** nested JSON containers, **400,000** scalar/key tokens and **100,016** containers in v1, or **20,000** scalar/key tokens per JSONL line, checked before decoding. Unknown metadata and duplicate keys count too. +- Browser requests stop after **30 seconds** total or **10 seconds** without the next response/chunk; the editor also allows 30 seconds for player assets and loading together. -The older asciicast v1 format is limited to **2 MiB**. Its JSON must be -pretty-printed, with the opening `{` on a line of its own; the bundled player -cannot read compact, single-line v1 files. Asciicast v2 and v3 use standard JSONL. +The cell budget covers initial dimensions and every resize, including effective +Columns/Rows overrides. Overrides are also checked against the player's initial +80×24 defaults before creating its terminal, so a single-axis override must fit +both the initial terminal and the recording. A zero header dimension uses the player's default; +ordinary blank/comment lines and safe unknown event types remain compatible. +Asciicast v2 and v3 use JSONL; legacy v1 remains supported within its smaller limit. Lower site or server upload limits still apply. Invalid recordings are rejected; this does not enable general JSON, HTML or SVG uploads. +These limits also apply to older or externally hosted recordings at playback. +Very large terminals or marker-heavy recordings that previously loaded may now +show a clear limit error. Split or simplify those recordings rather than relying +on the browser to handle unlimited data. Existing files and posts are not rewritten. + +The browser reads and validates a single recording request before handing it to +the player. There is no server proxy or additional metadata request. A timed-out +or canceled load is stopped; switching recordings and leaving a preview cancel +its old request. Remote hosts must still allow CORS, and browser credentials and +referrer rules are unchanged. + ## Languages The plugin's interface includes English and Simplified Chinese (`zh_CN`). diff --git a/SOURCE.md b/SOURCE.md index 16c7247..77c6741 100644 --- a/SOURCE.md +++ b/SOURCE.md @@ -38,6 +38,24 @@ installs the release ZIP into the test site before checking it. Refer to the workflow for setup details. Running a unit test is not a substitute for the WordPress browser integration suite. +## Security recording regression fixtures + +The full repository contains a test-only corpus in +[`tests/fixtures/security`](tests/fixtures/security/README.md). Small `.cast` +controls are checked in; fixed-seed, exact-boundary larger recordings are generated +only when a test requests them. The manifest records expected acceptance, byte +counts and hashes so PHP upload checks and the browser loader exercise identical +inputs. The corpus README explains official recorder provenance, format-specific +coverage, and the distinction between valid-format over-budget and malformed cases. + + node tests/fixtures/security/generate.mjs --list + node tests/fixtures/security/generate.mjs --verify + +Use these fixtures only in isolated local/CI test environments. Do not upload +resource-limit probes to a live WordPress site or open unvalidated large recordings +in a player. The normal test commands above run the regression assertions; the +browser cases use representative bounded samples rather than stressing the host. + ## Translation maintenance The English gettext strings are the fallback. Edit `languages/wp-asciiplayer-zh_CN.po` diff --git a/includes/uploads.php b/includes/uploads.php index 961065a..4a11afb 100644 --- a/includes/uploads.php +++ b/includes/uploads.php @@ -17,6 +17,146 @@ const CAST_MAX_LINE_BYTES = 262144; // Bound individual JSON decodes to 256 KiB. const CAST_MAX_V1_BYTES = 2097152; // Legacy v1 is a single JSON document, not a stream. const CAST_MAX_EVENTS = 100000; const CAST_MAX_DIMENSION = 1000; +const CAST_MAX_CELLS = 40000; +const CAST_MAX_MARKERS = 1000; +// Browser timers use signed 32-bit millisecond delays (~24.85 days). Keep the +// raw timeline in this range; playback additionally checks the selected speed. +const CAST_MAX_TIME_MS = 2147483647; +const CAST_MAX_JSON_TOKENS = 400000; +const CAST_MAX_JSON_LINE_TOKENS = 20000; +const CAST_MAX_JSON_CONTAINERS = 100016; +const CAST_JSON_DEPTH = 16; + +/** + * Reject allocation-heavy JSON before decoding it, without building a graph. + * + * Count container openings and scalar/key tokens, including duplicate keys. + * Escapes and punctuation inside strings do not contribute to the budget. + * Counters may be shared across JSONL records. This lexical resource gate is + * not a JSON validator: json_decode remains responsible for grammar and UTF-8. + */ +function is_cast_json_within_budget( $text, &$containers, &$tokens, $token_limit = CAST_MAX_JSON_TOKENS ) { + $length = strlen( $text ); + $depth = 0; + $in_string = false; + $escaped = false; + $in_atom = false; + for ( $index = 0; $index < $length; ++$index ) { + $char = $text[ $index ]; + if ( $in_string ) { + if ( $escaped ) { + $escaped = false; + } elseif ( '\\' === $char ) { + $escaped = true; + } elseif ( '"' === $char ) { + $in_string = false; + } + continue; + } + if ( '"' === $char ) { + $in_string = true; + $in_atom = false; + ++$tokens; + } elseif ( '{' === $char || '[' === $char ) { + $in_atom = false; + ++$containers; + ++$depth; + // json_decode's depth includes the scalar level inside containers. + if ( $depth >= CAST_JSON_DEPTH ) { + return false; + } + } elseif ( '}' === $char || ']' === $char ) { + --$depth; + $in_atom = false; + if ( $depth < 0 ) { + return false; + } + } elseif ( ',' === $char || ':' === $char || ' ' === $char || "\n" === $char || "\r" === $char || "\t" === $char ) { + $in_atom = false; + } elseif ( ! $in_atom ) { + ++$tokens; + $in_atom = true; + } + if ( $containers > CAST_MAX_JSON_CONTAINERS || $tokens > $token_limit ) { + return false; + } + } + return true; +} + +/** + * Identify the last top-level version key without decoding a document graph. + * + * Run only after the lexical budget. Short JSON key/number decodes correctly + * handle escaped keys and duplicate-key last-wins semantics. Nested metadata + * never selects the format. This is a discriminator, not a grammar validator. + */ +function cast_top_level_version( $text ) { + $length = strlen( $text ); + $depth = 0; + $expect_key = false; + $version = null; + for ( $index = 0; $index < $length; ++$index ) { + $char = $text[ $index ]; + if ( '"' === $char ) { + $start = $index; + $escaped = false; + while ( ++$index < $length ) { + if ( $escaped ) { + $escaped = false; + } elseif ( '\\' === $text[ $index ] ) { + $escaped = true; + } elseif ( '"' === $text[ $index ] ) { + break; + } + } + if ( 1 !== $depth || ! $expect_key ) { + continue; + } + $expect_key = false; + // Seven fully escaped characters plus quotes need at most 44 bytes. + $key_length = $index - $start + 1; + if ( $key_length < 9 || $key_length > 44 || 'version' !== json_decode( substr( $text, $start, $key_length ) ) ) { + continue; + } + $version = null; + $cursor = $index + 1; + while ( $cursor < $length && false !== strpos( " \t\r\n", $text[ $cursor ] ) ) { + ++$cursor; + } + if ( $cursor >= $length || ':' !== $text[ $cursor++ ] ) { + continue; + } + while ( $cursor < $length && false !== strpos( " \t\r\n", $text[ $cursor ] ) ) { + ++$cursor; + } + $start = $cursor; + while ( $cursor < $length && false === strpos( ",}] \t\r\n", $text[ $cursor ] ) ) { + ++$cursor; + if ( $cursor - $start > 32 ) { + break; + } + } + if ( $cursor > $start && $cursor - $start <= 32 ) { + $value = json_decode( substr( $text, $start, $cursor - $start ) ); + $version = is_int( $value ) ? $value : null; + } + } elseif ( '{' === $char || '[' === $char ) { + ++$depth; + if ( 1 === $depth ) { + if ( '{' !== $char ) { + return null; + } + $expect_key = true; + } + } elseif ( '}' === $char || ']' === $char ) { + --$depth; + } elseif ( ',' === $char && 1 === $depth ) { + $expect_key = true; + } + } + return $version; +} /** Whether this user and, on multisite, the network permit .cast uploads. */ function can_upload_cast( $user = null ) { @@ -44,9 +184,9 @@ function is_cast_filename( $filename ) { return is_string( $filename ) && 1 === preg_match( '/\.cast\z/i', $filename ); } -/** Finite, nonnegative seconds that remain finite in the player's milliseconds. */ +/** Nonnegative seconds within the supported browser timer/precision horizon. */ function is_cast_time( $value ) { - return ( is_int( $value ) || is_float( $value ) ) && $value >= 0 && is_finite( $value * 1000 ); + return ( is_int( $value ) || is_float( $value ) ) && $value >= 0 && $value * 1000 <= CAST_MAX_TIME_MS; } /** Bound both initial and resize dimensions before they reach the terminal. */ @@ -54,6 +194,11 @@ function is_cast_dimension( $value ) { return is_int( $value ) && $value > 0 && $value <= CAST_MAX_DIMENSION; } +/** Bound the cell product as well as each independent axis. */ +function is_cast_size( $cols, $rows ) { + return is_cast_dimension( $cols ) && is_cast_dimension( $rows ) && $cols * $rows <= CAST_MAX_CELLS; +} + /** Validate metadata used by asciinema-player; unknown fields remain compatible. */ function is_cast_header( $header ) { if ( ! is_object( $header ) || ! isset( $header->version ) || ! in_array( $header->version, array( 1, 2, 3 ), true ) ) { @@ -65,7 +210,10 @@ function is_cast_header( $header ) { } $cols = 3 === $header->version ? ( $terminal->cols ?? null ) : ( $terminal->width ?? null ); $rows = 3 === $header->version ? ( $terminal->rows ?? null ) : ( $terminal->height ?? null ); - if ( ! is_cast_dimension( $cols ) || ! is_cast_dimension( $rows ) ) { + // The bundled player treats explicit zero header dimensions as defaults. + $cols = 0 === $cols ? 80 : $cols; + $rows = 0 === $rows ? 24 : $rows; + if ( ! is_cast_size( $cols, $rows ) ) { return false; } foreach ( array( 'duration', 'idle_time_limit' ) as $key ) { @@ -78,17 +226,23 @@ function is_cast_header( $header ) { /** Validate a whole bounded legacy v1 document, including every stdout frame. */ function is_cast_v1( $text ) { - $recording = json_decode( $text, false, 16 ); + $containers = 0; + $tokens = 0; + if ( strlen( $text ) > CAST_MAX_V1_BYTES || ! is_cast_json_within_budget( $text, $containers, $tokens ) || 1 !== cast_top_level_version( $text ) ) { + return false; + } + $recording = json_decode( $text, false, CAST_JSON_DEPTH ); if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_header( $recording ) || 1 !== $recording->version || ! isset( $recording->stdout ) || ! is_array( $recording->stdout ) || count( $recording->stdout ) > CAST_MAX_EVENTS ) { return false; } - $time = 0; + $time_ms = 0; foreach ( $recording->stdout as $frame ) { if ( ! is_array( $frame ) || 2 !== count( $frame ) || ! is_cast_time( $frame[0] ) || ! is_string( $frame[1] ) ) { return false; } - $time += $frame[0]; - if ( ! is_cast_time( $time ) ) { + // Match upstream's arithmetic order, including floating-point rounding. + $time_ms += $frame[0] * 1000; + if ( ! is_finite( $time_ms ) || $time_ms > CAST_MAX_TIME_MS ) { return false; } } @@ -96,19 +250,21 @@ function is_cast_v1( $text ) { } /** Validate one JSONL event, with absolute v2 time or relative v3 intervals. */ -function is_cast_event( $event, $version, &$time ) { +function is_cast_event( $event, $version, &$time_ms, &$previous_time ) { if ( ! is_array( $event ) || 3 !== count( $event ) || ! is_cast_time( $event[0] ) || ! is_string( $event[1] ) || '' === $event[1] || ! is_string( $event[2] ) ) { return false; } - if ( 2 === $version && $event[0] < $time ) { + $event_ms = $event[0] * 1000; + if ( 2 === $version && $event[0] < $previous_time ) { return false; } - $time = 2 === $version ? $event[0] : $time + $event[0]; - if ( ! is_cast_time( $time ) ) { + $previous_time = $event[0]; + $time_ms = 2 === $version ? $event_ms : $time_ms + $event_ms; + if ( ! is_finite( $time_ms ) || $time_ms > CAST_MAX_TIME_MS ) { return false; } if ( 'r' === $event[1] ) { - if ( 1 !== preg_match( '/^([1-9][0-9]{0,3})x([1-9][0-9]{0,3})$/D', $event[2], $matches ) || ! is_cast_dimension( (int) $matches[1] ) || ! is_cast_dimension( (int) $matches[2] ) ) { + if ( 1 !== preg_match( '/^([1-9][0-9]{0,3})x([1-9][0-9]{0,3})$/D', $event[2], $matches ) || ! is_cast_size( (int) $matches[1], (int) $matches[2] ) ) { return false; } } @@ -141,16 +297,18 @@ function is_valid_cast_file( $path ) { return false; } $line = fgets( $handle, CAST_MAX_LINE_BYTES + 2 ); - if ( false === $line || strlen( $line ) > CAST_MAX_LINE_BYTES ) { + if ( false === $line ) { return false; } - $header = json_decode( $line, false, 16 ); - // Player 3.17 interprets a complete first-line object as JSONL and rejects - // version 1 there. Keep uploads playable: legacy v1 must be pretty-printed. - if ( is_object( $header ) && isset( $header->version ) && 1 === $header->version ) { - return false; + $containers = 0; + $tokens = 0; + $header = null; + if ( strlen( $line ) <= CAST_MAX_LINE_BYTES && is_cast_json_within_budget( $line, $containers, $tokens, CAST_MAX_JSON_LINE_TOKENS ) ) { + $header = json_decode( $line, false, CAST_JSON_DEPTH ); } - if ( ! is_cast_header( $header ) ) { + if ( ! is_cast_header( $header ) || 1 === $header->version ) { + // Legacy v1 may be compact or pretty-printed. Its whole-document + // byte and structure budgets apply before any complete decode. if ( $stat['size'] > CAST_MAX_V1_BYTES || 0 !== fseek( $handle, 0 ) ) { return false; } @@ -159,23 +317,29 @@ function is_valid_cast_file( $path ) { } $bytes = strlen( $line ); $count = 0; - $time = 0; + $markers = 0; + $time_ms = 0; + $previous_time = 0; while ( false !== ( $line = fgets( $handle, CAST_MAX_LINE_BYTES + 2 ) ) ) { $bytes += strlen( $line ); if ( $bytes > CAST_MAX_BYTES || strlen( $line ) > CAST_MAX_LINE_BYTES || ++$count > CAST_MAX_EVENTS ) { return false; } - if ( 3 === $header->version && '#' === $line[0] ) { + // Match the bundled player's parser: only lines beginning with '[' + // are events. Ignored lines still consume byte and line budgets. + if ( '[' !== $line[0] ) { continue; } - // The bundled player's JSONL parser only consumes lines starting with - // '['; reject indented events rather than silently losing their output. - if ( '[' !== $line[0] ) { + $containers = 0; + $tokens = 0; + if ( ! is_cast_json_within_budget( $line, $containers, $tokens, CAST_MAX_JSON_LINE_TOKENS ) ) { return false; } - // Empty extra lines and non-event trailing content are not valid JSONL. - $event = json_decode( $line, false, 16 ); - if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_event( $event, $header->version, $time ) ) { + $event = json_decode( $line, false, CAST_JSON_DEPTH ); + if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_event( $event, $header->version, $time_ms, $previous_time ) ) { + return false; + } + if ( 'm' === $event[1] && ++$markers > CAST_MAX_MARKERS ) { return false; } } @@ -194,7 +358,7 @@ function validate_cast_upload( $file ) { if ( ! can_upload_cast() || ! isset( $allowed['cast'] ) || CAST_MIME !== $allowed['cast'] ) { $file['error'] = __( 'You are not allowed to upload Asciicast files.', 'wp-asciiplayer' ); } elseif ( ! is_valid_cast_file( $file['tmp_name'] ?? null ) ) { - $file['error'] = __( 'Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).', 'wp-asciiplayer' ); + $file['error'] = __( 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).', 'wp-asciiplayer' ); } return $file; } diff --git a/languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-editor.json b/languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-editor.json index 24ed6fd..6b949bc 100644 --- a/languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-editor.json +++ b/languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-editor.json @@ -205,9 +205,6 @@ "Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.": [ "无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。" ], - "The recording is taking too long to load. Check your connection and try again.": [ - "录制文件加载超时。请检查网络连接后重试。" - ], "The local player could not start. Try again, or check that the plugin’s built assets are installed.": [ "本地播放器无法启动。请重试,或检查插件的构建资源是否已安装。" ], @@ -220,14 +217,41 @@ "Interactive terminal recording preview": [ "可交互的终端录屏预览" ], + "This recording exceeds the file size limit.": [ + "该录屏超过文件大小限制。" + ], + "This recording contains a line that exceeds the size limit.": [ + "该录屏包含超出大小限制的行。" + ], + "This recording contains too many events.": [ + "该录屏包含过多事件。" + ], + "This recording contains too many markers.": [ + "该录屏包含过多时间标记。" + ], + "This recording requests terminal dimensions that exceed the supported limits.": [ + "该录屏请求的终端尺寸超出支持范围。" + ], + "This recording requests too many terminal cells.": [ + "该录屏请求的终端单元格过多。" + ], + "This recording is too complex to load safely.": [ + "该录屏结构过于复杂,无法安全加载。" + ], + "The recording is taking too long to load. Check your connection and try again.": [ + "录制文件加载超时。请检查网络连接后重试。" + ], + "This recording contains an invalid or unsupported timestamp.": [ + "该录屏包含无效或不支持的时间戳。" + ], "Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.": [ "无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。" ], "You are not allowed to upload Asciicast files.": [ "你没有上传 Asciicast 文件的权限。" ], - "Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).": [ - "请上传有效的 Asciicast v2/v3 JSONL 或格式化的 v1 .cast 录制文件(最大 32 MiB;v1 最大 2 MiB;最多 100,000 个事件;每行 JSONL最大 256 KiB;列数和行数均不超过 1,000)。" + "Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).": [ + "请上传有效的 Asciicast v2/v3 JSONL 或 v1 .cast 录屏(最大 32 MiB;v1 最大 2 MiB、100,000 个事件、每行 JSONL 最大 256 KiB、1,000 个时间标记、1,000 列或行、40,000 个终端单元格,且 JSON 结构复杂度受限)。" ], "Add interactive terminal recordings to posts and pages with a block or shortcode.": [ "通过区块或简码在文章和页面中添加可交互的终端录屏。" diff --git a/languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-view.json b/languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-view.json index 24ed6fd..6b949bc 100644 --- a/languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-view.json +++ b/languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-view.json @@ -205,9 +205,6 @@ "Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.": [ "无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。" ], - "The recording is taking too long to load. Check your connection and try again.": [ - "录制文件加载超时。请检查网络连接后重试。" - ], "The local player could not start. Try again, or check that the plugin’s built assets are installed.": [ "本地播放器无法启动。请重试,或检查插件的构建资源是否已安装。" ], @@ -220,14 +217,41 @@ "Interactive terminal recording preview": [ "可交互的终端录屏预览" ], + "This recording exceeds the file size limit.": [ + "该录屏超过文件大小限制。" + ], + "This recording contains a line that exceeds the size limit.": [ + "该录屏包含超出大小限制的行。" + ], + "This recording contains too many events.": [ + "该录屏包含过多事件。" + ], + "This recording contains too many markers.": [ + "该录屏包含过多时间标记。" + ], + "This recording requests terminal dimensions that exceed the supported limits.": [ + "该录屏请求的终端尺寸超出支持范围。" + ], + "This recording requests too many terminal cells.": [ + "该录屏请求的终端单元格过多。" + ], + "This recording is too complex to load safely.": [ + "该录屏结构过于复杂,无法安全加载。" + ], + "The recording is taking too long to load. Check your connection and try again.": [ + "录制文件加载超时。请检查网络连接后重试。" + ], + "This recording contains an invalid or unsupported timestamp.": [ + "该录屏包含无效或不支持的时间戳。" + ], "Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.": [ "无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。" ], "You are not allowed to upload Asciicast files.": [ "你没有上传 Asciicast 文件的权限。" ], - "Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).": [ - "请上传有效的 Asciicast v2/v3 JSONL 或格式化的 v1 .cast 录制文件(最大 32 MiB;v1 最大 2 MiB;最多 100,000 个事件;每行 JSONL最大 256 KiB;列数和行数均不超过 1,000)。" + "Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).": [ + "请上传有效的 Asciicast v2/v3 JSONL 或 v1 .cast 录屏(最大 32 MiB;v1 最大 2 MiB、100,000 个事件、每行 JSONL 最大 256 KiB、1,000 个时间标记、1,000 列或行、40,000 个终端单元格,且 JSON 结构复杂度受限)。" ], "Add interactive terminal recordings to posts and pages with a block or shortcode.": [ "通过区块或简码在文章和页面中添加可交互的终端录屏。" diff --git a/languages/wp-asciiplayer-zh_CN.mo b/languages/wp-asciiplayer-zh_CN.mo index 4eedc4025c9084efc44b67c308d46df6cbd3b89a..5539053b8c4651c90876eecd71f7b4696e4a7ff3 100644 GIT binary patch delta 2431 zcmaLWYiyHM7{Ku}9V!Sb4jpnCdj$gy=Tblj;LrpV4Jare$fD8GzQ7B;j9#{ZgtEc1 zO^0O}V*)~k83HcSL2)dDg+vm(C8%Hc0HQ(qcIA@>6AcNd|EGOBhM=VD@0`G|~r_`GRZdpk4E&9JYO>+wOnh=Z^f2jVr9 zc{i;7ko%PyNq;ypq$cBZrNU|kjeG|DC=0fuoV_3UsDpgTf+!BgPHX%OK1Bap+<=#G z8NTs=QY)|nXX7xUk%O1wy|@l@FoZVFS6gYk#J~>Rg_kfJD@aG&h$FBH$KxJr{0n@T z{+H;*A8`oIrySyPyoRfgSX3#|%fU{xp&tixzN)4n2SiX79!AOR1dhV5t#K2jGQXn) zb{%KoUpNd)Se%QmqU_`3s{q&GB5cHI7)KpP5lwgjjVcSG z;sP9w$1K0WJo>+&Jl5;@2j+1P6L82Qyp=4arXn9z!sPk52q}`wE<=_v|zytU;+8$ME zG5W$Z=F&KWvhg6wAPe$Q`V&#!z$|% zl>Ka!QLd%{nIBeDX^drHHa>?s&cFj$ia%os&g692umUIICbZ*W ztD9q4fwHb0*W!7sQ7#VFl)A~lSGW+*@&F{WJfd2Lg_yciloB^$5q^d*;sun9$Bs(} zSY$Z`bfgH zN7n+z2A!WgMzC1@=UT63c*`Ab!=?HBTF4s+m6iGYLEWVV4UZlOIy_~W#o;?o4*GnW z$KhSC>E*gN7|6{0pNSraf35Dnb7udzR~qiS1%K;&${;5@eV#J6UP)VX`y4JU;8>}< z*WVF@Utbp@6V~W{kKuK=H5aLQ1BQ><^($JsW_|gm3fDi-3F)%m+AfoP-@Z=W?G6;j zUeC$NYVzAkb0!tp?RE;3O1Y@%J6qnABJF8=YV`I+MViCw(pLCFUKgdGw|L7U>+IdVHMzgx%I0eI zuc?Wa)|?)t2Lly4YP7Bv03xZM);$@5fJeW_}L$KRfli zwL@!d@<>N!R%#NVu|r~KEzA1{c-y4jlTC?zTbUQ{{=jV8me^bU>!}8bG}de$sW)p5 zneVkGdwTlTESJ=i(G!WI)kNQWvaYv1YIby+(XMnQ(upM-wwQa4_bs~Hnr+Qy&6Y&# zsdSP|jTMeA$Qr7ZPtuB=jzCaLSGj3T{@C!9%~g}^>FbJjeVQpqRU#Up(y3c|SxbDh znIyHzQ>SV3joGpyb-m2Ly+GEuS=Yi%q%Nw;dI?Om^2x+TDdJr_w2`TIkgim^MrQXX OW~7DtjwSOWS^oeJw2?#r delta 1440 zcmYMzSxA&o6u|L2u32tlYKxYi3W=dM7Fl5?m|3Z~m*5tr5+<0a1eG~GBqOK^iAq{f zP(&7F4T#H>AoLJIg%46;fjKiyFS$S(5z+tD2gx|UyM5=}bMH5AGS-inKL>gAD*m$h z59hzdO?pbrdHgq)<|q2g=VxmZKEEuKNqO(Kk@uE(}ANPs3n5j`diEemJfB0axiSBDvH@ zj!6Dcn;D=Ak_I7^Q$`n1It*g+Fl% zR#1(25kv6?%DeW!$oa3)m|`FX$B6D_P--4S=({K@3x6X;s7%gV-i2c1R8<8^<+aEy zsjC=?7L;|5a32n%ykmBh0^A5L^C2Oezcj)bkO0vrcN4EKNI^-Qj_5Li%6@JBZ^yC=sU?xglmsxKtp)6d(ofx$B--Z%V#*^_p7NaDX(tV5b z^yg3lzT_Tc{uN3gGrC_;;;tgMqKy0`WW(kt8ZxmT<-sD9lc+=qScmfKXhaD(ffTQ% zQP$666n?{0G_u=6n2#mcfrrtF5-*yIufyHgCa*~!jTr{Qxu9HJLfKg=yDG*4l*B_w z3^k5%IE%;8omX5ooQ0C$lx`WyyHOQkE%9vev0e%EGx#?&)-*R?if?GFt#7WW?y(q4 z-7D*>dzOu%)ziju*X-_7P{F#Xd38 z;}IEEwqzT0-oECzKcFR=OmQZYNwbd**~dGWm#L@Su6vzYW?^nl_TOa>wY~e3w5-}R kCLQhl&fa0i%}$m` text } } }, URL }); if (readyState === 'loading') { assert.equal(mounts, 0); diff --git a/src/preview.js b/src/preview.js index 913e9b9..a6f6dff 100644 --- a/src/preview.js +++ b/src/preview.js @@ -4,7 +4,8 @@ import { useRef, useState } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { normalizePlayerOptions, previewHeight } from './options.js'; import { playerAssets, playerForDocument } from './player-bridge.js'; -import { readRecordingSize } from './recording-metadata.js'; +import { loadRecording, validateInitialDimensions } from './recording-loader.js'; +import { recordingErrorMessage } from './recording-errors.js'; export default function Preview( { source, attributes, attempt, onRetry, onRecordingSize } ) { const [ status, setStatus ] = useState( 'loading' ); @@ -42,19 +43,26 @@ export default function Preview( { source, attributes, attempt, onRetry, onRecor canvasWindow.clearTimeout( deadline ); setStatus( 'ready' ); }; + deadline = canvasWindow.setTimeout( () => fail( recordingErrorMessage( { code: 'timeout' } ) ), 30000 ); playerForDocument( container.ownerDocument, playerAssets() ).then( ( api ) => { - if ( disposed ) return; + if ( disposed || failed ) return; + try { + validateInitialDimensions( JSON.parse( optionsJSON ) ); + } catch ( error ) { + fail( recordingErrorMessage( error ) ); + return; + } player = api.create( { - data: async () => { - // The parser checks instanceof Response in the canvas realm. - // Reuse this one request for playback and original-size hints. - const response = await canvasWindow.fetch( source, { signal: request.signal } ); - if ( ! response.ok ) throw new Error( `Recording request failed: ${ response.status }` ); - readRecordingSize( response ).then( ( size ) => { - if ( ! failed ) reportSize( size ); - } ); - return response; - }, + data: () => loadRecording( source, { + fetchImpl: canvasWindow.fetch.bind( canvasWindow ), + signal: request.signal, + options: JSON.parse( optionsJSON ), + onMetadata: ( size ) => { if ( ! failed ) reportSize( size ); }, + } ).catch( ( error ) => { + const message = recordingErrorMessage( error ); + if ( message ) fail( message ); + throw error; + } ), }, container, JSON.parse( optionsJSON ) ); player.addEventListener( 'error', () => fail( __( 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.', 'wp-asciiplayer' ) ) ); player.addEventListener( 'playing', ready ); @@ -65,7 +73,6 @@ export default function Preview( { source, attributes, attempt, onRetry, onRecor if ( typeof duration === 'number' && Number.isFinite( duration ) ) ready(); }; readinessTimer = canvasWindow.setInterval( checkReady, 150 ); - deadline = canvasWindow.setTimeout( () => fail( __( 'The recording is taking too long to load. Check your connection and try again.', 'wp-asciiplayer' ) ), 30000 ); checkReady(); } ).catch( () => fail( __( 'The local player could not start. Try again, or check that the plugin’s built assets are installed.', 'wp-asciiplayer' ) ) ); return () => { diff --git a/src/recording-errors.js b/src/recording-errors.js new file mode 100644 index 0000000..c5e86f6 --- /dev/null +++ b/src/recording-errors.js @@ -0,0 +1,22 @@ +import { __ } from '@wordpress/i18n'; + +/** Never expose remote content or raw exception messages in a recording notice. */ +export function recordingErrorMessage( error, { frontend = false } = {} ) { + switch ( error?.code ) { + case 'aborted': return ''; + case 'bytes': return __( 'This recording exceeds the file size limit.', 'wp-asciiplayer' ); + case 'line': return __( 'This recording contains a line that exceeds the size limit.', 'wp-asciiplayer' ); + case 'events': return __( 'This recording contains too many events.', 'wp-asciiplayer' ); + case 'markers': return __( 'This recording contains too many markers.', 'wp-asciiplayer' ); + case 'dimensions': return __( 'This recording requests terminal dimensions that exceed the supported limits.', 'wp-asciiplayer' ); + case 'cells': return __( 'This recording requests too many terminal cells.', 'wp-asciiplayer' ); + case 'complexity': return __( 'This recording is too complex to load safely.', 'wp-asciiplayer' ); + case 'timeout': return __( 'The recording is taking too long to load. Check your connection and try again.', 'wp-asciiplayer' ); + case 'time': return __( 'This recording contains an invalid or unsupported timestamp.', 'wp-asciiplayer' ); + // Invalid data, network/CORS failures, missing stream support, and policy + // configuration errors retain the existing localized fallback guidance. + default: return frontend + ? __( 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.', 'wp-asciiplayer' ) + : __( 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.', 'wp-asciiplayer' ); + } +} diff --git a/src/recording-loader.js b/src/recording-loader.js new file mode 100644 index 0000000..d63b3aa --- /dev/null +++ b/src/recording-loader.js @@ -0,0 +1,353 @@ +/** Resource policy for untrusted recordings, before handing data to the player. */ +export const DEFAULT_LIMITS = Object.freeze( { + bytes: 32 * 1024 * 1024, v1Bytes: 2 * 1024 * 1024, lineBytes: 256 * 1024, + depth: 15, containers: 100016, tokens: 400000, lineTokens: 20000, + events: 100000, lines: 100000, markers: 1000, dimension: 1000, cells: 40000, + // Web timers take a signed 32-bit millisecond delay (~24.85 days). This + // horizon also keeps upstream's 16.67 ms output batches numerically distinct. + timelineMs: 2147483647, + totalTimeoutMs: 30000, idleTimeoutMs: 10000, +} ); + +export class RecordingLoadError extends Error { + constructor( code ) { + super( `Recording load failed: ${ code }` ); + this.name = 'RecordingLoadError'; + this.code = code; + } +} +const fail = ( code ) => { throw new RecordingLoadError( code ); }; +const boundedTime = ( value, maxMs ) => typeof value === 'number' && value >= 0 && value * 1000 <= maxMs; +const object = ( value ) => value !== null && typeof value === 'object' && ! Array.isArray( value ); + +/** Guard the terminal allocated by api.create before its data loader runs. */ +export function validateInitialDimensions( options = {}, limits = {} ) { + const dimension = limits.dimension ?? DEFAULT_LIMITS.dimension; + const cells = limits.cells ?? DEFAULT_LIMITS.cells; + if ( ! Number.isSafeInteger( dimension ) || dimension <= 0 || ! Number.isSafeInteger( cells ) || cells <= 0 ) fail( 'policy' ); + const cols = options.cols ?? 80; + const rows = options.rows ?? 24; + if ( ! Number.isSafeInteger( cols ) || cols < 1 || cols > dimension || ! Number.isSafeInteger( rows ) || rows < 1 || rows > dimension ) fail( 'dimensions' ); + if ( cols * rows > cells ) fail( 'cells' ); +} + +/** Count allocation-driving JSON tokens before JSON.parse allocates containers. */ +function parseBounded( text, limits, v1 = false ) { + let quoted = false; + let escaped = false; + let primitive = false; + let depth = 0; + let tokens = 0; + let containers = 0; + const tokenLimit = v1 ? limits.tokens : limits.lineTokens; + for ( const character of text ) { + if ( quoted ) { + if ( escaped ) escaped = false; + else if ( character === '\\' ) escaped = true; + else if ( character === '"' ) quoted = false; + continue; + } + if ( character === '"' ) { + quoted = true; + primitive = false; + tokens++; + } else if ( character === '[' || character === '{' ) { + primitive = false; + if ( ++depth > limits.depth || ++containers > limits.containers ) fail( 'complexity' ); + } else if ( character === ']' || character === '}' ) { + primitive = false; + if ( --depth < 0 ) fail( 'invalid' ); + } else if ( character === ',' || character === ':' || /\s/.test( character ) ) { + primitive = false; + } else if ( ! primitive ) { + primitive = true; + tokens++; + } + if ( tokens > tokenLimit ) fail( 'complexity' ); + } + if ( quoted || depth !== 0 ) fail( 'invalid' ); + try { return JSON.parse( text ); } catch { fail( 'invalid' ); } +} + +/** Inspect version and structural completeness without allocating a JSON tree. */ +function inspectFirstLine( text ) { + let depth = 0; + let quoted = false; + let escaped = false; + let start = 0; + let version; + function member( end ) { + let cursor = start; + while ( cursor < end && /\s/.test( text[ cursor ] ) ) cursor++; + if ( text[ cursor ] !== '"' ) return; + const keyStart = cursor++; + let escape = false; + while ( cursor < end ) { + const character = text[ cursor++ ]; + if ( escape ) escape = false; + else if ( character === '\\' ) escape = true; + else if ( character === '"' ) break; + } + // "version" has seven characters, at most six JSON bytes each. + if ( cursor - keyStart > 44 ) return; + let key; + try { key = JSON.parse( text.slice( keyStart, cursor ) ); } catch { return; } + if ( key !== 'version' ) return; + version = undefined; + while ( cursor < end && /\s/.test( text[ cursor ] ) ) cursor++; + if ( text[ cursor++ ] !== ':' ) return; + while ( cursor < end && /\s/.test( text[ cursor ] ) ) cursor++; + while ( end > cursor && /\s/.test( text[ end - 1 ] ) ) end--; + // Numeric conversion allocates no JSON containers; the complete parser + // will still reject malformed numeric spellings or nonnumeric values. + version = Number( text.slice( cursor, end ) ); + } + for ( let index = 0; index < text.length; index++ ) { + const character = text[ index ]; + if ( quoted ) { + if ( escaped ) escaped = false; + else if ( character === '\\' ) escaped = true; + else if ( character === '"' ) quoted = false; + continue; + } + if ( character === '"' ) quoted = true; + else if ( character === '[' || character === '{' ) { + if ( ++depth === 1 ) start = index + 1; + } else if ( character === ']' || character === '}' ) { + if ( depth === 1 ) member( index ); + depth--; + } else if ( character === ',' && depth === 1 ) { + member( index ); + start = index + 1; + } + } + return { version, incomplete: depth > 0 || quoted }; +} + +/** + * Fetch once, count actual decoded-body bytes, and validate everything before + * returning an upstream-compatible v1 object or v2/v3 [header, ...events] array. + * limits are intended for policy configuration/tests, never recording metadata. + */ +export async function loadRecording( source, { fetchImpl = globalThis.fetch, signal, onMetadata, options = {}, limits = {} } = {} ) { + const policy = { ...DEFAULT_LIMITS }; + for ( const key of Object.keys( policy ) ) { + if ( Object.hasOwn( limits, key ) ) { + if ( ! Number.isSafeInteger( limits[ key ] ) || limits[ key ] <= 0 ) fail( 'policy' ); + policy[ key ] = limits[ key ]; + } + } + // Policy overrides may lower this safety ceiling, but cannot expand the + // platform timer range. Callers supply already-normalized player options. + if ( policy.timelineMs > DEFAULT_LIMITS.timelineMs ) fail( 'policy' ); + const speed = options.speed ?? 1; + if ( typeof speed !== 'number' || ! Number.isFinite( speed ) || speed < 0.01 || speed > 100 ) fail( 'time' ); + for ( const key of [ 'startAt', 'idleTimeLimit' ] ) { + if ( options[ key ] !== undefined && ! boundedTime( options[ key ], policy.timelineMs ) ) fail( 'time' ); + } + if ( typeof options.poster === 'string' && options.poster.startsWith( 'npt:' ) ) { + // Match upstream parseNpt's order of arithmetic for normalized timecodes. + const posterTime = options.poster.slice( 4 ).split( ':' ).reverse().map( parseFloat ).reduce( ( sum, part, index ) => sum + part * 60 ** index, 0 ); + if ( ! boundedTime( posterTime, policy.timelineMs ) ) fail( 'time' ); + } + function checkTimeline( milliseconds ) { + // Core passes (target - elapsed) / speed directly to setTimeout. Bound + // the whole horizon conservatively: adjacent gaps alone are insufficient + // because output batching can consume future events ahead of wall time. + if ( ! Number.isFinite( milliseconds ) || milliseconds > policy.timelineMs || milliseconds / speed > DEFAULT_LIMITS.timelineMs ) fail( 'time' ); + } + const controller = new AbortController(); + let reader; + let totalTimer; + let rejectStopped; + let stoppedError; + const deadline = Date.now() + policy.totalTimeoutMs; + const stopped = new Promise( ( _, reject ) => { rejectStopped = reject; } ); + // A synchronous validation failure can precede the first Promise.race. + stopped.catch( () => {} ); + const stop = ( code ) => { + if ( stoppedError ) return; + stoppedError = new RecordingLoadError( code ); + rejectStopped( stoppedError ); + controller.abort(); + }; + const abort = () => stop( 'aborted' ); + async function waitFor( operation ) { + // Also enforce elapsed time when synthetic/cached streams resolve reads in + // microtasks without giving browser timer callbacks a turn. + if ( Date.now() >= deadline ) stop( 'timeout' ); + if ( stoppedError ) { + Promise.resolve( operation ).catch( () => {} ); + throw stoppedError; + } + let idleTimer; + try { + idleTimer = setTimeout( () => stop( 'timeout' ), policy.idleTimeoutMs ); + return await Promise.race( [ operation, stopped ] ); + } finally { clearTimeout( idleTimer ); } + } + const dimension = ( value, zero = false ) => Number.isSafeInteger( value ) && value >= ( zero ? 0 : 1 ) && value <= policy.dimension; + function checkSize( cols, rows, zero = false ) { + if ( ! dimension( cols, zero ) || ! dimension( rows, zero ) ) fail( 'dimensions' ); + // Upstream applies each override independently, including every resize. + const effectiveCols = options.cols ?? ( cols || 80 ); + const effectiveRows = options.rows ?? ( rows || 24 ); + if ( ! dimension( effectiveCols ) || ! dimension( effectiveRows ) ) fail( 'dimensions' ); + if ( ( cols || 80 ) * ( rows || 24 ) > policy.cells || effectiveCols * effectiveRows > policy.cells ) fail( 'cells' ); + } + let bytes = 0; + let mode = 'first'; + let header; + let timeMs = 0; + let lines = 0; + let markerCount = Array.isArray( options.markers ) ? options.markers.length : 0; + const events = []; + const v1Parts = []; + let lineParts = []; + let lineBytes = 0; + const decoder = new TextDecoder( 'utf-8', { fatal: true, ignoreBOM: true } ); + function checkHeader( value ) { + if ( ! object( value ) || ! [ 1, 2, 3 ].includes( value.version ) ) fail( 'invalid' ); + if ( value.version === 3 ) { + if ( ! object( value.term ) ) fail( 'dimensions' ); + checkSize( value.term.cols, value.term.rows, true ); + } else checkSize( value.width, value.height, true ); + for ( const key of [ 'duration', 'idle_time_limit' ] ) { + if ( Object.hasOwn( value, key ) && ! boundedTime( value[ key ], policy.timelineMs ) ) fail( 'time' ); + } + } + function acceptLine( text, size, newline ) { + if ( mode === 'first' ) { + // Response.text strips only the document's initial UTF-8 BOM. Keep + // later BOMs intact so resetting at LF cannot turn ignored lines into events. + if ( text.charCodeAt( 0 ) === 0xfeff ) text = text.slice( 1 ); + // Pretty-printed v1 is the only supported multiline JSON document. + // A syntax-incomplete first line is collected under the smaller v1 cap. + const first = inspectFirstLine( text ); + // A v1 document may put version after a long stdout/title member. + // Incomplete first lines therefore use the whole-document v1 budget. + if ( first.version === 1 || first.incomplete ) { + mode = 'v1'; + v1Parts.push( text, newline ? '\n' : '' ); + return; + } + if ( size + Number( newline ) > policy.lineBytes ) fail( 'line' ); + try { header = parseBounded( text, policy ); } catch ( error ) { + if ( error.code !== 'invalid' ) throw error; + mode = 'v1'; + v1Parts.push( text, newline ? '\n' : '' ); + return; + } + if ( header?.version === 1 ) { + mode = 'v1'; + v1Parts.push( text, newline ? '\n' : '' ); + return; + } + if ( size + Number( newline ) > policy.lineBytes ) fail( 'line' ); + checkHeader( header ); + mode = 'jsonl'; + return; + } + if ( size + Number( newline ) > policy.lineBytes ) fail( 'line' ); + // Match 3.17's JSONL filter: blank, comment, and other non-event lines + // (including indented arrays) are ignored, but still byte/line bounded. + if ( ++lines > policy.lines ) fail( 'events' ); + if ( text[ 0 ] !== '[' ) return; + if ( events.length >= policy.events ) fail( 'events' ); + const event = parseBounded( text, policy ); + if ( ! Array.isArray( event ) || event.length !== 3 || typeof event[ 1 ] !== 'string' || ! event[ 1 ] || typeof event[ 2 ] !== 'string' ) fail( 'invalid' ); + if ( ! boundedTime( event[ 0 ], policy.timelineMs ) ) fail( 'time' ); + const eventMs = event[ 0 ] * 1000; + if ( header.version === 2 && events.length && event[ 0 ] < events[ events.length - 1 ][ 0 ] ) fail( 'time' ); + // v1/v3 upstream converts each interval before adding, which can round + // differently from summing seconds and multiplying the result by 1000. + timeMs = header.version === 3 ? timeMs + eventMs : eventMs; + checkTimeline( timeMs ); + if ( event[ 1 ] === 'r' ) { + const match = /^([1-9][0-9]{0,3})x([1-9][0-9]{0,3})$/.exec( event[ 2 ] ); + if ( ! match ) fail( 'dimensions' ); + checkSize( Number( match[ 1 ] ), Number( match[ 2 ] ) ); + } + if ( event[ 1 ] === 'm' && ++markerCount > policy.markers ) fail( 'markers' ); + events.push( event ); + } + try { + if ( markerCount > policy.markers ) fail( 'markers' ); + if ( signal?.aborted ) fail( 'aborted' ); + signal?.addEventListener( 'abort', abort, { once: true } ); + totalTimer = setTimeout( () => stop( 'timeout' ), policy.totalTimeoutMs ); + const response = await waitFor( Promise.resolve().then( () => fetchImpl( source, { signal: controller.signal, credentials: 'same-origin' } ) ) ); + if ( ! response.ok ) fail( 'network' ); + if ( ! response.body?.getReader ) fail( 'stream' ); + reader = response.body.getReader(); + while ( true ) { + const { value, done } = await waitFor( reader.read() ); + if ( done ) break; + bytes += value.byteLength; + if ( bytes > policy.bytes || ( mode === 'v1' && bytes > policy.v1Bytes ) ) fail( 'bytes' ); + if ( mode === 'v1' ) { + v1Parts.push( decoder.decode( value, { stream: true } ) ); + continue; + } + let start = 0; + for ( let index = 0; index <= value.length; index++ ) { + if ( index !== value.length && value[ index ] !== 10 ) continue; + const part = value.subarray( start, index ); + lineBytes += part.byteLength; + if ( lineBytes > ( mode === 'first' ? policy.v1Bytes : policy.lineBytes ) ) fail( 'line' ); + if ( part.byteLength ) lineParts.push( decoder.decode( part, { stream: true } ) ); + if ( index < value.length ) { + lineParts.push( decoder.decode() ); + acceptLine( lineParts.join( '' ), lineBytes, true ); + lineParts = []; + lineBytes = 0; + start = index + 1; + if ( mode === 'v1' ) { + if ( bytes > policy.v1Bytes ) fail( 'bytes' ); + v1Parts.push( decoder.decode( value.subarray( start ), { stream: true } ) ); + break; + } + } + } + } + const tail = decoder.decode(); + if ( mode === 'v1' ) v1Parts.push( tail ); + else { + lineParts.push( tail ); + if ( lineBytes || mode === 'first' ) acceptLine( lineParts.join( '' ), lineBytes, false ); + } + let result; + if ( mode === 'v1' ) { + if ( bytes > policy.v1Bytes ) fail( 'bytes' ); + header = parseBounded( v1Parts.join( '' ), policy, true ); + checkHeader( header ); + if ( header.version !== 1 || ! Array.isArray( header.stdout ) ) fail( 'invalid' ); + if ( header.stdout.length > policy.events ) fail( 'events' ); + for ( const event of header.stdout ) { + if ( ! Array.isArray( event ) || event.length !== 2 || typeof event[ 1 ] !== 'string' ) fail( 'invalid' ); + if ( ! boundedTime( event[ 0 ], policy.timelineMs ) ) fail( 'time' ); + timeMs += event[ 0 ] * 1000; + checkTimeline( timeMs ); + } + result = header; + } else result = [ header, ...events ]; + const cols = header.version === 3 ? header.term.cols : header.width; + const rows = header.version === 3 ? header.term.rows : header.height; + if ( Date.now() >= deadline ) stop( 'timeout' ); + if ( stoppedError ) throw stoppedError; + onMetadata?.( cols > 0 && rows > 0 ? { cols, rows } : null ); + return result; + } catch ( error ) { + controller.abort(); + // Cancellation can itself stall (especially custom/teed streams). Never + // await it; the public promise must settle promptly on abort/timeout. + try { Promise.resolve( reader?.cancel() ).catch( () => {} ); } catch { /* Already closed. */ } + if ( stoppedError ) throw stoppedError; + if ( error instanceof RecordingLoadError ) throw error; + fail( error instanceof TypeError && reader ? 'invalid' : 'network' ); + } finally { + clearTimeout( totalTimer ); + signal?.removeEventListener( 'abort', abort ); + try { reader?.releaseLock(); } catch { /* A rejected read may still be pending. */ } + } +} diff --git a/src/view.js b/src/view.js index 21a987f..f4da5d2 100644 --- a/src/view.js +++ b/src/view.js @@ -1,23 +1,52 @@ -import { __ } from '@wordpress/i18n'; import { normalizePlayerOptions, normalizeSource } from './options.js'; +import { loadRecording, validateInitialDimensions } from './recording-loader.js'; +import { recordingErrorMessage } from './recording-errors.js'; const instances = new WeakMap(); +const documents = new WeakMap(); -function showError( container ) { +function showError( container, error ) { + const message = recordingErrorMessage( error, { frontend: true } ); + if ( ! message ) return; container.dataset.apStatus = 'error'; if ( container.querySelector( '.asciiplayer-error' ) ) return; const notice = container.ownerDocument.createElement( 'p' ); notice.className = 'asciiplayer-error'; notice.setAttribute( 'role', 'status' ); - notice.textContent = __( 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.', 'wp-asciiplayer' ); + notice.textContent = message; container.appendChild( notice ); } +/** One observer per document, visiting only owned players on removals. */ +function watchRemoval( container, dispose ) { + const document = container.ownerDocument; + let state = documents.get( document ); + if ( ! state ) { + const entries = new Map(); + const observer = new document.defaultView.MutationObserver( ( records ) => { + if ( ! records.some( ( record ) => record.removedNodes.length ) ) return; + for ( const [ node, cleanup ] of entries ) if ( ! node.isConnected ) cleanup(); + } ); + observer.observe( document.documentElement, { childList: true, subtree: true } ); + state = { entries, observer }; + documents.set( document, state ); + } + state.entries.set( container, dispose ); + return () => { + state.entries.delete( container ); + if ( ! state.entries.size ) { + state.observer.disconnect(); + documents.delete( document ); + } + }; +} + /** One explicit instance per front-end container; never scan an editor canvas. */ export function mountPlayers( root = document ) { const ownerDocument = root.ownerDocument || root; if ( ownerDocument.body?.classList.contains( 'wp-admin' ) || ownerDocument.querySelector( '.editor-styles-wrapper, .block-editor-block-list__layout' ) ) return; - const api = ownerDocument.defaultView?.AsciinemaPlayer; + const canvasWindow = ownerDocument.defaultView; + const api = canvasWindow?.AsciinemaPlayer; if ( typeof api?.create !== 'function' ) return; root.querySelectorAll( '.asciiplayer-container' ).forEach( ( container ) => { if ( instances.has( container ) ) return; @@ -25,8 +54,7 @@ export function mountPlayers( root = document ) { if ( ! source ) return showError( container ); let options; try { - // New markup uses escaped plain JSON. The legacy adapter used URL-encoded - // JSON; accepting it also lets cached old pages use the new local player. + // Accept both current plain JSON and the legacy URL-encoded options. const serialized = container.dataset.apOptions; options = serialized ? JSON.parse( serialized ) : JSON.parse( decodeURIComponent( container.dataset.apOpts || '{}' ) ); if ( ! options || Array.isArray( options ) || typeof options !== 'object' ) throw new Error( 'Invalid player options.' ); @@ -35,26 +63,59 @@ export function mountPlayers( root = document ) { showError( container ); return; } + const request = new canvasWindow.AbortController(); + let disposed = false; + let failed = false; + let player; + let timer; + let unwatch; + const dispose = () => { + if ( disposed ) return; + disposed = true; + request.abort(); + canvasWindow.clearInterval( timer ); + unwatch?.(); + player?.dispose(); + instances.delete( container ); + }; + const fail = ( error ) => { + if ( disposed || failed || ! recordingErrorMessage( error ) ) return; + failed = true; + request.abort(); + canvasWindow.clearInterval( timer ); + showError( container, error ); + }; + const ready = () => { + if ( ! disposed && ! failed ) { + container.dataset.apStatus = 'ready'; + canvasWindow.clearInterval( timer ); + } + }; try { + validateInitialDimensions( options ); container.dataset.apStatus = 'loading'; - const player = api.create( source, container, options ); - instances.set( container, player ); - player.addEventListener( 'error', () => showError( container ) ); - player.addEventListener( 'playing', () => { container.dataset.apStatus = 'ready'; } ); - // The upstream player owns loading/error/controls; readiness is confirmed - // by its parsed duration rather than merely by a mounted DOM wrapper. + // The player calls data lazily: preload=false causes no eager request. + player = api.create( { data: () => loadRecording( source, { + fetchImpl: canvasWindow.fetch.bind( canvasWindow ), signal: request.signal, options, + } ).catch( ( error ) => { fail( error ); throw error; } ) }, container, options ); + instances.set( container, { player, dispose } ); + unwatch = watchRemoval( container, dispose ); + player.addEventListener( 'error', () => fail() ); + player.addEventListener( 'playing', ready ); if ( options.preload || options.autoPlay || options.poster?.startsWith( 'npt:' ) ) { let ticks = 0; - const timer = ownerDocument.defaultView.setInterval( () => { + timer = canvasWindow.setInterval( () => { + if ( ! container.isConnected ) return dispose(); const duration = player.getDuration(); - if ( typeof duration === 'number' && Number.isFinite( duration ) ) container.dataset.apStatus = 'ready'; - if ( ! container.isConnected || container.dataset.apStatus !== 'loading' || ++ticks > 200 ) ownerDocument.defaultView.clearInterval( timer ); + if ( typeof duration === 'number' && Number.isFinite( duration ) ) ready(); + if ( ++ticks > 200 ) canvasWindow.clearInterval( timer ); }, 150 ); } else { container.dataset.apStatus = 'idle'; } - } catch { - showError( container ); + } catch ( error ) { + fail( error ); + dispose(); } } ); } diff --git a/tests/e2e/bounded-recording.spec.js b/tests/e2e/bounded-recording.spec.js new file mode 100644 index 0000000..47e5384 --- /dev/null +++ b/tests/e2e/bounded-recording.spec.js @@ -0,0 +1,341 @@ +import { test, expect } from '@playwright/test'; +import { DEFAULT_LIMITS } from '../../src/recording-loader.js'; + +const blockName = 'lamgc/asciiplayer'; +const fixtureRoot = '/wp-content/uploads/asciiplayer-fixtures'; +const messages = { + markers: 'This recording contains too many markers.', + dimensions: 'This recording requests terminal dimensions that exceed the supported limits.', + cells: 'This recording requests too many terminal cells.', +}; + +async function openEditor(page) { + await page.goto('/wp-login.php'); + await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin'); + await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password'); + await page.locator('#wp-submit').click(); + await expect(page).toHaveURL(/\/wp-admin\//); + await page.goto('/wp-admin/post-new.php'); + await page.waitForFunction((name) => Boolean( + window.wp?.blocks?.getBlockType(name) && + window.wp?.data?.select('core/editor')?.getCurrentPostId() + ), blockName); + await page.evaluate(() => { + for (const scope of ['core/edit-post', 'core/editor']) { + window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false); + } + }); + await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible(); +} + +function canvas(page) { + return page.frameLocator('iframe[name="editor-canvas"]'); +} + +async function insertPlayer(page, attributes = {}) { + const id = await page.evaluate(({ name, attrs }) => { + const block = window.wp.blocks.createBlock(name, attrs); + window.wp.data.dispatch('core/block-editor').insertBlocks(block); + window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId); + return block.clientId; + }, { name: blockName, attrs: attributes }); + return { id, block: canvas(page).locator(`[data-block="${id}"]`) }; +} + +async function removePlayer(page, id) { + await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), id); + await expect(canvas(page).locator(`[data-block="${id}"]`)).toHaveCount(0); +} + +async function changeSource(block, source) { + await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(source); + await block.getByRole('button', { name: 'Apply URL', exact: true }).click(); +} + +async function readyPreview(block) { + await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready'); + await expect(block.locator('.ap-wrapper')).toHaveCount(1); + await expect(block.locator('.ap-term')).toBeVisible(); +} + +async function expectGrid(block, cols, rows) { + await expect.poll(() => block.locator('.ap-term').evaluate((terminal) => ({ + cols: Number(terminal.style.getPropertyValue('--term-cols')), + rows: Number(terminal.style.getPropertyValue('--term-rows')), + }))).toEqual({ cols, rows }); +} + +async function dimensions(page) { + await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block')); + const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true }); + const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true }); + if (!await columns.isVisible()) { + await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click(); + } + await expect(columns).toBeVisible(); + return { columns, rows }; +} + +async function expectNativeSize(page, cols, rows) { + const controls = await dimensions(page); + await expect(controls.columns).toHaveAttribute('placeholder', cols === undefined ? 'From recording' : String(cols)); + await expect(controls.rows).toHaveAttribute('placeholder', rows === undefined ? 'From recording' : String(rows)); + return controls; +} + +function recording(version = 2, { cols = 64, rows = 12, label = 'bounded', events } = {}) { + const output = (part) => `\u001b[2J\u001b[H${part} ${label}\r\n`; + if (version === 1) { + return JSON.stringify({ version, width: cols, height: rows, duration: 12, stdout: [ + [0, output('START')], [8, output('SEEK')], [4, output('END')], + ] }, null, 2); + } + const header = version === 3 ? { version, term: { cols, rows } } : { version, width: cols, height: rows }; + const frames = events || [[0, 'o', output('START')], [8, 'o', output('SEEK')], [version === 3 ? 4 : 12, 'o', output('END')]]; + // The bundled parser permits blank/comment lines after either JSONL header. + // Routing the original bytes tests compatibility through the real loader. + return `${JSON.stringify(header)}\n\n# An ignored comment before output.\n${frames.map(JSON.stringify).join('\n\n# Between events.\n')}\n`; +} + +async function routeRecording(page, name, body) { + const source = new URL(`${fixtureRoot}/bounded-${name}.cast`, page.url()).href; + let requests = 0; + await page.route(source, async (route) => { + requests += 1; + await route.fulfill({ contentType: 'text/plain; charset=utf-8', body }); + }); + return { source, requests: () => requests }; +} + +async function playAndSeek(block, label) { + await block.locator('.ap-overlay-start .ap-play-button').click(); + await expect(block.locator('.ap-term-text')).toContainText(`START ${label}`); + const playback = block.locator('.ap-playback-button'); + await expect(playback).toHaveAttribute('aria-label', 'Pause'); + await playback.click(); + await expect(playback).toHaveAttribute('aria-label', 'Play'); + // The real player's numeric shortcuts seek to 80% and then back to 0%. + // The second frame is eight seconds in, so this cannot pass by just playing. + await block.locator('.ap-term-text').press('8'); + await expect(block.locator('.ap-term-text')).toContainText(`SEEK ${label}`); + await expect(block.locator('.ap-term-text')).not.toContainText(`START ${label}`); + await block.locator('.ap-term-text').press('0'); + await expect(block.locator('.ap-term-text')).toContainText(`START ${label}`); + await expect(block.locator('.ap-term-text')).not.toContainText(`SEEK ${label}`); +} + +for (const version of [1, 2, 3]) { + test(`bounded v${version} recordings play and seek in the editor iframe, including zero header dimensions`, async ({ page }) => { + await openEditor(page); + for (const zero of [false, true]) { + const label = `v${version}-${zero ? 'zero' : 'native'}`; + const routed = await routeRecording(page, label, recording(version, { + cols: zero ? 0 : 64, rows: zero ? 0 : 12, label, + })); + const { id, block } = await insertPlayer(page, { source: routed.source, controls: 'always' }); + await readyPreview(block); + await expectGrid(block, zero ? 80 : 64, zero ? 24 : 12); + const controls = await expectNativeSize(page, zero ? undefined : 64, zero ? undefined : 12); + await expect(controls.columns).toHaveValue(''); + await expect(controls.rows).toHaveValue(''); + await playAndSeek(block, label); + // Native-size hints and seeks must reuse the same validated fetch. + expect(routed.requests()).toBe(1); + const attributes = await page.evaluate((clientId) => window.wp.data.select('core/block-editor').getBlockAttributes(clientId), id); + expect(attributes.cols).toBeUndefined(); + expect(attributes.rows).toBeUndefined(); + await removePlayer(page, id); + } + }); +} + +const firstUnsafeRows = Math.floor(DEFAULT_LIMITS.cells / DEFAULT_LIMITS.dimension) + 1; +const rejectedRecordings = [ + { + name: 'marker count limit', code: 'markers', + body: () => recording(2, { events: Array.from({ length: DEFAULT_LIMITS.markers + 1 }, (_, index) => [index / 1000, 'm', 'marker']) }), + }, + { + name: 'resize axis limit', code: 'dimensions', + body: () => recording(2, { events: [[0, 'o', 'safe'], [1, 'r', `${DEFAULT_LIMITS.dimension + 1}x12`]] }), + }, + { + name: 'resize cell limit', code: 'cells', + body: () => recording(3, { events: [[0, 'o', 'safe'], [1, 'r', `${DEFAULT_LIMITS.dimension}x${firstUnsafeRows}`]] }), + }, + { + name: 'initial terminal dimensions before player creation', code: 'cells', noFetch: true, + attributes: { cols: DEFAULT_LIMITS.dimension, rows: firstUnsafeRows }, + body: () => recording(), + }, + { + name: 'effective resize dimensions with one overridden axis', code: 'cells', + attributes: { cols: DEFAULT_LIMITS.dimension }, + body: () => recording(2, { events: [[0, 'o', 'safe'], [1, 'r', `64x${firstUnsafeRows}`]] }), + }, +]; + +for (const entry of rejectedRecordings) { + test(`bounded preview rejects ${entry.name} with a useful error and recovers`, async ({ page }) => { + await openEditor(page); + const rejected = await routeRecording(page, `reject-${entry.code}`, entry.body()); + const valid = await routeRecording(page, 'recovery', recording(2, { label: 'recovered' })); + const { id, block } = await insertPlayer(page, { source: rejected.source, ...entry.attributes }); + await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error'); + await expect(block.locator('.components-notice')).toContainText(messages[entry.code]); + await expect(block.getByRole('button', { name: 'Retry preview', exact: true })).toBeVisible(); + await expectNativeSize(page); + expect(rejected.requests()).toBe(entry.noFetch ? 0 : 1); + if (entry.noFetch) await expect(block.locator('.ap-wrapper')).toHaveCount(0); + // Remove intentional overrides while changing source in one store update, + // so recovery cannot fail for the previous effective-size violation. + await page.evaluate(({ clientId, source }) => window.wp.data.dispatch('core/block-editor').updateBlockAttributes(clientId, { + source, cols: undefined, rows: undefined, + }), { clientId: id, source: valid.source }); + await readyPreview(block); + await expect(block.locator('.components-notice')).toHaveCount(0); + await expectNativeSize(page, 64, 12); + await expectGrid(block, 64, 12); + await playAndSeek(block, 'recovered'); + expect(valid.requests()).toBe(1); + }); +} + +test('bounded playback preserves independent dimension overrides across recorded resizes', async ({ page }) => { + await openEditor(page); + const routed = await routeRecording(page, 'safe-overrides', recording(2, { events: [ + [0, 'o', 'Original terminal\r\n'], [8, 'r', '100x30'], [8, 'o', 'Resized terminal\r\n'], [12, 'o', 'Finished\r\n'], + ] })); + for (const rows of [undefined, 20]) { + const { id, block } = await insertPlayer(page, { source: routed.source, cols: 80, rows, controls: 'always' }); + await readyPreview(block); + await expectGrid(block, 80, rows || 12); + await expectNativeSize(page, 64, 12); + await block.locator('.ap-overlay-start .ap-play-button').click(); + await expect(block.locator('.ap-term-text')).toContainText('Original terminal'); + await block.locator('.ap-playback-button').click(); + await block.locator('.ap-term-text').press('8'); + await expect(block.locator('.ap-term-text')).toContainText('Resized terminal'); + await expectGrid(block, 80, rows || 30); + await expectNativeSize(page, 64, 12); + await removePlayer(page, id); + } + expect(routed.requests()).toBe(2); +}); + +function deferred() { + let release; + const promise = new Promise((resolve) => { release = resolve; }); + return { promise, release }; +} + +async function observeNativeFetch(page) { + await canvas(page).locator('body').evaluate((body) => { + const window = body.ownerDocument.defaultView; + const fetch = window.fetch; + window.__boundedFetches = []; + // Observation only: retain the actual browser fetch, Response/stream, + // player, parser, and AbortController. No player API is mocked. + window.fetch = function (source, options) { + const entry = { source: String(source), aborted: Boolean(options?.signal?.aborted) }; + window.__boundedFetches.push(entry); + options?.signal?.addEventListener('abort', () => { entry.aborted = true; }, { once: true }); + return fetch.call(this, source, options); + }; + }); +} + +async function expectFetchAborted(page, source) { + await expect.poll(() => canvas(page).locator('body').evaluate((body, url) => + body.ownerDocument.defaultView.__boundedFetches?.find((entry) => entry.source === url)?.aborted, source + )).toBe(true); +} + +for (const action of ['change URL', 'unmount block']) { + test(`${action} aborts an in-flight bounded fetch and ignores its delayed result`, async ({ page }) => { + await openEditor(page); + await observeNativeFetch(page); + const pageErrors = []; + page.on('pageerror', (error) => pageErrors.push(error.message)); + const oldSource = new URL(`${fixtureRoot}/bounded-delayed.cast`, page.url()).href; + const current = await routeRecording(page, 'current', recording(2, { label: 'current' })); + const gate = deferred(); + let requested = false; + let settled = false; + await page.route(oldSource, async (route) => { + requested = true; + await gate.promise; + await route.fulfill({ contentType: 'text/plain', body: recording(2, { cols: 120, rows: 30, label: 'stale' }) }).catch(() => {}); + settled = true; + }); + try { + const old = await insertPlayer(page, { source: oldSource }); + await expect.poll(() => requested).toBe(true); + let active = old; + if (action === 'change URL') await changeSource(old.block, current.source); + else { + await removePlayer(page, old.id); + active = await insertPlayer(page, { source: current.source }); + } + await expectFetchAborted(page, oldSource); + await readyPreview(active.block); + await expectNativeSize(page, 64, 12); + await active.block.locator('.ap-term').evaluate((terminal) => { terminal.dataset.boundedIdentity = 'current'; }); + gate.release(); + await expect.poll(() => settled).toBe(true); + await readyPreview(active.block); + await expect(active.block.locator('.ap-term')).toHaveAttribute('data-bounded-identity', 'current'); + await expectNativeSize(page, 64, 12); + await expectGrid(active.block, 64, 12); + await expect(canvas(page).locator('.ap-wrapper')).toHaveCount(1); + await playAndSeek(active.block, 'current'); + expect(current.requests()).toBe(1); + expect(pageErrors).toEqual([]); + } finally { + gate.release(); + } + }); +} + +for (const action of ['change URL', 'unmount block']) { + test(`${action} while player assets are pending never starts the stale recording fetch`, async ({ page }) => { + await openEditor(page); + const pageErrors = []; + page.on('pageerror', (error) => pageErrors.push(error.message)); + const old = await routeRecording(page, 'before-assets', recording(2, { cols: 120, rows: 30, label: 'stale' })); + const current = await routeRecording(page, 'after-assets', recording(2, { label: 'current' })); + const scriptUrl = await page.evaluate(() => window.wpAsciiplayerSettings.playerScriptUrl); + expect(await canvas(page).locator('body').evaluate((body) => typeof body.ownerDocument.defaultView.AsciinemaPlayer)).toBe('undefined'); + const gate = deferred(); + let assetRequested = false; + await page.route(scriptUrl, async (route) => { + assetRequested = true; + await gate.promise; + // Resume the installed plugin's real local asset, not a test double. + await route.continue().catch(() => {}); + }); + try { + let active = await insertPlayer(page, { source: old.source }); + await expect.poll(() => assetRequested).toBe(true); + await expect(active.block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'loading'); + if (action === 'change URL') await changeSource(active.block, current.source); + else { + await removePlayer(page, active.id); + active = await insertPlayer(page, { source: current.source }); + } + expect(old.requests()).toBe(0); + expect(current.requests()).toBe(0); + gate.release(); + await readyPreview(active.block); + await expectNativeSize(page, 64, 12); + await expectGrid(active.block, 64, 12); + await expect(canvas(page).locator('.ap-wrapper')).toHaveCount(1); + await playAndSeek(active.block, 'current'); + expect(old.requests()).toBe(0); + expect(current.requests()).toBe(1); + expect(pageErrors).toEqual([]); + } finally { + gate.release(); + } + }); +} diff --git a/tests/e2e/i18n.spec.js b/tests/e2e/i18n.spec.js index bf7e9d9..f2e6ab0 100644 --- a/tests/e2e/i18n.spec.js +++ b/tests/e2e/i18n.spec.js @@ -10,7 +10,7 @@ const copy = { help: 'Help', retry: 'Retry preview', captionLabel: 'Recording caption', previewError: 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.', frontendError: 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.', - uploadError: 'Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).', + uploadError: 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).', }, zh_CN: { title: 'Asciicast 播放器', source: '录制文件 URL', apply: '应用 URL', @@ -18,7 +18,7 @@ const copy = { help: '帮助', retry: '重试预览', captionLabel: '录屏说明文字', previewError: '无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。', frontendError: '无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。', - uploadError: '请上传有效的 Asciicast v2/v3 JSONL 或格式化的 v1 .cast 录制文件(最大 32 MiB;v1 最大 2 MiB;最多 100,000 个事件;每行 JSONL最大 256 KiB;列数和行数均不超过 1,000)。', + uploadError: '请上传有效的 Asciicast v2/v3 JSONL 或 v1 .cast 录屏(最大 32 MiB;v1 最大 2 MiB、100,000 个事件、每行 JSONL 最大 256 KiB、1,000 个时间标记、1,000 列或行、40,000 个终端单元格,且 JSON 结构复杂度受限)。', }, }; diff --git a/tests/e2e/recording-source.spec.js b/tests/e2e/recording-source.spec.js index 563192d..d376e73 100644 --- a/tests/e2e/recording-source.spec.js +++ b/tests/e2e/recording-source.spec.js @@ -278,7 +278,7 @@ test('native Media Library rejects an invalid cast upload without applying a sou const malformed = await readFile(new URL('../fixtures/malformed.cast', import.meta.url)); const result = await uploadRecording(page, dialog, `asciiplayer-invalid-${Date.now()}-${testInfo.retry}.cast`, malformed); expect(result.success, JSON.stringify(result)).toBe(false); - const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).'; + const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).'; // A filesystem/permission failure is not evidence of content validation. expect(result.data.message).toBe(validationMessage); await expect(dialog).toContainText(validationMessage); diff --git a/tests/e2e/security-fixtures.spec.js b/tests/e2e/security-fixtures.spec.js new file mode 100644 index 0000000..851e14a --- /dev/null +++ b/tests/e2e/security-fixtures.spec.js @@ -0,0 +1,320 @@ +import { test, expect } from '@playwright/test'; +import { getSecurityCase, securityFixtureBuffer } from '../fixtures/security/generate.mjs'; + +const blockName = 'lamgc/asciiplayer'; +const fixtureRoot = '/wp-content/uploads/asciiplayer-fixtures/security'; +const messages = { + time: 'This recording contains an invalid or unsupported timestamp.', + markers: 'This recording contains too many markers.', + dimensions: 'This recording requests terminal dimensions that exceed the supported limits.', + cells: 'This recording requests too many terminal cells.', +}; + +async function openEditor(page) { + await page.goto('/wp-login.php'); + await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin'); + await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password'); + await page.locator('#wp-submit').click(); + await expect(page).toHaveURL(/\/wp-admin\//); + await page.goto('/wp-admin/post-new.php'); + await page.waitForFunction((name) => Boolean( + window.wp?.apiFetch && window.wp?.blocks?.getBlockType(name) && + window.wp?.data?.select('core/editor')?.getCurrentPostId() + ), blockName); + await page.evaluate(() => { + for (const scope of ['core/edit-post', 'core/editor']) { + window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false); + } + }); + await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible(); +} + +const canvas = (page) => page.frameLocator('iframe[name="editor-canvas"]'); + +async function insertPlayer(page, source) { + const id = await page.evaluate(({ name, source }) => { + const block = window.wp.blocks.createBlock(name, { source, controls: 'always' }); + window.wp.data.dispatch('core/block-editor').insertBlocks(block); + window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId); + return block.clientId; + }, { name: blockName, source }); + return { id, block: canvas(page).locator(`[data-block="${id}"]`) }; +} + +async function routeFixture(context, page, id) { + const fixture = getSecurityCase(id); + // Full 32 MiB and 100,000-event boundaries belong in Node/PHP, not a browser. + expect(fixture.bytes).toBeLessThan(128 * 1024); + const source = new URL(`${fixtureRoot}/${id}.cast`, page.url()).href; + const body = securityFixtureBuffer(id); + let requests = 0; + await context.route(source, async (route) => { + requests += 1; + await route.fulfill({ contentType: 'text/plain; charset=utf-8', body }); + }); + return { source, fixture, requests: () => requests }; +} + +/** Observe real fetch signals and allocation-facing DOM; do not mock the player. */ +function observeSecurityState() { + if (window.__securityFixtureState) return; + const state = window.__securityFixtureState = { + fetches: [], maxTerms: 0, maxCols: 0, maxRows: 0, maxCells: 0, + maxLines: 0, maxSymbolLines: 0, maxMarkers: 0, + }; + const fetch = window.fetch; + window.fetch = function (source, options) { + if (String(source).includes('/asciiplayer-fixtures/security/')) { + const entry = { source: String(source), aborted: Boolean(options?.signal?.aborted) }; + state.fetches.push(entry); + options?.signal?.addEventListener('abort', () => { entry.aborted = true; }, { once: true }); + } + return fetch.call(this, source, options); + }; + const sample = () => { + const terminals = document.querySelectorAll('.ap-term'); + state.maxTerms = Math.max(state.maxTerms, terminals.length); + state.maxMarkers = Math.max(state.maxMarkers, document.querySelectorAll('.ap-marker').length); + for (const terminal of terminals) { + const cols = Number(terminal.style.getPropertyValue('--term-cols')); + const rows = Number(terminal.style.getPropertyValue('--term-rows')); + state.maxCols = Math.max(state.maxCols, cols); + state.maxRows = Math.max(state.maxRows, rows); + state.maxCells = Math.max(state.maxCells, cols * rows); + state.maxLines = Math.max(state.maxLines, terminal.querySelectorAll('.ap-line').length); + state.maxSymbolLines = Math.max(state.maxSymbolLines, terminal.querySelectorAll('.ap-symbol-line').length); + } + }; + state.sample = sample; + new MutationObserver(sample).observe(document, { + childList: true, subtree: true, attributes: true, attributeFilter: ['style'], + }); + sample(); +} + +async function observedState(scope) { + return scope.locator('body').evaluate((body) => { + const state = body.ownerDocument.defaultView.__securityFixtureState; + state.sample(); + return { ...state, sample: undefined }; + }); +} + +async function expectFetch(scope, source, aborted) { + await expect.poll(async () => (await observedState(scope)).fetches.filter((entry) => entry.source === source)) + .toEqual([{ source, aborted }]); +} + +async function expectNativeSize(page, cols, rows) { + await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block')); + const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true }); + const height = page.getByRole('spinbutton', { name: 'Rows', exact: true }); + if (!await columns.isVisible()) { + await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click(); + } + await expect(columns).toHaveAttribute('placeholder', cols === undefined ? 'From recording' : String(cols)); + await expect(height).toHaveAttribute('placeholder', rows === undefined ? 'From recording' : String(rows)); + await expect(columns).toHaveValue(''); + await expect(height).toHaveValue(''); +} + +async function expectPlayable(container, fixture) { + const playback = fixture.playback; + expect(fixture.safePlayback).toBe(true); + expect(playback.seekPercent).toBe(80); + await expect(container.locator('.ap-wrapper')).toHaveCount(1); + await expect(container.locator('.ap-term')).toBeVisible(); + await expect.poll(() => container.locator('.ap-term').evaluate((terminal) => ({ + cols: Number(terminal.style.getPropertyValue('--term-cols')), + rows: Number(terminal.style.getPropertyValue('--term-rows')), + }))).toEqual({ cols: playback.cols, rows: playback.rows }); + await expect(container.locator('.ap-line')).toHaveCount(playback.rows); + await expect(container.locator('.ap-marker')).toHaveCount(0); + await container.locator('.ap-overlay-start .ap-play-button').click(); + const terminal = container.locator('.ap-term-text'); + await expect(terminal).toContainText(playback.startText); + const button = container.locator('.ap-playback-button'); + await expect(button).toHaveAttribute('aria-label', 'Pause'); + await button.click(); + await expect(button).toHaveAttribute('aria-label', 'Play'); + await expect(terminal).not.toContainText(playback.seekText); + // The real UI seeks to 80% (9.6s), beyond the seeded frame at 8s, then back. + await terminal.press(String(playback.seekPercent / 10)); + await expect(terminal).toContainText(playback.seekText); + await terminal.press('0'); + await expect(terminal).toContainText(playback.startText); + await expect(terminal).not.toContainText(playback.seekText); + await expect(container.locator('.ap-wrapper')).toHaveCount(1); + await expect(container.locator('.ap-line')).toHaveCount(playback.rows); +} + +async function expectNoUnsafeAllocation(scope, container) { + await expect(container.locator('.ap-marker')).toHaveCount(0); + // api.create legitimately creates an 80x24 shell before fetching. The + // untrusted header/resizes must never expand it or create marker elements. + expect(await container.locator('.ap-wrapper').count()).toBeLessThanOrEqual(1); + await expect(container.locator('.ap-term-text')).toHaveText(/^\s*$/); + const state = await observedState(scope); + expect(state.maxTerms).toBeLessThanOrEqual(1); + expect(state.maxCols).toBeLessThanOrEqual(80); + expect(state.maxRows).toBeLessThanOrEqual(24); + expect(state.maxCells).toBeLessThanOrEqual(80 * 24); + expect(state.maxLines).toBeLessThanOrEqual(24); + expect(state.maxSymbolLines).toBeLessThanOrEqual(24); + expect(state.maxMarkers).toBe(0); +} + +/** Real PHP-rendered public post; retain the editor page for guaranteed cleanup. */ +async function withPublicPlayer(control, context, source, run) { + const post = await control.evaluate(async ({ name, source }) => { + const content = window.wp.blocks.serialize([ + window.wp.blocks.createBlock(name, { source, controls: 'always' }), + ]); + return window.wp.apiFetch({ + path: '/wp/v2/posts', method: 'POST', + data: { title: `Security corpus regression ${Date.now()}`, status: 'publish', content }, + }); + }, { name: blockName, source }); + const frontend = await context.newPage(); + try { + await frontend.goto(post.link); + const container = frontend.locator('.asciiplayer-container'); + await expect(container).toHaveCount(1); + await run(frontend, container); + } finally { + await frontend.close(); + // REST's normal delete moves this isolated test post to recoverable + // Trash. It does not force-delete data or touch pre-existing posts. + await control.evaluate((id) => window.wp.apiFetch({ + path: `/wp/v2/posts/${id}`, method: 'DELETE', + }), post.id); + } +} + +test.beforeEach(async ({ page, context }) => { + await context.addInitScript(observeSecurityState); + await openEditor(page); + // Also cover WordPress versions that replace the iframe document in place. + await canvas(page).locator('body').evaluate(observeSecurityState); +}); + +for (const version of [1, 2, 3]) { + test(`seeded v${version} corpus plays and seeks in the actual editor and public player`, async ({ page, context }) => { + const routed = await routeFixture(context, page, `seeded-v${version}-valid`); + const { id, block } = await insertPlayer(page, routed.source); + await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready'); + await expectNativeSize(page, routed.fixture.playback.cols, routed.fixture.playback.rows); + await expectPlayable(block, routed.fixture); + await expectFetch(canvas(page), routed.source, false); + expect(routed.requests()).toBe(1); + const attributes = await page.evaluate((id) => window.wp.data.select('core/block-editor').getBlockAttributes(id), id); + expect(attributes.cols).toBeUndefined(); + expect(attributes.rows).toBeUndefined(); + await withPublicPlayer(page, context, routed.source, async (frontend, container) => { + await expect(container).toHaveAttribute('data-ap-status', 'ready'); + await expectPlayable(container, routed.fixture); + await expectFetch(frontend, routed.source, false); + expect(routed.requests()).toBe(2); + }); + }); +} + +const rejectionIds = [ + 'dimensions-v1-over', 'dimensions-v2-over', 'dimensions-v3-over', + 'markers-v2-over', 'markers-v3-over', + 'late-resize-v2-over', 'late-resize-v3-over', + 'time-v1-ms-rounding-over', 'time-v2-output-nonprogress', 'time-v3-ms-sum-overflow', +]; +for (const id of rejectionIds) { + test(`shared ${id} is rejected before unsafe DOM allocation on both playback paths`, async ({ page, context }) => { + const rejected = await routeFixture(context, page, id); + const recovery = await routeFixture(context, page, `seeded-v${rejected.fixture.format}-valid`); + const { block } = await insertPlayer(page, rejected.source); + const message = messages[rejected.fixture.expected.jsError]; + expect(message).toBeTruthy(); + await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error'); + await expect(block.locator('.components-notice')).toContainText(message); + await expectNativeSize(page); + await expectFetch(canvas(page), rejected.source, true); + await expectNoUnsafeAllocation(canvas(page), block); + expect(rejected.requests()).toBe(1); + await withPublicPlayer(page, context, rejected.source, async (frontend, container) => { + await expect(container).toHaveAttribute('data-ap-status', 'error'); + await expect(container.locator('.asciiplayer-error')).toHaveText(message); + await expectFetch(frontend, rejected.source, true); + await expectNoUnsafeAllocation(frontend, container); + expect(rejected.requests()).toBe(2); + }); + // A rejected corpus member must not poison the next valid recording. + await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(recovery.source); + await block.getByRole('button', { name: 'Apply URL', exact: true }).click(); + await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready'); + await expect(block.locator('.components-notice')).toHaveCount(0); + await expectNativeSize(page, recovery.fixture.playback.cols, recovery.fixture.playback.rows); + await expectPlayable(block, recovery.fixture); + await expectFetch(canvas(page), recovery.source, false); + expect(recovery.requests()).toBe(1); + }); +} + +async function openMedia(page, block) { + await block.getByRole('button', { name: 'Choose recording', exact: true }).click(); + const dialog = page.getByRole('dialog', { name: 'Choose an Asciicast recording', exact: true }); + await expect(dialog).toBeVisible(); + return dialog; +} + +async function uploadCorpusFixture(page, dialog, id, unique) { + const fixture = getSecurityCase(id); + expect(fixture.bytes).toBeLessThan(32 * 1024); + await dialog.getByRole('tab', { name: 'Upload files', exact: true }).click(); + // The real WordPress Plupload input can live outside the media modal. + // Observe the actual upload endpoint rather than substituting its response. + const input = page.locator('.moxie-shim input[type="file"]').last(); + await expect(input).toBeAttached(); + const response = page.waitForResponse((result) => + /\/wp-admin\/async-upload\.php(?:\?|$)/.test(result.url()) && result.request().method() === 'POST' + ); + await input.setInputFiles({ + name: `security-${id}-${unique}.cast`, mimeType: 'application/x-asciicast', + buffer: securityFixtureBuffer(id), + }); + return (await response).json(); +} + +test('real WordPress uploads reject shared marker/cell fixtures and accept a seeded recording', async ({ page }, testInfo) => { + const { id, block } = await insertPlayer(page, ''); + const unique = `${Date.now()}-${testInfo.retry}`; + const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).'; + for (const fixtureId of ['markers-v2-over', 'cells-v1-over', 'time-v1-ms-rounding-over', 'time-v2-output-nonprogress', 'time-v3-ms-sum-overflow']) { + const dialog = await openMedia(page, block); + const result = await uploadCorpusFixture(page, dialog, fixtureId, unique); + expect(result.success, JSON.stringify(result)).toBe(false); + // Exact plugin copy distinguishes registered resource validation from + // MIME, filesystem, transport, or unrelated WordPress upload failures. + expect(result.data.message).toBe(validationMessage); + await expect(dialog).toContainText(validationMessage); + await expect(dialog.locator('.media-button-select')).toBeDisabled(); + await dialog.locator('.media-modal-close').click(); + await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue(''); + expect(await page.evaluate((id) => window.wp.data.select('core/block-editor').getBlockAttributes(id).source, id)).toBe(''); + await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0); + } + const fixture = getSecurityCase('seeded-v3-valid'); + const dialog = await openMedia(page, block); + const accepted = await uploadCorpusFixture(page, dialog, fixture.id, unique); + expect(accepted.success, JSON.stringify(accepted)).toBe(true); + expect(accepted.data.mime).toBe('application/x-asciicast'); + await dialog.getByRole('tab', { name: 'Media Library', exact: true }).click(); + const attachment = dialog.locator(`.attachment[data-id="${accepted.data.id}"]`); + await expect(attachment).toBeVisible(); + if (!await attachment.evaluate((element) => element.classList.contains('selected'))) await attachment.click(); + await expect(dialog.locator('.media-button-select')).toBeEnabled(); + await dialog.locator('.media-button-select').click(); + await expect(dialog).toBeHidden(); + await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue(accepted.data.url); + await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready'); + await expectNativeSize(page, fixture.playback.cols, fixture.playback.rows); + // This fetches the file WordPress actually saved, without a route mock. + await expectPlayable(block, fixture); +}); diff --git a/tests/fixtures/security/PROVENANCE.md b/tests/fixtures/security/PROVENANCE.md new file mode 100644 index 0000000..9c981f8 --- /dev/null +++ b/tests/fixtures/security/PROVENANCE.md @@ -0,0 +1,69 @@ +# Official asciinema fixture provenance + +These three small baselines were recorded by the official, unmodified asciinema CLI. They are genuine recordings, not hand-written files labeled as recorder output. They contain only a controlled synthetic program and are safe for public source control. None includes input capture, credentials, a user name, a host name, or an absolute workspace path. + +## Recorder support and sources + +- asciicast v1: official PyPI `asciinema` **1.4.0** source distribution, executed unchanged using Python **3.12.14** and its `python3 -m asciinema` entrypoint. [Published package and hash](https://pypi.org/project/asciinema/1.4.0/#files). +- asciicast v2 and v3: official Linux x86_64 GNU release binary of asciinema **3.0.1**. [Official release](https://github.com/asciinema/asciinema/releases/tag/v3.0.1), [release asset metadata](https://api.github.com/repos/asciinema/asciinema/releases/tags/v3.0.1). +- CLI 3.x defaults to v3 and provides `--output-format asciicast-v2`. It does not offer v1 recording output. Using the historical CLI for v1 avoids a custom conversion here. [Official 3.0 release notes](https://github.com/asciinema/asciinema/releases/tag/v3.0.0). + +The source downloads were verified against the publisher-provided SHA-256 values before execution: + +| Download | SHA-256 | +| --- | --- | +| `asciinema-x86_64-unknown-linux-gnu`, v3.0.1 | `eb3a55e8778f6b86575ad58b47f1ee21d934e4baa8f01abaa5151cad490021f8` | +| `asciinema-1.4.0.tar.gz` | `fb31457e7a4689340b872f625658dbaea33bcf6863fb5d696cf3857010432ecb` | + +The binaries and legacy package are not vendored in the test corpus. The official [installation guide](https://docs.asciinema.org/manual/cli/installation/) documents release binaries and the historical PyPI package. + +## Safe, reproducible payload + +`synthetic-output.py` writes a fixed introductory line, four harmless hexadecimal samples, and an ANSI green completion line. It reads no files or user input and uses no network. The seed is `0x41c0ffee` (1103167470), with unsigned 32-bit xorshift operations `<< 13`, `>> 17`, `<< 5`. Terminal line discipline converts its newline characters to CRLF in the captures. + +All recorders receive an environment cleared with `env -i`, a temporary HOME and configuration directory, fixed locale/TERM/SHELL values, and an 80×24 terminal. CLI 1.4.0 requires a token field even for local recording; its isolated config contains the fixed noncredential value `fixture-no-upload`. No real credential is created, loaded or sent. Every `rec` command has an explicit local filename, and no upload, streaming or authentication command is used. + +The recorded command is exactly `python3 synthetic-output.py`. `record-official-baselines.sh` contains the complete shell invocations and refuses to overwrite a previous capture. With the two verified tools available: + +```sh +ASCIINEMA3=/path/to/asciinema-3.0.1 \ +ASCIINEMA1_SRC=/path/to/asciinema-1.4.0 \ +./record-official-baselines.sh /path/to/new-captures +``` + +The essential recorder commands are: + +```sh +python3 -m asciinema rec --title 'PR41 synthetic baseline' \ + --command 'python3 synthetic-output.py' official-v1.cast + +asciinema-3.0.1 rec --headless --window-size 80x24 \ + --output-format asciicast-v2 --title 'PR41 synthetic baseline' \ + --command 'python3 synthetic-output.py' official-v2.cast + +asciinema-3.0.1 rec --headless --window-size 80x24 \ + --output-format asciicast-v3 --title 'PR41 synthetic baseline' \ + --command 'python3 synthetic-output.py' official-v3.cast +``` + +Use the wrapper to supply the isolation, Python module path and legacy terminal dimensions; the commands alone omit that setup. + +## Baseline identity and validation + +| Raw capture | SHA-256 | +| --- | --- | +| `official-v1.cast` | `5570c9cdec60a779585db195ecd8dee4756d84706d6b27d3ccd87cf3ba311c97` | +| `official-v2.cast` | `6be6f5cd70d4a428692fc7807549b9c1437c1c8b60902220ad5e7e01a201f3ee` | +| `official-v3.cast` | `8c07c04edf86605558a9795152fcba32337d72aeaa073bc89adb1c285f06763e` | + +All three captures were successfully read using the official CLI 3.0.1 `convert --output-format raw` command. The resulting 187-byte exports are identical by `cmp` and SHA-256: `c759f03280f9a48ecfafbe7b11d7f2b75a2b418d368bc5fd5d13f1d957ee7d4d`. The official converter prepends the terminal-size escape sequence `ESC[8;24;80t`. Independently concatenating the recorded output events produces the same 177 bytes for all three formats, SHA-256 `390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550`. + +Each has six output events. The v2 and v3 captures also contain the official recorder's trailing `x` exit event. Preserve those raw files exactly; do not silently delete metadata or events and continue calling the result an unmodified capture. + +`provenance.json` records tool/source versions, source hashes, exact command arguments, baseline hashes, header fields, event counts and shared output hash. The repository tests exercise the raw baselines and deterministic derived fixtures against its pinned asciinema-player **3.17.0** parser/core; see the test results separately for what was executed. + +## What is deterministic + +The payload, seed and corpus mutation recipes are deterministic. A fresh terminal recording is **not byte-for-byte deterministic**: wall-clock timestamps, scheduling delays, total duration and PTY read boundaries can differ. The checked-in raw captures are therefore immutable, hash-pinned provenance anchors. Large and boundary fixtures are explicitly generated derivatives, with fixed timing/metadata and documented mutation recipes; they must not be described as untouched CLI output. + +Format semantics are checked against the official specifications: [v1](https://docs.asciinema.org/manual/asciicast/v1/) uses a whole JSON document with per-output delays; [v2](https://docs.asciinema.org/manual/asciicast/v2/) uses JSON lines with elapsed timestamps; [v3](https://docs.asciinema.org/manual/asciicast/v3/) uses JSON lines with relative event intervals and nested terminal dimensions. Format conformance and genuine provenance complement, rather than replace, resource-boundary and real-player regression tests. diff --git a/tests/fixtures/security/README.md b/tests/fixtures/security/README.md new file mode 100644 index 0000000..28e3ed3 --- /dev/null +++ b/tests/fixtures/security/README.md @@ -0,0 +1,169 @@ +# TEST ONLY: deterministic recording-security corpus + +This corpus exercises PR41's resource gates against ordinary, boundary and +intentionally malformed asciicast input. It is **not** a collection to open in an +unprotected terminal player. Do not upload generated boundary files to a real +WordPress site, serve them publicly, or commit expanded large payloads. + +Only small, readable `.cast` files are checked in. Large cases are compact +literal/repeat recipes materialized one at a time in temporary storage. The +largest possible file is **32 MiB + 1 byte**. There is no arbitrary size argument, +unbounded fuzz loop, network request, remote command, or production-code import +in the generator. The ordinary plugin package excludes the `tests` directory. + +## Provenance and reproducibility + +- `official-v1.cast`, `official-v2.cast`, and `official-v3.cast` are unmodified + **native recordings** from pinned official CLI versions. Legacy CLI 1.4.0 + produced v1; CLI 3.0.1 produced v2 and v3. Their actual timestamps and PTY delays + remain intact. See [PROVENANCE.md](PROVENANCE.md) and `provenance.json` for + official source URLs, verified package hashes, commands and capture hashes. +- `seeded-v*-valid.cast` are explicitly **normalized derivatives**, not raw CLI + output. They retain the captured output text and the recorded format/dimension + envelope, remove nondeterministic metadata, add seeded harmless UTF-8 output, + and use fixed visible START/SEEK/END frames across a 12-second timeline. v2 + stores absolute time; v1/v3 store matching intervals. These are the interactive + playback/seek controls. +- Resource-boundary derivatives mutate one documented resource purpose. JSONL + byte and line fillers are actual output events, not padding comments. Wide + metadata, deep metadata and large valid grids are valid-format resource-unsafe + cases; they must fail the intended policy rather than generic JSON syntax. +- Blank/comment/indented lines, zero header dimensions and duplicate keys are + marked `upstream-compatible`, independently of strict format provenance. +- `malformed-v*` cases deliberately contain broken JSON and are labeled + `intentionally-malformed`. + +`recipes.mjs` uses real unsigned xorshift32 (`<<13`, `>>>17`, `<<5`) with the +single allowed seed `0x41c0ffee` (1103167470). Randomized output chunks, text and +bounded timings are deterministic. Equivalent purposes use all three formats +where their semantics permit it. v1 has a whole-document 2 MiB budget and no +marker/resize event types; those JSONL-only purposes apply to v2/v3. A fresh +official PTY recording is not byte-identical; the checked-in raw captures are +immutable, independently hash-pinned anchors, not regenerated during tests. + +## Commands + +Run from the repository root using the project's supported Node version: + +```sh +# List bounded, known case IDs, sizes and expected results. +node tests/fixtures/security/generate.mjs --list + +# Compare deterministic recipes to the golden manifest and verify every hash. +node tests/fixtures/security/generate.mjs --verify + +# Write exactly one known file to a new OS temporary directory. +node tests/fixtures/security/generate.mjs --case markers-v2-over + +# Independent corpus metrics plus actual production loader and player Core. +node --test tests/js/security-fixtures.test.js tests/js/security-loader-fixtures.test.js + +# All JavaScript checks, including both corpus suites. +npm test + +# Native PHP 7.4+; needs neither Node nor the asciinema CLI. +php tests/php/run.php + +# Real isolated WordPress/Chromium integration; see tests/e2e/README.md setup. +npx --no-install playwright test tests/e2e/security-fixtures.spec.js +``` + +The `--case` command prints the temporary path, byte count, SHA-256 and cleanup +directory. Delete that directory after inspection. Test consumers clean up their +own temporary files in `finally` blocks. Never replace the named case ID with a +user-controlled arbitrary size. Large samples must stay outside source control. + +When intentionally changing a recipe, run `--refresh` and review the complete +manifest/hash/small-fixture diff, then rerun the checks above. This writes only +the manifest and tiny derivative files; it never rewrites official captures or +expands large cases into the repository. Provenance checks independently reject +a changed raw baseline even if someone refreshes the golden manifest. + +## Shared cross-language contract + +`manifest.json` has `schemaVersion: 1`, an independently pinned `policy`, seed, +and a `cases` array. Each case declares: + +- `id`, `format`, `description`, `category`, `validity`, and `provenance` +- Exactly one `source.file` relative to this directory, or ordered + `source.segments: [{ "text": "literal UTF-8", "repeat": positiveInteger }]` +- `bytes` and lowercase SHA-256 of the exact generated bytes +- `expected.accepted` and exact `expected.jsError` (null for accepted controls) +- Optional `boundary: {metric, limit, value}` and independent `metrics` +- `safePlayback: true` only for the six tiny official/seeded accepted controls +- Optional `playback` expectations for the normalized interactive controls + +Concatenate the UTF-8 bytes of each literal repeated by its count in order. Do +not normalize newlines, strip BOMs, reserialize JSON, execute text, or shell out +to Node from PHP. The JavaScript reader verifies size and SHA-256 before use; +the PHP reader streams at most 64 KiB at a time to one temporary file and checks +the same identity before invoking the actual file/upload/sideload gates. + +`expected.noDecodeAtOrAboveBytes` is a witness threshold for rejected JSON trees: +the decoder must not see any tree input that large. Small safe headers or tiny +version-discriminator scalar parses may still occur. Byte-over JSONL differs by +consumer: PHP rejects from file size before any decode, expressed by the stronger +`expected.phpNoDecodeAtOrAboveBytes: 1`; a browser stream must parse safe earlier +records before discovering the final byte, then cancel without handing the +recording to the player. This is not a claim that all streaming prefix parsing +can or should be avoided. + +## Coverage map + +| Purpose | Case IDs | Boundary | +| --- | --- | --- | +| Official provenance and real playback | `official-v{1,2,3}`, `seeded-v{1,2,3}-valid` | Same native output; normalized equivalent timelines | +| Zero/blank/multiline compatibility | `valid-v*-zero`, `valid-v{2,3}-filtered-lines`, `valid-v1-multiline-late-version` | Small actual files | +| Format discrimination | `valid-v1-escaped-version`, `valid-v1-duplicate-version`, `valid-v1-long-first-line`, `invalid-v2-duplicate-version-wide` | v1 limits cannot leak into v2 | +| Whole body bytes | `bytes-v{2,3}-{at,over}` | 33,554,432 / 33,554,433 bytes | +| Legacy v1 bytes | `v1-bytes-{at,over}` | 2,097,152 / 2,097,153 bytes | +| JSONL bytes including LF | `line-v{2,3}-{at,over}` | 262,144 / 262,145 bytes | +| Events | `events-v{1,2,3}-{at,over}` | 100,000 / 100,001 events | +| Physical JSONL work | `ignored-lines-v{2,3}-{at,over}` | 100,000 / 100,001 lines; exactly one output event | +| Markers | `markers-v{2,3}-{at,over}` | 1,000 / 1,001 markers | +| Header and late-resize axes | `dimensions-v*-{at,over}`, `late-resize-v{2,3}-dimensions-{at,over}` | 1,000 / 1,001 columns, otherwise safe | +| Header and late-resize cells | `cells-v*-{at,over}`, `late-resize-v{2,3}-{at,over}` | 200×200 / 201×200; each axis remains valid | +| v1 scalar/key allocation | `tokens-v1-{at,over}` | 400,000 / 400,001 tokens | +| v1 container allocation | `containers-v1-{at,over}` | 100,016 / 100,017 containers | +| JSONL scalar/key allocation | `line-tokens-v{2,3}-{at,over}` | 20,000 / 20,001 tokens | +| Nesting | `depth-v{1,2,3}-{at,over}` | 15 / 16 container levels | +| Recording timeline | `timeline-v{1,2,3}-{at,over}` | 2,147,483,647 / 2,147,483,648 milliseconds | +| Relative timeline sum | `interval-timeline-v{1,3}-{at,over}` | Millisecond-order accumulation at / over the horizon | +| Time metadata | `duration-v*-{zero,at,over}`, `idle-limit-v*-{zero,at,over}` | Zero remains valid; inclusive horizon applies | +| Floating-point regressions | `time-v{1,3}-ms-rounding-over`, `time-v{1,3}-ms-sum-overflow`, `time-v2-output-nonprogress` | Valid JSON with unsafe upstream millisecond arithmetic | +| Intentional bad syntax | `malformed-v1-json`, `malformed-v{2,3}-event` | Stable invalid-result controls | + +The cells-over value is 40,200, not an assertion that every integer cell count +has a valid integer grid. Event-only JSONL reaches the physical-line and event +caps together; the ignored-line pair independently isolates physical-line work. +There is no separate per-line cap on whole-document v1, and no JSONL-wide 400,000 +token budget: those distinctions are explicit rather than false all-format +equivalence. + +The corpus invariant suite independently parses tightly bounded test data to +measure structure, verify valid/malformed labels, pin exact boundary values, +and prove an unrelated limit is not masking the intended one. Only the six +`safePlayback` controls use ordinary real pinned player Core playback. Separate +tiny timestamp regressions use captured timers and bounded callbacks to verify +upstream numeric behavior without scheduling long waits or an unbounded loop. +Hostile/boundary recordings first exercise the production loader guard or PHP +upload validator. + +The supported raw timeline is about 24.85 days. Browser playback conservatively +requires cumulative time divided by speed to fit the same signed timer ceiling; +at 0.01×, this permits about 5.97 hours of source time. Per-event gap checks alone +are insufficient because the player batches future output ahead of wall time. +The v1/v3 rounding witness specifically distinguishes summing milliseconds from +summing seconds before conversion; these two operations are not interchangeable. +Browser tests use the existing isolated WordPress setup and check visible errors +and recovery. Passing Node/PHP checks does not imply that a browser run occurred. + +## Relationship to existing tests + +Existing `hello.cast`, `replacement.cast`, `resize.cast`, `v1-pretty.cast`, and +`v3-comments.cast` remain the ordinary UI regression fixtures. Existing inline +small-limit unit tests remain useful for cancellation, option overrides, UTF-8 +failures and timing edge cases. This corpus adds durable official provenance, +actual full-default at/over resource pairs, deterministic cross-language input, +decoder-order witnesses and a common source for upload and playback integration; +it does not replace those focused tests. diff --git a/tests/fixtures/security/cells-v1-at.cast b/tests/fixtures/security/cells-v1-at.cast new file mode 100644 index 0000000..281ef64 --- /dev/null +++ b/tests/fixtures/security/cells-v1-at.cast @@ -0,0 +1 @@ +{"version":1,"width":200,"height":200,"stdout":[[0,"PR41 bounded control\r\n"]]} diff --git a/tests/fixtures/security/cells-v1-over.cast b/tests/fixtures/security/cells-v1-over.cast new file mode 100644 index 0000000..69fb19b --- /dev/null +++ b/tests/fixtures/security/cells-v1-over.cast @@ -0,0 +1 @@ +{"version":1,"width":201,"height":200,"stdout":[[0,"PR41 bounded control\r\n"]]} diff --git a/tests/fixtures/security/cells-v2-at.cast b/tests/fixtures/security/cells-v2-at.cast new file mode 100644 index 0000000..f37ac5c --- /dev/null +++ b/tests/fixtures/security/cells-v2-at.cast @@ -0,0 +1,2 @@ +{"version":2,"width":200,"height":200} +[0,"o","PR41 bounded control\r\n"] diff --git a/tests/fixtures/security/cells-v2-over.cast b/tests/fixtures/security/cells-v2-over.cast new file mode 100644 index 0000000..c561b33 --- /dev/null +++ b/tests/fixtures/security/cells-v2-over.cast @@ -0,0 +1,2 @@ +{"version":2,"width":201,"height":200} +[0,"o","PR41 bounded control\r\n"] diff --git a/tests/fixtures/security/cells-v3-at.cast b/tests/fixtures/security/cells-v3-at.cast new file mode 100644 index 0000000..f1d45ff --- /dev/null +++ b/tests/fixtures/security/cells-v3-at.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":200,"rows":200}} +[0,"o","PR41 bounded control\r\n"] diff --git a/tests/fixtures/security/cells-v3-over.cast b/tests/fixtures/security/cells-v3-over.cast new file mode 100644 index 0000000..50fe684 --- /dev/null +++ b/tests/fixtures/security/cells-v3-over.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":201,"rows":200}} +[0,"o","PR41 bounded control\r\n"] diff --git a/tests/fixtures/security/depth-v1-at.cast b/tests/fixtures/security/depth-v1-at.cast new file mode 100644 index 0000000..86f9f45 --- /dev/null +++ b/tests/fixtures/security/depth-v1-at.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"stdout":[],"metadata":[[[[[[[[[[[[[[0]]]]]]]]]]]]]]} diff --git a/tests/fixtures/security/depth-v1-over.cast b/tests/fixtures/security/depth-v1-over.cast new file mode 100644 index 0000000..170a41c --- /dev/null +++ b/tests/fixtures/security/depth-v1-over.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"stdout":[],"metadata":[[[[[[[[[[[[[[[0]]]]]]]]]]]]]]]} diff --git a/tests/fixtures/security/depth-v2-at.cast b/tests/fixtures/security/depth-v2-at.cast new file mode 100644 index 0000000..b4e8cf9 --- /dev/null +++ b/tests/fixtures/security/depth-v2-at.cast @@ -0,0 +1 @@ +{"version":2,"width":80,"height":24,"metadata":[[[[[[[[[[[[[[0]]]]]]]]]]]]]]} diff --git a/tests/fixtures/security/depth-v2-over.cast b/tests/fixtures/security/depth-v2-over.cast new file mode 100644 index 0000000..9f87dba --- /dev/null +++ b/tests/fixtures/security/depth-v2-over.cast @@ -0,0 +1 @@ +{"version":2,"width":80,"height":24,"metadata":[[[[[[[[[[[[[[[0]]]]]]]]]]]]]]]} diff --git a/tests/fixtures/security/depth-v3-at.cast b/tests/fixtures/security/depth-v3-at.cast new file mode 100644 index 0000000..6512219 --- /dev/null +++ b/tests/fixtures/security/depth-v3-at.cast @@ -0,0 +1 @@ +{"version":3,"term":{"cols":80,"rows":24},"metadata":[[[[[[[[[[[[[[0]]]]]]]]]]]]]]} diff --git a/tests/fixtures/security/depth-v3-over.cast b/tests/fixtures/security/depth-v3-over.cast new file mode 100644 index 0000000..48fc26e --- /dev/null +++ b/tests/fixtures/security/depth-v3-over.cast @@ -0,0 +1 @@ +{"version":3,"term":{"cols":80,"rows":24},"metadata":[[[[[[[[[[[[[[[0]]]]]]]]]]]]]]]} diff --git a/tests/fixtures/security/dimensions-v1-at.cast b/tests/fixtures/security/dimensions-v1-at.cast new file mode 100644 index 0000000..72c679a --- /dev/null +++ b/tests/fixtures/security/dimensions-v1-at.cast @@ -0,0 +1 @@ +{"version":1,"width":1000,"height":24,"stdout":[[0,"PR41 bounded control\r\n"]]} diff --git a/tests/fixtures/security/dimensions-v1-over.cast b/tests/fixtures/security/dimensions-v1-over.cast new file mode 100644 index 0000000..5feb231 --- /dev/null +++ b/tests/fixtures/security/dimensions-v1-over.cast @@ -0,0 +1 @@ +{"version":1,"width":1001,"height":24,"stdout":[[0,"PR41 bounded control\r\n"]]} diff --git a/tests/fixtures/security/dimensions-v2-at.cast b/tests/fixtures/security/dimensions-v2-at.cast new file mode 100644 index 0000000..5b0f853 --- /dev/null +++ b/tests/fixtures/security/dimensions-v2-at.cast @@ -0,0 +1,2 @@ +{"version":2,"width":1000,"height":24} +[0,"o","PR41 bounded control\r\n"] diff --git a/tests/fixtures/security/dimensions-v2-over.cast b/tests/fixtures/security/dimensions-v2-over.cast new file mode 100644 index 0000000..ed6495c --- /dev/null +++ b/tests/fixtures/security/dimensions-v2-over.cast @@ -0,0 +1,2 @@ +{"version":2,"width":1001,"height":24} +[0,"o","PR41 bounded control\r\n"] diff --git a/tests/fixtures/security/dimensions-v3-at.cast b/tests/fixtures/security/dimensions-v3-at.cast new file mode 100644 index 0000000..570379c --- /dev/null +++ b/tests/fixtures/security/dimensions-v3-at.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":1000,"rows":24}} +[0,"o","PR41 bounded control\r\n"] diff --git a/tests/fixtures/security/dimensions-v3-over.cast b/tests/fixtures/security/dimensions-v3-over.cast new file mode 100644 index 0000000..d7ea8c8 --- /dev/null +++ b/tests/fixtures/security/dimensions-v3-over.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":1001,"rows":24}} +[0,"o","PR41 bounded control\r\n"] diff --git a/tests/fixtures/security/duration-v1-at.cast b/tests/fixtures/security/duration-v1-at.cast new file mode 100644 index 0000000..d5c48bf --- /dev/null +++ b/tests/fixtures/security/duration-v1-at.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"duration":2147483.647,"stdout":[[0,"x"]]} diff --git a/tests/fixtures/security/duration-v1-over.cast b/tests/fixtures/security/duration-v1-over.cast new file mode 100644 index 0000000..d233b60 --- /dev/null +++ b/tests/fixtures/security/duration-v1-over.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"duration":2147483.648,"stdout":[[0,"x"]]} diff --git a/tests/fixtures/security/duration-v1-zero.cast b/tests/fixtures/security/duration-v1-zero.cast new file mode 100644 index 0000000..285444c --- /dev/null +++ b/tests/fixtures/security/duration-v1-zero.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"duration":0,"stdout":[[0,"x"]]} diff --git a/tests/fixtures/security/duration-v2-at.cast b/tests/fixtures/security/duration-v2-at.cast new file mode 100644 index 0000000..e39b2e2 --- /dev/null +++ b/tests/fixtures/security/duration-v2-at.cast @@ -0,0 +1,2 @@ +{"version":2,"width":80,"height":24,"duration":2147483.647} +[0,"o","x"] diff --git a/tests/fixtures/security/duration-v2-over.cast b/tests/fixtures/security/duration-v2-over.cast new file mode 100644 index 0000000..28f2d0a --- /dev/null +++ b/tests/fixtures/security/duration-v2-over.cast @@ -0,0 +1,2 @@ +{"version":2,"width":80,"height":24,"duration":2147483.648} +[0,"o","x"] diff --git a/tests/fixtures/security/duration-v2-zero.cast b/tests/fixtures/security/duration-v2-zero.cast new file mode 100644 index 0000000..674493a --- /dev/null +++ b/tests/fixtures/security/duration-v2-zero.cast @@ -0,0 +1,2 @@ +{"version":2,"width":80,"height":24,"duration":0} +[0,"o","x"] diff --git a/tests/fixtures/security/duration-v3-at.cast b/tests/fixtures/security/duration-v3-at.cast new file mode 100644 index 0000000..91e1ab1 --- /dev/null +++ b/tests/fixtures/security/duration-v3-at.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":80,"rows":24},"duration":2147483.647} +[0,"o","x"] diff --git a/tests/fixtures/security/duration-v3-over.cast b/tests/fixtures/security/duration-v3-over.cast new file mode 100644 index 0000000..02c6481 --- /dev/null +++ b/tests/fixtures/security/duration-v3-over.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":80,"rows":24},"duration":2147483.648} +[0,"o","x"] diff --git a/tests/fixtures/security/duration-v3-zero.cast b/tests/fixtures/security/duration-v3-zero.cast new file mode 100644 index 0000000..3b5887b --- /dev/null +++ b/tests/fixtures/security/duration-v3-zero.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":80,"rows":24},"duration":0} +[0,"o","x"] diff --git a/tests/fixtures/security/generate.mjs b/tests/fixtures/security/generate.mjs new file mode 100644 index 0000000..2932eb6 --- /dev/null +++ b/tests/fixtures/security/generate.mjs @@ -0,0 +1,88 @@ +/** TEST ONLY. Materialize one pinned fixture; never accepts arbitrary sizes. */ +import { createHash } from 'node:crypto'; +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createManifest, createRecipes, MAX_FIXTURE_BYTES } from './recipes.mjs'; + +const root = dirname( fileURLToPath( import.meta.url ) ); +const manifestPath = join( root, 'manifest.json' ); +const invoked = process.argv[ 1 ] && resolve( process.argv[ 1 ] ) === fileURLToPath( import.meta.url ); + +// Maintenance only: deterministic recipes write the small fixtures plus golden +// manifest. No large expanded payload is ever written into the repository. +if ( invoked && process.argv.slice( 2 ).join( ' ' ) === '--refresh' ) { + const recipes = createRecipes(); + for ( const { entry, parts } of recipes ) { + if ( ! entry.source.file ) continue; + if ( entry.provenance === 'official-raw-capture' ) continue; + if ( entry.bytes > 16384 ) throw new RangeError( 'Checked-in fixtures must stay small.' ); + writeFileSync( join( root, entry.source.file ), parts.map( ( part ) => part.text.repeat( part.repeat ) ).join( '' ), 'utf8' ); + } + writeFileSync( manifestPath, JSON.stringify( createManifest(), null, 2 ) + '\n', 'utf8' ); + process.stdout.write( `Refreshed ${ recipes.length } recipes and their small controls.\n` ); +} + +export const securityManifest = JSON.parse( readFileSync( manifestPath, 'utf8' ) ); +export const securityCases = securityManifest.cases; + +export function getSecurityCase( id ) { + const fixture = securityCases.find( ( item ) => item.id === id ); + if ( ! fixture ) throw new RangeError( `Unknown security fixture: ${ id }` ); + return fixture; +} + +export function securityFixtureBuffer( id ) { + const fixture = getSecurityCase( id ); + if ( ! Number.isSafeInteger( fixture.bytes ) || fixture.bytes < 1 || fixture.bytes > MAX_FIXTURE_BYTES ) throw new RangeError( 'Fixture byte cap exceeded.' ); + let buffer; + if ( fixture.source.file ) { + if ( ! /^[a-z0-9-]+\.cast$/.test( fixture.source.file ) ) throw new Error( 'Fixture file must stay in its own directory.' ); + buffer = readFileSync( join( root, fixture.source.file ) ); + } else { + let length = 0; + for ( const { text, repeat } of fixture.source.segments ) { + if ( typeof text !== 'string' || ! text.length || ! Number.isSafeInteger( repeat ) || repeat < 1 ) throw new Error( 'Invalid literal-repeat segment.' ); + length += Buffer.byteLength( text ) * repeat; + if ( ! Number.isSafeInteger( length ) || length > MAX_FIXTURE_BYTES ) throw new RangeError( 'Recipe byte cap exceeded.' ); + } + if ( length !== fixture.bytes ) throw new Error( `Recipe length differs for ${ id }` ); + buffer = Buffer.allocUnsafe( length ); + let offset = 0; + for ( const { text, repeat } of fixture.source.segments ) { + const unit = Buffer.from( text, 'utf8' ); + const end = offset + unit.length * repeat; + buffer.fill( unit, offset, end ); + offset = end; + } + } + if ( buffer.length !== fixture.bytes || createHash( 'sha256' ).update( buffer ).digest( 'hex' ) !== fixture.sha256 ) throw new Error( `Fixture integrity failure: ${ id }` ); + return buffer; +} + +export function writeSecurityFixture( id, directory ) { + const buffer = securityFixtureBuffer( id ); + const path = join( directory, `${ id }.cast` ); + writeFileSync( path, buffer, { flag: 'wx' } ); + return path; +} + +if ( invoked ) { + const args = process.argv.slice( 2 ); + if ( args.length === 1 && args[ 0 ] === '--list' ) { + for ( const item of securityCases ) process.stdout.write( `${ item.id }\t${ item.bytes } bytes\t${ item.expected.accepted ? 'accept' : item.expected.jsError }\n` ); + } else if ( args.length === 1 && args[ 0 ] === '--verify' ) { + if ( JSON.stringify( securityManifest ) !== JSON.stringify( createManifest() ) ) throw new Error( 'Golden manifest differs; inspect recipes before --refresh.' ); + for ( const item of securityCases ) securityFixtureBuffer( item.id ); + process.stdout.write( `Verified ${ securityCases.length } deterministic fixtures.\n` ); + } else if ( args.length === 2 && args[ 0 ] === '--case' ) { + const fixture = getSecurityCase( args[ 1 ] ); + const directory = mkdtempSync( join( tmpdir(), 'asciiplayer-security-' ) ); + const path = writeSecurityFixture( fixture.id, directory ); + process.stdout.write( JSON.stringify( { path, bytes: fixture.bytes, sha256: fixture.sha256, cleanup: `Remove ${ directory } after testing.` }, null, 2 ) + '\n' ); + } else if ( args.length !== 1 || args[ 0 ] !== '--refresh' ) { + process.stderr.write( 'Usage: node tests/fixtures/security/generate.mjs --list | --verify | --case | --refresh\n' ); + process.exitCode = 1; + } +} diff --git a/tests/fixtures/security/idle-limit-v1-at.cast b/tests/fixtures/security/idle-limit-v1-at.cast new file mode 100644 index 0000000..de218bd --- /dev/null +++ b/tests/fixtures/security/idle-limit-v1-at.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"idle_time_limit":2147483.647,"stdout":[[0,"x"]]} diff --git a/tests/fixtures/security/idle-limit-v1-over.cast b/tests/fixtures/security/idle-limit-v1-over.cast new file mode 100644 index 0000000..bfc04fc --- /dev/null +++ b/tests/fixtures/security/idle-limit-v1-over.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"idle_time_limit":2147483.648,"stdout":[[0,"x"]]} diff --git a/tests/fixtures/security/idle-limit-v1-zero.cast b/tests/fixtures/security/idle-limit-v1-zero.cast new file mode 100644 index 0000000..7e1aa10 --- /dev/null +++ b/tests/fixtures/security/idle-limit-v1-zero.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"idle_time_limit":0,"stdout":[[0,"x"]]} diff --git a/tests/fixtures/security/idle-limit-v2-at.cast b/tests/fixtures/security/idle-limit-v2-at.cast new file mode 100644 index 0000000..5e89418 --- /dev/null +++ b/tests/fixtures/security/idle-limit-v2-at.cast @@ -0,0 +1,2 @@ +{"version":2,"width":80,"height":24,"idle_time_limit":2147483.647} +[0,"o","x"] diff --git a/tests/fixtures/security/idle-limit-v2-over.cast b/tests/fixtures/security/idle-limit-v2-over.cast new file mode 100644 index 0000000..49678fa --- /dev/null +++ b/tests/fixtures/security/idle-limit-v2-over.cast @@ -0,0 +1,2 @@ +{"version":2,"width":80,"height":24,"idle_time_limit":2147483.648} +[0,"o","x"] diff --git a/tests/fixtures/security/idle-limit-v2-zero.cast b/tests/fixtures/security/idle-limit-v2-zero.cast new file mode 100644 index 0000000..e48a4b3 --- /dev/null +++ b/tests/fixtures/security/idle-limit-v2-zero.cast @@ -0,0 +1,2 @@ +{"version":2,"width":80,"height":24,"idle_time_limit":0} +[0,"o","x"] diff --git a/tests/fixtures/security/idle-limit-v3-at.cast b/tests/fixtures/security/idle-limit-v3-at.cast new file mode 100644 index 0000000..23ad8e4 --- /dev/null +++ b/tests/fixtures/security/idle-limit-v3-at.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":80,"rows":24},"idle_time_limit":2147483.647} +[0,"o","x"] diff --git a/tests/fixtures/security/idle-limit-v3-over.cast b/tests/fixtures/security/idle-limit-v3-over.cast new file mode 100644 index 0000000..593d2f7 --- /dev/null +++ b/tests/fixtures/security/idle-limit-v3-over.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":80,"rows":24},"idle_time_limit":2147483.648} +[0,"o","x"] diff --git a/tests/fixtures/security/idle-limit-v3-zero.cast b/tests/fixtures/security/idle-limit-v3-zero.cast new file mode 100644 index 0000000..e1ec531 --- /dev/null +++ b/tests/fixtures/security/idle-limit-v3-zero.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":80,"rows":24},"idle_time_limit":0} +[0,"o","x"] diff --git a/tests/fixtures/security/interval-timeline-v1-at.cast b/tests/fixtures/security/interval-timeline-v1-at.cast new file mode 100644 index 0000000..3622018 --- /dev/null +++ b/tests/fixtures/security/interval-timeline-v1-at.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"stdout":[[1073741.823,"x"],[1073741.824,"end"]]} diff --git a/tests/fixtures/security/interval-timeline-v1-over.cast b/tests/fixtures/security/interval-timeline-v1-over.cast new file mode 100644 index 0000000..40404ae --- /dev/null +++ b/tests/fixtures/security/interval-timeline-v1-over.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"stdout":[[1073741.823,"x"],[1073741.825,"end"]]} diff --git a/tests/fixtures/security/interval-timeline-v3-at.cast b/tests/fixtures/security/interval-timeline-v3-at.cast new file mode 100644 index 0000000..59daa69 --- /dev/null +++ b/tests/fixtures/security/interval-timeline-v3-at.cast @@ -0,0 +1,3 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[1073741.823,"o","x"] +[1073741.824,"o","end"] diff --git a/tests/fixtures/security/interval-timeline-v3-over.cast b/tests/fixtures/security/interval-timeline-v3-over.cast new file mode 100644 index 0000000..41ab183 --- /dev/null +++ b/tests/fixtures/security/interval-timeline-v3-over.cast @@ -0,0 +1,3 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[1073741.823,"o","x"] +[1073741.825,"o","end"] diff --git a/tests/fixtures/security/late-resize-v2-at.cast b/tests/fixtures/security/late-resize-v2-at.cast new file mode 100644 index 0000000..7bb044d --- /dev/null +++ b/tests/fixtures/security/late-resize-v2-at.cast @@ -0,0 +1,3 @@ +{"version":2,"width":80,"height":24} +[0,"o","safe prefix\r\n"] +[12,"r","200x200"] diff --git a/tests/fixtures/security/late-resize-v2-dimensions-at.cast b/tests/fixtures/security/late-resize-v2-dimensions-at.cast new file mode 100644 index 0000000..93ea635 --- /dev/null +++ b/tests/fixtures/security/late-resize-v2-dimensions-at.cast @@ -0,0 +1,3 @@ +{"version":2,"width":80,"height":24} +[0,"o","safe prefix\r\n"] +[12,"r","1000x24"] diff --git a/tests/fixtures/security/late-resize-v2-dimensions-over.cast b/tests/fixtures/security/late-resize-v2-dimensions-over.cast new file mode 100644 index 0000000..1faae6e --- /dev/null +++ b/tests/fixtures/security/late-resize-v2-dimensions-over.cast @@ -0,0 +1,3 @@ +{"version":2,"width":80,"height":24} +[0,"o","safe prefix\r\n"] +[12,"r","1001x24"] diff --git a/tests/fixtures/security/late-resize-v2-over.cast b/tests/fixtures/security/late-resize-v2-over.cast new file mode 100644 index 0000000..21552ae --- /dev/null +++ b/tests/fixtures/security/late-resize-v2-over.cast @@ -0,0 +1,3 @@ +{"version":2,"width":80,"height":24} +[0,"o","safe prefix\r\n"] +[12,"r","201x200"] diff --git a/tests/fixtures/security/late-resize-v3-at.cast b/tests/fixtures/security/late-resize-v3-at.cast new file mode 100644 index 0000000..bdc2bfd --- /dev/null +++ b/tests/fixtures/security/late-resize-v3-at.cast @@ -0,0 +1,3 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[0,"o","safe prefix\r\n"] +[12,"r","200x200"] diff --git a/tests/fixtures/security/late-resize-v3-dimensions-at.cast b/tests/fixtures/security/late-resize-v3-dimensions-at.cast new file mode 100644 index 0000000..a4fad71 --- /dev/null +++ b/tests/fixtures/security/late-resize-v3-dimensions-at.cast @@ -0,0 +1,3 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[0,"o","safe prefix\r\n"] +[12,"r","1000x24"] diff --git a/tests/fixtures/security/late-resize-v3-dimensions-over.cast b/tests/fixtures/security/late-resize-v3-dimensions-over.cast new file mode 100644 index 0000000..e4ebbcf --- /dev/null +++ b/tests/fixtures/security/late-resize-v3-dimensions-over.cast @@ -0,0 +1,3 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[0,"o","safe prefix\r\n"] +[12,"r","1001x24"] diff --git a/tests/fixtures/security/late-resize-v3-over.cast b/tests/fixtures/security/late-resize-v3-over.cast new file mode 100644 index 0000000..141496b --- /dev/null +++ b/tests/fixtures/security/late-resize-v3-over.cast @@ -0,0 +1,3 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[0,"o","safe prefix\r\n"] +[12,"r","201x200"] diff --git a/tests/fixtures/security/malformed-v1-json.cast b/tests/fixtures/security/malformed-v1-json.cast new file mode 100644 index 0000000..ebaaa44 --- /dev/null +++ b/tests/fixtures/security/malformed-v1-json.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"stdout":[} diff --git a/tests/fixtures/security/malformed-v2-event.cast b/tests/fixtures/security/malformed-v2-event.cast new file mode 100644 index 0000000..7177597 --- /dev/null +++ b/tests/fixtures/security/malformed-v2-event.cast @@ -0,0 +1,2 @@ +{"version":2,"width":80,"height":24} +[0,"o",broken] diff --git a/tests/fixtures/security/malformed-v3-event.cast b/tests/fixtures/security/malformed-v3-event.cast new file mode 100644 index 0000000..acb2143 --- /dev/null +++ b/tests/fixtures/security/malformed-v3-event.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[0,"o",broken] diff --git a/tests/fixtures/security/manifest.json b/tests/fixtures/security/manifest.json new file mode 100644 index 0000000..eafa9c3 --- /dev/null +++ b/tests/fixtures/security/manifest.json @@ -0,0 +1,2925 @@ +{ + "schemaVersion": 1, + "seed": "0x41c0ffee", + "generator": "xorshift32-v1; fixed case IDs and fixed resource policies", + "policy": { + "bytes": 33554432, + "v1Bytes": 2097152, + "lineBytes": 262144, + "events": 100000, + "lines": 100000, + "markers": 1000, + "dimension": 1000, + "cells": 40000, + "depth": 15, + "containers": 100016, + "tokens": 400000, + "lineTokens": 20000, + "timelineMs": 2147483647 + }, + "cases": [ + { + "id": "official-v1", + "format": 1, + "description": "Unmodified native capture from the pinned official asciinema recorder; original PTY timings are intentionally retained.", + "category": "valid-control", + "provenance": "official-raw-capture", + "safePlayback": true, + "validity": "format-valid", + "source": { + "file": "official-v1.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 669, + "sha256": "5570c9cdec60a779585db195ecd8dee4756d84706d6b27d3ccd87cf3ba311c97" + }, + { + "id": "seeded-v1-valid", + "format": 1, + "description": "Official captured output plus fixed-seed text; normalized equivalent absolute times across all formats.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": true, + "validity": "format-valid", + "source": { + "file": "seeded-v1-valid.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 567, + "sha256": "05387dceb975f6f8ea5364071517a51a31aeb68337429ae943b07ad2c1da1a67", + "playback": { + "startText": "PR41 START seed 41c0ffee", + "seekText": "PR41 SEEK seed 41c0ffee", + "seekPercent": 80, + "cols": 80, + "rows": 24, + "duration": 12 + } + }, + { + "id": "valid-v1-zero", + "format": 1, + "description": "Zero header dimensions retain upstream 80 by 24 defaults.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "file": "valid-v1-zero.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 77, + "sha256": "04c504e1dbcbf547e86e6bd270d71e9c8b42264f2a3100865f3385a5c7db9199" + }, + { + "id": "dimensions-v1-at", + "format": 1, + "description": "The inclusive per-axis cap still fits within the independent cell budget.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "dimensions-v1-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 81, + "sha256": "7bc9633d4dfdd9044979a1cb6cea2f5a2bb4adc06e4a27a66385ec9c00d66b68", + "boundary": { + "metric": "dimension", + "limit": 1000, + "value": 1000 + } + }, + { + "id": "dimensions-v1-over", + "format": 1, + "description": "Syntactically valid header requests an axis one beyond the dimension cap.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "dimensions-v1-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "dimensions" + }, + "bytes": 81, + "sha256": "f79a1f77a45b62ab7968c8264855af9597254001cf26f4d821c85e8802423a57", + "boundary": { + "metric": "dimension", + "limit": 1000, + "value": 1001 + } + }, + { + "id": "cells-v1-at", + "format": 1, + "description": "Each axis is valid; their product alone selects the cell boundary.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "cells-v1-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 81, + "sha256": "26ecff895ea0a4e099e873b3f513bcd3230572094890519ea238929dc98574cc", + "boundary": { + "metric": "cells", + "limit": 40000, + "value": 40000 + } + }, + { + "id": "depth-v1-at", + "format": 1, + "description": "Unknown metadata reaches the lexical container-depth boundary before JSON allocation.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "depth-v1-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 90, + "sha256": "2cd6cb52a9ed80fa48f794dccb146a50680f8674767d0c484e14b0f5b13e93a5", + "boundary": { + "metric": "depth", + "limit": 15, + "value": 15 + } + }, + { + "id": "events-v1-at", + "format": 1, + "description": "Full default v1 event boundary without first exhausting scalar/container budgets.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":1,\"width\":80,\"height\":24,\"stdout\":[", + "repeat": 1 + }, + { + "text": "[0,\"\"],", + "repeat": 99999 + }, + { + "text": "[0,\"\"]]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 700048, + "sha256": "c71c76ef080410c006fed3b52c51c5eb65394930e8a9e5ebaec098338facf96e", + "boundary": { + "metric": "events", + "limit": 100000, + "value": 100000 + }, + "metrics": { + "events": 100000, + "containers": 100002 + } + }, + { + "id": "cells-v1-over", + "format": 1, + "description": "Each axis is valid; their product alone selects the cell boundary.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "cells-v1-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "cells" + }, + "bytes": 81, + "sha256": "9f1d8560e94e24a113b53cdc97d095ed4d4807756e92ff8464bf7a33f5ba7771", + "boundary": { + "metric": "cells", + "limit": 40000, + "value": 40200 + } + }, + { + "id": "depth-v1-over", + "format": 1, + "description": "Unknown metadata reaches the lexical container-depth boundary before JSON allocation.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "depth-v1-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "complexity", + "noDecodeAtOrAboveBytes": 91 + }, + "bytes": 92, + "sha256": "3b2252fefdbfba79c360cd472ba03238d47f787319fb4b1fc7623a7f03abd57e", + "boundary": { + "metric": "depth", + "limit": 15, + "value": 16 + } + }, + { + "id": "events-v1-over", + "format": 1, + "description": "Full default v1 event boundary without first exhausting scalar/container budgets.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":1,\"width\":80,\"height\":24,\"stdout\":[", + "repeat": 1 + }, + { + "text": "[0,\"\"],", + "repeat": 100000 + }, + { + "text": "[0,\"\"]]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "events" + }, + "bytes": 700055, + "sha256": "25e6ee13936ea8804b8bd7c501ca767e89ac9d8274eb02af5e6ee6750d4103bd", + "boundary": { + "metric": "events", + "limit": 100000, + "value": 100001 + }, + "metrics": { + "events": 100001, + "containers": 100003 + } + }, + { + "id": "official-v2", + "format": 2, + "description": "Unmodified native capture from the pinned official asciinema recorder; original PTY timings are intentionally retained.", + "category": "valid-control", + "provenance": "official-raw-capture", + "safePlayback": true, + "validity": "format-valid", + "source": { + "file": "official-v2.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 498, + "sha256": "6be6f5cd70d4a428692fc7807549b9c1437c1c8b60902220ad5e7e01a201f3ee" + }, + { + "id": "seeded-v2-valid", + "format": 2, + "description": "Official captured output plus fixed-seed text; normalized equivalent absolute times across all formats.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": true, + "validity": "format-valid", + "source": { + "file": "seeded-v2-valid.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 449, + "sha256": "85d9dcb646d6f308d5f46804fb2adccf4f4b930b758a0d0b892383611464c539", + "playback": { + "startText": "PR41 START seed 41c0ffee", + "seekText": "PR41 SEEK seed 41c0ffee", + "seekPercent": 80, + "cols": 80, + "rows": 24, + "duration": 12 + } + }, + { + "id": "valid-v2-zero", + "format": 2, + "description": "Zero header dimensions retain upstream 80 by 24 defaults.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "file": "valid-v2-zero.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 70, + "sha256": "ec1527865e0a55285f085006343a5deb943c209bb7081a9ad4c660a272511bea" + }, + { + "id": "dimensions-v2-at", + "format": 2, + "description": "The inclusive per-axis cap still fits within the independent cell budget.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "dimensions-v2-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 74, + "sha256": "255875d5c33c50f26f126a9e7a25929ebeceaeefc56a3a6367ef8ab84df2edac", + "boundary": { + "metric": "dimension", + "limit": 1000, + "value": 1000 + } + }, + { + "id": "dimensions-v2-over", + "format": 2, + "description": "Syntactically valid header requests an axis one beyond the dimension cap.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "dimensions-v2-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "dimensions" + }, + "bytes": 74, + "sha256": "0f2176efd6907d3c66d2d4c6ad11bd9551ab07e96f80d4a9c02d3e5ad686ac47", + "boundary": { + "metric": "dimension", + "limit": 1000, + "value": 1001 + } + }, + { + "id": "cells-v2-at", + "format": 2, + "description": "Each axis is valid; their product alone selects the cell boundary.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "cells-v2-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 74, + "sha256": "df554764f21861bd394bb27cc249996a8f32285d4f4ce0f1e48280a142d1377a", + "boundary": { + "metric": "cells", + "limit": 40000, + "value": 40000 + } + }, + { + "id": "depth-v2-at", + "format": 2, + "description": "Unknown metadata reaches the lexical container-depth boundary before JSON allocation.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "depth-v2-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 78, + "sha256": "f7fd7b690ef5d53bbd5c585a4043a82c2dc78924724dad1f98d01fc314a74a88", + "boundary": { + "metric": "depth", + "limit": 15, + "value": 15 + } + }, + { + "id": "events-v2-at", + "format": 2, + "description": "Event and physical-line caps coincide for output-only JSONL.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24}\n", + "repeat": 1 + }, + { + "text": "[0,\"o\",\"\"]\n", + "repeat": 100000 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 1100037, + "sha256": "57fc86b48ccad1660dec8ae1d77ea6c4374e177e966ff34797e971150aaa0145", + "boundary": { + "metric": "events", + "limit": 100000, + "value": 100000 + }, + "metrics": { + "events": 100000 + } + }, + { + "id": "cells-v2-over", + "format": 2, + "description": "Each axis is valid; their product alone selects the cell boundary.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "cells-v2-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "cells" + }, + "bytes": 74, + "sha256": "af1d48e1597d1e51c856defb7abeb1eabcc4db4d420ea65ee78c5de6dedac5f8", + "boundary": { + "metric": "cells", + "limit": 40000, + "value": 40200 + } + }, + { + "id": "depth-v2-over", + "format": 2, + "description": "Unknown metadata reaches the lexical container-depth boundary before JSON allocation.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "depth-v2-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "complexity", + "noDecodeAtOrAboveBytes": 79 + }, + "bytes": 80, + "sha256": "51e078ee1319a808671b350b10fe262ec0df75d0636a29c5cf5a3dcda8aca333", + "boundary": { + "metric": "depth", + "limit": 15, + "value": 16 + } + }, + { + "id": "events-v2-over", + "format": 2, + "description": "Event and physical-line caps coincide for output-only JSONL.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24}\n", + "repeat": 1 + }, + { + "text": "[0,\"o\",\"\"]\n", + "repeat": 100001 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "events" + }, + "bytes": 1100048, + "sha256": "6af91a929e95c14806735cbf669b3f9a7d05a9be8b3468653e5bbd585441d3ad", + "boundary": { + "metric": "events", + "limit": 100000, + "value": 100001 + }, + "metrics": { + "events": 100001 + } + }, + { + "id": "official-v3", + "format": 3, + "description": "Unmodified native capture from the pinned official asciinema recorder; original PTY timings are intentionally retained.", + "category": "valid-control", + "provenance": "official-raw-capture", + "safePlayback": true, + "validity": "format-valid", + "source": { + "file": "official-v3.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 509, + "sha256": "8c07c04edf86605558a9795152fcba32337d72aeaa073bc89adb1c285f06763e" + }, + { + "id": "seeded-v3-valid", + "format": 3, + "description": "Official captured output plus fixed-seed text; normalized equivalent absolute times across all formats.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": true, + "validity": "format-valid", + "source": { + "file": "seeded-v3-valid.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 454, + "sha256": "6de8e2475abdcd517381e8ce74b62e665c8e841c4d792dae54a3f8c7ff9a1a69", + "playback": { + "startText": "PR41 START seed 41c0ffee", + "seekText": "PR41 SEEK seed 41c0ffee", + "seekPercent": 80, + "cols": 80, + "rows": 24, + "duration": 12 + } + }, + { + "id": "valid-v3-zero", + "format": 3, + "description": "Zero header dimensions retain upstream 80 by 24 defaults.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "file": "valid-v3-zero.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 76, + "sha256": "35bdaac124b7062a9bd5ed6789c4bdae51abcd3e763a227e71830e388ae6d297" + }, + { + "id": "dimensions-v3-at", + "format": 3, + "description": "The inclusive per-axis cap still fits within the independent cell budget.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "dimensions-v3-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 80, + "sha256": "1278fec4786bc368ab96e9b9e338f48d3e14f877953387f725690ba9bc643afb", + "boundary": { + "metric": "dimension", + "limit": 1000, + "value": 1000 + } + }, + { + "id": "dimensions-v3-over", + "format": 3, + "description": "Syntactically valid header requests an axis one beyond the dimension cap.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "dimensions-v3-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "dimensions" + }, + "bytes": 80, + "sha256": "3c5ced3045d1c010de16b8d0cd282a79bb17551d0c0c1fc53b189a82425169ba", + "boundary": { + "metric": "dimension", + "limit": 1000, + "value": 1001 + } + }, + { + "id": "cells-v3-at", + "format": 3, + "description": "Each axis is valid; their product alone selects the cell boundary.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "cells-v3-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 80, + "sha256": "61231dbb565ec0cdd7c89d3f4d8688c5d6bf2d17b3294c7f0ef98deaaea16c0e", + "boundary": { + "metric": "cells", + "limit": 40000, + "value": 40000 + } + }, + { + "id": "depth-v3-at", + "format": 3, + "description": "Unknown metadata reaches the lexical container-depth boundary before JSON allocation.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "depth-v3-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 84, + "sha256": "a6cfe309d36ae639275b67a1a2c00bc03ce3235974ca7294fde8ff60f8208cf2", + "boundary": { + "metric": "depth", + "limit": 15, + "value": 15 + } + }, + { + "id": "events-v3-at", + "format": 3, + "description": "Event and physical-line caps coincide for output-only JSONL.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24}}\n", + "repeat": 1 + }, + { + "text": "[0,\"o\",\"\"]\n", + "repeat": 100000 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 1100043, + "sha256": "965c22bbad2905fdcd25d82b5aa002abb8f34a57c18c4f3c4668cf90bbcb2468", + "boundary": { + "metric": "events", + "limit": 100000, + "value": 100000 + }, + "metrics": { + "events": 100000 + } + }, + { + "id": "cells-v3-over", + "format": 3, + "description": "Each axis is valid; their product alone selects the cell boundary.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "cells-v3-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "cells" + }, + "bytes": 80, + "sha256": "60edabd87f7cc6015e1a67b316fa6f32fa586017fce48fcd3893fd3898371e82", + "boundary": { + "metric": "cells", + "limit": 40000, + "value": 40200 + } + }, + { + "id": "depth-v3-over", + "format": 3, + "description": "Unknown metadata reaches the lexical container-depth boundary before JSON allocation.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "depth-v3-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "complexity", + "noDecodeAtOrAboveBytes": 85 + }, + "bytes": 86, + "sha256": "eecde03b2cc45a188375df173650c54d0eea47887c65385d6ccdb49e602f7ad5", + "boundary": { + "metric": "depth", + "limit": 15, + "value": 16 + } + }, + { + "id": "events-v3-over", + "format": 3, + "description": "Event and physical-line caps coincide for output-only JSONL.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24}}\n", + "repeat": 1 + }, + { + "text": "[0,\"o\",\"\"]\n", + "repeat": 100001 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "events" + }, + "bytes": 1100054, + "sha256": "9c3fd37d34b5949bd88d501cd27ac03915169296c55c2e32c271986f43fb519e", + "boundary": { + "metric": "events", + "limit": 100000, + "value": 100001 + }, + "metrics": { + "events": 100001 + } + }, + { + "id": "timeline-v1-at", + "format": 1, + "description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "timeline-v1-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 66, + "sha256": "5622319d9372013c48101ef2944cd5d079084b0df144a1fcc69140cd5b66d9f5", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "duration-v1-at", + "format": 1, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "duration-v1-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 79, + "sha256": "02b5c0e111adb26dfb6dd5c792ea48ebb853d0618cf1860fd2857d2d06f4980c", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "idle-limit-v1-at", + "format": 1, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "idle-limit-v1-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 86, + "sha256": "76038e9c90775dc12c299c3c2dd4f265bf4ee3b6e4cd2b66c95688b859becd43", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "timeline-v1-over", + "format": 1, + "description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "timeline-v1-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 66, + "sha256": "177d6d8d97d72f2a5416b7eb1b9e32c2cc2b620a20ae1c70d5494406befc17f9", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "duration-v1-over", + "format": 1, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "duration-v1-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 79, + "sha256": "32da9450dc0f53f8d044006c967296ac50d9311a7e8a86f4730aebff191d03f3", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "idle-limit-v1-over", + "format": 1, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "idle-limit-v1-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 86, + "sha256": "7ad90f6743ea0f90c4ed00a9c1dc361d5640b8abeaaf0c7cfd5dd9e190209398", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "duration-v1-zero", + "format": 1, + "description": "Zero remains valid for optional timing metadata.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "duration-v1-zero.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 69, + "sha256": "14f1b40e1d57c7b00a6024c1e4e5a4d68723207eb447c91f721a6cfce0674d4e" + }, + { + "id": "idle-limit-v1-zero", + "format": 1, + "description": "Zero remains valid for optional timing metadata.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "idle-limit-v1-zero.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 76, + "sha256": "ba707de0f768ed2fe89ebd7d8751c4febc6c7eb4be4ac21b4be6e69324353c98" + }, + { + "id": "timeline-v2-at", + "format": 2, + "description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "timeline-v2-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 59, + "sha256": "5dcb182b6e3ccf2573e58408f7ac44599fcc6ac92b3951f8fd3c2bb3138d1e4f", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "duration-v2-at", + "format": 2, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "duration-v2-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 72, + "sha256": "257b671345d8f515afa242242f313125fecbe58a92f7e690861d6b38e0b1ec36", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "idle-limit-v2-at", + "format": 2, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "idle-limit-v2-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 79, + "sha256": "e5f12262b1b1a76970785cbbe98126f0d8061dffce1b623aeaa150dac0f4ffea", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "timeline-v2-over", + "format": 2, + "description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "timeline-v2-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 59, + "sha256": "7717e9978f2767db79388c597a683e216445146c0f7fe2e639401cdafad94267", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "duration-v2-over", + "format": 2, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "duration-v2-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 72, + "sha256": "a7eaae002cebeec39c2c1ea0832a261ec66a8bab76dafaeaaa252e1e6ab641dd", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "idle-limit-v2-over", + "format": 2, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "idle-limit-v2-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 79, + "sha256": "c10e47c6405d2f2087ff4348584722bc5e89c9c7bb8d69648d446189d268ce01", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "duration-v2-zero", + "format": 2, + "description": "Zero remains valid for optional timing metadata.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "duration-v2-zero.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 62, + "sha256": "f8ccb56b4dc1b3b8535af7ea4eaad3c6f0d6475563aa9c593ca0e4a4821943dd" + }, + { + "id": "idle-limit-v2-zero", + "format": 2, + "description": "Zero remains valid for optional timing metadata.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "idle-limit-v2-zero.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 69, + "sha256": "b34ea66b9bd4c165b55ca39523a5874f29d68cc9277eb3cca4de589691732d1a" + }, + { + "id": "timeline-v3-at", + "format": 3, + "description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "timeline-v3-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 65, + "sha256": "1e234fb56af6cc042a6daf77a6b833db2f5ecab6aae35a1c7e3821051dce2ec5", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "duration-v3-at", + "format": 3, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "duration-v3-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 78, + "sha256": "b363b4bc5077858e30fa0e188cb49d5b50c9d40fe5f0f14ced04bf835b2e2d21", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "idle-limit-v3-at", + "format": 3, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "idle-limit-v3-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 85, + "sha256": "b787da8e6ba022bc3a2ac8780aa8073ea4ca82b92d018cccbf22655846122dd0", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "timeline-v3-over", + "format": 3, + "description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "timeline-v3-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 65, + "sha256": "aafb1fabc891df6843942f69ac945e13ea77865a2542cca1d02db6bb1c8080bf", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "duration-v3-over", + "format": 3, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "duration-v3-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 78, + "sha256": "5fcf1f75486d94f71463e6320886d0a51721f8fdbe1063593b5a1d14c14978d1", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "idle-limit-v3-over", + "format": 3, + "description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "idle-limit-v3-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 85, + "sha256": "a3624e3fc0bd3c420dbfe91018b47b840b7fb09e10fba7365fee079e2615bef6", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "duration-v3-zero", + "format": 3, + "description": "Zero remains valid for optional timing metadata.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "duration-v3-zero.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 68, + "sha256": "2d40499454b3b7a1589b91004115e2a9d53a18e7167ccefe9352eda66bbfb2d8" + }, + { + "id": "idle-limit-v3-zero", + "format": 3, + "description": "Zero remains valid for optional timing metadata.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "idle-limit-v3-zero.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 75, + "sha256": "bdc71879c2d7f3d8338d31038133d070b2d9dc6e398f6b133c45e90750509016" + }, + { + "id": "interval-timeline-v1-at", + "format": 1, + "description": "Each interval is inside the horizon; only their upstream-order millisecond sum selects the boundary.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "interval-timeline-v1-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 86, + "sha256": "8e9c5b96b20566f12fe9a15e1c8269461d0dbc6ba6d1a06a83aff581f872d0fc", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "interval-timeline-v1-over", + "format": 1, + "description": "Each interval is inside the horizon; only their upstream-order millisecond sum selects the boundary.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "interval-timeline-v1-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 86, + "sha256": "7fec7732286f679ef8f0e71f4f3fae0f9078dab6684eda81f517bd1d5b39d3bf", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "time-v1-ms-rounding-over", + "format": 1, + "description": "Adding seconds before conversion rounds to the allowed cap, but summing each interval in milliseconds exceeds it.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "time-v1-ms-rounding-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 99, + "sha256": "06283761ce7b12acdc6352ebaa71b7691e723aa3be6592bd6b9eb3c4ad3a547c", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647.0000002 + } + }, + { + "id": "time-v1-ms-sum-overflow", + "format": 1, + "description": "Both converted intervals and the converted seconds sum are finite, but upstream interval-by-interval millisecond addition overflows.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "time-v1-ms-sum-overflow.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 109, + "sha256": "7ac8311d1533b23a5115195bd004804d7b0b1f1540a5782ff865af22dec295d7" + }, + { + "id": "interval-timeline-v3-at", + "format": 3, + "description": "Each interval is inside the horizon; only their upstream-order millisecond sum selects the boundary.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "interval-timeline-v3-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 89, + "sha256": "3f76fc28485f0670f5b62210fd580950c404a1809ede166e53ad75c0960cb8bc", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647 + } + }, + { + "id": "interval-timeline-v3-over", + "format": 3, + "description": "Each interval is inside the horizon; only their upstream-order millisecond sum selects the boundary.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "interval-timeline-v3-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 89, + "sha256": "9f311bc12ed12e6208d8821a593ab6e1ec17cf4c7d926ff00f83ca06741e1758", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483648 + } + }, + { + "id": "time-v3-ms-rounding-over", + "format": 3, + "description": "Adding seconds before conversion rounds to the allowed cap, but summing each interval in milliseconds exceeds it.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "time-v3-ms-rounding-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 102, + "sha256": "21bdf134dee3e29fce0166b4c71c2657d47796b3e7cb33667b82de08df3bcadf", + "boundary": { + "metric": "timelineMs", + "limit": 2147483647, + "value": 2147483647.0000002 + } + }, + { + "id": "time-v3-ms-sum-overflow", + "format": 3, + "description": "Both converted intervals and the converted seconds sum are finite, but upstream interval-by-interval millisecond addition overflows.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "time-v3-ms-sum-overflow.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 112, + "sha256": "4ce89449651ac5435e81a8635dda115b2022d325217871177079d41cd143be5a" + }, + { + "id": "time-v2-output-nonprogress", + "format": 2, + "description": "A tiny finite timestamp makes the upstream output batching deadline equal its start, so callbacks repeat without consuming output.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "time-v2-output-nonprogress.cast" + }, + "expected": { + "accepted": false, + "jsError": "time" + }, + "bytes": 69, + "sha256": "92abcf13adcfc3f65e61c7ab7d367f9e7cd41bb7bd38b4b11bef280b51fee536" + }, + { + "id": "valid-v1-multiline-late-version", + "format": 1, + "description": "Pretty v1 document places its version after stdout and nested metadata.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "valid-v1-multiline-late-version.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 118, + "sha256": "b880e78e1eda1c7af9f4314c3a8616b6b0f59d5b303da32b42c12666d8f9631f" + }, + { + "id": "valid-v1-escaped-version", + "format": 1, + "description": "Escaped top-level version key is still v1.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "valid-v1-escaped-version.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 54, + "sha256": "1751cc02e9b68aaba282bec2ec342284e34156ce14c4ba14e19c7c1e50b450fd" + }, + { + "id": "valid-v1-duplicate-version", + "format": 1, + "description": "Last duplicate version wins under the bundled JSON parsers.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "file": "valid-v1-duplicate-version.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 61, + "sha256": "b5fab04e377aff641d356ce60df56d32500e9b5d2ba6e708c954098071570d77" + }, + { + "id": "malformed-v1-json", + "format": 1, + "description": "Deliberately missing the stdout array closer.", + "category": "malformed", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "intentionally-malformed", + "source": { + "file": "malformed-v1-json.cast" + }, + "expected": { + "accepted": false, + "jsError": "invalid" + }, + "bytes": 48, + "sha256": "5f45f691f06d91df269bc770f33238421b30d49b97133dafef165448559bd2d8" + }, + { + "id": "valid-v2-filtered-lines", + "format": 2, + "description": "Blank/comment/indented non-event lines follow upstream filtering, not strict canonical JSONL.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "file": "valid-v2-filtered-lines.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 126, + "sha256": "221d89e55f0649959be5eb8394571e3f83aa05176ac65dcc1c52d3d91b809100" + }, + { + "id": "late-resize-v2-at", + "format": 2, + "description": "Ordinary output precedes an inclusive 40,000-cell late resize.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "late-resize-v2-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 82, + "sha256": "ffb49928a780aea6067e634de60511f9aebbbd6ee0eb2582f93886ab94a5ad11", + "boundary": { + "metric": "cells", + "limit": 40000, + "value": 40000 + } + }, + { + "id": "late-resize-v2-over", + "format": 2, + "description": "Ordinary output precedes a late resize with valid axes but excessive cells.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "late-resize-v2-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "cells" + }, + "bytes": 82, + "sha256": "96565fabf9cb3ded67ee202a01aaccb76d1544023d2fac3378e41e4648c598df", + "boundary": { + "metric": "cells", + "limit": 40000, + "value": 40200 + } + }, + { + "id": "late-resize-v2-dimensions-at", + "format": 2, + "description": "Ordinary output precedes an inclusive 1,000-column late resize.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "late-resize-v2-dimensions-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 82, + "sha256": "bce032adcfd8c9d2e3f113de9ee0a5260830a385fb1dfdc2fbd000f322bed6b6", + "boundary": { + "metric": "dimension", + "limit": 1000, + "value": 1000 + } + }, + { + "id": "late-resize-v2-dimensions-over", + "format": 2, + "description": "Ordinary output precedes a late resize exceeding the per-axis dimension cap.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "late-resize-v2-dimensions-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "dimensions" + }, + "bytes": 82, + "sha256": "0b570ba590d999147de1cf0943aa3e750402d96a63d9982a6601ee0fc3f813e4", + "boundary": { + "metric": "dimension", + "limit": 1000, + "value": 1001 + } + }, + { + "id": "malformed-v2-event", + "format": 2, + "description": "Deliberately invalid JSON event after a valid header.", + "category": "malformed", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "intentionally-malformed", + "source": { + "file": "malformed-v2-event.cast" + }, + "expected": { + "accepted": false, + "jsError": "invalid" + }, + "bytes": 52, + "sha256": "7286d745ff6874798d4f79fbbf8584f9a7f20c3a9a60155ee45fc3e0f494915a" + }, + { + "id": "markers-v2-at", + "format": 2, + "description": "Marker count boundary; bytes, line count and dimensions remain small.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24}\n", + "repeat": 1 + }, + { + "text": "[0,\"m\",\"mark\"]\n", + "repeat": 1000 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 15037, + "sha256": "75fcbeb7634a6faf4de37303a1444117c0689857fb7ca940017be793a40f5780", + "boundary": { + "metric": "markers", + "limit": 1000, + "value": 1000 + } + }, + { + "id": "line-v2-at", + "format": 2, + "description": "One syntactically valid output event at the UTF-8 line-byte boundary, including LF.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24}\n[0,\"o\",\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 262133 + }, + { + "text": "\"]\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 262181, + "sha256": "4e748b9d68567d94985c2eb049b274ca7d080908ae1e149ec8d1d2d7e7931568", + "boundary": { + "metric": "lineBytes", + "limit": 262144, + "value": 262144 + } + }, + { + "id": "bytes-v2-at", + "format": 2, + "description": "Full 32 MiB body boundary using valid output events; no padding comments or oversized line.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24}\n", + "repeat": 1 + }, + { + "text": "[0,\"o\",\"6ikeld355ettzbav0edcciasg9oz66x012w65rtw3ws0todkm42n3n3h9gas4fobyg2kip4331i5eplpt53ce8b01eel3h2a19zr4jzpp7lztthp0ab5kzmrbark8skestajv9jh80hwv9mwqacu3i49xw6bfzszeuydlmqhenm8m0e8lwddrf73lquqs2dtj1iepx6ledrkeuh0j3rj0q5d6q70x4bvmxfv8iyz6e0zlbrihyk56h7z43sf0fsx5y53aojl61w1o7n1och9kkx6d7z5f7f1npm76na6t5ai2d17f734g7mfznexz1eujxxbilmrqkorwkkkk6suxkcloklwgj9a6jq77jl4p40decjvb81xf7we6fcv1amd95s6xqe1payaoqon5v8tjxn8sqdlezaagajkug7a80uy2sju546d1h1w9eeznwugvpimmrvkgv5nycpuat4vi7oi4bk7qqm2l40jwr2xkoqo7tbtnsvkda6bz9sk14uob9jwn80q0zm60bnydmhx5mzt8yyul7rwio8v6xww52xgrpyldh7irah2kojd11xr0qnoc09axnzdrr34pfluxq7jzk9nkkg4ovmgo5lmlae0zqmyodqed13v4mhbsfma0828xlhg3wcirghnh46e8dm40brg0scm8ftg30qg6osqwivxx3a6o4psz35nv4ct186929fp7zgui190sbhkfght9kne77sobkt2hllgu91ksdx9ci0fxoudvweonwih1umugmbr9vbeofilryqtx3gown7f59jyv71p14hkc5mt3yrb1e2v1fy8c7ew4wkicsu5wtghwkrr09dhquxouymvmwjmshqqtgavk3j7452uo4pkgq6394ncfoh2csc8a8lxd506xly05jwy1zcv1whuqgcz7y09yq9wk4r1dbzibvs5o6xeg2b7uzhmxojcmlqhmi4echac5x4azrn3pfhnz7jxy3vo65zw63ewry7oqtt6vzrqs\"]\n", + "repeat": 32767 + }, + { + "text": "[0,\"o\",\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 976 + }, + { + "text": "\"]\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 33554432, + "sha256": "92ed2e090e4b8adcd0df98d8b40a843a9227bee54a63ff77d70dacd2eb365d36", + "boundary": { + "metric": "bytes", + "limit": 33554432, + "value": 33554432 + }, + "metrics": { + "events": 32768, + "maximumLineBytes": 1024 + } + }, + { + "id": "line-tokens-v2-at", + "format": 2, + "description": "Wide metadata uses the strict per-line scalar/key token cap, never the legacy v1 cap.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24,\"metadata\":[", + "repeat": 1 + }, + { + "text": "0,", + "repeat": 19992 + }, + { + "text": "0]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 40036, + "sha256": "f617da5b250cb33ed51fd83247bf7c1b0761b76adfae65fe6f59df2d46b2fb5a", + "boundary": { + "metric": "lineTokens", + "limit": 20000, + "value": 20000 + } + }, + { + "id": "ignored-lines-v2-at", + "format": 2, + "description": "One valid output event plus ignored blank lines isolates the physical JSONL processing budget.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24}\n[0,\"o\",\"line budget control\\r\\n\"]\n", + "repeat": 1 + }, + { + "text": "\n", + "repeat": 99999 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 100070, + "sha256": "3db79cec2faca5bdfe56fce05bdddf59de7a8acb96339b2473287e12377edb65", + "boundary": { + "metric": "lines", + "limit": 100000, + "value": 100000 + }, + "metrics": { + "events": 1 + } + }, + { + "id": "markers-v2-over", + "format": 2, + "description": "Marker count boundary; bytes, line count and dimensions remain small.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24}\n", + "repeat": 1 + }, + { + "text": "[0,\"m\",\"mark\"]\n", + "repeat": 1001 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "markers" + }, + "bytes": 15052, + "sha256": "90783145cf467368dff8925a73857f908436523c0ce19d2778cab6c62bed3f15", + "boundary": { + "metric": "markers", + "limit": 1000, + "value": 1001 + } + }, + { + "id": "line-v2-over", + "format": 2, + "description": "One syntactically valid output event at the UTF-8 line-byte boundary, including LF.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24}\n[0,\"o\",\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 262134 + }, + { + "text": "\"]\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "line", + "noDecodeAtOrAboveBytes": 262144 + }, + "bytes": 262182, + "sha256": "d0535f1b60bd84f891bbd4d4b0e2287bf3563c60d03d2ff5b5bef783dcb2a339", + "boundary": { + "metric": "lineBytes", + "limit": 262144, + "value": 262145 + } + }, + { + "id": "bytes-v2-over", + "format": 2, + "description": "Full 32 MiB body boundary using valid output events; no padding comments or oversized line.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24}\n", + "repeat": 1 + }, + { + "text": "[0,\"o\",\"6ikeld355ettzbav0edcciasg9oz66x012w65rtw3ws0todkm42n3n3h9gas4fobyg2kip4331i5eplpt53ce8b01eel3h2a19zr4jzpp7lztthp0ab5kzmrbark8skestajv9jh80hwv9mwqacu3i49xw6bfzszeuydlmqhenm8m0e8lwddrf73lquqs2dtj1iepx6ledrkeuh0j3rj0q5d6q70x4bvmxfv8iyz6e0zlbrihyk56h7z43sf0fsx5y53aojl61w1o7n1och9kkx6d7z5f7f1npm76na6t5ai2d17f734g7mfznexz1eujxxbilmrqkorwkkkk6suxkcloklwgj9a6jq77jl4p40decjvb81xf7we6fcv1amd95s6xqe1payaoqon5v8tjxn8sqdlezaagajkug7a80uy2sju546d1h1w9eeznwugvpimmrvkgv5nycpuat4vi7oi4bk7qqm2l40jwr2xkoqo7tbtnsvkda6bz9sk14uob9jwn80q0zm60bnydmhx5mzt8yyul7rwio8v6xww52xgrpyldh7irah2kojd11xr0qnoc09axnzdrr34pfluxq7jzk9nkkg4ovmgo5lmlae0zqmyodqed13v4mhbsfma0828xlhg3wcirghnh46e8dm40brg0scm8ftg30qg6osqwivxx3a6o4psz35nv4ct186929fp7zgui190sbhkfght9kne77sobkt2hllgu91ksdx9ci0fxoudvweonwih1umugmbr9vbeofilryqtx3gown7f59jyv71p14hkc5mt3yrb1e2v1fy8c7ew4wkicsu5wtghwkrr09dhquxouymvmwjmshqqtgavk3j7452uo4pkgq6394ncfoh2csc8a8lxd506xly05jwy1zcv1whuqgcz7y09yq9wk4r1dbzibvs5o6xeg2b7uzhmxojcmlqhmi4echac5x4azrn3pfhnz7jxy3vo65zw63ewry7oqtt6vzrqs\"]\n", + "repeat": 32767 + }, + { + "text": "[0,\"o\",\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 977 + }, + { + "text": "\"]\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "bytes", + "noDecodeAtOrAboveBytes": 33554432, + "phpNoDecodeAtOrAboveBytes": 1 + }, + "bytes": 33554433, + "sha256": "b78f14b8c2d6e84c4d05cc63f95aa2a4862df2554b9ada53e8ef44f72828866a", + "boundary": { + "metric": "bytes", + "limit": 33554432, + "value": 33554433 + }, + "metrics": { + "events": 32768, + "maximumLineBytes": 1024 + } + }, + { + "id": "line-tokens-v2-over", + "format": 2, + "description": "Wide metadata uses the strict per-line scalar/key token cap, never the legacy v1 cap.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24,\"metadata\":[", + "repeat": 1 + }, + { + "text": "0,", + "repeat": 19993 + }, + { + "text": "0]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "complexity", + "noDecodeAtOrAboveBytes": 40037 + }, + "bytes": 40038, + "sha256": "3b5bf2ed376decdd3374631712e422d87b44d3c2521f7b1a66c9b0f40a864a22", + "boundary": { + "metric": "lineTokens", + "limit": 20000, + "value": 20001 + } + }, + { + "id": "ignored-lines-v2-over", + "format": 2, + "description": "One valid output event plus ignored blank lines isolates the physical JSONL processing budget.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "segments": [ + { + "text": "{\"version\":2,\"width\":80,\"height\":24}\n[0,\"o\",\"line budget control\\r\\n\"]\n", + "repeat": 1 + }, + { + "text": "\n", + "repeat": 100000 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "events" + }, + "bytes": 100071, + "sha256": "649a236f1e63afb4ea6c1c00be4c84b5a416de4302779b5e29286e67484366b8", + "boundary": { + "metric": "lines", + "limit": 100000, + "value": 100001 + }, + "metrics": { + "events": 1 + } + }, + { + "id": "valid-v3-filtered-lines", + "format": 3, + "description": "Blank/comment/indented non-event lines follow upstream filtering, not strict canonical JSONL.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "file": "valid-v3-filtered-lines.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 132, + "sha256": "c64e6e629557c6ea131afdfe8f63ba75bb55dd0cee711370448f0c8f5649dac5" + }, + { + "id": "late-resize-v3-at", + "format": 3, + "description": "Ordinary output precedes an inclusive 40,000-cell late resize.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "late-resize-v3-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 88, + "sha256": "8bafb2d2c880b6075c3943acdeb9e44aead6d1c6b4903813fd3468915bcc4b82", + "boundary": { + "metric": "cells", + "limit": 40000, + "value": 40000 + } + }, + { + "id": "late-resize-v3-over", + "format": 3, + "description": "Ordinary output precedes a late resize with valid axes but excessive cells.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "late-resize-v3-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "cells" + }, + "bytes": 88, + "sha256": "73b4615865b143e7e47106cf3bff0a0a289c432d6d279455b81971676c834519", + "boundary": { + "metric": "cells", + "limit": 40000, + "value": 40200 + } + }, + { + "id": "late-resize-v3-dimensions-at", + "format": 3, + "description": "Ordinary output precedes an inclusive 1,000-column late resize.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "late-resize-v3-dimensions-at.cast" + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 88, + "sha256": "2ac50b0476d348fd3701c8ff124a8d541c5aa0527e7b2576162c62405db8c816", + "boundary": { + "metric": "dimension", + "limit": 1000, + "value": 1000 + } + }, + { + "id": "late-resize-v3-dimensions-over", + "format": 3, + "description": "Ordinary output precedes a late resize exceeding the per-axis dimension cap.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "file": "late-resize-v3-dimensions-over.cast" + }, + "expected": { + "accepted": false, + "jsError": "dimensions" + }, + "bytes": 88, + "sha256": "4cf8e961c853e43d1e47f36b08857bc11c687665fa6926974eefbf69fcdfd67a", + "boundary": { + "metric": "dimension", + "limit": 1000, + "value": 1001 + } + }, + { + "id": "malformed-v3-event", + "format": 3, + "description": "Deliberately invalid JSON event after a valid header.", + "category": "malformed", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "intentionally-malformed", + "source": { + "file": "malformed-v3-event.cast" + }, + "expected": { + "accepted": false, + "jsError": "invalid" + }, + "bytes": 58, + "sha256": "b82e19503846316be4778dca8088fed0855fdd94bc6d90ebd19f076df33737ce" + }, + { + "id": "markers-v3-at", + "format": 3, + "description": "Marker count boundary; bytes, line count and dimensions remain small.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24}}\n", + "repeat": 1 + }, + { + "text": "[0,\"m\",\"mark\"]\n", + "repeat": 1000 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 15043, + "sha256": "30bd77ed6c1795eb0549028be8d427bdb38f395e25ab6c52f0b8c41f5672cc21", + "boundary": { + "metric": "markers", + "limit": 1000, + "value": 1000 + } + }, + { + "id": "line-v3-at", + "format": 3, + "description": "One syntactically valid output event at the UTF-8 line-byte boundary, including LF.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24}}\n[0,\"o\",\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 262133 + }, + { + "text": "\"]\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 262187, + "sha256": "79fb2e9d2352332a849f5d61a932cf774be3a23544f98ab30ee6a1eb5e14e764", + "boundary": { + "metric": "lineBytes", + "limit": 262144, + "value": 262144 + } + }, + { + "id": "bytes-v3-at", + "format": 3, + "description": "Full 32 MiB body boundary using valid output events; no padding comments or oversized line.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24}}\n", + "repeat": 1 + }, + { + "text": "[0,\"o\",\"6ikeld355ettzbav0edcciasg9oz66x012w65rtw3ws0todkm42n3n3h9gas4fobyg2kip4331i5eplpt53ce8b01eel3h2a19zr4jzpp7lztthp0ab5kzmrbark8skestajv9jh80hwv9mwqacu3i49xw6bfzszeuydlmqhenm8m0e8lwddrf73lquqs2dtj1iepx6ledrkeuh0j3rj0q5d6q70x4bvmxfv8iyz6e0zlbrihyk56h7z43sf0fsx5y53aojl61w1o7n1och9kkx6d7z5f7f1npm76na6t5ai2d17f734g7mfznexz1eujxxbilmrqkorwkkkk6suxkcloklwgj9a6jq77jl4p40decjvb81xf7we6fcv1amd95s6xqe1payaoqon5v8tjxn8sqdlezaagajkug7a80uy2sju546d1h1w9eeznwugvpimmrvkgv5nycpuat4vi7oi4bk7qqm2l40jwr2xkoqo7tbtnsvkda6bz9sk14uob9jwn80q0zm60bnydmhx5mzt8yyul7rwio8v6xww52xgrpyldh7irah2kojd11xr0qnoc09axnzdrr34pfluxq7jzk9nkkg4ovmgo5lmlae0zqmyodqed13v4mhbsfma0828xlhg3wcirghnh46e8dm40brg0scm8ftg30qg6osqwivxx3a6o4psz35nv4ct186929fp7zgui190sbhkfght9kne77sobkt2hllgu91ksdx9ci0fxoudvweonwih1umugmbr9vbeofilryqtx3gown7f59jyv71p14hkc5mt3yrb1e2v1fy8c7ew4wkicsu5wtghwkrr09dhquxouymvmwjmshqqtgavk3j7452uo4pkgq6394ncfoh2csc8a8lxd506xly05jwy1zcv1whuqgcz7y09yq9wk4r1dbzibvs5o6xeg2b7uzhmxojcmlqhmi4echac5x4azrn3pfhnz7jxy3vo65zw63ewry7oqtt6vzrqs\"]\n", + "repeat": 32767 + }, + { + "text": "[0,\"o\",\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 970 + }, + { + "text": "\"]\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 33554432, + "sha256": "af99e69453aad5a30de993d441befb6fe4b190d8f45494f329dd859723abdfa7", + "boundary": { + "metric": "bytes", + "limit": 33554432, + "value": 33554432 + }, + "metrics": { + "events": 32768, + "maximumLineBytes": 1024 + } + }, + { + "id": "line-tokens-v3-at", + "format": 3, + "description": "Wide metadata uses the strict per-line scalar/key token cap, never the legacy v1 cap.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24},\"metadata\":[", + "repeat": 1 + }, + { + "text": "0,", + "repeat": 19991 + }, + { + "text": "0]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 40040, + "sha256": "93a7bde3000ae893b4e580d4667267447c85e66077798abf0ccd3318048395c4", + "boundary": { + "metric": "lineTokens", + "limit": 20000, + "value": 20000 + } + }, + { + "id": "ignored-lines-v3-at", + "format": 3, + "description": "One valid output event plus ignored blank lines isolates the physical JSONL processing budget.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24}}\n[0,\"o\",\"line budget control\\r\\n\"]\n", + "repeat": 1 + }, + { + "text": "\n", + "repeat": 99999 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 100076, + "sha256": "f6f475649caa909fa9f48b2e77053169f956769e6f97483af44d8de56d3073b8", + "boundary": { + "metric": "lines", + "limit": 100000, + "value": 100000 + }, + "metrics": { + "events": 1 + } + }, + { + "id": "markers-v3-over", + "format": 3, + "description": "Marker count boundary; bytes, line count and dimensions remain small.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24}}\n", + "repeat": 1 + }, + { + "text": "[0,\"m\",\"mark\"]\n", + "repeat": 1001 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "markers" + }, + "bytes": 15058, + "sha256": "d62809367a2f725465ff68c267e851cdc7eebc8f6738bc3462a759c0893e1962", + "boundary": { + "metric": "markers", + "limit": 1000, + "value": 1001 + } + }, + { + "id": "line-v3-over", + "format": 3, + "description": "One syntactically valid output event at the UTF-8 line-byte boundary, including LF.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24}}\n[0,\"o\",\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 262134 + }, + { + "text": "\"]\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "line", + "noDecodeAtOrAboveBytes": 262144 + }, + "bytes": 262188, + "sha256": "998cbd9183de4004285d3975c4bd23606f77bb06359fdfbb1b8d81449e61f763", + "boundary": { + "metric": "lineBytes", + "limit": 262144, + "value": 262145 + } + }, + { + "id": "bytes-v3-over", + "format": 3, + "description": "Full 32 MiB body boundary using valid output events; no padding comments or oversized line.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24}}\n", + "repeat": 1 + }, + { + "text": "[0,\"o\",\"6ikeld355ettzbav0edcciasg9oz66x012w65rtw3ws0todkm42n3n3h9gas4fobyg2kip4331i5eplpt53ce8b01eel3h2a19zr4jzpp7lztthp0ab5kzmrbark8skestajv9jh80hwv9mwqacu3i49xw6bfzszeuydlmqhenm8m0e8lwddrf73lquqs2dtj1iepx6ledrkeuh0j3rj0q5d6q70x4bvmxfv8iyz6e0zlbrihyk56h7z43sf0fsx5y53aojl61w1o7n1och9kkx6d7z5f7f1npm76na6t5ai2d17f734g7mfznexz1eujxxbilmrqkorwkkkk6suxkcloklwgj9a6jq77jl4p40decjvb81xf7we6fcv1amd95s6xqe1payaoqon5v8tjxn8sqdlezaagajkug7a80uy2sju546d1h1w9eeznwugvpimmrvkgv5nycpuat4vi7oi4bk7qqm2l40jwr2xkoqo7tbtnsvkda6bz9sk14uob9jwn80q0zm60bnydmhx5mzt8yyul7rwio8v6xww52xgrpyldh7irah2kojd11xr0qnoc09axnzdrr34pfluxq7jzk9nkkg4ovmgo5lmlae0zqmyodqed13v4mhbsfma0828xlhg3wcirghnh46e8dm40brg0scm8ftg30qg6osqwivxx3a6o4psz35nv4ct186929fp7zgui190sbhkfght9kne77sobkt2hllgu91ksdx9ci0fxoudvweonwih1umugmbr9vbeofilryqtx3gown7f59jyv71p14hkc5mt3yrb1e2v1fy8c7ew4wkicsu5wtghwkrr09dhquxouymvmwjmshqqtgavk3j7452uo4pkgq6394ncfoh2csc8a8lxd506xly05jwy1zcv1whuqgcz7y09yq9wk4r1dbzibvs5o6xeg2b7uzhmxojcmlqhmi4echac5x4azrn3pfhnz7jxy3vo65zw63ewry7oqtt6vzrqs\"]\n", + "repeat": 32767 + }, + { + "text": "[0,\"o\",\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 971 + }, + { + "text": "\"]\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "bytes", + "noDecodeAtOrAboveBytes": 33554432, + "phpNoDecodeAtOrAboveBytes": 1 + }, + "bytes": 33554433, + "sha256": "57ae49e6a4db50a55f13138e0ce063c0cc97aaece22cad3a4be8a7aaf7d826ba", + "boundary": { + "metric": "bytes", + "limit": 33554432, + "value": 33554433 + }, + "metrics": { + "events": 32768, + "maximumLineBytes": 1024 + } + }, + { + "id": "line-tokens-v3-over", + "format": 3, + "description": "Wide metadata uses the strict per-line scalar/key token cap, never the legacy v1 cap.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24},\"metadata\":[", + "repeat": 1 + }, + { + "text": "0,", + "repeat": 19992 + }, + { + "text": "0]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "complexity", + "noDecodeAtOrAboveBytes": 40041 + }, + "bytes": 40042, + "sha256": "9bf3a9a2a3febb1c7c66930f0099aedf51043c60fe111aed0fad73f39da520e6", + "boundary": { + "metric": "lineTokens", + "limit": 20000, + "value": 20001 + } + }, + { + "id": "ignored-lines-v3-over", + "format": 3, + "description": "One valid output event plus ignored blank lines isolates the physical JSONL processing budget.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "segments": [ + { + "text": "{\"version\":3,\"term\":{\"cols\":80,\"rows\":24}}\n[0,\"o\",\"line budget control\\r\\n\"]\n", + "repeat": 1 + }, + { + "text": "\n", + "repeat": 100000 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "events" + }, + "bytes": 100077, + "sha256": "172d9e554ba1cef284e2bca3dafe44887fc736fedea5d445e2063f5f0c9c4de0", + "boundary": { + "metric": "lines", + "limit": 100000, + "value": 100001 + }, + "metrics": { + "events": 1 + } + }, + { + "id": "v1-bytes-at", + "format": 1, + "description": "Legacy multiline document has its own 2 MiB budget, distinct from JSONL limits.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[[0,\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 2097096 + }, + { + "text": "\"]]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 2097152, + "sha256": "004c6039b7e8149864e1a9dd5179384920efb4c7405dcb1f15e17f200ed9be7e", + "boundary": { + "metric": "v1Bytes", + "limit": 2097152, + "value": 2097152 + } + }, + { + "id": "tokens-v1-at", + "format": 1, + "description": "Unknown scalar metadata reaches the complete v1 scalar/key allocation budget.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[],\"metadata\":[", + "repeat": 1 + }, + { + "text": "0,", + "repeat": 399991 + }, + { + "text": "0]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 800047, + "sha256": "dcabe9825fcb416f66b71d41739d886931769da001f4c8e88d890547f518be1b", + "boundary": { + "metric": "tokens", + "limit": 400000, + "value": 400000 + } + }, + { + "id": "containers-v1-at", + "format": 1, + "description": "Empty metadata objects isolate the container budget from scalar and event budgets.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[],\"metadata\":[", + "repeat": 1 + }, + { + "text": "{},", + "repeat": 100012 + }, + { + "text": "{}]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 300102, + "sha256": "b608e7b8ccb29206d9b835e0c37038dac8fe7dada8ce82deb2c7c8eb91d97f73", + "boundary": { + "metric": "containers", + "limit": 100016, + "value": 100016 + } + }, + { + "id": "v1-bytes-over", + "format": 1, + "description": "Legacy multiline document has its own 2 MiB budget, distinct from JSONL limits.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[[0,\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 2097097 + }, + { + "text": "\"]]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "bytes", + "noDecodeAtOrAboveBytes": 2097152 + }, + "bytes": 2097153, + "sha256": "6e7230f8e180e009fab853fbb8446b7657d7d2792b9d4ad745a5e25afeb0675c", + "boundary": { + "metric": "v1Bytes", + "limit": 2097152, + "value": 2097153 + } + }, + { + "id": "tokens-v1-over", + "format": 1, + "description": "Unknown scalar metadata reaches the complete v1 scalar/key allocation budget.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[],\"metadata\":[", + "repeat": 1 + }, + { + "text": "0,", + "repeat": 399992 + }, + { + "text": "0]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "complexity", + "noDecodeAtOrAboveBytes": 800048 + }, + "bytes": 800049, + "sha256": "0cea5476465537e8e46f20ab5a597c2d522f1318424189ddba30705bb13300e7", + "boundary": { + "metric": "tokens", + "limit": 400000, + "value": 400001 + } + }, + { + "id": "containers-v1-over", + "format": 1, + "description": "Empty metadata objects isolate the container budget from scalar and event budgets.", + "category": "resource-boundary", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[],\"metadata\":[", + "repeat": 1 + }, + { + "text": "{},", + "repeat": 100013 + }, + { + "text": "{}]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "complexity", + "noDecodeAtOrAboveBytes": 300104 + }, + "bytes": 300105, + "sha256": "ae6539bbd33f193dd35dfea6d968068dabe1cb31a644058b394c44f48f5bbd4e", + "boundary": { + "metric": "containers", + "limit": 100016, + "value": 100017 + } + }, + { + "id": "valid-v1-long-first-line", + "format": 1, + "description": "Version appears after a first line larger than the JSONL cap; v1 discrimination must preserve it.", + "category": "valid-control", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "format-valid", + "source": { + "segments": [ + { + "text": "{\"title\":\"", + "repeat": 1 + }, + { + "text": "x", + "repeat": 262144 + }, + { + "text": "\",\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[[0,\"late version\\r\\n\"]]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": true, + "jsError": null + }, + "bytes": 262227, + "sha256": "5f5c38129ff7b178a9b339a837dfd9cc1e93a8dc3707108f629cc10b07327117" + }, + { + "id": "invalid-v2-duplicate-version-wide", + "format": 2, + "description": "Last duplicate version is v2; wide metadata must not obtain a v1 allocation budget.", + "category": "upstream-compatibility", + "provenance": "normalized-mutation", + "safePlayback": false, + "validity": "upstream-compatible", + "source": { + "segments": [ + { + "text": "{\"version\":1,\"version\":2,\"width\":80,\"height\":24,\"metadata\":[", + "repeat": 1 + }, + { + "text": "0,", + "repeat": 20000 + }, + { + "text": "0]}\n", + "repeat": 1 + } + ] + }, + "expected": { + "accepted": false, + "jsError": "complexity", + "noDecodeAtOrAboveBytes": 40063 + }, + "bytes": 40064, + "sha256": "927c3ab6fd743a7618e3df59836345c40ec98883ac762981b40182099d061a75" + } + ] +} diff --git a/tests/fixtures/security/official-v1.cast b/tests/fixtures/security/official-v1.cast new file mode 100644 index 0000000..5f57364 --- /dev/null +++ b/tests/fixtures/security/official-v1.cast @@ -0,0 +1,38 @@ +{ + "version": 1, + "width": 80, + "height": 24, + "duration": 0.146063, + "command": "python3 synthetic-output.py", + "title": "PR41 synthetic baseline", + "env": { + "TERM": "xterm-256color", + "SHELL": "/bin/sh" + }, + "stdout": [ + [ + 0.019058, + "PR41 seed 41c0ffee\r\n" + ], + [ + 0.020274, + "fixture 00 sample 999f0ef0\r\n" + ], + [ + 0.020125, + "fixture 01 sample 706768d0\r\n" + ], + [ + 0.020121, + "fixture 02 sample 32d9ebae\r\n" + ], + [ + 0.020144, + "fixture 03 sample fa29a378\r\n" + ], + [ + 0.020086, + "\u001b[32msynthetic terminal output complete\u001b[0m\r\n" + ] + ] +} \ No newline at end of file diff --git a/tests/fixtures/security/official-v2.cast b/tests/fixtures/security/official-v2.cast new file mode 100644 index 0000000..df17c30 --- /dev/null +++ b/tests/fixtures/security/official-v2.cast @@ -0,0 +1,8 @@ +{"version":2,"width":80,"height":24,"timestamp":1792031567,"command":"python3 synthetic-output.py","title":"PR41 synthetic baseline","env":{"SHELL":"/bin/sh"}} +[0.020203, "o", "PR41 seed 41c0ffee\r\n"] +[0.040345, "o", "fixture 00 sample 999f0ef0\r\n"] +[0.06055, "o", "fixture 01 sample 706768d0\r\n"] +[0.080668, "o", "fixture 02 sample 32d9ebae\r\n"] +[0.100781, "o", "fixture 03 sample fa29a378\r\n"] +[0.12148, "o", "\u001b[32msynthetic terminal output complete\u001b[0m\r\n"] +[0.167553, "x", "0"] diff --git a/tests/fixtures/security/official-v3.cast b/tests/fixtures/security/official-v3.cast new file mode 100644 index 0000000..959b324 --- /dev/null +++ b/tests/fixtures/security/official-v3.cast @@ -0,0 +1,8 @@ +{"version":3,"term":{"cols":80,"rows":24,"type":"xterm-256color"},"timestamp":1792031567,"command":"python3 synthetic-output.py","title":"PR41 synthetic baseline","env":{"SHELL":"/bin/sh"}} +[0.022, "o", "PR41 seed 41c0ffee\r\n"] +[0.021, "o", "fixture 00 sample 999f0ef0\r\n"] +[0.021, "o", "fixture 01 sample 706768d0\r\n"] +[0.019, "o", "fixture 02 sample 32d9ebae\r\n"] +[0.020, "o", "fixture 03 sample fa29a378\r\n"] +[0.021, "o", "\u001b[32msynthetic terminal output complete\u001b[0m\r\n"] +[0.101, "x", "0"] diff --git a/tests/fixtures/security/provenance.json b/tests/fixtures/security/provenance.json new file mode 100644 index 0000000..0a13257 --- /dev/null +++ b/tests/fixtures/security/provenance.json @@ -0,0 +1,148 @@ +{ + "schema_version": 1, + "purpose": "PR41 format-valid official recorder baselines for deterministic security-test derivatives", + "seed_hex": "0x41c0ffee", + "seed_decimal": 1103167470, + "prng": "xorshift32 (unsigned 32-bit): x ^= x << 13; x ^= x >>> 17; x ^= x << 5", + "python_version": "3.12.14", + "sources": [ + { + "tool": "asciinema", + "version": "3.0.1", + "kind": "official release binary", + "url": "https://github.com/asciinema/asciinema/releases/download/v3.0.1/asciinema-x86_64-unknown-linux-gnu", + "sha256": "eb3a55e8778f6b86575ad58b47f1ee21d934e4baa8f01abaa5151cad490021f8", + "digest_reference": "https://api.github.com/repos/asciinema/asciinema/releases/tags/v3.0.1", + "digest_verified": true + }, + { + "tool": "asciinema", + "version": "1.4.0", + "kind": "unmodified official PyPI source distribution", + "url": "https://files.pythonhosted.org/packages/21/7a/265e78c86b4b4f8c74c0d8321f6f28faa19f80c5c9d7a834a989ed64154a/asciinema-1.4.0.tar.gz", + "sha256": "fb31457e7a4689340b872f625658dbaea33bcf6863fb5d696cf3857010432ecb", + "digest_reference": "https://pypi.org/project/asciinema/1.4.0/#files", + "digest_verified": true + } + ], + "commands": { + "v1": "python3 -m asciinema rec --title \"PR41 synthetic baseline\" --command \"python3 synthetic-output.py\" official-v1.cast", + "v2": "asciinema-3.0.1 rec --headless --window-size 80x24 --output-format asciicast-v2 --title \"PR41 synthetic baseline\" --command \"python3 synthetic-output.py\" official-v2.cast", + "v3": "asciinema-3.0.1 rec --headless --window-size 80x24 --output-format asciicast-v3 --title \"PR41 synthetic baseline\" --command \"python3 synthetic-output.py\" official-v3.cast", + "verify_output": "asciinema-3.0.1 convert --output-format raw official-vN.cast official-vN.output" + }, + "reproduction_script": "record-official-baselines.sh", + "payload_script": "synthetic-output.py", + "payload_script_sha256": "c23fee8e14fcc65ab372ea898c9e0884f53679393810db049e4749c2bfdb416f", + "reproduction_script_sha256": "2c2fe44b33b34c707efad515e97828d8f1dc2a545878e8042b43be1f243ff007", + "environment": { + "cleared_with": "env -i", + "fixed": { + "LANG": "C.UTF-8", + "LC_ALL": "C.UTF-8", + "TERM": "xterm-256color", + "SHELL": "/bin/sh" + }, + "scoped": "Temporary isolated HOME and ASCIINEMA_CONFIG_HOME; only pinned tool paths in PATH/PYTHONPATH; legacy COLUMNS=80 and LINES=24. No input capture, upload, streaming or auth command." + }, + "artifacts": [ + { + "file": "official-v1.cast", + "format": "asciicast-v1", + "sha256": "5570c9cdec60a779585db195ecd8dee4756d84706d6b27d3ccd87cf3ba311c97", + "bytes": 669, + "cli_version": "1.4.0", + "native_recorder_output": true, + "normalized": false, + "header": { + "version": 1, + "width": 80, + "height": 24, + "duration": 0.146063, + "command": "python3 synthetic-output.py", + "title": "PR41 synthetic baseline", + "env": { + "TERM": "xterm-256color", + "SHELL": "/bin/sh" + } + }, + "event_count": 6, + "output_event_count": 6, + "event_types": [ + "o" + ], + "duration_seconds": 0.146063, + "output_sha256": "390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550" + }, + { + "file": "official-v2.cast", + "format": "asciicast-v2", + "sha256": "6be6f5cd70d4a428692fc7807549b9c1437c1c8b60902220ad5e7e01a201f3ee", + "bytes": 498, + "cli_version": "3.0.1", + "native_recorder_output": true, + "normalized": false, + "header": { + "version": 2, + "width": 80, + "height": 24, + "timestamp": 1792031567, + "command": "python3 synthetic-output.py", + "title": "PR41 synthetic baseline", + "env": { + "SHELL": "/bin/sh" + } + }, + "event_count": 7, + "output_event_count": 6, + "event_types": [ + "o", + "x" + ], + "duration_seconds": 0.167553, + "output_sha256": "390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550" + }, + { + "file": "official-v3.cast", + "format": "asciicast-v3", + "sha256": "8c07c04edf86605558a9795152fcba32337d72aeaa073bc89adb1c285f06763e", + "bytes": 509, + "cli_version": "3.0.1", + "native_recorder_output": true, + "normalized": false, + "header": { + "version": 3, + "term": { + "cols": 80, + "rows": 24, + "type": "xterm-256color" + }, + "timestamp": 1792031567, + "command": "python3 synthetic-output.py", + "title": "PR41 synthetic baseline", + "env": { + "SHELL": "/bin/sh" + } + }, + "event_count": 7, + "output_event_count": 6, + "event_types": [ + "o", + "x" + ], + "duration_seconds": 0.225, + "output_sha256": "390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550" + } + ], + "verified": { + "official_cli_raw_conversion_all_three": true, + "identical_concatenated_stdout": true, + "public_safe_metadata_review": true, + "captured_stdout_bytes": 177, + "captured_stdout_sha256": "390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550", + "official_cli_raw_export_bytes": 187, + "official_cli_raw_export_sha256": "c759f03280f9a48ecfafbe7b11d7f2b75a2b418d368bc5fd5d13f1d957ee7d4d", + "official_cli_raw_export_prefix": "\u001b[8;24;80t" + }, + "reproducibility": "Synthetic output is fixed-seed reproducible. Raw recorder wall clock, event timing and output read boundaries can vary on recapture. Raw baseline files are retained byte-for-byte under their hashes. Deterministic corpus derivatives must explicitly declare their mutations and normalization; they are not untouched CLI captures." +} diff --git a/tests/fixtures/security/recipes.mjs b/tests/fixtures/security/recipes.mjs new file mode 100644 index 0000000..8f6768b --- /dev/null +++ b/tests/fixtures/security/recipes.mjs @@ -0,0 +1,212 @@ +/** TEST ONLY. Fixed, bounded recipes; never accepts attacker-selected sizes. */ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; + +export const FIXTURE_SEED = 0x41c0ffee; +export const MAX_FIXTURE_BYTES = 32 * 1024 * 1024 + 1; +export const POLICY = Object.freeze( { + bytes: 33554432, v1Bytes: 2097152, lineBytes: 262144, events: 100000, + lines: 100000, markers: 1000, dimension: 1000, cells: 40000, + depth: 15, containers: 100016, tokens: 400000, lineTokens: 20000, + timelineMs: 2147483647, +} ); + +// This PRNG is part of the reproducibility contract, not a security primitive. +export function seededRandom( seed = FIXTURE_SEED ) { + if ( seed !== FIXTURE_SEED ) throw new RangeError( 'Only the documented fixture seed is supported.' ); + let state = seed; + return () => { + state ^= state << 13; + state ^= state >>> 17; + state ^= state << 5; + return state >>> 0; + }; +} + +const segment = ( text, repeat = 1 ) => ( { text, repeat } ); +const json = JSON.stringify; +const byteLength = ( text ) => Buffer.byteLength( text, 'utf8' ); +const partsBytes = ( parts ) => parts.reduce( ( sum, part ) => sum + byteLength( part.text ) * part.repeat, 0 ); +const officialText = Object.fromEntries( [ 1, 2, 3 ].map( ( version ) => [ version, readFileSync( new URL( `official-v${ version }.cast`, import.meta.url ), 'utf8' ) ] ) ); +const officialData = Object.fromEntries( [ 1, 2, 3 ].map( ( version ) => [ version, version === 1 ? JSON.parse( officialText[ version ] ) : officialText[ version ].trimEnd().split( '\n' ).map( JSON.parse ) ] ) ); +const officialHeader = ( version ) => version === 1 ? officialData[ version ] : officialData[ version ][ 0 ]; +const officialOutput = ( version ) => version === 1 ? officialData[ version ].stdout.map( ( frame ) => frame[ 1 ] ).join( '' ) : officialData[ version ].slice( 1 ).filter( ( frame ) => frame[ 1 ] === 'o' ).map( ( frame ) => frame[ 2 ] ).join( '' ); +// Normalize only the envelope: discard wall clock, PTY timing and optional +// capture metadata; retain the officially recorded format and dimensions. +const header = ( version, cols, rows ) => { + const recorded = officialHeader( version ); + if ( recorded.version !== version ) throw new Error( 'Official capture format mismatch.' ); + return version === 3 + ? { version: recorded.version, term: { cols: cols ?? recorded.term.cols, rows: rows ?? recorded.term.rows } } + : { version: recorded.version, width: cols ?? recorded.width, height: rows ?? recorded.height }; +}; +const headerText = ( version, cols = 80, rows = 24 ) => json( header( version, cols, rows ) ); +const simpleCast = ( version, cols = 80, rows = 24 ) => version === 1 + ? json( { ...header( version, cols, rows ), stdout: [ [ 0, 'PR41 bounded control\r\n' ] ] } ) + '\n' + : headerText( version, cols, rows ) + '\n[0,"o","PR41 bounded control\\r\\n"]\n'; + +/** Identical output and absolute instants; v1/v3 serialize interval timestamps. */ +export function seededPlayback( seed = FIXTURE_SEED ) { + const next = seededRandom( seed ); + const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'; + const word = ( length ) => Array.from( { length }, () => alphabet[ next() % alphabet.length ] ).join( '' ); + const startText = 'PR41 START seed 41c0ffee'; + const seekText = 'PR41 SEEK seed 41c0ffee'; + const at = [ 0, 1 + ( next() % 8 ) / 4, 8, 12 ]; + const recordedOutput = officialOutput( 1 ); + if ( recordedOutput !== officialOutput( 2 ) || recordedOutput !== officialOutput( 3 ) ) throw new Error( 'Official captured output differs across formats.' ); + const output = [ startText + '\r\n', recordedOutput + 'seeded ' + word( 24 ) + ' café 你好 🌱\r\n', seekText + '\r\n', 'PR41 END\r\n' ]; + return { at, output, title: 'Seeded control ' + word( 8 ), playback: { startText, seekText, seekPercent: 80, cols: 80, rows: 24, duration: 12 } }; +} + +export function createRecipes( seed = FIXTURE_SEED ) { + const next = seededRandom( seed ); + const controls = seededPlayback( seed ); + const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'; + const bytePayload = Array.from( { length: 1013 }, () => alphabet[ next() % alphabet.length ] ).join( '' ); + const cases = []; + function add( id, format, description, parts, { error = null, boundary, small = false, category = 'resource-boundary', predecode, playback, metrics, safePlayback = false, provenance = 'normalized-mutation' } = {} ) { + const bytes = partsBytes( parts ); + if ( bytes > MAX_FIXTURE_BYTES ) throw new RangeError( `Unbounded recipe: ${ id }` ); + const hash = createHash( 'sha256' ); + // Hash each recipe without constructing a potentially 32 MiB string. + for ( const part of parts ) { + const chunkRepeats = Math.max( 1, Math.floor( 65536 / byteLength( part.text ) ) ); + let remaining = part.repeat; + while ( remaining ) { + const count = Math.min( remaining, chunkRepeats ); + hash.update( part.text.repeat( count ), 'utf8' ); + remaining -= count; + } + } + const entry = { + id, format, description, category, provenance, safePlayback, + validity: category === 'malformed' ? 'intentionally-malformed' : category === 'upstream-compatibility' ? 'upstream-compatible' : 'format-valid', + source: small ? { file: `${ id }.cast` } : { segments: parts }, + expected: { accepted: error === null, jsError: error }, bytes, sha256: hash.digest( 'hex' ), + }; + if ( boundary ) entry.boundary = boundary; + if ( predecode !== undefined ) entry.expected.noDecodeAtOrAboveBytes = predecode === 'document' ? bytes - 1 : predecode; + if ( playback ) entry.playback = playback; + if ( metrics ) entry.metrics = metrics; + cases.push( { entry, parts } ); + } + const pair = ( metric, limit, value ) => ( { metric, limit, value } ); + for ( const version of [ 1, 2, 3 ] ) { + add( `official-v${ version }`, version, 'Unmodified native capture from the pinned official asciinema recorder; original PTY timings are intentionally retained.', [ segment( officialText[ version ] ) ], { small: true, category: 'valid-control', safePlayback: true, provenance: 'official-raw-capture' } ); + const frames = controls.output.map( ( output, index ) => [ version === 2 ? controls.at[ index ] : controls.at[ index ] - ( controls.at[ index - 1 ] || 0 ), ...( version === 1 ? [] : [ 'o' ] ), output ] ); + const meta = { ...header( version ), title: controls.title, duration: 12 }; + const content = version === 1 ? json( { ...meta, stdout: frames }, null, 2 ) + '\n' : [ meta, ...frames ].map( json ).join( '\n' ) + '\n'; + add( `seeded-v${ version }-valid`, version, 'Official captured output plus fixed-seed text; normalized equivalent absolute times across all formats.', [ segment( content ) ], { small: true, category: 'valid-control', playback: controls.playback, safePlayback: true } ); + add( `valid-v${ version }-zero`, version, 'Zero header dimensions retain upstream 80 by 24 defaults.', [ segment( simpleCast( version, 0, 0 ) ) ], { small: true, category: 'upstream-compatibility' } ); + add( `dimensions-v${ version }-at`, version, 'The inclusive per-axis cap still fits within the independent cell budget.', [ segment( simpleCast( version, 1000, 24 ) ) ], { small: true, boundary: pair( 'dimension', POLICY.dimension, 1000 ) } ); + add( `dimensions-v${ version }-over`, version, 'Syntactically valid header requests an axis one beyond the dimension cap.', [ segment( simpleCast( version, 1001, 24 ) ) ], { small: true, error: 'dimensions', boundary: pair( 'dimension', POLICY.dimension, 1001 ) } ); + for ( const over of [ false, true ] ) { + const suffix = over ? 'over' : 'at'; + const cols = over ? 201 : 200; + add( `cells-v${ version }-${ suffix }`, version, 'Each axis is valid; their product alone selects the cell boundary.', [ segment( simpleCast( version, cols, 200 ) ) ], { small: true, error: over ? 'cells' : null, boundary: pair( 'cells', POLICY.cells, cols * 200 ) } ); + const depth = POLICY.depth + Number( over ); + const prefix = version === 1 ? '{"version":1,"width":80,"height":24,"stdout":[],"metadata":' : headerText( version ).slice( 0, -1 ) + ',"metadata":'; + add( `depth-v${ version }-${ suffix }`, version, 'Unknown metadata reaches the lexical container-depth boundary before JSON allocation.', [ segment( prefix + '['.repeat( depth - 1 ) + '0' + ']'.repeat( depth - 1 ) + '}\n' ) ], { small: true, error: over ? 'complexity' : null, boundary: pair( 'depth', POLICY.depth, depth ), predecode: over ? 'document' : undefined } ); + const count = POLICY.events + Number( over ); + const parts = version === 1 + ? [ segment( '{"version":1,"width":80,"height":24,"stdout":[' ), segment( '[0,""],', count - 1 ), segment( '[0,""]]}\n' ) ] + : [ segment( headerText( version ) + '\n' ), segment( '[0,"o",""]\n', count ) ]; + add( `events-v${ version }-${ suffix }`, version, version === 1 ? 'Full default v1 event boundary without first exhausting scalar/container budgets.' : 'Event and physical-line caps coincide for output-only JSONL.', parts, { error: over ? 'events' : null, boundary: pair( 'events', POLICY.events, count ), metrics: { events: count, ...( version === 1 ? { containers: count + 2 } : {} ) } } ); + } + } + + // Tiny time witnesses use a pinned policy independent of production constants. + // Keep official captures untouched and never mark these as browser-playable. + const timedCast = ( version, timestamps, metadata = {} ) => { + const meta = { ...header( version ), ...metadata }; + const frames = timestamps.map( ( time, index ) => [ time, ...( version === 1 ? [] : [ 'o' ] ), index ? 'end' : 'x' ] ); + return ( version === 1 ? json( { ...meta, stdout: frames } ) : [ meta, ...frames ].map( json ).join( '\n' ) ) + '\n'; + }; + for ( const version of [ 1, 2, 3 ] ) { + for ( const over of [ false, true ] ) { + const suffix = over ? 'over' : 'at'; + const seconds = over ? 2147483.648 : 2147483.647; + const options = { small: true, error: over ? 'time' : null, boundary: pair( 'timelineMs', 2147483647, over ? 2147483648 : 2147483647 ) }; + add( `timeline-v${ version }-${ suffix }`, version, 'One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.', [ segment( timedCast( version, [ seconds ] ) ) ], options ); + for ( const [ id, key ] of [ [ 'duration', 'duration' ], [ 'idle-limit', 'idle_time_limit' ] ] ) { + add( `${ id }-v${ version }-${ suffix }`, version, 'Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.', [ segment( timedCast( version, [ 0 ], { [ key ]: seconds } ) ) ], options ); + } + } + for ( const [ id, key ] of [ [ 'duration', 'duration' ], [ 'idle-limit', 'idle_time_limit' ] ] ) { + add( `${ id }-v${ version }-zero`, version, 'Zero remains valid for optional timing metadata.', [ segment( timedCast( version, [ 0 ], { [ key ]: 0 } ) ) ], { small: true, category: 'valid-control' } ); + } + } + for ( const version of [ 1, 3 ] ) { + for ( const over of [ false, true ] ) { + add( `interval-timeline-v${ version }-${ over ? 'over' : 'at' }`, version, 'Each interval is inside the horizon; only their upstream-order millisecond sum selects the boundary.', [ segment( timedCast( version, [ 1073741.823, over ? 1073741.825 : 1073741.824 ] ) ) ], { small: true, error: over ? 'time' : null, boundary: pair( 'timelineMs', 2147483647, over ? 2147483648 : 2147483647 ) } ); + } + add( `time-v${ version }-ms-rounding-over`, version, 'Adding seconds before conversion rounds to the allowed cap, but summing each interval in milliseconds exceeds it.', [ segment( timedCast( version, [ 307699.2378567164, 1839784.4091432837 ] ) ) ], { small: true, error: 'time', boundary: pair( 'timelineMs', 2147483647, 2147483647.0000002 ) } ); + add( `time-v${ version }-ms-sum-overflow`, version, 'Both converted intervals and the converted seconds sum are finite, but upstream interval-by-interval millisecond addition overflows.', [ segment( timedCast( version, [ 2.996155224770526e303, 1.7677315826146105e305 ] ) ) ], { small: true, error: 'time' } ); + } + add( 'time-v2-output-nonprogress', 2, 'A tiny finite timestamp makes the upstream output batching deadline equal its start, so callbacks repeat without consuming output.', [ segment( timedCast( 2, [ 1e20 ] ) ) ], { small: true, error: 'time' } ); + + add( 'valid-v1-multiline-late-version', 1, 'Pretty v1 document places its version after stdout and nested metadata.', [ segment( '{\n "stdout": [[0,"multiline v1\\r\\n"]],\n "metadata": {"version": 3},\n "width": 80,\n "height": 24,\n "version": 1\n}\n' ) ], { small: true, category: 'valid-control' } ); + add( 'valid-v1-escaped-version', 1, 'Escaped top-level version key is still v1.', [ segment( '{"ver\\u0073ion":1,"width":80,"height":24,"stdout":[]}\n' ) ], { small: true, category: 'valid-control' } ); + add( 'valid-v1-duplicate-version', 1, 'Last duplicate version wins under the bundled JSON parsers.', [ segment( '{"version":2,"version":1,"width":80,"height":24,"stdout":[]}\n' ) ], { small: true, category: 'upstream-compatibility' } ); + add( 'malformed-v1-json', 1, 'Deliberately missing the stdout array closer.', [ segment( '{"version":1,"width":80,"height":24,"stdout":[}\n' ) ], { small: true, category: 'malformed', error: 'invalid' } ); + + for ( const version of [ 2, 3 ] ) { + const head = headerText( version ) + '\n'; + add( `valid-v${ version }-filtered-lines`, version, 'Blank/comment/indented non-event lines follow upstream filtering, not strict canonical JSONL.', [ segment( head + '\n# compatibility comment\nignored text\n [999,"o","ignored"]\n[0,"o","accepted output\\r\\n"]\n' ) ], { small: true, category: 'upstream-compatibility' } ); + add( `late-resize-v${ version }-at`, version, 'Ordinary output precedes an inclusive 40,000-cell late resize.', [ segment( head + '[0,"o","safe prefix\\r\\n"]\n[12,"r","200x200"]\n' ) ], { small: true, boundary: pair( 'cells', POLICY.cells, 40000 ) } ); + add( `late-resize-v${ version }-over`, version, 'Ordinary output precedes a late resize with valid axes but excessive cells.', [ segment( head + '[0,"o","safe prefix\\r\\n"]\n[12,"r","201x200"]\n' ) ], { small: true, error: 'cells', boundary: pair( 'cells', POLICY.cells, 40200 ) } ); + add( `late-resize-v${ version }-dimensions-at`, version, 'Ordinary output precedes an inclusive 1,000-column late resize.', [ segment( head + '[0,"o","safe prefix\\r\\n"]\n[12,"r","1000x24"]\n' ) ], { small: true, boundary: pair( 'dimension', POLICY.dimension, 1000 ) } ); + add( `late-resize-v${ version }-dimensions-over`, version, 'Ordinary output precedes a late resize exceeding the per-axis dimension cap.', [ segment( head + '[0,"o","safe prefix\\r\\n"]\n[12,"r","1001x24"]\n' ) ], { small: true, error: 'dimensions', boundary: pair( 'dimension', POLICY.dimension, 1001 ) } ); + add( `malformed-v${ version }-event`, version, 'Deliberately invalid JSON event after a valid header.', [ segment( head + '[0,"o",broken]\n' ) ], { small: true, category: 'malformed', error: 'invalid' } ); + for ( const over of [ false, true ] ) { + const suffix = over ? 'over' : 'at'; + const markerCount = POLICY.markers + Number( over ); + add( `markers-v${ version }-${ suffix }`, version, 'Marker count boundary; bytes, line count and dimensions remain small.', [ segment( head ), segment( '[0,"m","mark"]\n', markerCount ) ], { error: over ? 'markers' : null, boundary: pair( 'markers', POLICY.markers, markerCount ) } ); + const lineBytes = POLICY.lineBytes + Number( over ); + const eventPrefix = '[0,"o","'; + const eventSuffix = '"]\n'; + add( `line-v${ version }-${ suffix }`, version, 'One syntactically valid output event at the UTF-8 line-byte boundary, including LF.', [ segment( head + eventPrefix ), segment( 'x', lineBytes - byteLength( eventPrefix + eventSuffix ) ), segment( eventSuffix ) ], { error: over ? 'line' : null, boundary: pair( 'lineBytes', POLICY.lineBytes, lineBytes ), predecode: over ? lineBytes - 1 : undefined } ); + const totalBytes = POLICY.bytes + Number( over ); + const block = eventPrefix + bytePayload + eventSuffix; + let blocks = Math.floor( ( totalBytes - byteLength( head ) ) / 1024 ); + let tailBytes = totalBytes - byteLength( head ) - blocks * 1024; + if ( tailBytes < byteLength( eventPrefix + eventSuffix ) ) { blocks--; tailBytes += 1024; } + add( `bytes-v${ version }-${ suffix }`, version, 'Full 32 MiB body boundary using valid output events; no padding comments or oversized line.', [ segment( head ), segment( block, blocks ), segment( eventPrefix ), segment( 'x', tailBytes - byteLength( eventPrefix + eventSuffix ) ), segment( eventSuffix ) ], { error: over ? 'bytes' : null, boundary: pair( 'bytes', POLICY.bytes, totalBytes ), predecode: over ? 'document' : undefined, metrics: { events: blocks + 1, maximumLineBytes: 1024 } } ); + if ( over ) cases.at( -1 ).entry.expected.phpNoDecodeAtOrAboveBytes = 1; + const tokenCount = POLICY.lineTokens + Number( over ); + const scalarCount = tokenCount - ( version === 2 ? 7 : 8 ); + const parts = [ segment( headerText( version ).slice( 0, -1 ) + ',"metadata":[' ), segment( '0,', scalarCount - 1 ), segment( '0]}\n' ) ]; + add( `line-tokens-v${ version }-${ suffix }`, version, 'Wide metadata uses the strict per-line scalar/key token cap, never the legacy v1 cap.', parts, { error: over ? 'complexity' : null, boundary: pair( 'lineTokens', POLICY.lineTokens, tokenCount ), predecode: over ? 'document' : undefined } ); + const lines = POLICY.lines + Number( over ); + add( `ignored-lines-v${ version }-${ suffix }`, version, 'One valid output event plus ignored blank lines isolates the physical JSONL processing budget.', [ segment( head + '[0,"o","line budget control\\r\\n"]\n' ), segment( '\n', lines - 1 ) ], { category: 'upstream-compatibility', error: over ? 'events' : null, boundary: pair( 'lines', POLICY.lines, lines ), metrics: { events: 1 } } ); + } + } + + for ( const over of [ false, true ] ) { + const suffix = over ? 'over' : 'at'; + const bytes = POLICY.v1Bytes + Number( over ); + const prefix = '{\n"version":1,"width":80,"height":24,"stdout":[[0,"'; + const end = '"]]}\n'; + add( `v1-bytes-${ suffix }`, 1, 'Legacy multiline document has its own 2 MiB budget, distinct from JSONL limits.', [ segment( prefix ), segment( 'x', bytes - byteLength( prefix + end ) ), segment( end ) ], { error: over ? 'bytes' : null, boundary: pair( 'v1Bytes', POLICY.v1Bytes, bytes ), predecode: over ? 'document' : undefined } ); + const prefixMetadata = '{\n"version":1,"width":80,"height":24,"stdout":[],"metadata":['; + const tokenCount = POLICY.tokens + Number( over ); + const scalarCount = tokenCount - 8; + add( `tokens-v1-${ suffix }`, 1, 'Unknown scalar metadata reaches the complete v1 scalar/key allocation budget.', [ segment( prefixMetadata ), segment( '0,', scalarCount - 1 ), segment( '0]}\n' ) ], { error: over ? 'complexity' : null, boundary: pair( 'tokens', POLICY.tokens, tokenCount ), predecode: over ? 'document' : undefined } ); + const containers = POLICY.containers + Number( over ); + add( `containers-v1-${ suffix }`, 1, 'Empty metadata objects isolate the container budget from scalar and event budgets.', [ segment( prefixMetadata ), segment( '{},', containers - 4 ), segment( '{}]}\n' ) ], { error: over ? 'complexity' : null, boundary: pair( 'containers', POLICY.containers, containers ), predecode: over ? 'document' : undefined } ); + } + add( 'valid-v1-long-first-line', 1, 'Version appears after a first line larger than the JSONL cap; v1 discrimination must preserve it.', [ segment( '{"title":"' ), segment( 'x', POLICY.lineBytes ), segment( '",\n"version":1,"width":80,"height":24,"stdout":[[0,"late version\\r\\n"]]}\n' ) ], { category: 'valid-control' } ); + add( 'invalid-v2-duplicate-version-wide', 2, 'Last duplicate version is v2; wide metadata must not obtain a v1 allocation budget.', [ segment( '{"version":1,"version":2,"width":80,"height":24,"metadata":[' ), segment( '0,', POLICY.lineTokens ), segment( '0]}\n' ) ], { category: 'upstream-compatibility', error: 'complexity', predecode: 'document' } ); + return cases; +} + +export function createManifest( seed = FIXTURE_SEED ) { + return { + schemaVersion: 1, + seed: '0x41c0ffee', + generator: 'xorshift32-v1; fixed case IDs and fixed resource policies', + policy: POLICY, + cases: createRecipes( seed ).map( ( item ) => item.entry ), + }; +} diff --git a/tests/fixtures/security/record-official-baselines.sh b/tests/fixtures/security/record-official-baselines.sh new file mode 100755 index 0000000..db08323 --- /dev/null +++ b/tests/fixtures/security/record-official-baselines.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Regenerate genuine CLI captures. Real PTY timing and wall clock are nondeterministic. +set -euo pipefail +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +: "${ASCIINEMA3:?Set ASCIINEMA3 to the verified official asciinema 3.0.1 executable}" +: "${ASCIINEMA1_SRC:?Set ASCIINEMA1_SRC to the extracted, unmodified PyPI asciinema-1.4.0 directory}" +ASCIINEMA3=$(realpath "$ASCIINEMA3") +ASCIINEMA1_SRC=$(realpath "$ASCIINEMA1_SRC") +PYTHON=$(command -v python3) +SAFE_PATH="$(dirname "$PYTHON"):/usr/bin:/bin" +OUT=$(realpath -m "${1:-$PWD/raw}") +mkdir -p "$OUT" +for v in 1 2 3; do + if [ -e "$OUT/official-v$v.cast" ]; then + printf 'Refusing to overwrite %s\n' "$OUT/official-v$v.cast" >&2 + exit 1 + fi +done +WORKDIR=$(mktemp -d) +trap 'rm -rf "$WORKDIR"' EXIT +mkdir -p "$WORKDIR/home" "$WORKDIR/config-legacy" "$WORKDIR/config-modern" +# CLI 1.4.0 requires a token field even for a local-only rec command. This is a +# fixed, noncredential dummy; no credential is created and no upload is invoked. +printf '[api]\ntoken = fixture-no-upload\n' > "$WORKDIR/config-legacy/config" +: > "$WORKDIR/config-modern/config.toml" +cp "$SCRIPT_DIR/synthetic-output.py" "$WORKDIR/synthetic-output.py" +cd "$WORKDIR" +COMMON=(env -i "PATH=$SAFE_PATH" LANG=C.UTF-8 LC_ALL=C.UTF-8 TERM=xterm-256color SHELL=/bin/sh "HOME=$WORKDIR/home") +"${COMMON[@]}" "ASCIINEMA_CONFIG_HOME=$WORKDIR/config-modern" "$ASCIINEMA3" --version +"${COMMON[@]}" "ASCIINEMA_CONFIG_HOME=$WORKDIR/config-legacy" "PYTHONPATH=$ASCIINEMA1_SRC" "$PYTHON" -m asciinema --version +for v in 2 3; do + "${COMMON[@]}" "ASCIINEMA_CONFIG_HOME=$WORKDIR/config-modern" "$ASCIINEMA3" rec \ + --headless --window-size 80x24 --output-format "asciicast-v$v" \ + --title 'PR41 synthetic baseline' --command 'python3 synthetic-output.py' \ + "$OUT/official-v$v.cast" +done +"${COMMON[@]}" "ASCIINEMA_CONFIG_HOME=$WORKDIR/config-legacy" "PYTHONPATH=$ASCIINEMA1_SRC" \ + COLUMNS=80 LINES=24 "$PYTHON" -m asciinema rec \ + --title 'PR41 synthetic baseline' --command 'python3 synthetic-output.py' \ + "$OUT/official-v1.cast" +for v in 1 2 3; do + "${COMMON[@]}" "ASCIINEMA_CONFIG_HOME=$WORKDIR/config-modern" "$ASCIINEMA3" convert \ + --output-format raw "$OUT/official-v$v.cast" "$OUT/official-v$v.output" +done +cmp "$OUT/official-v1.output" "$OUT/official-v2.output" +cmp "$OUT/official-v2.output" "$OUT/official-v3.output" +sha256sum "$OUT"/official-v{1,2,3}.cast "$OUT"/official-v1.output diff --git a/tests/fixtures/security/seeded-v1-valid.cast b/tests/fixtures/security/seeded-v1-valid.cast new file mode 100644 index 0000000..0231136 --- /dev/null +++ b/tests/fixtures/security/seeded-v1-valid.cast @@ -0,0 +1,25 @@ +{ + "version": 1, + "width": 80, + "height": 24, + "title": "Seeded control 9oz66x01", + "duration": 12, + "stdout": [ + [ + 0, + "PR41 START seed 41c0ffee\r\n" + ], + [ + 1, + "PR41 seed 41c0ffee\r\nfixture 00 sample 999f0ef0\r\nfixture 01 sample 706768d0\r\nfixture 02 sample 32d9ebae\r\nfixture 03 sample fa29a378\r\n\u001b[32msynthetic terminal output complete\u001b[0m\r\nseeded ikeld355ettzbav0edcciasg café 你好 🌱\r\n" + ], + [ + 7, + "PR41 SEEK seed 41c0ffee\r\n" + ], + [ + 4, + "PR41 END\r\n" + ] + ] +} diff --git a/tests/fixtures/security/seeded-v2-valid.cast b/tests/fixtures/security/seeded-v2-valid.cast new file mode 100644 index 0000000..bd6469d --- /dev/null +++ b/tests/fixtures/security/seeded-v2-valid.cast @@ -0,0 +1,5 @@ +{"version":2,"width":80,"height":24,"title":"Seeded control 9oz66x01","duration":12} +[0,"o","PR41 START seed 41c0ffee\r\n"] +[1,"o","PR41 seed 41c0ffee\r\nfixture 00 sample 999f0ef0\r\nfixture 01 sample 706768d0\r\nfixture 02 sample 32d9ebae\r\nfixture 03 sample fa29a378\r\n\u001b[32msynthetic terminal output complete\u001b[0m\r\nseeded ikeld355ettzbav0edcciasg café 你好 🌱\r\n"] +[8,"o","PR41 SEEK seed 41c0ffee\r\n"] +[12,"o","PR41 END\r\n"] diff --git a/tests/fixtures/security/seeded-v3-valid.cast b/tests/fixtures/security/seeded-v3-valid.cast new file mode 100644 index 0000000..492a44e --- /dev/null +++ b/tests/fixtures/security/seeded-v3-valid.cast @@ -0,0 +1,5 @@ +{"version":3,"term":{"cols":80,"rows":24},"title":"Seeded control 9oz66x01","duration":12} +[0,"o","PR41 START seed 41c0ffee\r\n"] +[1,"o","PR41 seed 41c0ffee\r\nfixture 00 sample 999f0ef0\r\nfixture 01 sample 706768d0\r\nfixture 02 sample 32d9ebae\r\nfixture 03 sample fa29a378\r\n\u001b[32msynthetic terminal output complete\u001b[0m\r\nseeded ikeld355ettzbav0edcciasg café 你好 🌱\r\n"] +[7,"o","PR41 SEEK seed 41c0ffee\r\n"] +[4,"o","PR41 END\r\n"] diff --git a/tests/fixtures/security/synthetic-output.py b/tests/fixtures/security/synthetic-output.py new file mode 100644 index 0000000..183e3fd --- /dev/null +++ b/tests/fixtures/security/synthetic-output.py @@ -0,0 +1,20 @@ +"""Harmless deterministic terminal output. No input, files, secrets or network.""" +import os +import time +state = 0x41C0FFEE + +def next_u32(): + global state + state ^= (state << 13) & 0xFFFFFFFF + state ^= state >> 17 + state ^= (state << 5) & 0xFFFFFFFF + state &= 0xFFFFFFFF + return state + +lines = ['PR41 seed 41c0ffee\n'] +for index in range(4): + lines.append(f'fixture {index:02d} sample {next_u32():08x}\n') +lines.append('\x1b[32msynthetic terminal output complete\x1b[0m\n') +for line in lines: + os.write(1, line.encode('utf-8')) + time.sleep(0.02) diff --git a/tests/fixtures/security/time-v1-ms-rounding-over.cast b/tests/fixtures/security/time-v1-ms-rounding-over.cast new file mode 100644 index 0000000..0a335b8 --- /dev/null +++ b/tests/fixtures/security/time-v1-ms-rounding-over.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"stdout":[[307699.2378567164,"x"],[1839784.4091432837,"end"]]} diff --git a/tests/fixtures/security/time-v1-ms-sum-overflow.cast b/tests/fixtures/security/time-v1-ms-sum-overflow.cast new file mode 100644 index 0000000..f873553 --- /dev/null +++ b/tests/fixtures/security/time-v1-ms-sum-overflow.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"stdout":[[2.996155224770526e+303,"x"],[1.7677315826146105e+305,"end"]]} diff --git a/tests/fixtures/security/time-v2-output-nonprogress.cast b/tests/fixtures/security/time-v2-output-nonprogress.cast new file mode 100644 index 0000000..8c962d7 --- /dev/null +++ b/tests/fixtures/security/time-v2-output-nonprogress.cast @@ -0,0 +1,2 @@ +{"version":2,"width":80,"height":24} +[100000000000000000000,"o","x"] diff --git a/tests/fixtures/security/time-v3-ms-rounding-over.cast b/tests/fixtures/security/time-v3-ms-rounding-over.cast new file mode 100644 index 0000000..5dec3b1 --- /dev/null +++ b/tests/fixtures/security/time-v3-ms-rounding-over.cast @@ -0,0 +1,3 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[307699.2378567164,"o","x"] +[1839784.4091432837,"o","end"] diff --git a/tests/fixtures/security/time-v3-ms-sum-overflow.cast b/tests/fixtures/security/time-v3-ms-sum-overflow.cast new file mode 100644 index 0000000..62828c3 --- /dev/null +++ b/tests/fixtures/security/time-v3-ms-sum-overflow.cast @@ -0,0 +1,3 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[2.996155224770526e+303,"o","x"] +[1.7677315826146105e+305,"o","end"] diff --git a/tests/fixtures/security/timeline-v1-at.cast b/tests/fixtures/security/timeline-v1-at.cast new file mode 100644 index 0000000..06182a9 --- /dev/null +++ b/tests/fixtures/security/timeline-v1-at.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"stdout":[[2147483.647,"x"]]} diff --git a/tests/fixtures/security/timeline-v1-over.cast b/tests/fixtures/security/timeline-v1-over.cast new file mode 100644 index 0000000..26ba08a --- /dev/null +++ b/tests/fixtures/security/timeline-v1-over.cast @@ -0,0 +1 @@ +{"version":1,"width":80,"height":24,"stdout":[[2147483.648,"x"]]} diff --git a/tests/fixtures/security/timeline-v2-at.cast b/tests/fixtures/security/timeline-v2-at.cast new file mode 100644 index 0000000..ec0a6c1 --- /dev/null +++ b/tests/fixtures/security/timeline-v2-at.cast @@ -0,0 +1,2 @@ +{"version":2,"width":80,"height":24} +[2147483.647,"o","x"] diff --git a/tests/fixtures/security/timeline-v2-over.cast b/tests/fixtures/security/timeline-v2-over.cast new file mode 100644 index 0000000..e6e50aa --- /dev/null +++ b/tests/fixtures/security/timeline-v2-over.cast @@ -0,0 +1,2 @@ +{"version":2,"width":80,"height":24} +[2147483.648,"o","x"] diff --git a/tests/fixtures/security/timeline-v3-at.cast b/tests/fixtures/security/timeline-v3-at.cast new file mode 100644 index 0000000..bb7860e --- /dev/null +++ b/tests/fixtures/security/timeline-v3-at.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[2147483.647,"o","x"] diff --git a/tests/fixtures/security/timeline-v3-over.cast b/tests/fixtures/security/timeline-v3-over.cast new file mode 100644 index 0000000..d350b28 --- /dev/null +++ b/tests/fixtures/security/timeline-v3-over.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":80,"rows":24}} +[2147483.648,"o","x"] diff --git a/tests/fixtures/security/valid-v1-duplicate-version.cast b/tests/fixtures/security/valid-v1-duplicate-version.cast new file mode 100644 index 0000000..3f7aba9 --- /dev/null +++ b/tests/fixtures/security/valid-v1-duplicate-version.cast @@ -0,0 +1 @@ +{"version":2,"version":1,"width":80,"height":24,"stdout":[]} diff --git a/tests/fixtures/security/valid-v1-escaped-version.cast b/tests/fixtures/security/valid-v1-escaped-version.cast new file mode 100644 index 0000000..1d5c7e6 --- /dev/null +++ b/tests/fixtures/security/valid-v1-escaped-version.cast @@ -0,0 +1 @@ +{"ver\u0073ion":1,"width":80,"height":24,"stdout":[]} diff --git a/tests/fixtures/security/valid-v1-multiline-late-version.cast b/tests/fixtures/security/valid-v1-multiline-late-version.cast new file mode 100644 index 0000000..1a1e08f --- /dev/null +++ b/tests/fixtures/security/valid-v1-multiline-late-version.cast @@ -0,0 +1,7 @@ +{ + "stdout": [[0,"multiline v1\r\n"]], + "metadata": {"version": 3}, + "width": 80, + "height": 24, + "version": 1 +} diff --git a/tests/fixtures/security/valid-v1-zero.cast b/tests/fixtures/security/valid-v1-zero.cast new file mode 100644 index 0000000..4dac0c4 --- /dev/null +++ b/tests/fixtures/security/valid-v1-zero.cast @@ -0,0 +1 @@ +{"version":1,"width":0,"height":0,"stdout":[[0,"PR41 bounded control\r\n"]]} diff --git a/tests/fixtures/security/valid-v2-filtered-lines.cast b/tests/fixtures/security/valid-v2-filtered-lines.cast new file mode 100644 index 0000000..dbf49e3 --- /dev/null +++ b/tests/fixtures/security/valid-v2-filtered-lines.cast @@ -0,0 +1,6 @@ +{"version":2,"width":80,"height":24} + +# compatibility comment +ignored text + [999,"o","ignored"] +[0,"o","accepted output\r\n"] diff --git a/tests/fixtures/security/valid-v2-zero.cast b/tests/fixtures/security/valid-v2-zero.cast new file mode 100644 index 0000000..0c15f77 --- /dev/null +++ b/tests/fixtures/security/valid-v2-zero.cast @@ -0,0 +1,2 @@ +{"version":2,"width":0,"height":0} +[0,"o","PR41 bounded control\r\n"] diff --git a/tests/fixtures/security/valid-v3-filtered-lines.cast b/tests/fixtures/security/valid-v3-filtered-lines.cast new file mode 100644 index 0000000..ca90825 --- /dev/null +++ b/tests/fixtures/security/valid-v3-filtered-lines.cast @@ -0,0 +1,6 @@ +{"version":3,"term":{"cols":80,"rows":24}} + +# compatibility comment +ignored text + [999,"o","ignored"] +[0,"o","accepted output\r\n"] diff --git a/tests/fixtures/security/valid-v3-zero.cast b/tests/fixtures/security/valid-v3-zero.cast new file mode 100644 index 0000000..6d4cc10 --- /dev/null +++ b/tests/fixtures/security/valid-v3-zero.cast @@ -0,0 +1,2 @@ +{"version":3,"term":{"cols":0,"rows":0}} +[0,"o","PR41 bounded control\r\n"] diff --git a/tests/js/playback.test.js b/tests/js/playback.test.js new file mode 100644 index 0000000..c2f4a92 --- /dev/null +++ b/tests/js/playback.test.js @@ -0,0 +1,118 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { recordingErrorMessage } from '../../src/recording-errors.js'; + +// Front-end lifecycle contract with the real bounded loader and a minimal DOM. +// Actual vendor playback/iframe rendering is covered by WordPress Playwright. +globalThis.document = { readyState: 'loading', addEventListener() {} }; +const { mountPlayers } = await import('../../src/view.js'); +delete globalThis.document; + +function setup({ preload = false, fetchImpl, options = {} } = {}) { + const notices = []; + const calls = []; + let observer; + const ownerDocument = { + body: { classList: { contains: () => false } }, documentElement: {}, + querySelector: () => null, + createElement: () => ({ setAttribute() {} }), + defaultView: { + AbortController, fetch: fetchImpl, setInterval, clearInterval, + MutationObserver: class { + constructor(callback) { observer = this; this.callback = callback; } + observe() {} disconnect() { this.disconnected = true; } + }, + AsciinemaPlayer: { create(source, container, options) { + const listeners = {}; + const player = { dispose() { this.disposed = true; }, getDuration: () => undefined, + addEventListener(name, callback) { listeners[name] = callback; } }; + calls.push({ source, container, options, player, listeners }); + return player; + } }, + }, + }; + const container = { ownerDocument, isConnected: true, + dataset: { apSrc: '/demo.cast', apOptions: JSON.stringify({ preload, ...options }) }, + querySelector: () => notices[0], appendChild: (notice) => notices.push(notice), + }; + const root = { ownerDocument, querySelectorAll: () => [container] }; + return { root, calls, container, notices, remove() { + container.isConnected = false; + observer.callback([{ removedNodes: [container] }]); + assert.equal(observer.disconnected, true); + } }; +} +const cast = '{"version":2,"width":80,"height":24}\n[0,"o","hello"]\n'; + +test('public preload=false stays lazy, loads parsed data once and owns one instance', async () => { + let requests = 0; + const fixture = setup({ fetchImpl: async (_url, options) => { + requests++; + assert.equal(options.credentials, 'same-origin'); + return new Response(cast); + } }); + mountPlayers(fixture.root); + mountPlayers(fixture.root); + assert.equal(fixture.calls.length, 1); + assert.equal(requests, 0); + assert.equal(fixture.container.dataset.apStatus, 'idle'); + const data = await fixture.calls[0].source.data(); + assert.equal(requests, 1); + assert.equal(data[0].version, 2); + assert.equal(data[1][2], 'hello'); + fixture.calls[0].listeners.playing(); + assert.equal(fixture.container.dataset.apStatus, 'ready'); + fixture.remove(); + assert.equal(fixture.calls[0].player.disposed, true); +}); + +test('removing a public player aborts the in-flight fetch and keeps cancellation quiet', async () => { + let signal; + const fixture = setup({ fetchImpl: (_url, options) => { + signal = options.signal; + return new Promise(() => {}); + } }); + mountPlayers(fixture.root); + const pending = fixture.calls[0].source.data(); + await new Promise(resolve => setImmediate(resolve)); + fixture.remove(); + assert.equal(signal.aborted, true); + await assert.rejects(pending, { code: 'aborted' }); + fixture.calls[0].listeners.error(); + assert.equal(fixture.notices.length, 0); +}); + +test('validation errors remain specific when the upstream player emits a generic error', async () => { + const fixture = setup({ fetchImpl: async () => new Response('{"version":2,"width":1001,"height":24}\n') }); + mountPlayers(fixture.root); + await assert.rejects(fixture.calls[0].source.data(), { code: 'dimensions' }); + fixture.calls[0].listeners.error(); + fixture.calls[0].listeners.playing(); + assert.equal(fixture.container.dataset.apStatus, 'error'); + assert.equal(fixture.notices.length, 1); + assert.match(fixture.notices[0].textContent, /terminal dimensions/); + fixture.remove(); +}); + +test('error messages are localized fixed copy; cancellation never leaks an exception', () => { + assert.equal(recordingErrorMessage({ code: 'aborted', message: '' }), ''); + for (const code of ['bytes', 'line', 'events', 'markers', 'dimensions', 'cells', 'complexity', 'time', 'timeout', 'network', 'stream', 'policy', 'invalid']) { + const message = recordingErrorMessage({ code, message: '' }); + assert.ok(message.length > 10); + assert.ok(!message.includes('')); + } + assert.match(recordingErrorMessage(null, { frontend: true }), /terminal recording/); +}); + + +test('public initial terminal grid is bounded before create even with preload disabled', () => { + for (const preload of [false, true]) { + let requests = 0; + const fixture = setup({ preload, options: { cols: 1000, rows: 1000 }, fetchImpl: () => { requests++; } }); + mountPlayers(fixture.root); + assert.equal(fixture.calls.length, 0); + assert.equal(requests, 0); + assert.equal(fixture.container.dataset.apStatus, 'error'); + assert.match(fixture.notices[0].textContent, /terminal cells/); + } +}); diff --git a/tests/js/preview-lifecycle.test.js b/tests/js/preview-lifecycle.test.js new file mode 100644 index 0000000..a1662e8 --- /dev/null +++ b/tests/js/preview-lifecycle.test.js @@ -0,0 +1,116 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { transformSync } from '@babel/core'; +import * as options from '../../src/options.js'; +import * as errors from '../../src/recording-errors.js'; +import * as loader from '../../src/recording-loader.js'; + +const compiled = transformSync(fs.readFileSync(new URL('../../src/preview.js', import.meta.url), 'utf8'), { + configFile: false, babelrc: false, + presets: [['@babel/preset-react', { pragma: 'element' }]], + plugins: ['@babel/plugin-transform-modules-commonjs'], +}).code; +const flush = () => new Promise(resolve => setImmediate(resolve)); + +function harness(attributes = {}) { + let effect; + let resolveAssets; + const assets = new Promise(resolve => { resolveAssets = resolve; }); + const updates = []; + const sizes = []; + const calls = []; + const timers = new Map(); + let nextTimer = 0; + const window = { AbortController, + setTimeout(callback) { timers.set(++nextTimer, callback); return nextTimer; }, + clearTimeout(id) { timers.delete(id); }, setInterval: () => 0, clearInterval() {}, + fetch: async () => new Response('{"version":2,"width":80,"height":24}\n[0,"o","ok"]\n'), + }; + const container = { ownerDocument: { defaultView: window }, replaceChildren() {} }; + const api = { create(source) { + const player = { addEventListener() {}, getDuration: () => undefined, + dispose() { this.disposed = true; } }; + calls.push({ source, player }); + return player; + } }; + const modules = { + '@wordpress/components': {}, '@wordpress/compose': { useRefEffect(callback) { effect = callback; } }, + '@wordpress/element': { useRef: value => ({ current: value }), useState: value => [value, update => updates.push(update)] }, + '@wordpress/i18n': { __: value => value }, './options.js': options, + './recording-errors.js': errors, './recording-loader.js': loader, + './player-bridge.js': { playerAssets: () => ({}), playerForDocument: () => assets }, + }; + const module = { exports: {} }; + new Function('require', 'module', 'exports', 'element', compiled)(name => { + assert.ok(Object.hasOwn(modules, name), `Unexpected module ${name}`); + return modules[name]; + }, module, module.exports, () => null); + module.exports.default({ source: '/original.cast', attributes, attempt: 0, onRecordingSize: (...args) => sizes.push(args) }); + const cleanup = effect(container); + return { cleanup, updates, sizes, calls, timers, window, resolveAssets: () => resolveAssets(api) }; +} + +test('unmount while player assets load never creates a player or stale state', async () => { + const h = harness(); + h.cleanup(); + const count = h.updates.length; + h.resolveAssets(); + await flush(); + assert.equal(h.calls.length, 0); + assert.equal(h.updates.length, count); + assert.equal(h.timers.size, 0); +}); + +test('asset startup deadline cannot create a late player after showing an error', async () => { + const h = harness(); + [...h.timers.values()][0](); + assert.equal(h.updates.at(-1), 'error'); + h.resolveAssets(); + await flush(); + assert.equal(h.calls.length, 0); + h.cleanup(); +}); + +test('unmount during a request aborts it without stale metadata or status', async () => { + const h = harness(); + let signal; + h.window.fetch = (_source, init) => { signal = init.signal; return new Promise(() => {}); }; + h.resolveAssets(); + await flush(); + const pending = h.calls[0].source.data(); + await flush(); + h.cleanup(); + const count = h.updates.length; + await assert.rejects(pending, { code: 'aborted' }); + assert.equal(signal.aborted, true); + assert.equal(h.calls[0].player.disposed, true); + assert.deepEqual(h.sizes, [['/original.cast', null]]); + assert.equal(h.updates.length, count); +}); + +test('preview reports original dimensions only after validated data finishes', async () => { + const h = harness(); + h.resolveAssets(); + await flush(); + const data = await h.calls[0].source.data(); + assert.equal(data[0].width, 80); + assert.deepEqual(h.sizes, [['/original.cast', null], ['/original.cast', { cols: 80, rows: 24 }]]); + h.cleanup(); +}); + + +test('preview rejects unsafe initial options before create or recording fetch', async () => { + for (const attributes of [{ cols: 1000, rows: 1000 }, { rows: 1000 }]) { + const h = harness(attributes); + let requests = 0; + h.window.fetch = () => { requests++; }; + h.resolveAssets(); + await flush(); + assert.equal(h.calls.length, 0); + assert.equal(requests, 0); + assert.equal(h.updates.at(-1), 'error'); + assert.match(h.updates.at(-2), /terminal cells/); + h.cleanup(); + } +}); diff --git a/tests/js/recording-loader.test.js b/tests/js/recording-loader.test.js new file mode 100644 index 0000000..75375cf --- /dev/null +++ b/tests/js/recording-loader.test.js @@ -0,0 +1,357 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { loadRecording, DEFAULT_LIMITS, RecordingLoadError, validateInitialDimensions } from '../../src/recording-loader.js'; +import { normalizePlayerOptions } from '../../src/options.js'; + +const encode = ( text ) => new TextEncoder().encode( text ); +const h2 = { version: 2, width: 80, height: 24 }; +const h3 = { version: 3, term: { cols: 80, rows: 24 } }; +const cast = ( header = h2, events = [ [ 0, 'o', 'hello' ] ] ) => [ header, ...events ].map( JSON.stringify ).join( '\n' ); +function fixture( text, { chunks, headers } = {} ) { + let reads = 0; + let canceled = false; + let released = false; + const parts = chunks || [ encode( text ) ]; + const response = { ok: true, headers: new Headers( headers ), body: { getReader: () => ( { + read: async () => reads < parts.length ? { value: parts[ reads++ ], done: false } : { done: true }, + cancel: () => { canceled = true; return Promise.resolve(); }, + releaseLock: () => { released = true; }, + } ) } }; + const calls = []; + const fetchImpl = async ( ...args ) => { calls.push( args ); return response; }; + return { fetchImpl, calls, get canceled() { return canceled; }, get released() { return released; } }; +} +async function rejectCode( text, code, config = {}, responseOptions ) { + const input = fixture( text, responseOptions ); + await assert.rejects( loadRecording( '/cast', { fetchImpl: input.fetchImpl, ...config } ), ( error ) => error instanceof RecordingLoadError && error.code === code ); + assert.equal( input.canceled, true ); + assert.equal( input.released, true ); +} + +test( 'single fetch returns validated v2 data and original metadata', async () => { + const input = fixture( cast() ); + const metadata = []; + assert.deepEqual( await loadRecording( '/cast', { fetchImpl: input.fetchImpl, options: { cols: 100 }, onMetadata: ( value ) => metadata.push( value ) } ), [ h2, [ 0, 'o', 'hello' ] ] ); + assert.deepEqual( metadata, [ { cols: 80, rows: 24 } ] ); + assert.equal( input.calls.length, 1 ); + assert.equal( input.calls[ 0 ][ 1 ].credentials, 'same-origin' ); + assert.ok( input.calls[ 0 ][ 1 ].signal instanceof AbortSignal ); + assert.equal( input.canceled, false ); + assert.equal( input.released, true ); +} ); + +test( 'stream boundaries preserve UTF-8, escapes, and CRLF', async () => { + const content = cast( h3, [ [ 0, 'o', '你好 🌱 " \\ \n' ], [ 1, 'x-custom', 'safe' ] ] ).replaceAll( '\n', '\r\n' ); + const bytes = encode( content ); + const input = fixture( '', { chunks: Array.from( bytes, ( byte ) => Uint8Array.of( byte ) ) } ); + assert.deepEqual( await loadRecording( '/cast', { fetchImpl: input.fetchImpl } ), [ h3, [ 0, 'o', '你好 🌱 " \\ \n' ], [ 1, 'x-custom', 'safe' ] ] ); +} ); + +test( 'blank, comment, and non-event lines retain upstream filtering semantics', async () => { + const content = `${ JSON.stringify( h3 ) }\n\n# comment\nignored\n [999999,"o","ignored"]\n[0,"o","ok"]\n`; + assert.deepEqual( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } ), [ h3, [ 0, 'o', 'ok' ] ] ); +} ); + +test( 'v1 compact, pretty, CRLF, and large single line are accepted as objects', async () => { + const header = { version: 1, width: 80, height: 24, stdout: [ [ 0.1, 'hello' ], [ 0.2, 'world' ] ] }; + for ( const content of [ JSON.stringify( header ), JSON.stringify( header, null, 2 ), JSON.stringify( header, null, 2 ).replaceAll( '\n', '\r\n' ) ] ) { + assert.deepEqual( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } ), header ); + } + const large = { ...header, stdout: [ [ 0, 'x'.repeat( DEFAULT_LIMITS.lineBytes ) ] ] }; + assert.deepEqual( await loadRecording( '/cast', { fetchImpl: fixture( JSON.stringify( large ) ).fetchImpl } ), large ); +} ); + +test( 'normal 100000-frame v1 fits preparse allocation budgets', async () => { + const header = { version: 1, width: 80, height: 24, stdout: Array.from( { length: 100000 }, () => [ 0, '' ] ) }; + const result = await loadRecording( '/cast', { fetchImpl: fixture( JSON.stringify( header ) ).fetchImpl } ); + assert.equal( result.stdout.length, 100000 ); +} ); + +test( 'zero header dimensions preserve default behavior and unknown metadata', async () => { + for ( const header of [ { ...h2, width: 0, height: 0 }, { version: 3, term: { cols: 0, rows: 0 } } ] ) { + let metadata = 'unset'; + const result = await loadRecording( '/cast', { fetchImpl: fixture( cast( header ) ).fetchImpl, onMetadata: ( value ) => { metadata = value; } } ); + assert.deepEqual( result[ 0 ], header ); + assert.equal( metadata, null ); + } +} ); + +test( 'actual received bytes reject oversized chunks despite missing or false Content-Length', async () => { + for ( const headers of [ {}, { 'Content-Length': '1' }, { 'Content-Length': 'not-a-number' } ] ) { + await rejectCode( cast(), 'bytes', { limits: { bytes: 10 } }, { headers } ); + } + // An advertised size is not a replacement for measuring decoded bytes. + assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast(), { headers: { 'Content-Length': '999999999' } } ).fetchImpl } ) ).length, 2 ); +} ); + +test( 'line byte limit counts multibyte output and ignored lines', async () => { + await rejectCode( cast( h2, [ [ 0, 'o', '界'.repeat( 30 ) ] ] ), 'line', { limits: { lineBytes: 80 } } ); + await rejectCode( `${ JSON.stringify( h2 ) }\n#${ 'x'.repeat( 81 ) }`, 'line', { limits: { lineBytes: 80 } } ); +} ); + +test( 'v1 byte cap covers pretty documents and compact documents', async () => { + const header = { version: 1, width: 80, height: 24, stdout: [ [ 0, 'x'.repeat( 100 ) ] ] }; + await rejectCode( JSON.stringify( header, null, 2 ), 'bytes', { limits: { v1Bytes: 100 } } ); + await rejectCode( JSON.stringify( header ), 'line', { limits: { v1Bytes: 100 } } ); +} ); + +test( 'depth, container, and token budgets run before parsing unknown metadata', async () => { + await rejectCode( cast( { ...h2, extra: [ [ [ [] ] ] ] } ), 'complexity', { limits: { depth: 4 } } ); + await rejectCode( cast( { ...h2, extra: [ [], [], [] ] } ), 'complexity', { limits: { containers: 4 } } ); + await rejectCode( cast( { ...h2, extra: [ 1, 2, 3, 4, 5 ] } ), 'complexity', { limits: { lineTokens: 10 } } ); +} ); + +test( 'event and marker boundaries are inclusive', async () => { + const content = cast( h2, [ [ 0, 'm', 'one' ], [ 1, 'm', 'two' ] ] ); + assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, limits: { markers: 2, events: 2 } } ) ).length, 3 ); + await rejectCode( content, 'markers', { limits: { markers: 1 } } ); + await rejectCode( content, 'events', { limits: { events: 1 } } ); + await rejectCode( content, 'markers', { options: { markers: [ [ 0, 'external' ] ] }, limits: { markers: 2 } } ); +} ); + +test( 'all dimensions, late resizes, raw cells and independent effective overrides are validated', async () => { + await rejectCode( cast( { ...h2, width: 1001 } ), 'dimensions', { options: { cols: 80 } } ); + await rejectCode( cast( { ...h2, width: 1000, height: 1000 } ), 'cells', { options: { cols: 80, rows: 24 } } ); + await rejectCode( cast( { ...h2, height: 100 } ), 'cells', { options: { cols: 1000 } } ); + await rejectCode( cast(), 'cells', { options: { cols: 1000, rows: 1000 } } ); + for ( const resize of [ '0x24', '80x0', '1001x24', '-1x24', '80x24oops' ] ) { + await rejectCode( cast( h2, [ [ 0, 'o', 'safe' ], [ 100, 'r', resize ] ] ), 'dimensions' ); + } + await rejectCode( cast( h2, [ [ 100, 'r', '80x100' ] ] ), 'cells', { options: { cols: 1000 } } ); + assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast( { ...h2, width: 1000, height: 40 } ) ).fetchImpl } ) ).length, 2 ); +} ); + +test( 'non-finite timestamps and cumulative time overflow are rejected', async () => { + await rejectCode( `${ JSON.stringify( h2 ) }\n[1e999,"o","x"]`, 'time' ); + await rejectCode( cast( h2, [ [ -1, 'o', 'x' ] ] ), 'time' ); + await rejectCode( cast( h3, [ [ 1e305, 'o', 'x' ], [ 1e305, 'o', 'x' ] ] ), 'time' ); + await rejectCode( JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ 1e305, 'x' ], [ 1e305, 'x' ] ] } ), 'time' ); +} ); + +test( 'supported timeline boundary is inclusive across all formats and timing metadata', async () => { + const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000; + assert.equal( DEFAULT_LIMITS.timelineMs, 2147483647 ); + for ( const version of [ 1, 2, 3 ] ) { + const header = version === 3 ? h3 : { ...h2, version }; + const content = ( seconds, extra = {} ) => version === 1 + ? JSON.stringify( { ...header, ...extra, stdout: [ [ seconds, 'x' ] ] } ) + : cast( { ...header, ...extra }, [ [ seconds, 'o', 'x' ] ] ); + assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( maxSeconds ) ).fetchImpl } ) ); + await rejectCode( content( maxSeconds + 0.001 ), 'time' ); + await rejectCode( content( -0.001 ), 'time' ); + for ( const key of [ 'duration', 'idle_time_limit' ] ) { + assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( 0, { [ key ]: maxSeconds } ) ).fetchImpl } ) ); + for ( const value of [ maxSeconds + 0.001, -0.001, '1', null ] ) await rejectCode( content( 0, { [ key ]: value } ), 'time' ); + } + } +} ); + +test( 'relative formats accumulate individually converted milliseconds in upstream order', async () => { + const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000; + const rounding = [ 307699.2378567164, 1839784.4091432837 ]; + assert.equal( ( rounding[ 0 ] + rounding[ 1 ] ) * 1000, DEFAULT_LIMITS.timelineMs ); + assert.ok( rounding[ 0 ] * 1000 + rounding[ 1 ] * 1000 > DEFAULT_LIMITS.timelineMs ); + for ( const version of [ 1, 3 ] ) { + const content = ( intervals ) => version === 1 + ? JSON.stringify( { version: 1, width: 80, height: 24, stdout: intervals.map( ( time ) => [ time, 'x' ] ) } ) + : cast( h3, intervals.map( ( time ) => [ time, 'o', 'x' ] ) ); + assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( [ 1, maxSeconds - 1 ] ) ).fetchImpl } ) ); + for ( const intervals of [ [ 1, maxSeconds ], rounding, [ 2.996155224770526e303, 1.7677315826146105e305 ] ] ) { + await rejectCode( content( intervals ), 'time' ); + } + } + await rejectCode( cast( h2, [ [ 1e20, 'o', 'x' ] ] ), 'time' ); +} ); + +test( 'slow playback stays within native timer range without expanding the base horizon at higher speeds', async () => { + const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000; + for ( const version of [ 1, 2, 3 ] ) { + const content = ( seconds ) => version === 1 + ? JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ seconds, 'x' ] ] } ) + : cast( version === 3 ? h3 : h2, [ [ seconds, 'o', 'x' ] ] ); + for ( const speed of [ 0.01, 0.5, 1, 100 ] ) { + const seconds = maxSeconds * Math.min( speed, 1 ); + const options = { speed }; + assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( seconds ) ).fetchImpl, options } ) ); + await rejectCode( content( seconds + 0.001 ), 'time', { options } ); + } + } + // An idle limiter or late start does not waive validation of the raw horizon. + await rejectCode( cast( h2, [ [ maxSeconds, 'o', 'x' ] ] ), 'time', { options: { speed: 0.01, idleTimeLimit: 0.001, startAt: maxSeconds } } ); +} ); + +test( 'normalized timing options are checked before any recording request', async () => { + const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000; + for ( const options of [ + ...[ 0, -1, NaN, Infinity, 0.009, 101, '1' ].map( ( speed ) => ( { speed } ) ), + ...[ 'startAt', 'idleTimeLimit' ].flatMap( ( key ) => [ maxSeconds + 0.001, -1, Infinity, NaN ].map( ( value ) => ( { [ key ]: value } ) ) ), + { poster: 'npt:596:31:23.648' }, + normalizePlayerOptions( { startAt: `${ '9'.repeat( 400 ) }:00:00` } ), + normalizePlayerOptions( { poster: `npt:${ '9'.repeat( 400 ) }:00:00` } ), + ] ) { + const input = fixture( cast() ); + await assert.rejects( loadRecording( '/cast', { fetchImpl: input.fetchImpl, options } ), { code: 'time' } ); + assert.equal( input.calls.length, 0 ); + } + for ( const options of [ { startAt: maxSeconds, idleTimeLimit: maxSeconds }, { poster: 'npt:596:31:23.647' }, { poster: 'data:text/plain,2147483648' } ] ) { + assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( cast() ).fetchImpl, options } ) ); + } + await assert.rejects( loadRecording( '/cast', { limits: { timelineMs: DEFAULT_LIMITS.timelineMs + 1 } } ), { code: 'policy' } ); + assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( cast( h2, [ [ 1, 'o', 'x' ] ] ) ).fetchImpl, limits: { timelineMs: 1000 } } ) ); + await rejectCode( cast( h2, [ [ 1.001, 'o', 'x' ] ] ), 'time', { limits: { timelineMs: 1000 } } ); +} ); + +test( 'invalid records do not report metadata', async () => { + for ( const content of [ '', '{}', cast( h2, [ [ 0, 'o', {} ] ] ), cast( h2, [ [ 0, '', 'x' ] ] ), `${ JSON.stringify( h2 ) }\n[invalid` ] ) { + let notified = false; + await assert.rejects( loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, onMetadata: () => { notified = true; } } ) ); + assert.equal( notified, false ); + } +} ); + +test( 'invalid UTF-8 cannot be repaired across a newline', async () => { + await rejectCode( '', 'invalid', {}, { chunks: [ encode( `${ JSON.stringify( h2 ) }\n` ), Uint8Array.of( 0xe2, 10, 0x82, 0xac ) ] } ); +} ); + +test( 'untrusted prototype-shaped metadata remains inert', async () => { + const header = JSON.parse( '{"version":2,"width":80,"height":24,"__proto__":{"polluted":true},"constructor":{"prototype":{"polluted":true}}}' ); + const result = await loadRecording( '/cast', { fetchImpl: fixture( cast( header ) ).fetchImpl } ); + assert.equal( {}.polluted, undefined ); + assert.equal( Object.getPrototypeOf( result[ 0 ] ), Object.prototype ); + assert.equal( Object.hasOwn( result[ 0 ], '__proto__' ), true ); +} ); + +test( 'pre-abort never fetches', async () => { + const controller = new AbortController(); + controller.abort(); + const input = fixture( cast() ); + await assert.rejects( loadRecording( '/cast', { fetchImpl: input.fetchImpl, signal: controller.signal } ), { code: 'aborted' } ); + assert.equal( input.calls.length, 0 ); +} ); + +test( 'abort and idle timeout interrupt stalled reads even when cancellation stalls', async () => { + for ( const explicitAbort of [ true, false ] ) { + const controller = new AbortController(); + let canceled = false; + let fetchSignal; + const fetchImpl = async ( _, config ) => { + fetchSignal = config.signal; + return { ok: true, body: { getReader: () => ( { read: () => new Promise( () => {} ), cancel: () => { canceled = true; return new Promise( () => {} ); }, releaseLock() {} } ) } }; + }; + const promise = loadRecording( '/cast', { fetchImpl, signal: controller.signal, limits: { idleTimeoutMs: explicitAbort ? 1000 : 10 } } ); + if ( explicitAbort ) setTimeout( () => controller.abort(), 5 ); + await assert.rejects( promise, { code: explicitAbort ? 'aborted' : 'timeout' } ); + assert.equal( canceled, true ); + assert.equal( fetchSignal.aborted, true ); + } +} ); + +test( 'total deadline interrupts an indefinitely pending fetch', async () => { + await assert.rejects( loadRecording( '/cast', { fetchImpl: () => new Promise( () => {} ), limits: { totalTimeoutMs: 10, idleTimeoutMs: 1000 } } ), { code: 'timeout' } ); +} ); + +test( 'unsupported streaming and network failures use stable codes', async () => { + await assert.rejects( loadRecording( '/cast', { fetchImpl: async () => ( { ok: true } ) } ), { code: 'stream' } ); + await assert.rejects( loadRecording( '/cast', { fetchImpl: async () => ( { ok: false } ) } ), { code: 'network' } ); + await assert.rejects( loadRecording( '/cast', { fetchImpl: async () => { throw new TypeError( 'Failed to fetch' ); } } ), { code: 'network' } ); +} ); + +test( 'ignored JSONL lines count toward the processing budget', async () => { + await rejectCode( `${ JSON.stringify( h2 ) }\n\n#comment\n[0,"o","x"]`, 'events', { limits: { lines: 2 } } ); +} ); + +test( 'one-byte-over boundaries and exact boundaries use actual body bytes', async () => { + const content = cast(); + const bytes = encode( content ).byteLength; + assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, limits: { bytes } } ) ).length, 2 ); + await rejectCode( content, 'bytes', { limits: { bytes: bytes - 1 } } ); + const first = encode( content.slice( 0, 10 ) ); + const rest = encode( content.slice( 10 ) ); + await rejectCode( '', 'bytes', { limits: { bytes: bytes - 1 } }, { chunks: [ first, rest ] } ); +} ); + +test( 'v1 allocation budgets count scalar tokens separately from containers', async () => { + const content = JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ 0, '' ] ] } ); + // Seven header scalar/key tokens, plus stdout key, then two frame scalars. + assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, limits: { tokens: 9, containers: 3 } } ) ).stdout.length, 1 ); + await rejectCode( content, 'complexity', { limits: { tokens: 8 } } ); + await rejectCode( content, 'complexity', { limits: { containers: 2 } } ); +} ); + +test( 'total deadline also bounds continuously resolved reads', async () => { + let canceled = false; + const fetchImpl = async () => ( { ok: true, body: { getReader: () => ( { + read: async () => ( { value: new Uint8Array(), done: false } ), + cancel: async () => { canceled = true; }, releaseLock() {}, + } ) } } ); + await assert.rejects( loadRecording( '/cast', { fetchImpl, limits: { totalTimeoutMs: 10, idleTimeoutMs: 1000 } } ), { code: 'timeout' } ); + assert.equal( canceled, true ); +} ); + +test( 'initial BOM is removed but later BOM-prefixed lines remain ignored', async () => { + const content = `\ufeff${ JSON.stringify( h2 ) }\n\ufeff[0,"o","ignored"]\n[1,"o","ok"]`; + const input = fixture( '', { chunks: Array.from( encode( content ), ( byte ) => Uint8Array.of( byte ) ) } ); + assert.deepEqual( await loadRecording( '/cast', { fetchImpl: input.fetchImpl } ), [ h2, [ 1, 'o', 'ok' ] ] ); +} ); + +test( 'v2 absolute timestamps cannot move backward; equal timestamps remain valid', async () => { + await rejectCode( cast( h2, [ [ 2, 'o', 'x' ], [ 1, 'o', 'y' ] ] ), 'time' ); + assert.equal( 10004.674 * 1000, 10004.673999999999 * 1000 ); + await rejectCode( cast( h2, [ [ 10004.674, 'o', 'x' ], [ 10004.673999999999, 'o', 'y' ] ] ), 'time' ); + assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast( h2, [ [ 1, 'o', 'x' ], [ 1, 'o', 'y' ] ] ) ).fetchImpl } ) ).length, 3 ); +} ); + +test( 'JSONL line budget includes newline bytes like the upload validator', async () => { + const headerLine = JSON.stringify( h2 ); + await rejectCode( `${ headerLine }\n`, 'line', { limits: { lineBytes: encode( headerLine ).length } } ); +} ); + +test( 'v2 header complexity is rejected before allocating the header JSON tree', async () => { + const content = cast( { ...h2, extra: Array( 40 ).fill( 1 ) } ); + const original = JSON.parse; + let treeParses = 0; + JSON.parse = ( text, ...args ) => { + if ( text.startsWith( '{' ) ) treeParses++; + return original( text, ...args ); + }; + try { + await rejectCode( content, 'complexity', { limits: { lineTokens: 20 } } ); + assert.equal( treeParses, 0 ); + } finally { JSON.parse = original; } +} ); + +test( 'version sniffing honors escaped keys, nesting and last duplicate value', async () => { + const v1 = '{"stdout":[[0,"ok"]],"nested":{"version":2},"width":80,"height":24,"vers\\u0069on":1}'; + assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( v1 ).fetchImpl } ) ).version, 1 ); + const v2 = '{"version":1,"width":80,"height":24,"extra":[1,2,3,4,5,6,7,8,9,10],"version":2}'; + await rejectCode( v2, 'complexity', { limits: { lineTokens: 15 } } ); +} ); + + +test( 'initial options are validated synchronously before the player can allocate a terminal', () => { + assert.doesNotThrow( () => validateInitialDimensions() ); + assert.doesNotThrow( () => validateInitialDimensions( { cols: 1000, rows: 40 } ) ); + assert.throws( () => validateInitialDimensions( { cols: 1000, rows: 1000 } ), { code: 'cells' } ); + assert.throws( () => validateInitialDimensions( { rows: 1000 } ), { code: 'cells' } ); + assert.throws( () => validateInitialDimensions( { cols: 1001 } ), { code: 'dimensions' } ); + assert.throws( () => validateInitialDimensions( { cols: -1 } ), { code: 'dimensions' } ); + assert.throws( () => validateInitialDimensions( { rows: NaN } ), { code: 'dimensions' } ); + assert.throws( () => validateInitialDimensions( { cols: 0 } ), { code: 'dimensions' } ); +} ); + + +test( 'multiline v1 can put version after an allocation-heavy first member', async () => { + const frames = Array( 10001 ).fill( '[0,""]' ).join( ',' ); + const content = `{"stdout":[${ frames }],\n"version":1,"width":80,"height":24}`; + const result = await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } ); + assert.equal( result.version, 1 ); + assert.equal( result.stdout.length, 10001 ); +} ); + +test( 'multiline v1 can put version after a first line larger than the JSONL cap', async () => { + const title = 'x'.repeat( DEFAULT_LIMITS.lineBytes ); + const content = `{"title":"${ title }",\n"version":1,"width":80,"height":24,"stdout":[[0,""]]}`; + const result = await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } ); + assert.equal( result.version, 1 ); + assert.equal( result.title.length, title.length ); +} ); diff --git a/tests/js/security-fixtures.test.js b/tests/js/security-fixtures.test.js new file mode 100644 index 0000000..4171e9a --- /dev/null +++ b/tests/js/security-fixtures.test.js @@ -0,0 +1,256 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createManifest, FIXTURE_SEED, MAX_FIXTURE_BYTES, POLICY, seededPlayback, seededRandom } from '../fixtures/security/recipes.mjs'; +import { getSecurityCase, securityCases, securityFixtureBuffer, securityManifest, writeSecurityFixture } from '../fixtures/security/generate.mjs'; + +const root = new URL( '../fixtures/security/', import.meta.url ); +const sha256 = ( bytes ) => createHash( 'sha256' ).update( bytes ).digest( 'hex' ); + +// Independent test-only measurements from a native JSON parse, not from the +// production budget scanner. Even rejected fixtures here are tightly bounded; +// they never reach the real terminal/player. Duplicate-key compatibility cases +// are not used as exact-token witnesses because native parsing collapses keys. +function structure( value, parentDepth = 0 ) { + if ( value === null || typeof value !== 'object' ) return { tokens: 1, containers: 0, depth: parentDepth }; + const depth = parentDepth + 1; + const result = { tokens: Array.isArray( value ) ? 0 : Object.keys( value ).length, containers: 1, depth }; + for ( const child of Object.values( value ) ) { + const measured = structure( child, depth ); + result.tokens += measured.tokens; + result.containers += measured.containers; + result.depth = Math.max( result.depth, measured.depth ); + } + return result; +} + +function measure( entry, bytes ) { + const text = bytes.toString( 'utf8' ); + let header; + let frames; + const metrics = { bytes: bytes.length, v1Bytes: bytes.length, lineBytes: 0, events: 0, lines: 0, markers: 0, dimension: 0, cells: 0, depth: 0, tokens: 0, containers: 0, lineTokens: 0, timelineMs: 0 }; + if ( entry.format === 1 ) { + header = JSON.parse( text ); + assert.ok( Array.isArray( header.stdout ) ); + frames = header.stdout.map( ( frame ) => { + assert.equal( frame.length, 2 ); + return [ frame[ 0 ], 'o', frame[ 1 ] ]; + } ); + Object.assign( metrics, structure( header ) ); + } else { + const lines = text.split( '\n' ); + if ( text.endsWith( '\n' ) ) lines.pop(); + metrics.lines = lines.length - 1; + header = JSON.parse( lines[ 0 ] ); + frames = []; + for ( const [ index, line ] of lines.entries() ) { + const lineBytes = Buffer.byteLength( line ) + Number( index < lines.length - 1 || text.endsWith( '\n' ) ); + metrics.lineBytes = Math.max( metrics.lineBytes, lineBytes ); + if ( index && ! line.startsWith( '[' ) ) { + assert.equal( entry.validity, 'upstream-compatible', 'strict-format cases must contain actual events, not ignored padding' ); + continue; + } + const value = index ? JSON.parse( line ) : header; + const parsed = structure( value ); + metrics.depth = Math.max( metrics.depth, parsed.depth ); + metrics.containers = Math.max( metrics.containers, parsed.containers ); + metrics.lineTokens = Math.max( metrics.lineTokens, parsed.tokens ); + if ( index ) frames.push( value ); + } + } + assert.equal( header.version, entry.format ); + const dimensions = entry.format === 3 ? [ header.term.cols, header.term.rows ] : [ header.width, header.height ]; + function size( cols, rows ) { + assert.ok( Number.isSafeInteger( cols ) && cols >= 0 ); + assert.ok( Number.isSafeInteger( rows ) && rows >= 0 ); + metrics.dimension = Math.max( metrics.dimension, cols, rows ); + metrics.cells = Math.max( metrics.cells, ( cols || 80 ) * ( rows || 24 ) ); + } + size( ...dimensions ); + let time = 0; + let milliseconds = 0; + for ( const key of [ 'duration', 'idle_time_limit' ] ) { + if ( Object.hasOwn( header, key ) ) metrics.timelineMs = Math.max( metrics.timelineMs, header[ key ] * 1000 ); + } + for ( const frame of frames ) { + assert.ok( Array.isArray( frame ) ); + assert.equal( frame.length, 3 ); + assert.ok( Number.isFinite( frame[ 0 ] ) && frame[ 0 ] >= 0 ); + assert.equal( typeof frame[ 1 ], 'string' ); + assert.ok( frame[ 1 ].length ); + assert.equal( typeof frame[ 2 ], 'string' ); + if ( entry.format === 2 ) assert.ok( frame[ 0 ] >= time ); + time = entry.format === 2 ? frame[ 0 ] : time + frame[ 0 ]; + assert.ok( Number.isFinite( time ) ); + milliseconds = entry.format === 2 ? frame[ 0 ] * 1000 : milliseconds + frame[ 0 ] * 1000; + metrics.timelineMs = Math.max( metrics.timelineMs, milliseconds ); + if ( frame[ 1 ] === 'm' ) metrics.markers++; + if ( frame[ 1 ] === 'r' ) { + assert.match( frame[ 2 ], /^[1-9][0-9]*x[1-9][0-9]*$/ ); + size( ...frame[ 2 ].split( 'x' ).map( Number ) ); + } + } + metrics.events = frames.length; + return metrics; +} + +test( 'golden recipes are deterministic, genuinely seeded, and bounded to known cases', () => { + assert.equal( FIXTURE_SEED, 0x41c0ffee ); + assert.deepEqual( createManifest(), securityManifest ); + assert.deepEqual( createManifest(), createManifest() ); + assert.deepEqual( seededPlayback(), seededPlayback() ); + const next = seededRandom(); + assert.deepEqual( Array.from( { length: 4 }, () => next().toString( 16 ) ), [ '999f0ef0', '706768d0', '32d9ebae', 'fa29a378' ] ); + assert.throws( () => seededRandom( 0 ), RangeError ); + assert.throws( () => createManifest( 1 ), RangeError ); + assert.throws( () => securityFixtureBuffer( '../../arbitrary' ), RangeError ); + assert.throws( () => securityFixtureBuffer( 'bytes-v2-999999999' ), RangeError ); + assert.equal( new Set( securityCases.map( ( entry ) => entry.id ) ).size, securityCases.length ); +} ); + +test( 'every shared resource purpose retains its exact at/over pair', () => { + for ( const version of [ 1, 2, 3 ] ) { + for ( const purpose of [ 'dimensions', 'cells', 'depth', 'events', 'timeline', 'duration', 'idle-limit' ] ) { + for ( const side of [ 'at', 'over' ] ) { + const entry = getSecurityCase( `${ purpose }-v${ version }-${ side }` ); + assert.equal( entry.expected.accepted, side === 'at' ); + } + } + assert.equal( getSecurityCase( `official-v${ version }` ).safePlayback, true ); + assert.equal( getSecurityCase( `seeded-v${ version }-valid` ).safePlayback, true ); + } + for ( const purpose of [ 'v1-bytes', 'tokens-v1', 'containers-v1', ...[ 2, 3 ].flatMap( ( version ) => [ 'bytes', 'line', 'line-tokens', 'markers', 'ignored-lines', 'late-resize' ].map( ( kind ) => `${ kind }-v${ version }` ) ) ] ) { + assert.equal( getSecurityCase( `${ purpose }-at` ).expected.accepted, true ); + assert.equal( getSecurityCase( `${ purpose }-over` ).expected.accepted, false ); + } + for ( const version of [ 2, 3 ] ) { + assert.equal( getSecurityCase( `late-resize-v${ version }-dimensions-at` ).expected.accepted, true ); + assert.equal( getSecurityCase( `late-resize-v${ version }-dimensions-over` ).expected.accepted, false ); + } +} ); + +test( 'timestamp regressions retain independently pinned witnesses and arithmetic', () => { + assert.equal( POLICY.timelineMs, 2147483647 ); + assert.equal( securityManifest.policy.timelineMs, 2147483647 ); + for ( const version of [ 1, 2, 3 ] ) { + for ( const purpose of [ 'timeline', 'duration', 'idle-limit' ] ) { + for ( const [ suffix, value ] of [ [ 'at', 2147483647 ], [ 'over', 2147483648 ] ] ) { + const entry = getSecurityCase( `${ purpose }-v${ version }-${ suffix }` ); + assert.deepEqual( entry.boundary, { metric: 'timelineMs', limit: 2147483647, value } ); + assert.equal( entry.expected.jsError, suffix === 'over' ? 'time' : null ); + } + } + for ( const purpose of [ 'duration', 'idle-limit' ] ) assert.equal( getSecurityCase( `${ purpose }-v${ version }-zero` ).expected.accepted, true ); + } + for ( const version of [ 1, 3 ] ) { + for ( const suffix of [ 'at', 'over' ] ) { + const entry = getSecurityCase( `interval-timeline-v${ version }-${ suffix }` ); + assert.equal( entry.expected.jsError, suffix === 'over' ? 'time' : null ); + const text = securityFixtureBuffer( entry.id ).toString( 'utf8' ); + const frames = version === 1 ? JSON.parse( text ).stdout : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse ); + assert.ok( frames.every( ( frame ) => frame[ 0 ] * 1000 < 2147483647 ), 'no individual interval may mask the cumulative boundary' ); + } + for ( const [ id, a, b ] of [ + [ 'ms-rounding-over', 307699.2378567164, 1839784.4091432837 ], + [ 'ms-sum-overflow', 2.996155224770526e303, 1.7677315826146105e305 ], + ] ) { + const entry = getSecurityCase( `time-v${ version }-${ id }` ); + assert.equal( entry.expected.jsError, 'time' ); + assert.equal( entry.expected.accepted, false ); + assert.ok( entry.bytes < 256, 'arithmetic witnesses must stay tiny' ); + const text = securityFixtureBuffer( entry.id ).toString( 'utf8' ); + const frames = version === 1 ? JSON.parse( text ).stdout : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse ); + assert.deepEqual( frames.map( ( frame ) => frame[ 0 ] ), [ a, b ], 'the exact floating-point witness cannot silently change' ); + assert.ok( Number.isFinite( a * 1000 ) && Number.isFinite( b * 1000 ) && Number.isFinite( ( a + b ) * 1000 ) ); + assert.equal( ( a + b ) * 1000, id === 'ms-rounding-over' ? 2147483647 : 1.7976931348623155e308 ); + assert.equal( a * 1000 + b * 1000, id === 'ms-rounding-over' ? 2147483647.0000002 : Infinity ); + } + } + const stalled = getSecurityCase( 'time-v2-output-nonprogress' ); + assert.equal( stalled.expected.jsError, 'time' ); + assert.equal( stalled.expected.accepted, false ); + assert.ok( stalled.bytes < 100 ); + assert.deepEqual( JSON.parse( securityFixtureBuffer( stalled.id ).toString( 'utf8' ).split( '\n' )[ 1 ] ), [ 1e20, 'o', 'x' ] ); + assert.equal( 1e20 * 1000 + 1000 / 60, 1e20 * 1000, 'the real 3.17 batch deadline cannot advance at this magnitude' ); +} ); + +test( 'official native captures retain independently pinned provenance and identical output', () => { + const provenance = JSON.parse( readFileSync( new URL( 'provenance.json', root ), 'utf8' ) ); + assert.deepEqual( provenance.artifacts.map( ( artifact ) => artifact.file ).sort(), [ 'official-v1.cast', 'official-v2.cast', 'official-v3.cast' ] ); + assert.equal( sha256( readFileSync( new URL( provenance.payload_script, root ) ) ), provenance.payload_script_sha256 ); + assert.equal( sha256( readFileSync( new URL( provenance.reproduction_script, root ) ) ), provenance.reproduction_script_sha256 ); + for ( const artifact of provenance.artifacts ) { + const bytes = readFileSync( new URL( artifact.file, root ) ); + assert.equal( bytes.length, artifact.bytes ); + assert.equal( sha256( bytes ), artifact.sha256 ); + const text = bytes.toString( 'utf8' ); + const output = artifact.format === 'asciicast-v1' ? JSON.parse( text ).stdout.map( ( frame ) => frame[ 1 ] ).join( '' ) : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse ).filter( ( frame ) => frame[ 1 ] === 'o' ).map( ( frame ) => frame[ 2 ] ).join( '' ); + assert.equal( Buffer.byteLength( output ), provenance.verified.captured_stdout_bytes ); + assert.equal( sha256( output ), provenance.verified.captured_stdout_sha256 ); + } +} ); + +test( 'seeded recordings preserve equivalent visible output and timing in all formats', () => { + const comparable = []; + for ( const version of [ 1, 2, 3 ] ) { + const text = securityFixtureBuffer( `seeded-v${ version }-valid` ).toString( 'utf8' ); + const frames = version === 1 ? JSON.parse( text ).stdout.map( ( frame ) => [ frame[ 0 ], 'o', frame[ 1 ] ] ) : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse ); + let time = 0; + comparable.push( frames.map( ( frame ) => { time = version === 2 ? frame[ 0 ] : time + frame[ 0 ]; return [ time, frame[ 2 ] ]; } ) ); + assert.ok( text.includes( 'café 你好 🌱' ), 'fragmented-stream tests need actual multibyte content' ); + } + assert.deepEqual( comparable[ 0 ], comparable[ 1 ] ); + assert.deepEqual( comparable[ 1 ], comparable[ 2 ] ); +} ); + +for ( const entry of securityCases ) { + test( `fixture validity and independent boundary measurement: ${ entry.id }`, () => { + assert.ok( entry.bytes > 0 && entry.bytes <= MAX_FIXTURE_BYTES ); + assert.equal( Boolean( entry.source.file ), ! Boolean( entry.source.segments ) ); + const bytes = securityFixtureBuffer( entry.id ); + assert.equal( bytes.length, entry.bytes ); + assert.equal( sha256( bytes ), entry.sha256 ); + if ( entry.validity === 'intentionally-malformed' ) { + assert.equal( entry.expected.accepted, false ); + assert.throws( () => measure( entry, bytes ), SyntaxError ); + return; + } + const metrics = measure( entry, bytes ); + if ( entry.boundary ) { + assert.equal( entry.boundary.limit, POLICY[ entry.boundary.metric ] ); + assert.equal( metrics[ entry.boundary.metric ], entry.boundary.value ); + assert.equal( entry.expected.accepted, entry.boundary.value <= entry.boundary.limit ); + // Rejections isolate their named budget. In JSONL the event and line + // thresholds necessarily coincide for an event-only recording. + for ( const metric of Object.keys( POLICY ) ) { + if ( metric === entry.boundary.metric || ( entry.format === 1 ? [ 'lineBytes', 'lineTokens', 'lines' ] : [ 'v1Bytes', 'tokens' ] ).includes( metric ) ) continue; + if ( entry.boundary.metric === 'events' && metric === 'lines' ) continue; + assert.ok( metrics[ metric ] <= POLICY[ metric ], `${ metric } must not mask ${ entry.boundary.metric }: ${ metrics[ metric ] }` ); + } + } + if ( entry.metrics ) for ( const [ key, value ] of Object.entries( entry.metrics ) ) { + assert.equal( metrics[ key === 'maximumLineBytes' ? 'lineBytes' : key ], value ); + } + if ( entry.safePlayback ) { + assert.equal( entry.expected.accepted, true ); + assert.ok( entry.bytes < 16384 ); + assert.ok( entry.id.startsWith( 'official-' ) || entry.id.startsWith( 'seeded-' ) ); + } + } ); +} + +test( 'checked-in cast files stay tiny and temporary materialization refuses overwrites', () => { + for ( const name of readdirSync( root ).filter( ( file ) => file.endsWith( '.cast' ) ) ) { + assert.ok( readFileSync( new URL( name, root ) ).length < 16384, `${ name } must not be a committed large payload` ); + assert.ok( securityCases.some( ( entry ) => entry.source.file === name ), `${ name } must have an explicit manifest expectation` ); + } + const directory = mkdtempSync( join( tmpdir(), 'asciiplayer-fixture-test-' ) ); + try { + const path = writeSecurityFixture( 'seeded-v2-valid', directory ); + assert.deepEqual( readFileSync( path ), securityFixtureBuffer( 'seeded-v2-valid' ) ); + assert.throws( () => writeSecurityFixture( 'seeded-v2-valid', directory ), { code: 'EEXIST' } ); + } finally { rmSync( directory, { recursive: true, force: true } ); } +} ); diff --git a/tests/js/security-loader-fixtures.test.js b/tests/js/security-loader-fixtures.test.js new file mode 100644 index 0000000..a8826c1 --- /dev/null +++ b/tests/js/security-loader-fixtures.test.js @@ -0,0 +1,397 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { spawnSync } from 'node:child_process'; +import { readFile } from 'node:fs/promises'; +import { loadRecording, RecordingLoadError, DEFAULT_LIMITS } from '../../src/recording-loader.js'; +import { securityManifest, securityCases, getSecurityCase, securityFixtureBuffer } from '../fixtures/security/generate.mjs'; + +test('shared security corpus pins the production policy and all six safe controls', () => { + assert.equal(DEFAULT_LIMITS.timelineMs, 2147483647, 'the test horizon is independently pinned'); + assert.equal(securityManifest.schemaVersion, 1); + for (const [name, value] of Object.entries(securityManifest.policy)) { + assert.equal(DEFAULT_LIMITS[name], value, `the ${name} fixture boundary must match production`); + } + assert.deepEqual(securityCases.filter((entry) => entry.safePlayback).map((entry) => entry.id).sort(), [ + 'official-v1', 'official-v2', 'official-v3', + 'seeded-v1-valid', 'seeded-v2-valid', 'seeded-v3-valid', + ]); +}); + +/** A bounded stream, with observations rather than a replacement loader/parser. */ +function streamedFixture(bytes, chunkSizes = [16 * 1024]) { + let offset = 0; + let reads = 0; + const state = { fetches: 0, cancels: 0, releases: 0, eof: 0, signal: undefined }; + const fetchImpl = async (source, options) => { + state.fetches += 1; + assert.equal(source, '/security-fixture.cast'); + assert.equal(options.credentials, 'same-origin'); + state.signal = options.signal; + return { + ok: true, + // A false advertised length must not replace measuring actual bytes. + headers: new Headers({ 'Content-Length': '1' }), + body: { getReader: () => ({ + read: async () => { + if (offset === bytes.length) { + state.eof += 1; + return { done: true }; + } + const end = Math.min(offset + chunkSizes[reads++ % chunkSizes.length], bytes.length); + const value = bytes.subarray(offset, end); + offset = end; + return { done: false, value }; + }, + cancel: async () => { state.cancels += 1; }, + releaseLock: () => { state.releases += 1; }, + }) }, + }; + }; + return { fetchImpl, state }; +} + +for (const entry of securityCases) { + test(`shared security corpus: ${entry.id}`, async (t) => { + const bytes = await securityFixtureBuffer(entry.id); + assert.equal(bytes.length, entry.bytes, 'fixture byte length is reproducible'); + assert.equal(createHash('sha256').update(bytes).digest('hex'), entry.sha256, 'fixture bytes match the cross-language manifest'); + const input = streamedFixture(bytes); + const metadata = []; + let largestParsedTree = 0; + const parse = JSON.parse; + t.after(() => { JSON.parse = parse; }); + JSON.parse = (text, ...args) => { + // Version-sniffing parses short scalar keys. Only full JSON trees + // allocate the arrays/objects that the structural guard must bound. + if (/^\s*[\[{]/.test(text)) largestParsedTree = Math.max(largestParsedTree, Buffer.byteLength(text)); + return parse(text, ...args); + }; + const pending = loadRecording('/security-fixture.cast', { + fetchImpl: input.fetchImpl, + onMetadata: (value) => metadata.push(value), + }); + if (entry.expected.accepted) { + const result = await pending; + const header = entry.format === 1 ? result : result[0]; + assert.equal(header.version, entry.format); + const cols = entry.format === 3 ? header.term.cols : header.width; + const rows = entry.format === 3 ? header.term.rows : header.height; + assert.deepEqual(metadata, [cols > 0 && rows > 0 ? { cols, rows } : null], 'metadata is emitted exactly once, only after complete validation'); + assert.equal(input.state.eof, 1, 'an accepted recording is validated through EOF'); + assert.equal(input.state.cancels, 0); + assert.equal(input.state.signal.aborted, false); + } else { + await assert.rejects(pending, (error) => error instanceof RecordingLoadError && error.code === entry.expected.jsError, + `expected the production ${entry.expected.jsError} guard`); + assert.deepEqual(metadata, [], 'rejected content must not leak native-size metadata'); + assert.equal(input.state.cancels, 1, 'the rejected body reader is canceled once'); + assert.equal(input.state.signal.aborted, true, 'the rejected fetch is aborted'); + const threshold = entry.expected.noDecodeAtOrAboveBytes; + if (threshold !== undefined) { + assert.ok(largestParsedTree < threshold, + `unsafe JSON at/above ${threshold} bytes reached JSON.parse: ${largestParsedTree}`); + } + } + assert.equal(input.state.fetches, 1, 'validation and metadata share a single fetch'); + assert.equal(input.state.releases, 1, 'the body reader lock is released exactly once'); + }); +} + +for (const version of [1, 2, 3]) { + test(`seeded v${version} corpus survives byte and JSON token stream boundaries`, async () => { + const entry = getSecurityCase(`seeded-v${version}-valid`); + const bytes = await securityFixtureBuffer(entry.id); + const fragmented = streamedFixture(bytes, [1, 2, 3, 5, 13]); + const contiguous = streamedFixture(bytes, [bytes.length]); + const metadata = []; + const actual = await loadRecording('/security-fixture.cast', { + fetchImpl: fragmented.fetchImpl, onMetadata: (value) => metadata.push(value), + }); + assert.deepEqual(actual, await loadRecording('/security-fixture.cast', { fetchImpl: contiguous.fetchImpl })); + assert.equal(metadata.length, 1); + assert.equal(fragmented.state.fetches, 1); + assert.equal(fragmented.state.cancels, 0); + assert.equal(fragmented.state.releases, 1); + }); +} + +/** + * Exercise the actual pinned player parser/recording driver without importing + * its DOM UI. Discover Core through the package's own entrypoint import, rather + * than hard-coding a generated chunk hash or copying upstream parser code. + * A package layout/version change deliberately fails this compatibility check. + */ +async function playerCore() { + const entrypoint = new URL(import.meta.resolve('asciinema-player')); + const manifest = JSON.parse(await readFile(new URL('../package.json', entrypoint), 'utf8')); + assert.equal(manifest.version, '3.17.0'); + const source = await readFile(entrypoint, 'utf8'); + const imported = /import \{ (\w+) as Core \} from ['"]([^'"]+)['"]/.exec(source); + assert.ok(imported, 'the pinned player entrypoint must expose its Core import for compatibility tests'); + const module = await import(new URL(imported[2], entrypoint)); + assert.equal(typeof module[imported[1]], 'function'); + return module[imported[1]]; +} + +function expectedPlayback(data) { + const header = Array.isArray(data) ? data[0] : data; + let time = 0; + const frames = header.version === 1 ? data.stdout.map(([delta, text]) => [delta, 'o', text]) : data.slice(1); + const absolute = frames.map(([timestamp, type, text]) => { + time = header.version === 2 ? timestamp : time + timestamp; + return [time, type, text]; + }); + return { + cols: (header.version === 3 ? header.term.cols : header.width) || 80, + rows: (header.version === 3 ? header.term.rows : header.height) || 24, + duration: time, + events: absolute, + output: absolute.filter((event) => event[1] === 'o').map((event) => event[2]).join(''), + markers: absolute.filter((event) => event[1] === 'm').map((event) => [event[0], event[2]]), + }; +} + +async function inspectPlayer(data) { + const Core = await playerCore(); + const events = { metadata: [], reset: [], output: [], error: [] }; + const core = new Core({ data }, { + preload: true, speed: 1, + logger: { debug() {}, info() {}, warn() {}, error() {} }, + }); + for (const [name, values] of Object.entries(events)) core.addEventListener(name, (value) => values.push(value)); + try { + core.terminalReady(); + await core.init(); + const duration = core.getDuration(); + assert.ok(Number.isFinite(duration)); + assert.ok(Number.isFinite(core.getCurrentTime())); + await core.seek('100%'); + assert.ok(Number.isFinite(core.getCurrentTime()), 'the actual seek destination remains finite'); + assert.ok(Number.isFinite(core.getProgress()), 'the actual progress calculation remains finite'); + const output = events.output.flat().join(''); + await core.seek('0%'); + assert.equal(core.getCurrentTime(), 0, 'the real driver can seek back to the start'); + assert.deepEqual(events.error, []); + assert.equal(events.metadata.length, 1); + return { duration, output, metadata: events.metadata[0], reset: events.reset[0] }; + } finally { + await core.stop(); + } +} + +// Only known-small, accepted controls reach the real upstream parser/driver here. +// The tiny numeric witnesses below run separately with captured timers and a hard +// child-process deadline; no oversized payload reaches the real player. +const playableCases = securityCases.filter((entry) => entry.safePlayback === true); +for (const entry of playableCases) { + test(`pinned player 3.17 parses and seeks validated ${entry.id}`, async () => { + assert.equal(entry.expected.accepted, true); + assert.ok(entry.bytes < 128 * 1024, 'actual-player controls must remain small'); + const bytes = await securityFixtureBuffer(entry.id); + const data = await loadRecording('/security-fixture.cast', { fetchImpl: streamedFixture(bytes).fetchImpl }); + const text = bytes.toString('utf8'); + const original = entry.format === 1 ? JSON.parse(text) : text.split('\n') + .filter((line, index) => index === 0 || line.startsWith('[')).map((line) => JSON.parse(line)); + assert.deepEqual(data, original, 'the guard preserves every original header and event'); + const expected = expectedPlayback(original); + const actual = await inspectPlayer(data); + assert.ok(Math.abs(actual.duration - expected.duration) < 1e-8); + assert.deepEqual(actual.reset.size, { cols: expected.cols, rows: expected.rows }); + assert.equal(actual.output, expected.output, 'the real parser preserves complete terminal output'); + assert.deepEqual(actual.metadata.markers, expected.markers); + // Independently prove both official captures and seeded mutations also + // work through upstream's original raw-input path before our adapter. + const raw = await inspectPlayer(new Response(bytes)); + assert.deepEqual(raw, actual); + }); +} + + +test('official outputs and seeded playback timelines are equivalent across all three formats', async () => { + const controls = { official: [], seeded: [] }; + for (const version of [1, 2, 3]) { + for (const kind of ['official', 'seeded']) { + const id = kind === 'official' ? `official-v${version}` : `seeded-v${version}-valid`; + const bytes = securityFixtureBuffer(id); + const text = bytes.toString('utf8'); + const data = version === 1 ? JSON.parse(text) : text.trimEnd().split('\n').map(JSON.parse); + controls[kind].push(expectedPlayback(data)); + } + } + assert.equal(controls.official[0].output, controls.official[1].output); + assert.equal(controls.official[0].output, controls.official[2].output); + assert.deepEqual(controls.seeded[0], controls.seeded[1]); + assert.deepEqual(controls.seeded[0], controls.seeded[2]); + assert.deepEqual(controls.seeded[0].events.map((event) => event[0]), [0, 1, 8, 12]); + assert.ok(controls.seeded[0].output.includes(controls.official[0].output), 'seeded mutations retain the official captured output'); +}); + + +/** + * Actual upstream Core witness, isolated from the main runner. All timers are + * captured, never scheduled; at most three callbacks are invoked per witness. + * The parent also kills this child after 10 seconds if an upstream change causes + * an unexpected synchronous loop. No browser, terminal, real playback delay, or + * large payload is involved. The arithmetic checks above are not a Core double. + */ +async function timestampCoreRegression() { + const Core = await playerCore(); + const realSetTimeout = globalThis.setTimeout; + const realClearTimeout = globalThis.clearTimeout; + const timers = new Map(); + let timerId = 0; + globalThis.setTimeout = (callback, delay) => { + const id = ++timerId; + timers.set(id, { callback, delay }); + return id; + }; + globalThis.clearTimeout = (id) => { timers.delete(id); }; + const parseFixture = (id) => { + const entry = getSecurityCase(id); + assert.ok(entry.bytes < 256, 'only pinned tiny witnesses may enter this child'); + const text = securityFixtureBuffer(id).toString('utf8'); + return entry.format === 1 ? JSON.parse(text) : text.trimEnd().split('\n').map(JSON.parse); + }; + const createCore = (data) => { + const core = new Core({ data }, { + preload: true, speed: 1, + logger: { debug() {}, info() {}, warn() {}, error() {} }, + }); + const events = { output: [], error: [], ended: [] }; + for (const [name, values] of Object.entries(events)) core.addEventListener(name, (value) => values.push(value)); + core.terminalReady(); + return { core, events }; + }; + const takeTimer = () => { + assert.equal(timers.size, 1, 'exactly one recording callback is pending'); + const [id, timer] = timers.entries().next().value; + timers.delete(id); + return timer; + }; + try { + // Deliberately bypass the guard ONLY for this fixed tiny upstream bug + // witness. A premature timer call safely exposes non-progress without + // waiting for 1e23 ms or advancing the clock into a synchronous loop. + const stalled = createCore(parseFixture('time-v2-output-nonprogress')); + try { + await stalled.core.init(); + assert.ok(Number.isFinite(stalled.core.getDuration())); + assert.equal(timers.size, 0, 'initial loading timeout was cleared'); + await stalled.core.play(); + let previousCallback; + for (let n = 0; n < 3; n++) { + const timer = takeTimer(); + assert.equal(timer.delay, 1e23, 'the unsafe upstream delay exceeds signed 32-bit timer range'); + if (previousCallback) assert.equal(timer.callback, previousCallback, 'the same unconsumed event is rescheduled'); + previousCallback = timer.callback; + timer.callback(); + await Promise.resolve(); + assert.deepEqual(stalled.events.output, Array.from({ length: n + 1 }, () => []), 'batching emits empty output without consuming x'); + assert.deepEqual(stalled.events.ended, []); + } + assert.deepEqual(stalled.events.error, []); + process.stdout.write('v2 non-progress reproduced with three captured callbacks\n'); + } finally { + await stalled.core.stop(); + assert.equal(timers.size, 0, 'stopping removes the captured non-progress callback'); + } + for (const version of [1, 3]) { + const overflow = createCore(parseFixture(`time-v${version}-ms-sum-overflow`)); + try { + await overflow.core.init(); + assert.equal(overflow.core.getDuration(), Infinity, 'real upstream interval arithmetic overflows although converted seconds sum is finite'); + await overflow.core.seek('100%'); + assert.equal(overflow.core.getCurrentTime(), Infinity); + assert.ok(Number.isNaN(overflow.core.getProgress()), 'real upstream progress is corrupted'); + assert.deepEqual(overflow.events.error, []); + process.stdout.write(`v${version} infinite duration/seek reproduced\n`); + } finally { + await overflow.core.stop(); + assert.equal(timers.size, 0); + } + } + // The production loader must reject all five pinned numerical attacks + // before their data can be handed to Core, including rounding-order bugs. + let coreHandoffs = 0; + for (const id of [ + 'time-v2-output-nonprogress', + 'time-v1-ms-sum-overflow', 'time-v3-ms-sum-overflow', + 'time-v1-ms-rounding-over', 'time-v3-ms-rounding-over', + ]) { + assert.equal(getSecurityCase(id).expected.jsError, 'time'); + const stream = streamedFixture(securityFixtureBuffer(id)); + const handoff = async () => { + const data = await loadRecording('/security-fixture.cast', { fetchImpl: stream.fetchImpl }); + coreHandoffs++; + return createCore(data); + }; + await assert.rejects(handoff(), (error) => error instanceof RecordingLoadError && error.code === 'time'); + assert.equal(coreHandoffs, 0, 'rejected data never reaches the actual Core constructor'); + assert.equal(stream.state.cancels, 1); + assert.equal(stream.state.signal.aborted, true); + assert.equal(timers.size, 0, 'rejected loader leaves no captured timeouts'); + process.stdout.write(`${id} rejected before Core handoff\n`); + } + // Accepted exact-boundary fixtures survive actual parser preparation, + // duration/progress arithmetic, end/start seeking and output batching. + for (const id of [ + 'timeline-v1-at', 'timeline-v2-at', 'timeline-v3-at', + 'interval-timeline-v1-at', 'interval-timeline-v3-at', + ]) { + const bytes = securityFixtureBuffer(id); + const data = await loadRecording('/security-fixture.cast', { fetchImpl: streamedFixture(bytes).fetchImpl }); + assert.deepEqual(data, parseFixture(id), 'near-bound timestamps are preserved without clamping'); + const expectedOutput = id.startsWith('interval-') ? 'xend' : 'x'; + const inspected = await inspectPlayer(data); + assert.equal(inspected.duration, 2147483.647); + assert.equal(inspected.output, expectedOutput); + assert.equal(timers.size, 0); + const playback = createCore(data); + try { + await playback.core.init(); + await playback.core.play(); + for (let n = 0; n < (id.startsWith('interval-') ? 2 : 1); n++) { + const timer = takeTimer(); + assert.ok(Number.isFinite(timer.delay) && timer.delay >= 0 && timer.delay <= 2147483647); + timer.callback(); + await Promise.resolve(); + } + assert.equal(playback.events.output.flat().join(''), expectedOutput, 'accepted boundary output always advances'); + assert.equal(playback.events.ended.length, 1); + assert.ok(Number.isFinite(playback.core.getDuration())); + assert.ok(Number.isFinite(playback.core.getCurrentTime())); + assert.ok(Number.isFinite(playback.core.getProgress())); + assert.deepEqual(playback.events.error, []); + assert.equal(timers.size, 0, 'accepted output does not reschedule a consumed event'); + process.stdout.write(`${id} actual Core init/seek/playback is finite and advances\n`); + } finally { await playback.core.stop(); } + } + } finally { + globalThis.setTimeout = realSetTimeout; + globalThis.clearTimeout = realClearTimeout; + } +} + +test('actual 3.17 Core timestamp regressions are bounded and blocked before handoff', () => { + const script = ` + import assert from 'node:assert/strict'; + import { readFile } from 'node:fs/promises'; + import { loadRecording, RecordingLoadError } from ${JSON.stringify(new URL('../../src/recording-loader.js', import.meta.url).href)}; + import { getSecurityCase, securityFixtureBuffer } from ${JSON.stringify(new URL('../fixtures/security/generate.mjs', import.meta.url).href)}; + ${playerCore.toString()} + ${streamedFixture.toString()} + ${inspectPlayer.toString()} + await (${timestampCoreRegression.toString()})(); + process.stdout.write('bounded actual-Core timestamp witnesses passed\\n'); + `; + const child = spawnSync(process.execPath, ['--input-type=module', '--eval', script], { + cwd: new URL('../../', import.meta.url), timeout: 10000, maxBuffer: 64 * 1024, + encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '' }, + }); + const diagnostics = `stdout:\n${child.stdout}\nstderr:\n${child.stderr}`; + assert.equal(child.error, undefined, `the bounded Core witness must finish: ${child.error?.message}\n${diagnostics}`); + assert.equal(child.signal, null, `the bounded Core witness was killed\n${diagnostics}`); + assert.equal(child.status, 0, diagnostics); + assert.match(child.stdout, /bounded actual-Core timestamp witnesses passed/); +}); diff --git a/tests/php/cast-budget-decoder.php b/tests/php/cast-budget-decoder.php new file mode 100644 index 0000000..18bef54 --- /dev/null +++ b/tests/php/cast-budget-decoder.php @@ -0,0 +1,11 @@ + 3, 'term' => array( 'cols' => 80, 'rows' => 24 ) ) : array( 'version' => $version, 'width' => 80, 'height' => 24 ); + $header = array_merge( $header, $metadata ); + $frames = array(); + foreach ( $intervals as $time ) { + $frames[] = 1 === $version ? array( $time, 'x' ) : array( $time, 'o', 'x' ); + } + if ( 1 === $version ) { + $header['stdout'] = $frames; + return json_encode( $header ); + } + return json_encode( $header ) . "\n" . implode( "\n", array_map( 'json_encode', $frames ) ); + } + + same( 2147483647, CAST_MAX_TIME_MS, 'The timeline ceiling matches the signed browser timer range.' ); + $max_seconds = CAST_MAX_TIME_MS / 1000; + foreach ( array( 1, 2, 3 ) as $version ) { + same( true, cast_contents_are_valid( cast_time_contents( $version, array( $max_seconds ) ) ), 'Accept the exact v' . $version . ' timer horizon.' ); + same( false, cast_contents_are_valid( cast_time_contents( $version, array( $max_seconds + 0.001 ) ) ), 'Reject v' . $version . ' one millisecond beyond the horizon.' ); + same( false, cast_contents_are_valid( cast_time_contents( $version, array( -0.001 ) ) ), 'Reject negative v' . $version . ' time.' ); + foreach ( array( 'duration', 'idle_time_limit' ) as $key ) { + same( true, cast_contents_are_valid( cast_time_contents( $version, array( 0 ), array( $key => $max_seconds ) ) ), 'Accept exact v' . $version . ' ' . $key . ' horizon.' ); + foreach ( array( $max_seconds + 0.001, -0.001, '1', null ) as $value ) { + same( false, cast_contents_are_valid( cast_time_contents( $version, array( 0 ), array( $key => $value ) ) ), 'Reject invalid v' . $version . ' ' . $key . '.' ); + } + } + } + foreach ( array( INF, -INF, NAN, -1, '1', null ) as $value ) { + same( false, is_cast_time( $value ), 'Time validation rejects nonfinite, negative, and nonnumeric values.' ); + } + $rounding_intervals = array( 307699.2378567164, 1839784.4091432837 ); + same( (float) CAST_MAX_TIME_MS, ( $rounding_intervals[0] + $rounding_intervals[1] ) * 1000, 'Seconds-first rounding hides the over-limit result.' ); + same( true, $rounding_intervals[0] * 1000 + $rounding_intervals[1] * 1000 > CAST_MAX_TIME_MS, 'The actual player millisecond sum is over the horizon.' ); + foreach ( array( 1, 3 ) as $version ) { + same( true, cast_contents_are_valid( cast_time_contents( $version, array( 1, $max_seconds - 1 ) ) ), 'Accept cumulative v' . $version . ' at the horizon.' ); + foreach ( array( array( 1, $max_seconds ), $rounding_intervals, array( 2.996155224770526e303, 1.7677315826146105e305 ) ) as $intervals ) { + same( false, cast_contents_are_valid( cast_time_contents( $version, $intervals ) ), 'Reject v' . $version . ' cumulative upstream millisecond overflow.' ); + } + } + same( false, cast_contents_are_valid( cast_time_contents( 2, array( 1e20 ) ) ), 'Reject a tiny v2 cast whose output batching cannot make progress.' ); + same( false, cast_contents_are_valid( cast_time_contents( 2, array( 10004.674, 10004.673999999999 ) ) ), 'Reject backward v2 seconds even when conversion rounds to equal milliseconds.' ); + same( true, cast_contents_are_valid( cast_time_contents( 2, array( 1, 1 ) ) ), 'Equal v2 timestamps remain accepted.' ); + + foreach ( array( + 'zero v2 dimensions' => '{"version":2,"width":0,"height":0}', + 'zero v3 dimensions' => '{"version":3,"term":{"cols":0,"rows":0}}', + '40,000 cells' => '{"version":2,"width":1000,"height":40}', + 'normal ignored lines' => $v2 . "\n\n# comment\nnot an event\n [broken ignored JSON\n[0,\"o\",\"works\"]\n", + '1,000 markers' => $v2 . "\n" . str_repeat( "[0,\"m\",\"mark\"]\n", 1000 ), + '40,000-cell resize' => $v2 . "\n[0,\"r\",\"200x200\"]\n", + ) as $description => $contents ) { + same( true, cast_contents_are_valid( $contents ), 'Accept ' . $description . '.' ); + } + foreach ( array( + 'cell-product overflow' => '{"version":2,"width":201,"height":200}', + 'zero width defaults before cell check' => '{"version":2,"width":0,"height":501}', + 'zero height defaults before cell check' => '{"version":2,"width":1000,"height":0}' . "\n[0,\"r\",\"1000x41\"]\n", + 'v3 cell-product overflow' => '{"version":3,"term":{"cols":201,"rows":200}}', + '1,001 markers' => $v3 . "\n" . str_repeat( "[0,\"m\",\"mark\"]\n", 1001 ), + 'resize cell-product overflow' => $v2 . "\n[0,\"r\",\"201x200\"]\n", + 'zero resize has no header defaults' => $v3 . "\n[0,\"r\",\"80x0\"]\n", + 'ignored line count overflow' => $v2 . "\n" . str_repeat( "\n", 100001 ), + 'ignored line byte overflow' => $v2 . "\n#" . str_repeat( 'x', 262144 ), + 'missing dimensions' => '{"version":2}', + 'empty malformed event' => $v2 . "\n[]\n", + ) as $description => $contents ) { + same( false, cast_contents_are_valid( $contents ), 'Reject ' . $description . '.' ); + } + + $containers = 0; + $tokens = 0; + $escaped = json_encode( array( 'key"\\' => '[{}], : \\" braces', 'value' => true ) ); + same( true, is_cast_json_within_budget( " \n\t" . $escaped . "\r\n", $containers, $tokens ), 'Escapes and JSON whitespace are scanned.' ); + same( 1, $containers, 'String punctuation does not inflate containers.' ); + same( 4, $tokens, 'Keys and scalar values each consume a token.' ); + same( true, cast_budget_accepts( str_repeat( '[', 15 ) . '0' . str_repeat( ']', 15 ) ), 'Container nesting 15 fits decoder depth 16.' ); + same( false, cast_budget_accepts( str_repeat( '[', 16 ) . '0' . str_repeat( ']', 16 ) ), 'Reject depth before decoder allocation.' ); + same( true, cast_budget_accepts( '[' . str_repeat( '0,', CAST_MAX_JSON_TOKENS - 1 ) . '0]' ), 'Scalar token budget is inclusive.' ); + same( false, cast_budget_accepts( '[' . str_repeat( '0,', CAST_MAX_JSON_TOKENS ) . '0]' ), 'Reject excessive scalar tokens.' ); + same( true, cast_budget_accepts( '[' . str_repeat( '{},', CAST_MAX_JSON_CONTAINERS - 2 ) . '{}]' ), 'Container budget is inclusive.' ); + same( false, cast_budget_accepts( '[' . str_repeat( '{},', CAST_MAX_JSON_CONTAINERS - 1 ) . '{}]' ), 'Reject excessive empty containers.' ); + $containers = 0; + $tokens = CAST_MAX_JSON_TOKENS - 2; + same( true, is_cast_json_within_budget( '[0,"o"]', $containers, $tokens ), 'Shared record budget reaches its boundary.' ); + same( false, is_cast_json_within_budget( '[0]', $containers, $tokens ), 'Shared record budget cannot reset per event.' ); + + foreach ( array( + 'wide metadata scalars' => '[' . str_repeat( '0,', CAST_MAX_JSON_TOKENS ) . '0]', + 'wide metadata containers' => '[' . str_repeat( '{},', CAST_MAX_JSON_CONTAINERS ) . '{}]', + 'duplicate metadata keys' => '{' . str_repeat( '"x":0,', 200000 ) . '"x":0}', + 'deep metadata' => str_repeat( '[', 16 ) . '0' . str_repeat( ']', 16 ), + ) as $description => $metadata ) { + $text = "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[],\"metadata\":" . $metadata . '}'; + $GLOBALS['cast_decode_lengths'] = array(); + same( false, is_cast_v1( $text ), 'Reject ' . $description . ' before decoding.' ); + same( array(), $GLOBALS['cast_decode_lengths'], 'No native decode runs for ' . $description . '.' ); + same( false, cast_contents_are_valid( $text ), 'Upload path rejects ' . $description . '.' ); + same( false, in_array( strlen( $text ), $GLOBALS['cast_decode_lengths'], true ), 'Upload path never decodes the full rejected document.' ); + } + $prefix = '{"version":2,"width":80,"height":24,"metadata":['; + same( true, cast_contents_are_valid( $prefix . str_repeat( '0,', 19992 ) . '0]}' ), 'JSONL header accepts exactly 20,000 scalar/key tokens.' ); + same( false, cast_contents_are_valid( $prefix . str_repeat( '0,', 19993 ) . '0]}' ), 'JSONL header rejects 20,001 scalar/key tokens.' ); + foreach ( array( 2, 3 ) as $version ) { + $prefix = 2 === $version ? '{"version":2,"width":80,"height":24,"metadata":[' : '{"version":3,"term":{"cols":80,"rows":24},"metadata":['; + $wide_header = $prefix . str_repeat( '0,', 20000 ) . '0]}'; + $GLOBALS['cast_decode_lengths'] = array(); + same( false, cast_contents_are_valid( $wide_header ), 'Wide JSONL header is rejected without v1 budget fallback.' ); + same( false, in_array( strlen( $wide_header ), $GLOBALS['cast_decode_lengths'], true ), 'Over-budget v2/v3 header never reaches full decoder.' ); + } + foreach ( array( + 'escaped version key' => '{"ver\\u0073ion":1,"width":80,"height":24,"stdout":[]}', + 'duplicate version last wins' => '{"version":2,"version":1,"width":80,"height":24,"stdout":[]}', + 'nested version ignored' => '{"version":1,"meta":{"version":2},"width":80,"height":24,"stdout":[]}', + 'frame-rich first line' => '{"stdout":[' . str_repeat( '[0,""],', 10000 ) . '[0,""]],'. "\n" .'"version":1,"width":80,"height":24}', + 'title-rich first line' => '{"title":"' . str_repeat( 'x', 262144 ) . '",'. "\n" .'"version":1,"width":80,"height":24,"stdout":[]}', + ) as $description => $text ) { + same( true, cast_contents_are_valid( $text ), 'Format discriminator preserves ' . $description . '.' ); + } + $text = '{"version":1,"version":2,"width":80,"height":24,"stdout":[],"metadata":[' . str_repeat( '0,', 20000 ) . '0]}'; + $GLOBALS['cast_decode_lengths'] = array(); + same( false, cast_contents_are_valid( $text ), 'Last duplicate version cannot receive a legacy budget.' ); + same( false, in_array( strlen( $text ), $GLOBALS['cast_decode_lengths'], true ), 'Last duplicate version rejects before full decode.' ); + + $wide_event = '[0,"o",[' . str_repeat( '0,', 19999 ) . '0]]'; + $GLOBALS['cast_decode_lengths'] = array(); + same( false, cast_contents_are_valid( $v2 . "\n" . $wide_event ), 'Reject wide event data with the per-line gate.' ); + same( false, in_array( strlen( $wide_event ), $GLOBALS['cast_decode_lengths'], true ), 'Wide event never reaches the native decoder.' ); + $deep_header = '{"version":2,"width":80,"height":24,"metadata":' . str_repeat( '[', 14 ) . '0' . str_repeat( ']', 14 ) . '}'; + same( true, cast_contents_are_valid( $deep_header ), 'Decoder and lexical gate agree on depth boundary.' ); + + $GLOBALS['cast_decode_lengths'] = array(); + same( false, is_cast_v1( '{"version":1,broken}' ), 'Final decoder still rejects malformed JSON.' ); + same( true, in_array( strlen( '{"version":1,broken}' ), $GLOBALS['cast_decode_lengths'], true ), 'Within-budget grammar errors reach the real decoder.' ); + $text = '{"version":1,"width":0,"height":0,"stdout":[' . str_repeat( '[0,""],', 99999 ) . '[0,""]]}'; + same( true, cast_contents_are_valid( $text ), '100,000 compact v1 frames fit byte, structure and event budgets.' ); + $GLOBALS['cast_decode_lengths'] = array(); +} diff --git a/tests/php/run.php b/tests/php/run.php index 76e93bd..e55bef6 100644 --- a/tests/php/run.php +++ b/tests/php/run.php @@ -1,6 +1,7 @@ CAST_MAX_BYTES + 1 ) { + throw new RuntimeException( 'A security fixture exceeded the 32 MiB + 1 byte generation cap.' ); + } + $offset = 0; + while ( $offset < $length ) { + $written = fwrite( $handle, substr( $chunk, $offset ) ); + if ( false === $written || 0 === $written ) { + throw new RuntimeException( 'Could not write a security fixture.' ); + } + $offset += $written; + } + hash_update( $hash, $chunk ); + $bytes += $length; +} + +/** Expand only literal/repeat recipes; never interpret executable generators. */ +function security_fixture_materialize( $fixture, $root, $path ) { + $handle = fopen( $path, 'wb' ); + if ( false === $handle ) { + throw new RuntimeException( 'Could not open the security fixture temporary file.' ); + } + $hash = hash_init( 'sha256' ); + $bytes = 0; + try { + $source = $fixture['source']; + if ( isset( $source['file'] ) ) { + $file = realpath( $root . '/' . $source['file'] ); + if ( false === $file || 0 !== strpos( $file, $root . DIRECTORY_SEPARATOR ) || ! is_file( $file ) ) { + throw new RuntimeException( 'Security fixture files must stay inside their corpus directory.' ); + } + $input = fopen( $file, 'rb' ); + if ( false === $input ) { + throw new RuntimeException( 'Could not open a checked-in security fixture.' ); + } + try { + while ( ! feof( $input ) ) { + $chunk = fread( $input, 65536 ); + if ( false === $chunk || ( '' === $chunk && ! feof( $input ) ) ) { + throw new RuntimeException( 'Could not read a checked-in security fixture.' ); + } + security_fixture_write_chunk( $handle, $chunk, $hash, $bytes ); + } + } finally { + fclose( $input ); + } + } else { + foreach ( $source['segments'] as $segment ) { + $text = $segment['text']; + $remaining = $segment['repeat']; + if ( ! is_string( $text ) || '' === $text || ! is_int( $remaining ) || $remaining < 1 ) { + throw new RuntimeException( 'Security recipes require nonempty text and a positive integer repeat.' ); + } + $length = strlen( $text ); + if ( $length <= 65536 ) { + $batch = min( $remaining, intdiv( 65536, $length ) ); + $chunk = str_repeat( $text, $batch ); + while ( $remaining >= $batch ) { + security_fixture_write_chunk( $handle, $chunk, $hash, $bytes ); + $remaining -= $batch; + } + if ( $remaining > 0 ) { + security_fixture_write_chunk( $handle, str_repeat( $text, $remaining ), $hash, $bytes ); + } + } else { + while ( $remaining-- > 0 ) { + for ( $offset = 0; $offset < $length; $offset += 65536 ) { + security_fixture_write_chunk( $handle, substr( $text, $offset, 65536 ), $hash, $bytes ); + } + } + } + } + } + } finally { + fclose( $handle ); + } + clearstatcache( true, $path ); + same( $fixture['bytes'], $bytes, $fixture['id'] . ': generated byte count matches the shared manifest.' ); + same( $bytes, filesize( $path ), $fixture['id'] . ': the actual upload file has those bytes.' ); + same( $fixture['sha256'], hash_final( $hash ), $fixture['id'] . ': generated bytes match the shared SHA-256.' ); +} + +/** Verify ordering at the real decoder, not merely a generic false result. */ +function security_fixture_assert_decodes( $fixture, $label ) { + $lengths = $GLOBALS['cast_decode_lengths']; + if ( $fixture['expected']['accepted'] ) { + same( true, count( $lengths ) > 0, $label . ': a valid control actually reaches the native JSON decoder.' ); + } + $threshold = $fixture['expected']['phpNoDecodeAtOrAboveBytes'] ?? $fixture['expected']['noDecodeAtOrAboveBytes'] ?? null; + if ( null !== $threshold ) { + same( true, is_int( $threshold ) && $threshold > 0 && $threshold <= $fixture['bytes'], $label . ': decoder witness is bounded by the rejected file.' ); + $largest = empty( $lengths ) ? 0 : max( $lengths ); + same( true, $largest < $threshold, $label . ': rejected payload never reaches the full decoder (largest decode: ' . $largest . ' bytes).' ); + } +} + +$security_fixture_root = realpath( dirname( __DIR__ ) . '/fixtures/security' ); +$security_fixture_manifest = json_decode( file_get_contents( $security_fixture_root . '/manifest.json' ), true ); +same( JSON_ERROR_NONE, json_last_error(), 'The shared security manifest is valid JSON.' ); +same( 1, $security_fixture_manifest['schemaVersion'], 'PHP consumes the versioned shared security corpus.' ); +same( true, count( $security_fixture_manifest['cases'] ) > 0, 'The security corpus cannot silently become empty.' ); + +// Independent policy pins keep a production constant change from moving the +// goalposts, including cell limits whose next representable grid may skip one. +foreach ( array( + 'CAST_MAX_BYTES' => 33554432, + 'CAST_MAX_LINE_BYTES' => 262144, + 'CAST_MAX_V1_BYTES' => 2097152, + 'CAST_MAX_EVENTS' => 100000, + 'CAST_MAX_DIMENSION' => 1000, + 'CAST_MAX_CELLS' => 40000, + 'CAST_MAX_MARKERS' => 1000, + 'CAST_MAX_JSON_TOKENS' => 400000, + 'CAST_MAX_JSON_LINE_TOKENS' => 20000, + 'CAST_MAX_JSON_CONTAINERS' => 100016, + 'CAST_JSON_DEPTH' => 16, + 'CAST_MAX_TIME_MS' => 2147483647, +) as $constant => $limit ) { + same( $limit, constant( 'LamGC\\Asciiplayer\\' . $constant ), $constant . ': the documented production limit is unchanged.' ); +} + +$security_fixture_callbacks = array(); +foreach ( $GLOBALS['ap_test']['filters'] as $filter ) { + if ( in_array( $filter[0], array( 'wp_handle_upload_prefilter', 'wp_handle_sideload_prefilter' ), true ) ) { + $security_fixture_callbacks[ $filter[0] ] = $filter[1]; + } +} +same( 2, count( $security_fixture_callbacks ), 'Both registered upload and sideload paths consume the security corpus.' ); + +$security_fixture_wp_state = $GLOBALS['ap_test']; +$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true, 'unfiltered_upload' => true ); +$GLOBALS['ap_test']['multisite'] = false; +unset( $GLOBALS['ap_test']['allowed_mimes'] ); +$security_fixture_ids = array(); +$security_fixture_records = array(); +try { + foreach ( $security_fixture_manifest['cases'] as $fixture ) { + same( false, isset( $security_fixture_ids[ $fixture['id'] ] ), 'Each security fixture has a unique ID.' ); + $security_fixture_ids[ $fixture['id'] ] = $fixture['expected']; + $security_fixture_records[ $fixture['id'] ] = $fixture; + same( true, isset( $fixture['source']['file'] ) !== isset( $fixture['source']['segments'] ), $fixture['id'] . ': exactly one fixture source is defined.' ); + same( true, is_bool( $fixture['expected']['accepted'] ), $fixture['id'] . ': the expected upload result is explicit.' ); + $path = tempnam( sys_get_temp_dir(), 'ap-security-' ); + if ( false === $path ) { + throw new RuntimeException( 'Could not create the security fixture temporary file.' ); + } + try { + security_fixture_materialize( $fixture, $security_fixture_root, $path ); + $GLOBALS['cast_decode_lengths'] = array(); + same( $fixture['expected']['accepted'], is_valid_cast_file( $path ), $fixture['id'] . ': actual file validator result.' ); + security_fixture_assert_decodes( $fixture, $fixture['id'] . ' / file validator' ); + // Browser MIME and size are deliberately wrong: inspect the actual file. + $upload = array( 'name' => $fixture['id'] . '.cast', 'tmp_name' => $path, 'error' => 0, 'type' => 'image/png', 'size' => 1 ); + foreach ( $security_fixture_callbacks as $hook => $callback ) { + $GLOBALS['cast_decode_lengths'] = array(); + $result = call_user_func( $callback, $upload ); + if ( $fixture['expected']['accepted'] ) { + same( $upload, $result, $fixture['id'] . ' / ' . $hook . ': valid content passes unchanged.' ); + } else { + same( true, is_string( $result['error'] ) && 0 === strpos( $result['error'], 'Upload a valid Asciicast' ), $fixture['id'] . ' / ' . $hook . ': content rejection occurs even for unfiltered_upload.' ); + $result['error'] = 0; + same( $upload, $result, $fixture['id'] . ' / ' . $hook . ': only the upload error changes.' ); + } + security_fixture_assert_decodes( $fixture, $fixture['id'] . ' / ' . $hook ); + } + } finally { + unlink( $path ); + } + } + // Required numeric witnesses cannot disappear while the remaining generic + // manifest loop still passes. These expectations do not import guard limits. + same( 2147483647, $security_fixture_manifest['policy']['timelineMs'] ?? null, 'The corpus independently pins the signed 32-bit millisecond horizon.' ); + foreach ( array( 1, 2, 3 ) as $version ) { + foreach ( array( 'timeline', 'duration', 'idle-limit' ) as $purpose ) { + foreach ( array( 'at' => 2147483647, 'over' => 2147483648 ) as $suffix => $milliseconds ) { + $id = $purpose . '-v' . $version . '-' . $suffix; + $fixture = $security_fixture_records[ $id ] ?? array(); + same( array( 'metric' => 'timelineMs', 'limit' => 2147483647, 'value' => $milliseconds ), $fixture['boundary'] ?? null, $id . ': the exact timing boundary remains in the shared corpus.' ); + same( 'at' === $suffix, $fixture['expected']['accepted'] ?? null, $id . ': both sides retain their independently pinned acceptance result.' ); + same( 'over' === $suffix ? 'time' : null, $fixture['expected']['jsError'] ?? null, $id . ': timing rejection reason is explicit.' ); + } + } + foreach ( array( 'duration', 'idle-limit' ) as $purpose ) { + $id = $purpose . '-v' . $version . '-zero'; + same( true, $security_fixture_ids[ $id ]['accepted'] ?? null, $id . ': zero timing metadata remains supported.' ); + } + } + foreach ( array( 1, 3 ) as $version ) { + foreach ( array( 'at', 'over' ) as $suffix ) { + $id = 'interval-timeline-v' . $version . '-' . $suffix; + same( 'at' === $suffix, $security_fixture_ids[ $id ]['accepted'] ?? null, $id . ': interval cumulative boundary remains covered.' ); + } + } + foreach ( array( + 'time-v2-output-nonprogress', + 'time-v1-ms-sum-overflow', 'time-v3-ms-sum-overflow', + 'time-v1-ms-rounding-over', 'time-v3-ms-rounding-over', + ) as $id ) { + same( false, $security_fixture_ids[ $id ]['accepted'] ?? null, $id . ': the required actual-player arithmetic witness remains rejected.' ); + same( 'time', $security_fixture_ids[ $id ]['jsError'] ?? null, $id . ': both languages retain the same explicit timestamp expectation.' ); + same( true, ( $security_fixture_records[ $id ]['bytes'] ?? 256 ) < 256, $id . ': the numerical regression payload remains tiny.' ); + } + + foreach ( array( 'bytes-v2-over', 'bytes-v3-over' ) as $id ) { + same( 1, $security_fixture_ids[ $id ]['phpNoDecodeAtOrAboveBytes'] ?? null, $id . ': the PHP file-stat gate must reject before any native decode.' ); + } + // These cases must keep decoder witnesses: a false validator result alone + // would not prove that allocation was prevented before the native decode. + foreach ( array( + 'bytes-v2-over', 'bytes-v3-over', 'v1-bytes-over', + 'line-v2-over', 'line-v3-over', + 'tokens-v1-over', 'containers-v1-over', + 'depth-v1-over', 'depth-v2-over', 'depth-v3-over', + 'line-tokens-v2-over', 'line-tokens-v3-over', + ) as $id ) { + same( true, isset( $security_fixture_ids[ $id ]['noDecodeAtOrAboveBytes'] ), $id . ': required predecode witness remains in the corpus.' ); + same( false, $security_fixture_ids[ $id ]['accepted'], $id . ': the predecode witness remains a rejection case.' ); + } +} finally { + $GLOBALS['ap_test'] = $security_fixture_wp_state; + $GLOBALS['cast_decode_lengths'] = array(); +} diff --git a/tests/php/uploads.php b/tests/php/uploads.php index a9a1d44..b63a926 100644 --- a/tests/php/uploads.php +++ b/tests/php/uploads.php @@ -56,6 +56,16 @@ $v2 = '{"version":2,"width":80,"height":24}'; $v3 = '{"version":3,"term":{"cols":100,"rows":30}}'; $v1 = array( 'version' => 1, 'width' => 80, 'height' => 24, 'duration' => 1.5, 'stdout' => array( array( 0.1, "Hello\r\n" ), array( 1.4, 'World' ) ) ); foreach ( array( + 'zero width' => '{"version":2,"width":0,"height":24}', + 'event object' => $v2 . "\n{\"0\":0,\"1\":\"o\",\"2\":\"bad\"}\n", + 'trailing HTML' => $v2 . "\n[0,\"o\",\"ok\"]\n\n", + 'trailing JSON object' => $v2 . "\n[0,\"o\",\"ok\"]\n{\"unrelated\":true}\n", + 'blank event line' => $v2 . "\n\n", + 'indented event ignored by bundled player' => $v2 . "\n [0,\"o\",\"invisible\"]\n", + 'v2 comment' => $v2 . "\n# comment\n", + 'v3 indented comment' => $v3 . "\n # not a comment\n", + 'compact v1' => json_encode( $v1 ), + 'large compact v1' => json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_LINE_BYTES + 1 ) ) ) ), 'pretty v1' => json_encode( $v1, JSON_PRETTY_PRINT ), 'v2 output' => $v2 . "\n[0.1,\"o\",\"Hello\\r\\n\"]\n", 'v3 relative events' => $v3 . "\n[5,\"o\",\"Hello\"]\n[0.1,\"r\",\"120x40\"]\n[0,\"x\",\"0\"]\n", @@ -80,7 +90,6 @@ foreach ( array( 'SVG' => '', 'unsupported version' => '{"version":4,"width":80,"height":24}', 'string version' => '{"version":"2","width":80,"height":24}', - 'zero width' => '{"version":2,"width":0,"height":24}', 'oversized width' => '{"version":2,"width":1001,"height":24}', 'negative height' => '{"version":2,"width":80,"height":-1}', 'fractional width' => '{"version":2,"width":80.5,"height":24}', @@ -89,8 +98,6 @@ foreach ( array( 'v3 terminal array' => '{"version":3,"term":[100,30]}', 'v1 absent stdout' => "{\n\"version\":1,\"width\":80,\"height\":24\n}", 'v1 stdout object' => "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":{\"0\":[0,\"x\"]}\n}", - 'compact v1 unsupported by bundled player' => json_encode( $v1 ), - 'large compact v1 unsupported by bundled player' => json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_LINE_BYTES + 1 ) ) ) ), 'v1 negative delay' => json_encode( array_merge( $v1, array( 'stdout' => array( array( -1, 'x' ) ) ) ), JSON_PRETTY_PRINT ), 'v1 malformed later frame' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok' ), array( 0, array( 'x' ) ) ) ) ), JSON_PRETTY_PRINT ), 'v1 extra frame element' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok', 'extra' ) ) ) ), JSON_PRETTY_PRINT ), @@ -102,7 +109,6 @@ foreach ( array( 'milliseconds overflow' => $v2 . "\n[1e308,\"o\",\"bad\"]\n", 'v3 cumulative milliseconds overflow' => $v3 . "\n[1e305,\"o\",\"first\"]\n[1e305,\"o\",\"second\"]\n", 'v2 out of order' => $v2 . "\n[2,\"o\",\"first\"]\n[1,\"o\",\"second\"]\n", - 'event object' => $v2 . "\n{\"0\":0,\"1\":\"o\",\"2\":\"bad\"}\n", 'missing event data' => $v2 . "\n[0,\"o\"]\n", 'extra event element' => $v2 . "\n[0,\"o\",\"bad\",1]\n", 'event data array' => $v2 . "\n[0,\"o\",[\"bad\"]]\n", @@ -111,12 +117,6 @@ foreach ( array( 'oversized resize' => $v2 . "\n[0,\"r\",\"2000x20\"]\n", 'malformed resize' => $v2 . "\n[0,\"r\",\"80,24\"]\n", 'bad later JSON' => $v2 . "\n[0,\"o\",\"ok\"]\n[1,\"o\",\"truncated\"\n", - 'trailing HTML' => $v2 . "\n[0,\"o\",\"ok\"]\n\n", - 'trailing JSON object' => $v2 . "\n[0,\"o\",\"ok\"]\n{\"unrelated\":true}\n", - 'blank event line' => $v2 . "\n\n", - 'indented event ignored by bundled player' => $v2 . "\n [0,\"o\",\"invisible\"]\n", - 'v2 comment' => $v2 . "\n# comment\n", - 'v3 indented comment' => $v3 . "\n # not a comment\n", 'UTF-8 BOM' => "\xef\xbb\xbf" . $v2, 'invalid UTF-8' => $v2 . "\n[0,\"o\",\"\xff\"]\n", 'oversized JSONL line' => $v2 . "\n[0,\"o\",\"" . str_repeat( 'a', CAST_MAX_LINE_BYTES ) . "\"]\n", @@ -166,7 +166,7 @@ try { same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Upload permissions are enforced for valid content too.' ); same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'MIME override never grants upload capability.' ); $GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true, 'unfiltered_upload' => true ); - file_put_contents( $path, $v2 . "\n\n" ); + file_put_contents( $path, $v2 . "\n[invalid JSON\n" ); clearstatcache( true, $path ); same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Malformed content fails even with unfiltered_upload.' ); same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'Invalid content cannot keep a previous MIME approval.' );