From 92de7f86f4e85847ee32e25bd8824f0477d4d020 Mon Sep 17 00:00:00 2001 From: LamGC Date: Thu, 15 Oct 2026 10:13:55 +0800 Subject: [PATCH] Bound recording loading, terminal allocation, markers and upload JSON complexity --- README-zh.md | 26 +- README.md | 32 +- includes/uploads.php | 191 +++++++++- ...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 | 326 ++++++++++++++++ src/view.js | 95 ++++- tests/e2e/bounded-recording.spec.js | 352 ++++++++++++++++++ tests/e2e/i18n.spec.js | 4 +- tests/e2e/recording-source.spec.js | 2 +- tests/js/playback.test.js | 118 ++++++ tests/js/preview-lifecycle.test.js | 116 ++++++ tests/js/recording-loader.test.js | 281 ++++++++++++++ tests/php/cast-budget-decoder.php | 12 + tests/php/cast-budget.php | 110 ++++++ tests/php/run.php | 2 + tests/php/uploads.php | 22 +- 24 files changed, 1831 insertions(+), 115 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/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/php/cast-budget-decoder.php create mode 100644 tests/php/cast-budget.php diff --git a/README-zh.md b/README-zh.md index d0fa4dc..cce529f 100644 --- a/README-zh.md +++ b/README-zh.md @@ -70,17 +70,29 @@ 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** 个单元格。 +- 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..c4725a8 100644 --- a/README.md +++ b/README.md @@ -85,19 +85,35 @@ 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) use the same 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). +- 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/includes/uploads.php b/includes/uploads.php index 961065a..a73361b 100644 --- a/includes/uploads.php +++ b/includes/uploads.php @@ -17,6 +17,143 @@ 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; +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 ) { @@ -54,6 +191,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 +207,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,7 +223,12 @@ 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; } @@ -108,7 +258,7 @@ function is_cast_event( $event, $version, &$time ) { 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 +291,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,25 +311,30 @@ function is_valid_cast_file( $path ) { } $bytes = strlen( $line ); $count = 0; + $markers = 0; $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 ); + $event = json_decode( $line, false, CAST_JSON_DEPTH ); if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_event( $event, $header->version, $time ) ) { return false; } + if ( 'm' === $event[1] && ++$markers > CAST_MAX_MARKERS ) { + return false; + } } return feof( $handle ); } finally { @@ -194,7 +351,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..ad8ac58 --- /dev/null +++ b/src/recording-loader.js @@ -0,0 +1,326 @@ +/** 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, + 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 finiteTime = ( value ) => typeof value === 'number' && value >= 0 && Number.isFinite( value * 1000 ); +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 ]; + } + } + 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 time = 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 ) && ! finiteTime( value[ key ] ) ) 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 ( ! finiteTime( event[ 0 ] ) ) fail( 'time' ); + if ( header.version === 2 && event[ 0 ] < time ) fail( 'time' ); + time = header.version === 3 ? time + event[ 0 ] : event[ 0 ]; + if ( ! finiteTime( time ) ) fail( 'time' ); + 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 ( ! finiteTime( event[ 0 ] ) || ! finiteTime( time += event[ 0 ] ) ) fail( 'time' ); + } + 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..43fa842 --- /dev/null +++ b/tests/e2e/bounded-recording.spec.js @@ -0,0 +1,352 @@ +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 = { + bytes: 'This recording exceeds the file size limit.', + 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: 'actual received byte limit', code: 'bytes', + body: () => { + const header = `${JSON.stringify({ version: 2, width: 64, height: 12 })}\n`; + // Keep every comment line well below the line limit and use no + // events, isolating the total-byte cap without huge terminal output. + const comment = `#${'x'.repeat(1022)}\n`; + return header + comment.repeat(Math.ceil((DEFAULT_LIMITS.bytes + 1 - header.length) / comment.length)); + }, + }, + { + 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/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..b0fb869 --- /dev/null +++ b/tests/js/recording-loader.test.js @@ -0,0 +1,281 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { loadRecording, DEFAULT_LIMITS, RecordingLoadError, validateInitialDimensions } from '../../src/recording-loader.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( '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( ( 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/php/cast-budget-decoder.php b/tests/php/cast-budget-decoder.php new file mode 100644 index 0000000..d0ea97c --- /dev/null +++ b/tests/php/cast-budget-decoder.php @@ -0,0 +1,12 @@ + '{"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..b215166 100644 --- a/tests/php/run.php +++ b/tests/php/run.php @@ -1,6 +1,7 @@ 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.' );