fix: bound recording timestamps before playback

Match upstream millisecond accumulation and bound native timer horizons.
Add deterministic rounding, overflow and non-progress regression casts,
with captured-player and WordPress playback/upload coverage.
This commit is contained in:
2026-10-15 11:30:31 +08:00
parent 487eedf0ba
commit e1cd87f87d
49 changed files with 1273 additions and 33 deletions
+2 -1
View File
@@ -70,12 +70,13 @@ URL 要直接指向录制文件,例如 `.cast` 文件,而不是 asciinema
已有 WordPress `upload_files` 权限的用户可以上传 `.cast` 文件。
多站点还需要网络管理员允许 `cast` 扩展名。插件不会增加用户的上传权限,也不会另建录屏管理文章类型。
上传和浏览器播放(包括远程录屏)采用相同的资源限制:
上传和浏览器播放(包括远程录屏)执行以下资源限制:
- 接收到的录屏数据最多 **32 MiB**;旧的 v1 格式最多 **2 MiB**。
- 最多 **100,000** 个事件或流内行,忽略的行也计入。
- 每条 JSONL 行最多 **256 KiB**,最多 **1,000** 个时间标记。
- 终端每个方向不超过 **1,000** 列或行,列数 × 行数不超过 **40,000** 个单元格。
- 录屏时间轴和支持的时间值最多 **2,147,483,647 毫秒**(约 **24.85 天**)。v1/v3 的相对时间按播放器的顺序以毫秒累加。浏览器播放还要求累计录屏时间除以播放速度后不超过此上限;因此在 **0.01×** 速度下,原始录屏时长最多约 **5.97 小时**。这一保守边界确保原生定时器延迟和输出批处理处于支持的数值范围内。起始时间、空闲时间与时间戳封面选项也会检查。
- JSON 容器最多嵌套 **15** 层;v1 最多 **400,000** 个标量/键名与 **100,016** 个容器;每条 JSONL 行最多 **20,000** 个标量/键名。解码前检查,未知元数据与重复键名也计入。
- 浏览器请求总时限为 **30 秒**,等待下个响应或数据块的时限为 **10 秒**;编辑器加载播放器资源与录屏合计也限 30 秒。
+2 -1
View File
@@ -85,12 +85,13 @@ 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 and browser playback (including remote recordings) use the same resource limits:
Uploads and browser playback (including remote recordings) enforce these resource limits:
- **32 MiB** of received recording data; **2 MiB** for legacy v1.
- **100,000** events or stream lines, including ignored lines.
- **256 KiB** per JSONL line and **1,000** marker events.
- **1,000** columns or rows per axis, and **40,000** terminal cells (columns × rows).
- **2,147,483,647 milliseconds** (about **24.85 days**) for recording timelines and supported time values. Relative v1/v3 intervals are accumulated in milliseconds, matching the player. Browser playback also requires cumulative recording time divided by playback speed to fit this ceiling; at **0.01×**, this permits about **5.97 hours** of source time. This conservative bound keeps native timer delays and output batching within their supported numeric range. Playback start, idle-time and timestamp-poster options are checked too.
- At most **15** nested JSON containers, **400,000** scalar/key tokens and **100,016** containers in v1, or **20,000** scalar/key tokens per JSONL line, checked before decoding. Unknown metadata and duplicate keys count too.
- Browser requests stop after **30 seconds** total or **10 seconds** without the next response/chunk; the editor also allows 30 seconds for player assets and loading together.
+18 -11
View File
@@ -19,6 +19,9 @@ const CAST_MAX_EVENTS = 100000;
const CAST_MAX_DIMENSION = 1000;
const CAST_MAX_CELLS = 40000;
const CAST_MAX_MARKERS = 1000;
// Browser timers use signed 32-bit millisecond delays (~24.85 days). Keep the
// raw timeline in this range; playback additionally checks the selected speed.
const CAST_MAX_TIME_MS = 2147483647;
const CAST_MAX_JSON_TOKENS = 400000;
const CAST_MAX_JSON_LINE_TOKENS = 20000;
const CAST_MAX_JSON_CONTAINERS = 100016;
@@ -181,9 +184,9 @@ function is_cast_filename( $filename ) {
return is_string( $filename ) && 1 === preg_match( '/\.cast\z/i', $filename );
}
/** Finite, nonnegative seconds that remain finite in the player's milliseconds. */
/** Nonnegative seconds within the supported browser timer/precision horizon. */
function is_cast_time( $value ) {
return ( is_int( $value ) || is_float( $value ) ) && $value >= 0 && is_finite( $value * 1000 );
return ( is_int( $value ) || is_float( $value ) ) && $value >= 0 && $value * 1000 <= CAST_MAX_TIME_MS;
}
/** Bound both initial and resize dimensions before they reach the terminal. */
@@ -232,13 +235,14 @@ function is_cast_v1( $text ) {
if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_header( $recording ) || 1 !== $recording->version || ! isset( $recording->stdout ) || ! is_array( $recording->stdout ) || count( $recording->stdout ) > CAST_MAX_EVENTS ) {
return false;
}
$time = 0;
$time_ms = 0;
foreach ( $recording->stdout as $frame ) {
if ( ! is_array( $frame ) || 2 !== count( $frame ) || ! is_cast_time( $frame[0] ) || ! is_string( $frame[1] ) ) {
return false;
}
$time += $frame[0];
if ( ! is_cast_time( $time ) ) {
// Match upstream's arithmetic order, including floating-point rounding.
$time_ms += $frame[0] * 1000;
if ( ! is_finite( $time_ms ) || $time_ms > CAST_MAX_TIME_MS ) {
return false;
}
}
@@ -246,15 +250,17 @@ function is_cast_v1( $text ) {
}
/** Validate one JSONL event, with absolute v2 time or relative v3 intervals. */
function is_cast_event( $event, $version, &$time ) {
function is_cast_event( $event, $version, &$time_ms, &$previous_time ) {
if ( ! is_array( $event ) || 3 !== count( $event ) || ! is_cast_time( $event[0] ) || ! is_string( $event[1] ) || '' === $event[1] || ! is_string( $event[2] ) ) {
return false;
}
if ( 2 === $version && $event[0] < $time ) {
$event_ms = $event[0] * 1000;
if ( 2 === $version && $event[0] < $previous_time ) {
return false;
}
$time = 2 === $version ? $event[0] : $time + $event[0];
if ( ! is_cast_time( $time ) ) {
$previous_time = $event[0];
$time_ms = 2 === $version ? $event_ms : $time_ms + $event_ms;
if ( ! is_finite( $time_ms ) || $time_ms > CAST_MAX_TIME_MS ) {
return false;
}
if ( 'r' === $event[1] ) {
@@ -312,7 +318,8 @@ function is_valid_cast_file( $path ) {
$bytes = strlen( $line );
$count = 0;
$markers = 0;
$time = 0;
$time_ms = 0;
$previous_time = 0;
while ( false !== ( $line = fgets( $handle, CAST_MAX_LINE_BYTES + 2 ) ) ) {
$bytes += strlen( $line );
if ( $bytes > CAST_MAX_BYTES || strlen( $line ) > CAST_MAX_LINE_BYTES || ++$count > CAST_MAX_EVENTS ) {
@@ -329,7 +336,7 @@ function is_valid_cast_file( $path ) {
return false;
}
$event = json_decode( $line, false, CAST_JSON_DEPTH );
if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_event( $event, $header->version, $time ) ) {
if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_event( $event, $header->version, $time_ms, $previous_time ) ) {
return false;
}
if ( 'm' === $event[1] && ++$markers > CAST_MAX_MARKERS ) {
+2 -2
View File
@@ -327,7 +327,7 @@ msgid ""
"invalid, or blocked by the source server’s CORS policy."
msgstr ""
#: includes/uploads.php:354
#: includes/uploads.php:361
msgid ""
"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, "
@@ -358,7 +358,7 @@ msgstr ""
msgid "Width and height (legacy)"
msgstr ""
#: includes/uploads.php:352
#: includes/uploads.php:359
msgid "You are not allowed to upload Asciicast files."
msgstr ""
+1 -1
View File
@@ -47,7 +47,7 @@ Use a recording-file URL rather than a share-page URL. The remote server must pe
= What recording limits apply? =
Uploads and browser playback, including remote files, are bounded to 32 MiB (v1: 2 MiB), 100,000 events or stream lines, 256 KiB per JSONL line, 1,000 markers, 1,000 columns/rows per axis and 40,000 terminal cells. Initial dimensions, resize events and effective overrides are checked. JSON nesting and structure are checked before decoding. Existing files/posts are not rewritten; unusually large recordings may need splitting or simplification. The browser validates one request before playback, without an extra metadata request or a server proxy.
Uploads and browser playback, including remote files, are bounded to 32 MiB (v1: 2 MiB), 100,000 events or stream lines, 256 KiB per JSONL line, 1,000 markers, 1,000 columns/rows per axis and 40,000 terminal cells. Recording timelines and supported time values are capped at 2,147,483,647 milliseconds (about 24.85 days). Browser playback additionally bounds cumulative time divided by speed; at 0.01x, source time is limited to about 5.97 hours. Relative intervals are accumulated in the player's millisecond order, and start/idle/poster times are checked. Initial dimensions, resize events and effective overrides are checked. JSON nesting and structure are checked before decoding. Existing files/posts are not rewritten; unusually large recordings may need splitting or simplification. The browser validates one request before playback, without an extra metadata request or a server proxy.
= Are player resources loaded from a CDN? =
+35 -8
View File
@@ -3,6 +3,9 @@ export const DEFAULT_LIMITS = Object.freeze( {
bytes: 32 * 1024 * 1024, v1Bytes: 2 * 1024 * 1024, lineBytes: 256 * 1024,
depth: 15, containers: 100016, tokens: 400000, lineTokens: 20000,
events: 100000, lines: 100000, markers: 1000, dimension: 1000, cells: 40000,
// Web timers take a signed 32-bit millisecond delay (~24.85 days). This
// horizon also keeps upstream's 16.67 ms output batches numerically distinct.
timelineMs: 2147483647,
totalTimeoutMs: 30000, idleTimeoutMs: 10000,
} );
@@ -14,7 +17,7 @@ export class RecordingLoadError extends Error {
}
}
const fail = ( code ) => { throw new RecordingLoadError( code ); };
const finiteTime = ( value ) => typeof value === 'number' && value >= 0 && Number.isFinite( value * 1000 );
const boundedTime = ( value, maxMs ) => typeof value === 'number' && value >= 0 && value * 1000 <= maxMs;
const object = ( value ) => value !== null && typeof value === 'object' && ! Array.isArray( value );
/** Guard the terminal allocated by api.create before its data loader runs. */
@@ -134,6 +137,25 @@ export async function loadRecording( source, { fetchImpl = globalThis.fetch, sig
policy[ key ] = limits[ key ];
}
}
// Policy overrides may lower this safety ceiling, but cannot expand the
// platform timer range. Callers supply already-normalized player options.
if ( policy.timelineMs > DEFAULT_LIMITS.timelineMs ) fail( 'policy' );
const speed = options.speed ?? 1;
if ( typeof speed !== 'number' || ! Number.isFinite( speed ) || speed < 0.01 || speed > 100 ) fail( 'time' );
for ( const key of [ 'startAt', 'idleTimeLimit' ] ) {
if ( options[ key ] !== undefined && ! boundedTime( options[ key ], policy.timelineMs ) ) fail( 'time' );
}
if ( typeof options.poster === 'string' && options.poster.startsWith( 'npt:' ) ) {
// Match upstream parseNpt's order of arithmetic for normalized timecodes.
const posterTime = options.poster.slice( 4 ).split( ':' ).reverse().map( parseFloat ).reduce( ( sum, part, index ) => sum + part * 60 ** index, 0 );
if ( ! boundedTime( posterTime, policy.timelineMs ) ) fail( 'time' );
}
function checkTimeline( milliseconds ) {
// Core passes (target - elapsed) / speed directly to setTimeout. Bound
// the whole horizon conservatively: adjacent gaps alone are insufficient
// because output batching can consume future events ahead of wall time.
if ( ! Number.isFinite( milliseconds ) || milliseconds > policy.timelineMs || milliseconds / speed > DEFAULT_LIMITS.timelineMs ) fail( 'time' );
}
const controller = new AbortController();
let reader;
let totalTimer;
@@ -176,7 +198,7 @@ export async function loadRecording( source, { fetchImpl = globalThis.fetch, sig
let bytes = 0;
let mode = 'first';
let header;
let time = 0;
let timeMs = 0;
let lines = 0;
let markerCount = Array.isArray( options.markers ) ? options.markers.length : 0;
const events = [];
@@ -191,7 +213,7 @@ export async function loadRecording( source, { fetchImpl = globalThis.fetch, sig
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' );
if ( Object.hasOwn( value, key ) && ! boundedTime( value[ key ], policy.timelineMs ) ) fail( 'time' );
}
}
function acceptLine( text, size, newline ) {
@@ -234,10 +256,13 @@ export async function loadRecording( source, { fetchImpl = globalThis.fetch, sig
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 ( ! boundedTime( event[ 0 ], policy.timelineMs ) ) fail( 'time' );
const eventMs = event[ 0 ] * 1000;
if ( header.version === 2 && events.length && event[ 0 ] < events[ events.length - 1 ][ 0 ] ) fail( 'time' );
// v1/v3 upstream converts each interval before adding, which can round
// differently from summing seconds and multiplying the result by 1000.
timeMs = header.version === 3 ? timeMs + eventMs : eventMs;
checkTimeline( timeMs );
if ( event[ 1 ] === 'r' ) {
const match = /^([1-9][0-9]{0,3})x([1-9][0-9]{0,3})$/.exec( event[ 2 ] );
if ( ! match ) fail( 'dimensions' );
@@ -300,7 +325,9 @@ export async function loadRecording( source, { fetchImpl = globalThis.fetch, sig
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' );
if ( ! boundedTime( event[ 0 ], policy.timelineMs ) ) fail( 'time' );
timeMs += event[ 0 ] * 1000;
checkTimeline( timeMs );
}
result = header;
} else result = [ header, ...events ];
+3 -1
View File
@@ -4,6 +4,7 @@ import { getSecurityCase, securityFixtureBuffer } from '../fixtures/security/gen
const blockName = 'lamgc/asciiplayer';
const fixtureRoot = '/wp-content/uploads/asciiplayer-fixtures/security';
const messages = {
time: 'This recording contains an invalid or unsupported timestamp.',
markers: 'This recording contains too many markers.',
dimensions: 'This recording requests terminal dimensions that exceed the supported limits.',
cells: 'This recording requests too many terminal cells.',
@@ -222,6 +223,7 @@ const rejectionIds = [
'dimensions-v1-over', 'dimensions-v2-over', 'dimensions-v3-over',
'markers-v2-over', 'markers-v3-over',
'late-resize-v2-over', 'late-resize-v3-over',
'time-v1-ms-rounding-over', 'time-v2-output-nonprogress', 'time-v3-ms-sum-overflow',
];
for (const id of rejectionIds) {
test(`shared ${id} is rejected before unsafe DOM allocation on both playback paths`, async ({ page, context }) => {
@@ -284,7 +286,7 @@ test('real WordPress uploads reject shared marker/cell fixtures and accept a see
const { id, block } = await insertPlayer(page, '');
const unique = `${Date.now()}-${testInfo.retry}`;
const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).';
for (const fixtureId of ['markers-v2-over', 'cells-v1-over']) {
for (const fixtureId of ['markers-v2-over', 'cells-v1-over', 'time-v1-ms-rounding-over', 'time-v2-output-nonprogress', 'time-v3-ms-sum-overflow']) {
const dialog = await openMedia(page, block);
const result = await uploadCorpusFixture(page, dialog, fixtureId, unique);
expect(result.success, JSON.stringify(result)).toBe(false);
+16 -2
View File
@@ -127,6 +127,10 @@ can or should be avoided.
| v1 container allocation | `containers-v1-{at,over}` | 100,016 / 100,017 containers |
| JSONL scalar/key allocation | `line-tokens-v{2,3}-{at,over}` | 20,000 / 20,001 tokens |
| Nesting | `depth-v{1,2,3}-{at,over}` | 15 / 16 container levels |
| Recording timeline | `timeline-v{1,2,3}-{at,over}` | 2,147,483,647 / 2,147,483,648 milliseconds |
| Relative timeline sum | `interval-timeline-v{1,3}-{at,over}` | Millisecond-order accumulation at / over the horizon |
| Time metadata | `duration-v*-{zero,at,over}`, `idle-limit-v*-{zero,at,over}` | Zero remains valid; inclusive horizon applies |
| Floating-point regressions | `time-v{1,3}-ms-rounding-over`, `time-v{1,3}-ms-sum-overflow`, `time-v2-output-nonprogress` | Valid JSON with unsafe upstream millisecond arithmetic |
| Intentional bad syntax | `malformed-v1-json`, `malformed-v{2,3}-event` | Stable invalid-result controls |
The cells-over value is 40,200, not an assertion that every integer cell count
@@ -139,8 +143,18 @@ equivalence.
The corpus invariant suite independently parses tightly bounded test data to
measure structure, verify valid/malformed labels, pin exact boundary values,
and prove an unrelated limit is not masking the intended one. Only the six
`safePlayback` controls reach the real pinned player Core. Hostile/boundary
recordings first exercise the production loader guard or PHP upload validator.
`safePlayback` controls use ordinary real pinned player Core playback. Separate
tiny timestamp regressions use captured timers and bounded callbacks to verify
upstream numeric behavior without scheduling long waits or an unbounded loop.
Hostile/boundary recordings first exercise the production loader guard or PHP
upload validator.
The supported raw timeline is about 24.85 days. Browser playback conservatively
requires cumulative time divided by speed to fit the same signed timer ceiling;
at 0.01×, this permits about 5.97 hours of source time. Per-event gap checks alone
are insufficient because the player batches future output ahead of wall time.
The v1/v3 rounding witness specifically distinguishes summing milliseconds from
summing seconds before conversion; these two operations are not interchangeable.
Browser tests use the existing isolated WordPress setup and check visible errors
and recovery. Passing Node/PHP checks does not imply that a browser run occurred.
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"duration":2147483.647,"stdout":[[0,"x"]]}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"duration":2147483.648,"stdout":[[0,"x"]]}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"duration":0,"stdout":[[0,"x"]]}
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":80,"height":24,"duration":2147483.647}
[0,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":80,"height":24,"duration":2147483.648}
[0,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":80,"height":24,"duration":0}
[0,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":80,"rows":24},"duration":2147483.647}
[0,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":80,"rows":24},"duration":2147483.648}
[0,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":80,"rows":24},"duration":0}
[0,"o","x"]
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"idle_time_limit":2147483.647,"stdout":[[0,"x"]]}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"idle_time_limit":2147483.648,"stdout":[[0,"x"]]}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"idle_time_limit":0,"stdout":[[0,"x"]]}
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":80,"height":24,"idle_time_limit":2147483.647}
[0,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":80,"height":24,"idle_time_limit":2147483.648}
[0,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":80,"height":24,"idle_time_limit":0}
[0,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":80,"rows":24},"idle_time_limit":2147483.647}
[0,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":80,"rows":24},"idle_time_limit":2147483.648}
[0,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":80,"rows":24},"idle_time_limit":0}
[0,"o","x"]
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"stdout":[[1073741.823,"x"],[1073741.824,"end"]]}
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"stdout":[[1073741.823,"x"],[1073741.825,"end"]]}
+3
View File
@@ -0,0 +1,3 @@
{"version":3,"term":{"cols":80,"rows":24}}
[1073741.823,"o","x"]
[1073741.824,"o","end"]
@@ -0,0 +1,3 @@
{"version":3,"term":{"cols":80,"rows":24}}
[1073741.823,"o","x"]
[1073741.825,"o","end"]
+716 -1
View File
@@ -14,7 +14,8 @@
"depth": 15,
"containers": 100016,
"tokens": 400000,
"lineTokens": 20000
"lineTokens": 20000,
"timelineMs": 2147483647
},
"cases": [
{
@@ -840,6 +841,720 @@
"events": 100001
}
},
{
"id": "timeline-v1-at",
"format": 1,
"description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "timeline-v1-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 66,
"sha256": "5622319d9372013c48101ef2944cd5d079084b0df144a1fcc69140cd5b66d9f5",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "duration-v1-at",
"format": 1,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "duration-v1-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 79,
"sha256": "02b5c0e111adb26dfb6dd5c792ea48ebb853d0618cf1860fd2857d2d06f4980c",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "idle-limit-v1-at",
"format": 1,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "idle-limit-v1-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 86,
"sha256": "76038e9c90775dc12c299c3c2dd4f265bf4ee3b6e4cd2b66c95688b859becd43",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "timeline-v1-over",
"format": 1,
"description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "timeline-v1-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 66,
"sha256": "177d6d8d97d72f2a5416b7eb1b9e32c2cc2b620a20ae1c70d5494406befc17f9",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "duration-v1-over",
"format": 1,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "duration-v1-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 79,
"sha256": "32da9450dc0f53f8d044006c967296ac50d9311a7e8a86f4730aebff191d03f3",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "idle-limit-v1-over",
"format": 1,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "idle-limit-v1-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 86,
"sha256": "7ad90f6743ea0f90c4ed00a9c1dc361d5640b8abeaaf0c7cfd5dd9e190209398",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "duration-v1-zero",
"format": 1,
"description": "Zero remains valid for optional timing metadata.",
"category": "valid-control",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "duration-v1-zero.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 69,
"sha256": "14f1b40e1d57c7b00a6024c1e4e5a4d68723207eb447c91f721a6cfce0674d4e"
},
{
"id": "idle-limit-v1-zero",
"format": 1,
"description": "Zero remains valid for optional timing metadata.",
"category": "valid-control",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "idle-limit-v1-zero.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 76,
"sha256": "ba707de0f768ed2fe89ebd7d8751c4febc6c7eb4be4ac21b4be6e69324353c98"
},
{
"id": "timeline-v2-at",
"format": 2,
"description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "timeline-v2-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 59,
"sha256": "5dcb182b6e3ccf2573e58408f7ac44599fcc6ac92b3951f8fd3c2bb3138d1e4f",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "duration-v2-at",
"format": 2,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "duration-v2-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 72,
"sha256": "257b671345d8f515afa242242f313125fecbe58a92f7e690861d6b38e0b1ec36",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "idle-limit-v2-at",
"format": 2,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "idle-limit-v2-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 79,
"sha256": "e5f12262b1b1a76970785cbbe98126f0d8061dffce1b623aeaa150dac0f4ffea",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "timeline-v2-over",
"format": 2,
"description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "timeline-v2-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 59,
"sha256": "7717e9978f2767db79388c597a683e216445146c0f7fe2e639401cdafad94267",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "duration-v2-over",
"format": 2,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "duration-v2-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 72,
"sha256": "a7eaae002cebeec39c2c1ea0832a261ec66a8bab76dafaeaaa252e1e6ab641dd",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "idle-limit-v2-over",
"format": 2,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "idle-limit-v2-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 79,
"sha256": "c10e47c6405d2f2087ff4348584722bc5e89c9c7bb8d69648d446189d268ce01",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "duration-v2-zero",
"format": 2,
"description": "Zero remains valid for optional timing metadata.",
"category": "valid-control",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "duration-v2-zero.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 62,
"sha256": "f8ccb56b4dc1b3b8535af7ea4eaad3c6f0d6475563aa9c593ca0e4a4821943dd"
},
{
"id": "idle-limit-v2-zero",
"format": 2,
"description": "Zero remains valid for optional timing metadata.",
"category": "valid-control",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "idle-limit-v2-zero.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 69,
"sha256": "b34ea66b9bd4c165b55ca39523a5874f29d68cc9277eb3cca4de589691732d1a"
},
{
"id": "timeline-v3-at",
"format": 3,
"description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "timeline-v3-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 65,
"sha256": "1e234fb56af6cc042a6daf77a6b833db2f5ecab6aae35a1c7e3821051dce2ec5",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "duration-v3-at",
"format": 3,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "duration-v3-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 78,
"sha256": "b363b4bc5077858e30fa0e188cb49d5b50c9d40fe5f0f14ced04bf835b2e2d21",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "idle-limit-v3-at",
"format": 3,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "idle-limit-v3-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 85,
"sha256": "b787da8e6ba022bc3a2ac8780aa8073ea4ca82b92d018cccbf22655846122dd0",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "timeline-v3-over",
"format": 3,
"description": "One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "timeline-v3-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 65,
"sha256": "aafb1fabc891df6843942f69ac945e13ea77865a2542cca1d02db6bb1c8080bf",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "duration-v3-over",
"format": 3,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "duration-v3-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 78,
"sha256": "5fcf1f75486d94f71463e6320886d0a51721f8fdbe1063593b5a1d14c14978d1",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "idle-limit-v3-over",
"format": 3,
"description": "Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "idle-limit-v3-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 85,
"sha256": "a3624e3fc0bd3c420dbfe91018b47b840b7fb09e10fba7365fee079e2615bef6",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "duration-v3-zero",
"format": 3,
"description": "Zero remains valid for optional timing metadata.",
"category": "valid-control",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "duration-v3-zero.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 68,
"sha256": "2d40499454b3b7a1589b91004115e2a9d53a18e7167ccefe9352eda66bbfb2d8"
},
{
"id": "idle-limit-v3-zero",
"format": 3,
"description": "Zero remains valid for optional timing metadata.",
"category": "valid-control",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "idle-limit-v3-zero.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 75,
"sha256": "bdc71879c2d7f3d8338d31038133d070b2d9dc6e398f6b133c45e90750509016"
},
{
"id": "interval-timeline-v1-at",
"format": 1,
"description": "Each interval is inside the horizon; only their upstream-order millisecond sum selects the boundary.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "interval-timeline-v1-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 86,
"sha256": "8e9c5b96b20566f12fe9a15e1c8269461d0dbc6ba6d1a06a83aff581f872d0fc",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "interval-timeline-v1-over",
"format": 1,
"description": "Each interval is inside the horizon; only their upstream-order millisecond sum selects the boundary.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "interval-timeline-v1-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 86,
"sha256": "7fec7732286f679ef8f0e71f4f3fae0f9078dab6684eda81f517bd1d5b39d3bf",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "time-v1-ms-rounding-over",
"format": 1,
"description": "Adding seconds before conversion rounds to the allowed cap, but summing each interval in milliseconds exceeds it.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "time-v1-ms-rounding-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 99,
"sha256": "06283761ce7b12acdc6352ebaa71b7691e723aa3be6592bd6b9eb3c4ad3a547c",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647.0000002
}
},
{
"id": "time-v1-ms-sum-overflow",
"format": 1,
"description": "Both converted intervals and the converted seconds sum are finite, but upstream interval-by-interval millisecond addition overflows.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "time-v1-ms-sum-overflow.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 109,
"sha256": "7ac8311d1533b23a5115195bd004804d7b0b1f1540a5782ff865af22dec295d7"
},
{
"id": "interval-timeline-v3-at",
"format": 3,
"description": "Each interval is inside the horizon; only their upstream-order millisecond sum selects the boundary.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "interval-timeline-v3-at.cast"
},
"expected": {
"accepted": true,
"jsError": null
},
"bytes": 89,
"sha256": "3f76fc28485f0670f5b62210fd580950c404a1809ede166e53ad75c0960cb8bc",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647
}
},
{
"id": "interval-timeline-v3-over",
"format": 3,
"description": "Each interval is inside the horizon; only their upstream-order millisecond sum selects the boundary.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "interval-timeline-v3-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 89,
"sha256": "9f311bc12ed12e6208d8821a593ab6e1ec17cf4c7d926ff00f83ca06741e1758",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483648
}
},
{
"id": "time-v3-ms-rounding-over",
"format": 3,
"description": "Adding seconds before conversion rounds to the allowed cap, but summing each interval in milliseconds exceeds it.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "time-v3-ms-rounding-over.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 102,
"sha256": "21bdf134dee3e29fce0166b4c71c2657d47796b3e7cb33667b82de08df3bcadf",
"boundary": {
"metric": "timelineMs",
"limit": 2147483647,
"value": 2147483647.0000002
}
},
{
"id": "time-v3-ms-sum-overflow",
"format": 3,
"description": "Both converted intervals and the converted seconds sum are finite, but upstream interval-by-interval millisecond addition overflows.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "time-v3-ms-sum-overflow.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 112,
"sha256": "4ce89449651ac5435e81a8635dda115b2022d325217871177079d41cd143be5a"
},
{
"id": "time-v2-output-nonprogress",
"format": 2,
"description": "A tiny finite timestamp makes the upstream output batching deadline equal its start, so callbacks repeat without consuming output.",
"category": "resource-boundary",
"provenance": "normalized-mutation",
"safePlayback": false,
"validity": "format-valid",
"source": {
"file": "time-v2-output-nonprogress.cast"
},
"expected": {
"accepted": false,
"jsError": "time"
},
"bytes": 69,
"sha256": "92abcf13adcfc3f65e61c7ab7d367f9e7cd41bb7bd38b4b11bef280b51fee536"
},
{
"id": "valid-v1-multiline-late-version",
"format": 1,
+31
View File
@@ -8,6 +8,7 @@ export const POLICY = Object.freeze( {
bytes: 33554432, v1Bytes: 2097152, lineBytes: 262144, events: 100000,
lines: 100000, markers: 1000, dimension: 1000, cells: 40000,
depth: 15, containers: 100016, tokens: 400000, lineTokens: 20000,
timelineMs: 2147483647,
} );
// This PRNG is part of the reproducibility contract, not a security primitive.
@@ -115,6 +116,36 @@ export function createRecipes( seed = FIXTURE_SEED ) {
}
}
// Tiny time witnesses use a pinned policy independent of production constants.
// Keep official captures untouched and never mark these as browser-playable.
const timedCast = ( version, timestamps, metadata = {} ) => {
const meta = { ...header( version ), ...metadata };
const frames = timestamps.map( ( time, index ) => [ time, ...( version === 1 ? [] : [ 'o' ] ), index ? 'end' : 'x' ] );
return ( version === 1 ? json( { ...meta, stdout: frames } ) : [ meta, ...frames ].map( json ).join( '\n' ) ) + '\n';
};
for ( const version of [ 1, 2, 3 ] ) {
for ( const over of [ false, true ] ) {
const suffix = over ? 'over' : 'at';
const seconds = over ? 2147483.648 : 2147483.647;
const options = { small: true, error: over ? 'time' : null, boundary: pair( 'timelineMs', 2147483647, over ? 2147483648 : 2147483647 ) };
add( `timeline-v${ version }-${ suffix }`, version, 'One event isolates the inclusive 2^31 - 1 millisecond timeline horizon.', [ segment( timedCast( version, [ seconds ] ) ) ], options );
for ( const [ id, key ] of [ [ 'duration', 'duration' ], [ 'idle-limit', 'idle_time_limit' ] ] ) {
add( `${ id }-v${ version }-${ suffix }`, version, 'Timing metadata uses the same finite nonnegative millisecond horizon even when upstream ignores that field.', [ segment( timedCast( version, [ 0 ], { [ key ]: seconds } ) ) ], options );
}
}
for ( const [ id, key ] of [ [ 'duration', 'duration' ], [ 'idle-limit', 'idle_time_limit' ] ] ) {
add( `${ id }-v${ version }-zero`, version, 'Zero remains valid for optional timing metadata.', [ segment( timedCast( version, [ 0 ], { [ key ]: 0 } ) ) ], { small: true, category: 'valid-control' } );
}
}
for ( const version of [ 1, 3 ] ) {
for ( const over of [ false, true ] ) {
add( `interval-timeline-v${ version }-${ over ? 'over' : 'at' }`, version, 'Each interval is inside the horizon; only their upstream-order millisecond sum selects the boundary.', [ segment( timedCast( version, [ 1073741.823, over ? 1073741.825 : 1073741.824 ] ) ) ], { small: true, error: over ? 'time' : null, boundary: pair( 'timelineMs', 2147483647, over ? 2147483648 : 2147483647 ) } );
}
add( `time-v${ version }-ms-rounding-over`, version, 'Adding seconds before conversion rounds to the allowed cap, but summing each interval in milliseconds exceeds it.', [ segment( timedCast( version, [ 307699.2378567164, 1839784.4091432837 ] ) ) ], { small: true, error: 'time', boundary: pair( 'timelineMs', 2147483647, 2147483647.0000002 ) } );
add( `time-v${ version }-ms-sum-overflow`, version, 'Both converted intervals and the converted seconds sum are finite, but upstream interval-by-interval millisecond addition overflows.', [ segment( timedCast( version, [ 2.996155224770526e303, 1.7677315826146105e305 ] ) ) ], { small: true, error: 'time' } );
}
add( 'time-v2-output-nonprogress', 2, 'A tiny finite timestamp makes the upstream output batching deadline equal its start, so callbacks repeat without consuming output.', [ segment( timedCast( 2, [ 1e20 ] ) ) ], { small: true, error: 'time' } );
add( 'valid-v1-multiline-late-version', 1, 'Pretty v1 document places its version after stdout and nested metadata.', [ segment( '{\n "stdout": [[0,"multiline v1\\r\\n"]],\n "metadata": {"version": 3},\n "width": 80,\n "height": 24,\n "version": 1\n}\n' ) ], { small: true, category: 'valid-control' } );
add( 'valid-v1-escaped-version', 1, 'Escaped top-level version key is still v1.', [ segment( '{"ver\\u0073ion":1,"width":80,"height":24,"stdout":[]}\n' ) ], { small: true, category: 'valid-control' } );
add( 'valid-v1-duplicate-version', 1, 'Last duplicate version wins under the bundled JSON parsers.', [ segment( '{"version":2,"version":1,"width":80,"height":24,"stdout":[]}\n' ) ], { small: true, category: 'upstream-compatibility' } );
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"stdout":[[307699.2378567164,"x"],[1839784.4091432837,"end"]]}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"stdout":[[2.996155224770526e+303,"x"],[1.7677315826146105e+305,"end"]]}
@@ -0,0 +1,2 @@
{"version":2,"width":80,"height":24}
[100000000000000000000,"o","x"]
+3
View File
@@ -0,0 +1,3 @@
{"version":3,"term":{"cols":80,"rows":24}}
[307699.2378567164,"o","x"]
[1839784.4091432837,"o","end"]
+3
View File
@@ -0,0 +1,3 @@
{"version":3,"term":{"cols":80,"rows":24}}
[2.996155224770526e+303,"o","x"]
[1.7677315826146105e+305,"o","end"]
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"stdout":[[2147483.647,"x"]]}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"stdout":[[2147483.648,"x"]]}
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":80,"height":24}
[2147483.647,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":80,"height":24}
[2147483.648,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":80,"rows":24}}
[2147483.647,"o","x"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":80,"rows":24}}
[2147483.648,"o","x"]
+76
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadRecording, DEFAULT_LIMITS, RecordingLoadError, validateInitialDimensions } from '../../src/recording-loader.js';
import { normalizePlayerOptions } from '../../src/options.js';
const encode = ( text ) => new TextEncoder().encode( text );
const h2 = { version: 2, width: 80, height: 24 };
@@ -127,6 +128,79 @@ test( 'non-finite timestamps and cumulative time overflow are rejected', async (
await rejectCode( JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ 1e305, 'x' ], [ 1e305, 'x' ] ] } ), 'time' );
} );
test( 'supported timeline boundary is inclusive across all formats and timing metadata', async () => {
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
assert.equal( DEFAULT_LIMITS.timelineMs, 2147483647 );
for ( const version of [ 1, 2, 3 ] ) {
const header = version === 3 ? h3 : { ...h2, version };
const content = ( seconds, extra = {} ) => version === 1
? JSON.stringify( { ...header, ...extra, stdout: [ [ seconds, 'x' ] ] } )
: cast( { ...header, ...extra }, [ [ seconds, 'o', 'x' ] ] );
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( maxSeconds ) ).fetchImpl } ) );
await rejectCode( content( maxSeconds + 0.001 ), 'time' );
await rejectCode( content( -0.001 ), 'time' );
for ( const key of [ 'duration', 'idle_time_limit' ] ) {
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( 0, { [ key ]: maxSeconds } ) ).fetchImpl } ) );
for ( const value of [ maxSeconds + 0.001, -0.001, '1', null ] ) await rejectCode( content( 0, { [ key ]: value } ), 'time' );
}
}
} );
test( 'relative formats accumulate individually converted milliseconds in upstream order', async () => {
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
const rounding = [ 307699.2378567164, 1839784.4091432837 ];
assert.equal( ( rounding[ 0 ] + rounding[ 1 ] ) * 1000, DEFAULT_LIMITS.timelineMs );
assert.ok( rounding[ 0 ] * 1000 + rounding[ 1 ] * 1000 > DEFAULT_LIMITS.timelineMs );
for ( const version of [ 1, 3 ] ) {
const content = ( intervals ) => version === 1
? JSON.stringify( { version: 1, width: 80, height: 24, stdout: intervals.map( ( time ) => [ time, 'x' ] ) } )
: cast( h3, intervals.map( ( time ) => [ time, 'o', 'x' ] ) );
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( [ 1, maxSeconds - 1 ] ) ).fetchImpl } ) );
for ( const intervals of [ [ 1, maxSeconds ], rounding, [ 2.996155224770526e303, 1.7677315826146105e305 ] ] ) {
await rejectCode( content( intervals ), 'time' );
}
}
await rejectCode( cast( h2, [ [ 1e20, 'o', 'x' ] ] ), 'time' );
} );
test( 'slow playback stays within native timer range without expanding the base horizon at higher speeds', async () => {
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
for ( const version of [ 1, 2, 3 ] ) {
const content = ( seconds ) => version === 1
? JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ seconds, 'x' ] ] } )
: cast( version === 3 ? h3 : h2, [ [ seconds, 'o', 'x' ] ] );
for ( const speed of [ 0.01, 0.5, 1, 100 ] ) {
const seconds = maxSeconds * Math.min( speed, 1 );
const options = { speed };
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( seconds ) ).fetchImpl, options } ) );
await rejectCode( content( seconds + 0.001 ), 'time', { options } );
}
}
// An idle limiter or late start does not waive validation of the raw horizon.
await rejectCode( cast( h2, [ [ maxSeconds, 'o', 'x' ] ] ), 'time', { options: { speed: 0.01, idleTimeLimit: 0.001, startAt: maxSeconds } } );
} );
test( 'normalized timing options are checked before any recording request', async () => {
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
for ( const options of [
...[ 0, -1, NaN, Infinity, 0.009, 101, '1' ].map( ( speed ) => ( { speed } ) ),
...[ 'startAt', 'idleTimeLimit' ].flatMap( ( key ) => [ maxSeconds + 0.001, -1, Infinity, NaN ].map( ( value ) => ( { [ key ]: value } ) ) ),
{ poster: 'npt:596:31:23.648' },
normalizePlayerOptions( { startAt: `${ '9'.repeat( 400 ) }:00:00` } ),
normalizePlayerOptions( { poster: `npt:${ '9'.repeat( 400 ) }:00:00` } ),
] ) {
const input = fixture( cast() );
await assert.rejects( loadRecording( '/cast', { fetchImpl: input.fetchImpl, options } ), { code: 'time' } );
assert.equal( input.calls.length, 0 );
}
for ( const options of [ { startAt: maxSeconds, idleTimeLimit: maxSeconds }, { poster: 'npt:596:31:23.647' }, { poster: 'data:text/plain,2147483648' } ] ) {
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( cast() ).fetchImpl, options } ) );
}
await assert.rejects( loadRecording( '/cast', { limits: { timelineMs: DEFAULT_LIMITS.timelineMs + 1 } } ), { code: 'policy' } );
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( cast( h2, [ [ 1, 'o', 'x' ] ] ) ).fetchImpl, limits: { timelineMs: 1000 } } ) );
await rejectCode( cast( h2, [ [ 1.001, 'o', 'x' ] ] ), 'time', { limits: { timelineMs: 1000 } } );
} );
test( 'invalid records do not report metadata', async () => {
for ( const content of [ '', '{}', cast( h2, [ [ 0, 'o', {} ] ] ), cast( h2, [ [ 0, '', 'x' ] ] ), `${ JSON.stringify( h2 ) }\n[invalid` ] ) {
let notified = false;
@@ -222,6 +296,8 @@ test( 'initial BOM is removed but later BOM-prefixed lines remain ignored', asyn
test( 'v2 absolute timestamps cannot move backward; equal timestamps remain valid', async () => {
await rejectCode( cast( h2, [ [ 2, 'o', 'x' ], [ 1, 'o', 'y' ] ] ), 'time' );
assert.equal( 10004.674 * 1000, 10004.673999999999 * 1000 );
await rejectCode( cast( h2, [ [ 10004.674, 'o', 'x' ], [ 10004.673999999999, 'o', 'y' ] ] ), 'time' );
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast( h2, [ [ 1, 'o', 'x' ], [ 1, 'o', 'y' ] ] ) ).fetchImpl } ) ).length, 3 );
} );
+53 -2
View File
@@ -31,7 +31,7 @@ function measure( entry, bytes ) {
const text = bytes.toString( 'utf8' );
let header;
let frames;
const metrics = { bytes: bytes.length, v1Bytes: bytes.length, lineBytes: 0, events: 0, lines: 0, markers: 0, dimension: 0, cells: 0, depth: 0, tokens: 0, containers: 0, lineTokens: 0 };
const metrics = { bytes: bytes.length, v1Bytes: bytes.length, lineBytes: 0, events: 0, lines: 0, markers: 0, dimension: 0, cells: 0, depth: 0, tokens: 0, containers: 0, lineTokens: 0, timelineMs: 0 };
if ( entry.format === 1 ) {
header = JSON.parse( text );
assert.ok( Array.isArray( header.stdout ) );
@@ -71,6 +71,10 @@ function measure( entry, bytes ) {
}
size( ...dimensions );
let time = 0;
let milliseconds = 0;
for ( const key of [ 'duration', 'idle_time_limit' ] ) {
if ( Object.hasOwn( header, key ) ) metrics.timelineMs = Math.max( metrics.timelineMs, header[ key ] * 1000 );
}
for ( const frame of frames ) {
assert.ok( Array.isArray( frame ) );
assert.equal( frame.length, 3 );
@@ -81,6 +85,8 @@ function measure( entry, bytes ) {
if ( entry.format === 2 ) assert.ok( frame[ 0 ] >= time );
time = entry.format === 2 ? frame[ 0 ] : time + frame[ 0 ];
assert.ok( Number.isFinite( time ) );
milliseconds = entry.format === 2 ? frame[ 0 ] * 1000 : milliseconds + frame[ 0 ] * 1000;
metrics.timelineMs = Math.max( metrics.timelineMs, milliseconds );
if ( frame[ 1 ] === 'm' ) metrics.markers++;
if ( frame[ 1 ] === 'r' ) {
assert.match( frame[ 2 ], /^[1-9][0-9]*x[1-9][0-9]*$/ );
@@ -107,7 +113,7 @@ test( 'golden recipes are deterministic, genuinely seeded, and bounded to known
test( 'every shared resource purpose retains its exact at/over pair', () => {
for ( const version of [ 1, 2, 3 ] ) {
for ( const purpose of [ 'dimensions', 'cells', 'depth', 'events' ] ) {
for ( const purpose of [ 'dimensions', 'cells', 'depth', 'events', 'timeline', 'duration', 'idle-limit' ] ) {
for ( const side of [ 'at', 'over' ] ) {
const entry = getSecurityCase( `${ purpose }-v${ version }-${ side }` );
assert.equal( entry.expected.accepted, side === 'at' );
@@ -126,6 +132,51 @@ test( 'every shared resource purpose retains its exact at/over pair', () => {
}
} );
test( 'timestamp regressions retain independently pinned witnesses and arithmetic', () => {
assert.equal( POLICY.timelineMs, 2147483647 );
assert.equal( securityManifest.policy.timelineMs, 2147483647 );
for ( const version of [ 1, 2, 3 ] ) {
for ( const purpose of [ 'timeline', 'duration', 'idle-limit' ] ) {
for ( const [ suffix, value ] of [ [ 'at', 2147483647 ], [ 'over', 2147483648 ] ] ) {
const entry = getSecurityCase( `${ purpose }-v${ version }-${ suffix }` );
assert.deepEqual( entry.boundary, { metric: 'timelineMs', limit: 2147483647, value } );
assert.equal( entry.expected.jsError, suffix === 'over' ? 'time' : null );
}
}
for ( const purpose of [ 'duration', 'idle-limit' ] ) assert.equal( getSecurityCase( `${ purpose }-v${ version }-zero` ).expected.accepted, true );
}
for ( const version of [ 1, 3 ] ) {
for ( const suffix of [ 'at', 'over' ] ) {
const entry = getSecurityCase( `interval-timeline-v${ version }-${ suffix }` );
assert.equal( entry.expected.jsError, suffix === 'over' ? 'time' : null );
const text = securityFixtureBuffer( entry.id ).toString( 'utf8' );
const frames = version === 1 ? JSON.parse( text ).stdout : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse );
assert.ok( frames.every( ( frame ) => frame[ 0 ] * 1000 < 2147483647 ), 'no individual interval may mask the cumulative boundary' );
}
for ( const [ id, a, b ] of [
[ 'ms-rounding-over', 307699.2378567164, 1839784.4091432837 ],
[ 'ms-sum-overflow', 2.996155224770526e303, 1.7677315826146105e305 ],
] ) {
const entry = getSecurityCase( `time-v${ version }-${ id }` );
assert.equal( entry.expected.jsError, 'time' );
assert.equal( entry.expected.accepted, false );
assert.ok( entry.bytes < 256, 'arithmetic witnesses must stay tiny' );
const text = securityFixtureBuffer( entry.id ).toString( 'utf8' );
const frames = version === 1 ? JSON.parse( text ).stdout : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse );
assert.deepEqual( frames.map( ( frame ) => frame[ 0 ] ), [ a, b ], 'the exact floating-point witness cannot silently change' );
assert.ok( Number.isFinite( a * 1000 ) && Number.isFinite( b * 1000 ) && Number.isFinite( ( a + b ) * 1000 ) );
assert.equal( ( a + b ) * 1000, id === 'ms-rounding-over' ? 2147483647 : 1.7976931348623155e308 );
assert.equal( a * 1000 + b * 1000, id === 'ms-rounding-over' ? 2147483647.0000002 : Infinity );
}
}
const stalled = getSecurityCase( 'time-v2-output-nonprogress' );
assert.equal( stalled.expected.jsError, 'time' );
assert.equal( stalled.expected.accepted, false );
assert.ok( stalled.bytes < 100 );
assert.deepEqual( JSON.parse( securityFixtureBuffer( stalled.id ).toString( 'utf8' ).split( '\n' )[ 1 ] ), [ 1e20, 'o', 'x' ] );
assert.equal( 1e20 * 1000 + 1000 / 60, 1e20 * 1000, 'the real 3.17 batch deadline cannot advance at this magnitude' );
} );
test( 'official native captures retain independently pinned provenance and identical output', () => {
const provenance = JSON.parse( readFileSync( new URL( 'provenance.json', root ), 'utf8' ) );
assert.deepEqual( provenance.artifacts.map( ( artifact ) => artifact.file ).sort(), [ 'official-v1.cast', 'official-v2.cast', 'official-v3.cast' ] );
+178 -2
View File
@@ -1,11 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import { loadRecording, RecordingLoadError, DEFAULT_LIMITS } from '../../src/recording-loader.js';
import { securityManifest, securityCases, getSecurityCase, securityFixtureBuffer } from '../fixtures/security/generate.mjs';
test('shared security corpus pins the production policy and all six safe controls', () => {
assert.equal(DEFAULT_LIMITS.timelineMs, 2147483647, 'the test horizon is independently pinned');
assert.equal(securityManifest.schemaVersion, 1);
for (const [name, value] of Object.entries(securityManifest.policy)) {
assert.equal(DEFAULT_LIMITS[name], value, `the ${name} fixture boundary must match production`);
@@ -162,7 +164,11 @@ async function inspectPlayer(data) {
core.terminalReady();
await core.init();
const duration = core.getDuration();
assert.ok(Number.isFinite(duration));
assert.ok(Number.isFinite(core.getCurrentTime()));
await core.seek('100%');
assert.ok(Number.isFinite(core.getCurrentTime()), 'the actual seek destination remains finite');
assert.ok(Number.isFinite(core.getProgress()), 'the actual progress calculation remains finite');
const output = events.output.flat().join('');
await core.seek('0%');
assert.equal(core.getCurrentTime(), 0, 'the real driver can seek back to the start');
@@ -174,8 +180,9 @@ async function inspectPlayer(data) {
}
}
// Only known-small, accepted controls reach the real upstream parser/driver.
// Oversized/hostile corpus members are tested exclusively through our guard.
// Only known-small, accepted controls reach the real upstream parser/driver here.
// The tiny numeric witnesses below run separately with captured timers and a hard
// child-process deadline; no oversized payload reaches the real player.
const playableCases = securityCases.filter((entry) => entry.safePlayback === true);
for (const entry of playableCases) {
test(`pinned player 3.17 parses and seeks validated ${entry.id}`, async () => {
@@ -219,3 +226,172 @@ test('official outputs and seeded playback timelines are equivalent across all t
assert.deepEqual(controls.seeded[0].events.map((event) => event[0]), [0, 1, 8, 12]);
assert.ok(controls.seeded[0].output.includes(controls.official[0].output), 'seeded mutations retain the official captured output');
});
/**
* Actual upstream Core witness, isolated from the main runner. All timers are
* captured, never scheduled; at most three callbacks are invoked per witness.
* The parent also kills this child after 10 seconds if an upstream change causes
* an unexpected synchronous loop. No browser, terminal, real playback delay, or
* large payload is involved. The arithmetic checks above are not a Core double.
*/
async function timestampCoreRegression() {
const Core = await playerCore();
const realSetTimeout = globalThis.setTimeout;
const realClearTimeout = globalThis.clearTimeout;
const timers = new Map();
let timerId = 0;
globalThis.setTimeout = (callback, delay) => {
const id = ++timerId;
timers.set(id, { callback, delay });
return id;
};
globalThis.clearTimeout = (id) => { timers.delete(id); };
const parseFixture = (id) => {
const entry = getSecurityCase(id);
assert.ok(entry.bytes < 256, 'only pinned tiny witnesses may enter this child');
const text = securityFixtureBuffer(id).toString('utf8');
return entry.format === 1 ? JSON.parse(text) : text.trimEnd().split('\n').map(JSON.parse);
};
const createCore = (data) => {
const core = new Core({ data }, {
preload: true, speed: 1,
logger: { debug() {}, info() {}, warn() {}, error() {} },
});
const events = { output: [], error: [], ended: [] };
for (const [name, values] of Object.entries(events)) core.addEventListener(name, (value) => values.push(value));
core.terminalReady();
return { core, events };
};
const takeTimer = () => {
assert.equal(timers.size, 1, 'exactly one recording callback is pending');
const [id, timer] = timers.entries().next().value;
timers.delete(id);
return timer;
};
try {
// Deliberately bypass the guard ONLY for this fixed tiny upstream bug
// witness. A premature timer call safely exposes non-progress without
// waiting for 1e23 ms or advancing the clock into a synchronous loop.
const stalled = createCore(parseFixture('time-v2-output-nonprogress'));
try {
await stalled.core.init();
assert.ok(Number.isFinite(stalled.core.getDuration()));
assert.equal(timers.size, 0, 'initial loading timeout was cleared');
await stalled.core.play();
let previousCallback;
for (let n = 0; n < 3; n++) {
const timer = takeTimer();
assert.equal(timer.delay, 1e23, 'the unsafe upstream delay exceeds signed 32-bit timer range');
if (previousCallback) assert.equal(timer.callback, previousCallback, 'the same unconsumed event is rescheduled');
previousCallback = timer.callback;
timer.callback();
await Promise.resolve();
assert.deepEqual(stalled.events.output, Array.from({ length: n + 1 }, () => []), 'batching emits empty output without consuming x');
assert.deepEqual(stalled.events.ended, []);
}
assert.deepEqual(stalled.events.error, []);
process.stdout.write('v2 non-progress reproduced with three captured callbacks\n');
} finally {
await stalled.core.stop();
assert.equal(timers.size, 0, 'stopping removes the captured non-progress callback');
}
for (const version of [1, 3]) {
const overflow = createCore(parseFixture(`time-v${version}-ms-sum-overflow`));
try {
await overflow.core.init();
assert.equal(overflow.core.getDuration(), Infinity, 'real upstream interval arithmetic overflows although converted seconds sum is finite');
await overflow.core.seek('100%');
assert.equal(overflow.core.getCurrentTime(), Infinity);
assert.ok(Number.isNaN(overflow.core.getProgress()), 'real upstream progress is corrupted');
assert.deepEqual(overflow.events.error, []);
process.stdout.write(`v${version} infinite duration/seek reproduced\n`);
} finally {
await overflow.core.stop();
assert.equal(timers.size, 0);
}
}
// The production loader must reject all five pinned numerical attacks
// before their data can be handed to Core, including rounding-order bugs.
let coreHandoffs = 0;
for (const id of [
'time-v2-output-nonprogress',
'time-v1-ms-sum-overflow', 'time-v3-ms-sum-overflow',
'time-v1-ms-rounding-over', 'time-v3-ms-rounding-over',
]) {
assert.equal(getSecurityCase(id).expected.jsError, 'time');
const stream = streamedFixture(securityFixtureBuffer(id));
const handoff = async () => {
const data = await loadRecording('/security-fixture.cast', { fetchImpl: stream.fetchImpl });
coreHandoffs++;
return createCore(data);
};
await assert.rejects(handoff(), (error) => error instanceof RecordingLoadError && error.code === 'time');
assert.equal(coreHandoffs, 0, 'rejected data never reaches the actual Core constructor');
assert.equal(stream.state.cancels, 1);
assert.equal(stream.state.signal.aborted, true);
assert.equal(timers.size, 0, 'rejected loader leaves no captured timeouts');
process.stdout.write(`${id} rejected before Core handoff\n`);
}
// Accepted exact-boundary fixtures survive actual parser preparation,
// duration/progress arithmetic, end/start seeking and output batching.
for (const id of [
'timeline-v1-at', 'timeline-v2-at', 'timeline-v3-at',
'interval-timeline-v1-at', 'interval-timeline-v3-at',
]) {
const bytes = securityFixtureBuffer(id);
const data = await loadRecording('/security-fixture.cast', { fetchImpl: streamedFixture(bytes).fetchImpl });
assert.deepEqual(data, parseFixture(id), 'near-bound timestamps are preserved without clamping');
const expectedOutput = id.startsWith('interval-') ? 'xend' : 'x';
const inspected = await inspectPlayer(data);
assert.equal(inspected.duration, 2147483.647);
assert.equal(inspected.output, expectedOutput);
assert.equal(timers.size, 0);
const playback = createCore(data);
try {
await playback.core.init();
await playback.core.play();
for (let n = 0; n < (id.startsWith('interval-') ? 2 : 1); n++) {
const timer = takeTimer();
assert.ok(Number.isFinite(timer.delay) && timer.delay >= 0 && timer.delay <= 2147483647);
timer.callback();
await Promise.resolve();
}
assert.equal(playback.events.output.flat().join(''), expectedOutput, 'accepted boundary output always advances');
assert.equal(playback.events.ended.length, 1);
assert.ok(Number.isFinite(playback.core.getDuration()));
assert.ok(Number.isFinite(playback.core.getCurrentTime()));
assert.ok(Number.isFinite(playback.core.getProgress()));
assert.deepEqual(playback.events.error, []);
assert.equal(timers.size, 0, 'accepted output does not reschedule a consumed event');
process.stdout.write(`${id} actual Core init/seek/playback is finite and advances\n`);
} finally { await playback.core.stop(); }
}
} finally {
globalThis.setTimeout = realSetTimeout;
globalThis.clearTimeout = realClearTimeout;
}
}
test('actual 3.17 Core timestamp regressions are bounded and blocked before handoff', () => {
const script = `
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { loadRecording, RecordingLoadError } from ${JSON.stringify(new URL('../../src/recording-loader.js', import.meta.url).href)};
import { getSecurityCase, securityFixtureBuffer } from ${JSON.stringify(new URL('../fixtures/security/generate.mjs', import.meta.url).href)};
${playerCore.toString()}
${streamedFixture.toString()}
${inspectPlayer.toString()}
await (${timestampCoreRegression.toString()})();
process.stdout.write('bounded actual-Core timestamp witnesses passed\\n');
`;
const child = spawnSync(process.execPath, ['--input-type=module', '--eval', script], {
cwd: new URL('../../', import.meta.url), timeout: 10000, maxBuffer: 64 * 1024,
encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '' },
});
const diagnostics = `stdout:\n${child.stdout}\nstderr:\n${child.stderr}`;
assert.equal(child.error, undefined, `the bounded Core witness must finish: ${child.error?.message}\n${diagnostics}`);
assert.equal(child.signal, null, `the bounded Core witness was killed\n${diagnostics}`);
assert.equal(child.status, 0, diagnostics);
assert.match(child.stdout, /bounded actual-Core timestamp witnesses passed/);
});
-1
View File
@@ -9,4 +9,3 @@ namespace LamGC\Asciiplayer {
return \json_decode( $json, $associative, $depth, $flags );
}
}
+45
View File
@@ -5,8 +5,10 @@
namespace {
use function LamGC\Asciiplayer\is_cast_json_within_budget;
use function LamGC\Asciiplayer\is_cast_v1;
use function LamGC\Asciiplayer\is_cast_time;
use const LamGC\Asciiplayer\CAST_MAX_JSON_CONTAINERS;
use const LamGC\Asciiplayer\CAST_MAX_JSON_TOKENS;
use const LamGC\Asciiplayer\CAST_MAX_TIME_MS;
function cast_budget_accepts( $text ) {
$containers = 0;
@@ -14,6 +16,49 @@ namespace {
return is_cast_json_within_budget( $text, $containers, $tokens );
}
function cast_time_contents( $version, $intervals, $metadata = array() ) {
$header = 3 === $version ? array( 'version' => 3, 'term' => array( 'cols' => 80, 'rows' => 24 ) ) : array( 'version' => $version, 'width' => 80, 'height' => 24 );
$header = array_merge( $header, $metadata );
$frames = array();
foreach ( $intervals as $time ) {
$frames[] = 1 === $version ? array( $time, 'x' ) : array( $time, 'o', 'x' );
}
if ( 1 === $version ) {
$header['stdout'] = $frames;
return json_encode( $header );
}
return json_encode( $header ) . "\n" . implode( "\n", array_map( 'json_encode', $frames ) );
}
same( 2147483647, CAST_MAX_TIME_MS, 'The timeline ceiling matches the signed browser timer range.' );
$max_seconds = CAST_MAX_TIME_MS / 1000;
foreach ( array( 1, 2, 3 ) as $version ) {
same( true, cast_contents_are_valid( cast_time_contents( $version, array( $max_seconds ) ) ), 'Accept the exact v' . $version . ' timer horizon.' );
same( false, cast_contents_are_valid( cast_time_contents( $version, array( $max_seconds + 0.001 ) ) ), 'Reject v' . $version . ' one millisecond beyond the horizon.' );
same( false, cast_contents_are_valid( cast_time_contents( $version, array( -0.001 ) ) ), 'Reject negative v' . $version . ' time.' );
foreach ( array( 'duration', 'idle_time_limit' ) as $key ) {
same( true, cast_contents_are_valid( cast_time_contents( $version, array( 0 ), array( $key => $max_seconds ) ) ), 'Accept exact v' . $version . ' ' . $key . ' horizon.' );
foreach ( array( $max_seconds + 0.001, -0.001, '1', null ) as $value ) {
same( false, cast_contents_are_valid( cast_time_contents( $version, array( 0 ), array( $key => $value ) ) ), 'Reject invalid v' . $version . ' ' . $key . '.' );
}
}
}
foreach ( array( INF, -INF, NAN, -1, '1', null ) as $value ) {
same( false, is_cast_time( $value ), 'Time validation rejects nonfinite, negative, and nonnumeric values.' );
}
$rounding_intervals = array( 307699.2378567164, 1839784.4091432837 );
same( (float) CAST_MAX_TIME_MS, ( $rounding_intervals[0] + $rounding_intervals[1] ) * 1000, 'Seconds-first rounding hides the over-limit result.' );
same( true, $rounding_intervals[0] * 1000 + $rounding_intervals[1] * 1000 > CAST_MAX_TIME_MS, 'The actual player millisecond sum is over the horizon.' );
foreach ( array( 1, 3 ) as $version ) {
same( true, cast_contents_are_valid( cast_time_contents( $version, array( 1, $max_seconds - 1 ) ) ), 'Accept cumulative v' . $version . ' at the horizon.' );
foreach ( array( array( 1, $max_seconds ), $rounding_intervals, array( 2.996155224770526e303, 1.7677315826146105e305 ) ) as $intervals ) {
same( false, cast_contents_are_valid( cast_time_contents( $version, $intervals ) ), 'Reject v' . $version . ' cumulative upstream millisecond overflow.' );
}
}
same( false, cast_contents_are_valid( cast_time_contents( 2, array( 1e20 ) ) ), 'Reject a tiny v2 cast whose output batching cannot make progress.' );
same( false, cast_contents_are_valid( cast_time_contents( 2, array( 10004.674, 10004.673999999999 ) ) ), 'Reject backward v2 seconds even when conversion rounds to equal milliseconds.' );
same( true, cast_contents_are_valid( cast_time_contents( 2, array( 1, 1 ) ) ), 'Equal v2 timestamps remain accepted.' );
foreach ( array(
'zero v2 dimensions' => '{"version":2,"width":0,"height":0}',
'zero v3 dimensions' => '{"version":3,"term":{"cols":0,"rows":0}}',
+37
View File
@@ -128,6 +128,7 @@ foreach ( array(
'CAST_MAX_JSON_LINE_TOKENS' => 20000,
'CAST_MAX_JSON_CONTAINERS' => 100016,
'CAST_JSON_DEPTH' => 16,
'CAST_MAX_TIME_MS' => 2147483647,
) as $constant => $limit ) {
same( $limit, constant( 'LamGC\\Asciiplayer\\' . $constant ), $constant . ': the documented production limit is unchanged.' );
}
@@ -145,10 +146,12 @@ $GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true, 'unfiltered
$GLOBALS['ap_test']['multisite'] = false;
unset( $GLOBALS['ap_test']['allowed_mimes'] );
$security_fixture_ids = array();
$security_fixture_records = array();
try {
foreach ( $security_fixture_manifest['cases'] as $fixture ) {
same( false, isset( $security_fixture_ids[ $fixture['id'] ] ), 'Each security fixture has a unique ID.' );
$security_fixture_ids[ $fixture['id'] ] = $fixture['expected'];
$security_fixture_records[ $fixture['id'] ] = $fixture;
same( true, isset( $fixture['source']['file'] ) !== isset( $fixture['source']['segments'] ), $fixture['id'] . ': exactly one fixture source is defined.' );
same( true, is_bool( $fixture['expected']['accepted'] ), $fixture['id'] . ': the expected upload result is explicit.' );
$path = tempnam( sys_get_temp_dir(), 'ap-security-' );
@@ -178,6 +181,40 @@ try {
unlink( $path );
}
}
// Required numeric witnesses cannot disappear while the remaining generic
// manifest loop still passes. These expectations do not import guard limits.
same( 2147483647, $security_fixture_manifest['policy']['timelineMs'] ?? null, 'The corpus independently pins the signed 32-bit millisecond horizon.' );
foreach ( array( 1, 2, 3 ) as $version ) {
foreach ( array( 'timeline', 'duration', 'idle-limit' ) as $purpose ) {
foreach ( array( 'at' => 2147483647, 'over' => 2147483648 ) as $suffix => $milliseconds ) {
$id = $purpose . '-v' . $version . '-' . $suffix;
$fixture = $security_fixture_records[ $id ] ?? array();
same( array( 'metric' => 'timelineMs', 'limit' => 2147483647, 'value' => $milliseconds ), $fixture['boundary'] ?? null, $id . ': the exact timing boundary remains in the shared corpus.' );
same( 'at' === $suffix, $fixture['expected']['accepted'] ?? null, $id . ': both sides retain their independently pinned acceptance result.' );
same( 'over' === $suffix ? 'time' : null, $fixture['expected']['jsError'] ?? null, $id . ': timing rejection reason is explicit.' );
}
}
foreach ( array( 'duration', 'idle-limit' ) as $purpose ) {
$id = $purpose . '-v' . $version . '-zero';
same( true, $security_fixture_ids[ $id ]['accepted'] ?? null, $id . ': zero timing metadata remains supported.' );
}
}
foreach ( array( 1, 3 ) as $version ) {
foreach ( array( 'at', 'over' ) as $suffix ) {
$id = 'interval-timeline-v' . $version . '-' . $suffix;
same( 'at' === $suffix, $security_fixture_ids[ $id ]['accepted'] ?? null, $id . ': interval cumulative boundary remains covered.' );
}
}
foreach ( array(
'time-v2-output-nonprogress',
'time-v1-ms-sum-overflow', 'time-v3-ms-sum-overflow',
'time-v1-ms-rounding-over', 'time-v3-ms-rounding-over',
) as $id ) {
same( false, $security_fixture_ids[ $id ]['accepted'] ?? null, $id . ': the required actual-player arithmetic witness remains rejected.' );
same( 'time', $security_fixture_ids[ $id ]['jsError'] ?? null, $id . ': both languages retain the same explicit timestamp expectation.' );
same( true, ( $security_fixture_records[ $id ]['bytes'] ?? 256 ) < 256, $id . ': the numerical regression payload remains tiny.' );
}
foreach ( array( 'bytes-v2-over', 'bytes-v3-over' ) as $id ) {
same( 1, $security_fixture_ids[ $id ]['phpNoDecodeAtOrAboveBytes'] ?? null, $id . ': the PHP file-stat gate must reject before any native decode.' );
}