mirror of
https://github.com/LamGC/wp-asciiplayer.git
synced 2026-11-26 20:55:48 +00:00
fix: bound recording resources and add security regressions (#41)
Build and WordPress integration / Build and publish pristine package (push) Canceled after 0s
Build and WordPress integration / PHP 8.3 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / PHP 7.4 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / WordPress 6.3 / PHP 7.4 (push) Canceled after 0s
Build and WordPress integration / WordPress latest / PHP 8.2 (push) Canceled after 0s
Build and WordPress integration / Plugin Check (advisory) (push) Canceled after 0s
Build and WordPress integration / Build and publish pristine package (push) Canceled after 0s
Build and WordPress integration / PHP 8.3 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / PHP 7.4 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / WordPress 6.3 / PHP 7.4 (push) Canceled after 0s
Build and WordPress integration / WordPress latest / PHP 8.2 (push) Canceled after 0s
Build and WordPress integration / Plugin Check (advisory) (push) Canceled after 0s
- Bound recording bytes, JSON structure, events, markers, terminal dimensions and timestamp arithmetic before unsafe player allocation or scheduling. - Share validated playback data and metadata; cancel stale, failed and timed-out loads. - Add PHP 7.4-compatible predecode budgets and preserve supported v1/v2/v3 behavior. - Add localized errors, documented limits and 110 official/seeded recording fixtures. Verified 325 Node tests, native PHP 7.4/8.3 regression suites and 55 Chromium tests on each WordPress CI matrix. Preserve plugin version, vendor files and isolated package artifacts.
This commit is contained in:
@@ -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: '<secret>' }), '');
|
||||
for (const code of ['bytes', 'line', 'events', 'markers', 'dimensions', 'cells', 'complexity', 'time', 'timeout', 'network', 'stream', 'policy', 'invalid']) {
|
||||
const message = recordingErrorMessage({ code, message: '<secret>' });
|
||||
assert.ok(message.length > 10);
|
||||
assert.ok(!message.includes('<secret>'));
|
||||
}
|
||||
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/);
|
||||
}
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,357 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { loadRecording, DEFAULT_LIMITS, RecordingLoadError, validateInitialDimensions } from '../../src/recording-loader.js';
|
||||
import { normalizePlayerOptions } from '../../src/options.js';
|
||||
|
||||
const encode = ( text ) => new TextEncoder().encode( text );
|
||||
const h2 = { version: 2, width: 80, height: 24 };
|
||||
const h3 = { version: 3, term: { cols: 80, rows: 24 } };
|
||||
const cast = ( header = h2, events = [ [ 0, 'o', 'hello' ] ] ) => [ header, ...events ].map( JSON.stringify ).join( '\n' );
|
||||
function fixture( text, { chunks, headers } = {} ) {
|
||||
let reads = 0;
|
||||
let canceled = false;
|
||||
let released = false;
|
||||
const parts = chunks || [ encode( text ) ];
|
||||
const response = { ok: true, headers: new Headers( headers ), body: { getReader: () => ( {
|
||||
read: async () => reads < parts.length ? { value: parts[ reads++ ], done: false } : { done: true },
|
||||
cancel: () => { canceled = true; return Promise.resolve(); },
|
||||
releaseLock: () => { released = true; },
|
||||
} ) } };
|
||||
const calls = [];
|
||||
const fetchImpl = async ( ...args ) => { calls.push( args ); return response; };
|
||||
return { fetchImpl, calls, get canceled() { return canceled; }, get released() { return released; } };
|
||||
}
|
||||
async function rejectCode( text, code, config = {}, responseOptions ) {
|
||||
const input = fixture( text, responseOptions );
|
||||
await assert.rejects( loadRecording( '/cast', { fetchImpl: input.fetchImpl, ...config } ), ( error ) => error instanceof RecordingLoadError && error.code === code );
|
||||
assert.equal( input.canceled, true );
|
||||
assert.equal( input.released, true );
|
||||
}
|
||||
|
||||
test( 'single fetch returns validated v2 data and original metadata', async () => {
|
||||
const input = fixture( cast() );
|
||||
const metadata = [];
|
||||
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: input.fetchImpl, options: { cols: 100 }, onMetadata: ( value ) => metadata.push( value ) } ), [ h2, [ 0, 'o', 'hello' ] ] );
|
||||
assert.deepEqual( metadata, [ { cols: 80, rows: 24 } ] );
|
||||
assert.equal( input.calls.length, 1 );
|
||||
assert.equal( input.calls[ 0 ][ 1 ].credentials, 'same-origin' );
|
||||
assert.ok( input.calls[ 0 ][ 1 ].signal instanceof AbortSignal );
|
||||
assert.equal( input.canceled, false );
|
||||
assert.equal( input.released, true );
|
||||
} );
|
||||
|
||||
test( 'stream boundaries preserve UTF-8, escapes, and CRLF', async () => {
|
||||
const content = cast( h3, [ [ 0, 'o', '你好 🌱 " \\ \n' ], [ 1, 'x-custom', 'safe' ] ] ).replaceAll( '\n', '\r\n' );
|
||||
const bytes = encode( content );
|
||||
const input = fixture( '', { chunks: Array.from( bytes, ( byte ) => Uint8Array.of( byte ) ) } );
|
||||
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: input.fetchImpl } ), [ h3, [ 0, 'o', '你好 🌱 " \\ \n' ], [ 1, 'x-custom', 'safe' ] ] );
|
||||
} );
|
||||
|
||||
test( 'blank, comment, and non-event lines retain upstream filtering semantics', async () => {
|
||||
const content = `${ JSON.stringify( h3 ) }\n\n# comment\nignored\n [999999,"o","ignored"]\n[0,"o","ok"]\n`;
|
||||
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } ), [ h3, [ 0, 'o', 'ok' ] ] );
|
||||
} );
|
||||
|
||||
test( 'v1 compact, pretty, CRLF, and large single line are accepted as objects', async () => {
|
||||
const header = { version: 1, width: 80, height: 24, stdout: [ [ 0.1, 'hello' ], [ 0.2, 'world' ] ] };
|
||||
for ( const content of [ JSON.stringify( header ), JSON.stringify( header, null, 2 ), JSON.stringify( header, null, 2 ).replaceAll( '\n', '\r\n' ) ] ) {
|
||||
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } ), header );
|
||||
}
|
||||
const large = { ...header, stdout: [ [ 0, 'x'.repeat( DEFAULT_LIMITS.lineBytes ) ] ] };
|
||||
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: fixture( JSON.stringify( large ) ).fetchImpl } ), large );
|
||||
} );
|
||||
|
||||
test( 'normal 100000-frame v1 fits preparse allocation budgets', async () => {
|
||||
const header = { version: 1, width: 80, height: 24, stdout: Array.from( { length: 100000 }, () => [ 0, '' ] ) };
|
||||
const result = await loadRecording( '/cast', { fetchImpl: fixture( JSON.stringify( header ) ).fetchImpl } );
|
||||
assert.equal( result.stdout.length, 100000 );
|
||||
} );
|
||||
|
||||
test( 'zero header dimensions preserve default behavior and unknown metadata', async () => {
|
||||
for ( const header of [ { ...h2, width: 0, height: 0 }, { version: 3, term: { cols: 0, rows: 0 } } ] ) {
|
||||
let metadata = 'unset';
|
||||
const result = await loadRecording( '/cast', { fetchImpl: fixture( cast( header ) ).fetchImpl, onMetadata: ( value ) => { metadata = value; } } );
|
||||
assert.deepEqual( result[ 0 ], header );
|
||||
assert.equal( metadata, null );
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'actual received bytes reject oversized chunks despite missing or false Content-Length', async () => {
|
||||
for ( const headers of [ {}, { 'Content-Length': '1' }, { 'Content-Length': 'not-a-number' } ] ) {
|
||||
await rejectCode( cast(), 'bytes', { limits: { bytes: 10 } }, { headers } );
|
||||
}
|
||||
// An advertised size is not a replacement for measuring decoded bytes.
|
||||
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast(), { headers: { 'Content-Length': '999999999' } } ).fetchImpl } ) ).length, 2 );
|
||||
} );
|
||||
|
||||
test( 'line byte limit counts multibyte output and ignored lines', async () => {
|
||||
await rejectCode( cast( h2, [ [ 0, 'o', '界'.repeat( 30 ) ] ] ), 'line', { limits: { lineBytes: 80 } } );
|
||||
await rejectCode( `${ JSON.stringify( h2 ) }\n#${ 'x'.repeat( 81 ) }`, 'line', { limits: { lineBytes: 80 } } );
|
||||
} );
|
||||
|
||||
test( 'v1 byte cap covers pretty documents and compact documents', async () => {
|
||||
const header = { version: 1, width: 80, height: 24, stdout: [ [ 0, 'x'.repeat( 100 ) ] ] };
|
||||
await rejectCode( JSON.stringify( header, null, 2 ), 'bytes', { limits: { v1Bytes: 100 } } );
|
||||
await rejectCode( JSON.stringify( header ), 'line', { limits: { v1Bytes: 100 } } );
|
||||
} );
|
||||
|
||||
test( 'depth, container, and token budgets run before parsing unknown metadata', async () => {
|
||||
await rejectCode( cast( { ...h2, extra: [ [ [ [] ] ] ] } ), 'complexity', { limits: { depth: 4 } } );
|
||||
await rejectCode( cast( { ...h2, extra: [ [], [], [] ] } ), 'complexity', { limits: { containers: 4 } } );
|
||||
await rejectCode( cast( { ...h2, extra: [ 1, 2, 3, 4, 5 ] } ), 'complexity', { limits: { lineTokens: 10 } } );
|
||||
} );
|
||||
|
||||
test( 'event and marker boundaries are inclusive', async () => {
|
||||
const content = cast( h2, [ [ 0, 'm', 'one' ], [ 1, 'm', 'two' ] ] );
|
||||
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, limits: { markers: 2, events: 2 } } ) ).length, 3 );
|
||||
await rejectCode( content, 'markers', { limits: { markers: 1 } } );
|
||||
await rejectCode( content, 'events', { limits: { events: 1 } } );
|
||||
await rejectCode( content, 'markers', { options: { markers: [ [ 0, 'external' ] ] }, limits: { markers: 2 } } );
|
||||
} );
|
||||
|
||||
test( 'all dimensions, late resizes, raw cells and independent effective overrides are validated', async () => {
|
||||
await rejectCode( cast( { ...h2, width: 1001 } ), 'dimensions', { options: { cols: 80 } } );
|
||||
await rejectCode( cast( { ...h2, width: 1000, height: 1000 } ), 'cells', { options: { cols: 80, rows: 24 } } );
|
||||
await rejectCode( cast( { ...h2, height: 100 } ), 'cells', { options: { cols: 1000 } } );
|
||||
await rejectCode( cast(), 'cells', { options: { cols: 1000, rows: 1000 } } );
|
||||
for ( const resize of [ '0x24', '80x0', '1001x24', '-1x24', '80x24oops' ] ) {
|
||||
await rejectCode( cast( h2, [ [ 0, 'o', 'safe' ], [ 100, 'r', resize ] ] ), 'dimensions' );
|
||||
}
|
||||
await rejectCode( cast( h2, [ [ 100, 'r', '80x100' ] ] ), 'cells', { options: { cols: 1000 } } );
|
||||
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast( { ...h2, width: 1000, height: 40 } ) ).fetchImpl } ) ).length, 2 );
|
||||
} );
|
||||
|
||||
test( 'non-finite timestamps and cumulative time overflow are rejected', async () => {
|
||||
await rejectCode( `${ JSON.stringify( h2 ) }\n[1e999,"o","x"]`, 'time' );
|
||||
await rejectCode( cast( h2, [ [ -1, 'o', 'x' ] ] ), 'time' );
|
||||
await rejectCode( cast( h3, [ [ 1e305, 'o', 'x' ], [ 1e305, 'o', 'x' ] ] ), 'time' );
|
||||
await rejectCode( JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ 1e305, 'x' ], [ 1e305, 'x' ] ] } ), 'time' );
|
||||
} );
|
||||
|
||||
test( 'supported timeline boundary is inclusive across all formats and timing metadata', async () => {
|
||||
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
|
||||
assert.equal( DEFAULT_LIMITS.timelineMs, 2147483647 );
|
||||
for ( const version of [ 1, 2, 3 ] ) {
|
||||
const header = version === 3 ? h3 : { ...h2, version };
|
||||
const content = ( seconds, extra = {} ) => version === 1
|
||||
? JSON.stringify( { ...header, ...extra, stdout: [ [ seconds, 'x' ] ] } )
|
||||
: cast( { ...header, ...extra }, [ [ seconds, 'o', 'x' ] ] );
|
||||
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( maxSeconds ) ).fetchImpl } ) );
|
||||
await rejectCode( content( maxSeconds + 0.001 ), 'time' );
|
||||
await rejectCode( content( -0.001 ), 'time' );
|
||||
for ( const key of [ 'duration', 'idle_time_limit' ] ) {
|
||||
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( 0, { [ key ]: maxSeconds } ) ).fetchImpl } ) );
|
||||
for ( const value of [ maxSeconds + 0.001, -0.001, '1', null ] ) await rejectCode( content( 0, { [ key ]: value } ), 'time' );
|
||||
}
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'relative formats accumulate individually converted milliseconds in upstream order', async () => {
|
||||
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
|
||||
const rounding = [ 307699.2378567164, 1839784.4091432837 ];
|
||||
assert.equal( ( rounding[ 0 ] + rounding[ 1 ] ) * 1000, DEFAULT_LIMITS.timelineMs );
|
||||
assert.ok( rounding[ 0 ] * 1000 + rounding[ 1 ] * 1000 > DEFAULT_LIMITS.timelineMs );
|
||||
for ( const version of [ 1, 3 ] ) {
|
||||
const content = ( intervals ) => version === 1
|
||||
? JSON.stringify( { version: 1, width: 80, height: 24, stdout: intervals.map( ( time ) => [ time, 'x' ] ) } )
|
||||
: cast( h3, intervals.map( ( time ) => [ time, 'o', 'x' ] ) );
|
||||
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( [ 1, maxSeconds - 1 ] ) ).fetchImpl } ) );
|
||||
for ( const intervals of [ [ 1, maxSeconds ], rounding, [ 2.996155224770526e303, 1.7677315826146105e305 ] ] ) {
|
||||
await rejectCode( content( intervals ), 'time' );
|
||||
}
|
||||
}
|
||||
await rejectCode( cast( h2, [ [ 1e20, 'o', 'x' ] ] ), 'time' );
|
||||
} );
|
||||
|
||||
test( 'slow playback stays within native timer range without expanding the base horizon at higher speeds', async () => {
|
||||
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
|
||||
for ( const version of [ 1, 2, 3 ] ) {
|
||||
const content = ( seconds ) => version === 1
|
||||
? JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ seconds, 'x' ] ] } )
|
||||
: cast( version === 3 ? h3 : h2, [ [ seconds, 'o', 'x' ] ] );
|
||||
for ( const speed of [ 0.01, 0.5, 1, 100 ] ) {
|
||||
const seconds = maxSeconds * Math.min( speed, 1 );
|
||||
const options = { speed };
|
||||
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( seconds ) ).fetchImpl, options } ) );
|
||||
await rejectCode( content( seconds + 0.001 ), 'time', { options } );
|
||||
}
|
||||
}
|
||||
// An idle limiter or late start does not waive validation of the raw horizon.
|
||||
await rejectCode( cast( h2, [ [ maxSeconds, 'o', 'x' ] ] ), 'time', { options: { speed: 0.01, idleTimeLimit: 0.001, startAt: maxSeconds } } );
|
||||
} );
|
||||
|
||||
test( 'normalized timing options are checked before any recording request', async () => {
|
||||
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
|
||||
for ( const options of [
|
||||
...[ 0, -1, NaN, Infinity, 0.009, 101, '1' ].map( ( speed ) => ( { speed } ) ),
|
||||
...[ 'startAt', 'idleTimeLimit' ].flatMap( ( key ) => [ maxSeconds + 0.001, -1, Infinity, NaN ].map( ( value ) => ( { [ key ]: value } ) ) ),
|
||||
{ poster: 'npt:596:31:23.648' },
|
||||
normalizePlayerOptions( { startAt: `${ '9'.repeat( 400 ) }:00:00` } ),
|
||||
normalizePlayerOptions( { poster: `npt:${ '9'.repeat( 400 ) }:00:00` } ),
|
||||
] ) {
|
||||
const input = fixture( cast() );
|
||||
await assert.rejects( loadRecording( '/cast', { fetchImpl: input.fetchImpl, options } ), { code: 'time' } );
|
||||
assert.equal( input.calls.length, 0 );
|
||||
}
|
||||
for ( const options of [ { startAt: maxSeconds, idleTimeLimit: maxSeconds }, { poster: 'npt:596:31:23.647' }, { poster: 'data:text/plain,2147483648' } ] ) {
|
||||
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( cast() ).fetchImpl, options } ) );
|
||||
}
|
||||
await assert.rejects( loadRecording( '/cast', { limits: { timelineMs: DEFAULT_LIMITS.timelineMs + 1 } } ), { code: 'policy' } );
|
||||
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( cast( h2, [ [ 1, 'o', 'x' ] ] ) ).fetchImpl, limits: { timelineMs: 1000 } } ) );
|
||||
await rejectCode( cast( h2, [ [ 1.001, 'o', 'x' ] ] ), 'time', { limits: { timelineMs: 1000 } } );
|
||||
} );
|
||||
|
||||
test( 'invalid records do not report metadata', async () => {
|
||||
for ( const content of [ '', '{}', cast( h2, [ [ 0, 'o', {} ] ] ), cast( h2, [ [ 0, '', 'x' ] ] ), `${ JSON.stringify( h2 ) }\n[invalid` ] ) {
|
||||
let notified = false;
|
||||
await assert.rejects( loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, onMetadata: () => { notified = true; } } ) );
|
||||
assert.equal( notified, false );
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'invalid UTF-8 cannot be repaired across a newline', async () => {
|
||||
await rejectCode( '', 'invalid', {}, { chunks: [ encode( `${ JSON.stringify( h2 ) }\n` ), Uint8Array.of( 0xe2, 10, 0x82, 0xac ) ] } );
|
||||
} );
|
||||
|
||||
test( 'untrusted prototype-shaped metadata remains inert', async () => {
|
||||
const header = JSON.parse( '{"version":2,"width":80,"height":24,"__proto__":{"polluted":true},"constructor":{"prototype":{"polluted":true}}}' );
|
||||
const result = await loadRecording( '/cast', { fetchImpl: fixture( cast( header ) ).fetchImpl } );
|
||||
assert.equal( {}.polluted, undefined );
|
||||
assert.equal( Object.getPrototypeOf( result[ 0 ] ), Object.prototype );
|
||||
assert.equal( Object.hasOwn( result[ 0 ], '__proto__' ), true );
|
||||
} );
|
||||
|
||||
test( 'pre-abort never fetches', async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const input = fixture( cast() );
|
||||
await assert.rejects( loadRecording( '/cast', { fetchImpl: input.fetchImpl, signal: controller.signal } ), { code: 'aborted' } );
|
||||
assert.equal( input.calls.length, 0 );
|
||||
} );
|
||||
|
||||
test( 'abort and idle timeout interrupt stalled reads even when cancellation stalls', async () => {
|
||||
for ( const explicitAbort of [ true, false ] ) {
|
||||
const controller = new AbortController();
|
||||
let canceled = false;
|
||||
let fetchSignal;
|
||||
const fetchImpl = async ( _, config ) => {
|
||||
fetchSignal = config.signal;
|
||||
return { ok: true, body: { getReader: () => ( { read: () => new Promise( () => {} ), cancel: () => { canceled = true; return new Promise( () => {} ); }, releaseLock() {} } ) } };
|
||||
};
|
||||
const promise = loadRecording( '/cast', { fetchImpl, signal: controller.signal, limits: { idleTimeoutMs: explicitAbort ? 1000 : 10 } } );
|
||||
if ( explicitAbort ) setTimeout( () => controller.abort(), 5 );
|
||||
await assert.rejects( promise, { code: explicitAbort ? 'aborted' : 'timeout' } );
|
||||
assert.equal( canceled, true );
|
||||
assert.equal( fetchSignal.aborted, true );
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'total deadline interrupts an indefinitely pending fetch', async () => {
|
||||
await assert.rejects( loadRecording( '/cast', { fetchImpl: () => new Promise( () => {} ), limits: { totalTimeoutMs: 10, idleTimeoutMs: 1000 } } ), { code: 'timeout' } );
|
||||
} );
|
||||
|
||||
test( 'unsupported streaming and network failures use stable codes', async () => {
|
||||
await assert.rejects( loadRecording( '/cast', { fetchImpl: async () => ( { ok: true } ) } ), { code: 'stream' } );
|
||||
await assert.rejects( loadRecording( '/cast', { fetchImpl: async () => ( { ok: false } ) } ), { code: 'network' } );
|
||||
await assert.rejects( loadRecording( '/cast', { fetchImpl: async () => { throw new TypeError( 'Failed to fetch' ); } } ), { code: 'network' } );
|
||||
} );
|
||||
|
||||
test( 'ignored JSONL lines count toward the processing budget', async () => {
|
||||
await rejectCode( `${ JSON.stringify( h2 ) }\n\n#comment\n[0,"o","x"]`, 'events', { limits: { lines: 2 } } );
|
||||
} );
|
||||
|
||||
test( 'one-byte-over boundaries and exact boundaries use actual body bytes', async () => {
|
||||
const content = cast();
|
||||
const bytes = encode( content ).byteLength;
|
||||
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, limits: { bytes } } ) ).length, 2 );
|
||||
await rejectCode( content, 'bytes', { limits: { bytes: bytes - 1 } } );
|
||||
const first = encode( content.slice( 0, 10 ) );
|
||||
const rest = encode( content.slice( 10 ) );
|
||||
await rejectCode( '', 'bytes', { limits: { bytes: bytes - 1 } }, { chunks: [ first, rest ] } );
|
||||
} );
|
||||
|
||||
test( 'v1 allocation budgets count scalar tokens separately from containers', async () => {
|
||||
const content = JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ 0, '' ] ] } );
|
||||
// Seven header scalar/key tokens, plus stdout key, then two frame scalars.
|
||||
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, limits: { tokens: 9, containers: 3 } } ) ).stdout.length, 1 );
|
||||
await rejectCode( content, 'complexity', { limits: { tokens: 8 } } );
|
||||
await rejectCode( content, 'complexity', { limits: { containers: 2 } } );
|
||||
} );
|
||||
|
||||
test( 'total deadline also bounds continuously resolved reads', async () => {
|
||||
let canceled = false;
|
||||
const fetchImpl = async () => ( { ok: true, body: { getReader: () => ( {
|
||||
read: async () => ( { value: new Uint8Array(), done: false } ),
|
||||
cancel: async () => { canceled = true; }, releaseLock() {},
|
||||
} ) } } );
|
||||
await assert.rejects( loadRecording( '/cast', { fetchImpl, limits: { totalTimeoutMs: 10, idleTimeoutMs: 1000 } } ), { code: 'timeout' } );
|
||||
assert.equal( canceled, true );
|
||||
} );
|
||||
|
||||
test( 'initial BOM is removed but later BOM-prefixed lines remain ignored', async () => {
|
||||
const content = `\ufeff${ JSON.stringify( h2 ) }\n\ufeff[0,"o","ignored"]\n[1,"o","ok"]`;
|
||||
const input = fixture( '', { chunks: Array.from( encode( content ), ( byte ) => Uint8Array.of( byte ) ) } );
|
||||
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: input.fetchImpl } ), [ h2, [ 1, 'o', 'ok' ] ] );
|
||||
} );
|
||||
|
||||
test( 'v2 absolute timestamps cannot move backward; equal timestamps remain valid', async () => {
|
||||
await rejectCode( cast( h2, [ [ 2, 'o', 'x' ], [ 1, 'o', 'y' ] ] ), 'time' );
|
||||
assert.equal( 10004.674 * 1000, 10004.673999999999 * 1000 );
|
||||
await rejectCode( cast( h2, [ [ 10004.674, 'o', 'x' ], [ 10004.673999999999, 'o', 'y' ] ] ), 'time' );
|
||||
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast( h2, [ [ 1, 'o', 'x' ], [ 1, 'o', 'y' ] ] ) ).fetchImpl } ) ).length, 3 );
|
||||
} );
|
||||
|
||||
test( 'JSONL line budget includes newline bytes like the upload validator', async () => {
|
||||
const headerLine = JSON.stringify( h2 );
|
||||
await rejectCode( `${ headerLine }\n`, 'line', { limits: { lineBytes: encode( headerLine ).length } } );
|
||||
} );
|
||||
|
||||
test( 'v2 header complexity is rejected before allocating the header JSON tree', async () => {
|
||||
const content = cast( { ...h2, extra: Array( 40 ).fill( 1 ) } );
|
||||
const original = JSON.parse;
|
||||
let treeParses = 0;
|
||||
JSON.parse = ( text, ...args ) => {
|
||||
if ( text.startsWith( '{' ) ) treeParses++;
|
||||
return original( text, ...args );
|
||||
};
|
||||
try {
|
||||
await rejectCode( content, 'complexity', { limits: { lineTokens: 20 } } );
|
||||
assert.equal( treeParses, 0 );
|
||||
} finally { JSON.parse = original; }
|
||||
} );
|
||||
|
||||
test( 'version sniffing honors escaped keys, nesting and last duplicate value', async () => {
|
||||
const v1 = '{"stdout":[[0,"ok"]],"nested":{"version":2},"width":80,"height":24,"vers\\u0069on":1}';
|
||||
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( v1 ).fetchImpl } ) ).version, 1 );
|
||||
const v2 = '{"version":1,"width":80,"height":24,"extra":[1,2,3,4,5,6,7,8,9,10],"version":2}';
|
||||
await rejectCode( v2, 'complexity', { limits: { lineTokens: 15 } } );
|
||||
} );
|
||||
|
||||
|
||||
test( 'initial options are validated synchronously before the player can allocate a terminal', () => {
|
||||
assert.doesNotThrow( () => validateInitialDimensions() );
|
||||
assert.doesNotThrow( () => validateInitialDimensions( { cols: 1000, rows: 40 } ) );
|
||||
assert.throws( () => validateInitialDimensions( { cols: 1000, rows: 1000 } ), { code: 'cells' } );
|
||||
assert.throws( () => validateInitialDimensions( { rows: 1000 } ), { code: 'cells' } );
|
||||
assert.throws( () => validateInitialDimensions( { cols: 1001 } ), { code: 'dimensions' } );
|
||||
assert.throws( () => validateInitialDimensions( { cols: -1 } ), { code: 'dimensions' } );
|
||||
assert.throws( () => validateInitialDimensions( { rows: NaN } ), { code: 'dimensions' } );
|
||||
assert.throws( () => validateInitialDimensions( { cols: 0 } ), { code: 'dimensions' } );
|
||||
} );
|
||||
|
||||
|
||||
test( 'multiline v1 can put version after an allocation-heavy first member', async () => {
|
||||
const frames = Array( 10001 ).fill( '[0,""]' ).join( ',' );
|
||||
const content = `{"stdout":[${ frames }],\n"version":1,"width":80,"height":24}`;
|
||||
const result = await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } );
|
||||
assert.equal( result.version, 1 );
|
||||
assert.equal( result.stdout.length, 10001 );
|
||||
} );
|
||||
|
||||
test( 'multiline v1 can put version after a first line larger than the JSONL cap', async () => {
|
||||
const title = 'x'.repeat( DEFAULT_LIMITS.lineBytes );
|
||||
const content = `{"title":"${ title }",\n"version":1,"width":80,"height":24,"stdout":[[0,""]]}`;
|
||||
const result = await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } );
|
||||
assert.equal( result.version, 1 );
|
||||
assert.equal( result.title.length, title.length );
|
||||
} );
|
||||
@@ -0,0 +1,256 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createManifest, FIXTURE_SEED, MAX_FIXTURE_BYTES, POLICY, seededPlayback, seededRandom } from '../fixtures/security/recipes.mjs';
|
||||
import { getSecurityCase, securityCases, securityFixtureBuffer, securityManifest, writeSecurityFixture } from '../fixtures/security/generate.mjs';
|
||||
|
||||
const root = new URL( '../fixtures/security/', import.meta.url );
|
||||
const sha256 = ( bytes ) => createHash( 'sha256' ).update( bytes ).digest( 'hex' );
|
||||
|
||||
// Independent test-only measurements from a native JSON parse, not from the
|
||||
// production budget scanner. Even rejected fixtures here are tightly bounded;
|
||||
// they never reach the real terminal/player. Duplicate-key compatibility cases
|
||||
// are not used as exact-token witnesses because native parsing collapses keys.
|
||||
function structure( value, parentDepth = 0 ) {
|
||||
if ( value === null || typeof value !== 'object' ) return { tokens: 1, containers: 0, depth: parentDepth };
|
||||
const depth = parentDepth + 1;
|
||||
const result = { tokens: Array.isArray( value ) ? 0 : Object.keys( value ).length, containers: 1, depth };
|
||||
for ( const child of Object.values( value ) ) {
|
||||
const measured = structure( child, depth );
|
||||
result.tokens += measured.tokens;
|
||||
result.containers += measured.containers;
|
||||
result.depth = Math.max( result.depth, measured.depth );
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function measure( entry, bytes ) {
|
||||
const text = bytes.toString( 'utf8' );
|
||||
let header;
|
||||
let frames;
|
||||
const metrics = { bytes: bytes.length, v1Bytes: bytes.length, lineBytes: 0, events: 0, lines: 0, markers: 0, dimension: 0, cells: 0, depth: 0, tokens: 0, containers: 0, lineTokens: 0, timelineMs: 0 };
|
||||
if ( entry.format === 1 ) {
|
||||
header = JSON.parse( text );
|
||||
assert.ok( Array.isArray( header.stdout ) );
|
||||
frames = header.stdout.map( ( frame ) => {
|
||||
assert.equal( frame.length, 2 );
|
||||
return [ frame[ 0 ], 'o', frame[ 1 ] ];
|
||||
} );
|
||||
Object.assign( metrics, structure( header ) );
|
||||
} else {
|
||||
const lines = text.split( '\n' );
|
||||
if ( text.endsWith( '\n' ) ) lines.pop();
|
||||
metrics.lines = lines.length - 1;
|
||||
header = JSON.parse( lines[ 0 ] );
|
||||
frames = [];
|
||||
for ( const [ index, line ] of lines.entries() ) {
|
||||
const lineBytes = Buffer.byteLength( line ) + Number( index < lines.length - 1 || text.endsWith( '\n' ) );
|
||||
metrics.lineBytes = Math.max( metrics.lineBytes, lineBytes );
|
||||
if ( index && ! line.startsWith( '[' ) ) {
|
||||
assert.equal( entry.validity, 'upstream-compatible', 'strict-format cases must contain actual events, not ignored padding' );
|
||||
continue;
|
||||
}
|
||||
const value = index ? JSON.parse( line ) : header;
|
||||
const parsed = structure( value );
|
||||
metrics.depth = Math.max( metrics.depth, parsed.depth );
|
||||
metrics.containers = Math.max( metrics.containers, parsed.containers );
|
||||
metrics.lineTokens = Math.max( metrics.lineTokens, parsed.tokens );
|
||||
if ( index ) frames.push( value );
|
||||
}
|
||||
}
|
||||
assert.equal( header.version, entry.format );
|
||||
const dimensions = entry.format === 3 ? [ header.term.cols, header.term.rows ] : [ header.width, header.height ];
|
||||
function size( cols, rows ) {
|
||||
assert.ok( Number.isSafeInteger( cols ) && cols >= 0 );
|
||||
assert.ok( Number.isSafeInteger( rows ) && rows >= 0 );
|
||||
metrics.dimension = Math.max( metrics.dimension, cols, rows );
|
||||
metrics.cells = Math.max( metrics.cells, ( cols || 80 ) * ( rows || 24 ) );
|
||||
}
|
||||
size( ...dimensions );
|
||||
let time = 0;
|
||||
let milliseconds = 0;
|
||||
for ( const key of [ 'duration', 'idle_time_limit' ] ) {
|
||||
if ( Object.hasOwn( header, key ) ) metrics.timelineMs = Math.max( metrics.timelineMs, header[ key ] * 1000 );
|
||||
}
|
||||
for ( const frame of frames ) {
|
||||
assert.ok( Array.isArray( frame ) );
|
||||
assert.equal( frame.length, 3 );
|
||||
assert.ok( Number.isFinite( frame[ 0 ] ) && frame[ 0 ] >= 0 );
|
||||
assert.equal( typeof frame[ 1 ], 'string' );
|
||||
assert.ok( frame[ 1 ].length );
|
||||
assert.equal( typeof frame[ 2 ], 'string' );
|
||||
if ( entry.format === 2 ) assert.ok( frame[ 0 ] >= time );
|
||||
time = entry.format === 2 ? frame[ 0 ] : time + frame[ 0 ];
|
||||
assert.ok( Number.isFinite( time ) );
|
||||
milliseconds = entry.format === 2 ? frame[ 0 ] * 1000 : milliseconds + frame[ 0 ] * 1000;
|
||||
metrics.timelineMs = Math.max( metrics.timelineMs, milliseconds );
|
||||
if ( frame[ 1 ] === 'm' ) metrics.markers++;
|
||||
if ( frame[ 1 ] === 'r' ) {
|
||||
assert.match( frame[ 2 ], /^[1-9][0-9]*x[1-9][0-9]*$/ );
|
||||
size( ...frame[ 2 ].split( 'x' ).map( Number ) );
|
||||
}
|
||||
}
|
||||
metrics.events = frames.length;
|
||||
return metrics;
|
||||
}
|
||||
|
||||
test( 'golden recipes are deterministic, genuinely seeded, and bounded to known cases', () => {
|
||||
assert.equal( FIXTURE_SEED, 0x41c0ffee );
|
||||
assert.deepEqual( createManifest(), securityManifest );
|
||||
assert.deepEqual( createManifest(), createManifest() );
|
||||
assert.deepEqual( seededPlayback(), seededPlayback() );
|
||||
const next = seededRandom();
|
||||
assert.deepEqual( Array.from( { length: 4 }, () => next().toString( 16 ) ), [ '999f0ef0', '706768d0', '32d9ebae', 'fa29a378' ] );
|
||||
assert.throws( () => seededRandom( 0 ), RangeError );
|
||||
assert.throws( () => createManifest( 1 ), RangeError );
|
||||
assert.throws( () => securityFixtureBuffer( '../../arbitrary' ), RangeError );
|
||||
assert.throws( () => securityFixtureBuffer( 'bytes-v2-999999999' ), RangeError );
|
||||
assert.equal( new Set( securityCases.map( ( entry ) => entry.id ) ).size, securityCases.length );
|
||||
} );
|
||||
|
||||
test( 'every shared resource purpose retains its exact at/over pair', () => {
|
||||
for ( const version of [ 1, 2, 3 ] ) {
|
||||
for ( const purpose of [ 'dimensions', 'cells', 'depth', 'events', 'timeline', 'duration', 'idle-limit' ] ) {
|
||||
for ( const side of [ 'at', 'over' ] ) {
|
||||
const entry = getSecurityCase( `${ purpose }-v${ version }-${ side }` );
|
||||
assert.equal( entry.expected.accepted, side === 'at' );
|
||||
}
|
||||
}
|
||||
assert.equal( getSecurityCase( `official-v${ version }` ).safePlayback, true );
|
||||
assert.equal( getSecurityCase( `seeded-v${ version }-valid` ).safePlayback, true );
|
||||
}
|
||||
for ( const purpose of [ 'v1-bytes', 'tokens-v1', 'containers-v1', ...[ 2, 3 ].flatMap( ( version ) => [ 'bytes', 'line', 'line-tokens', 'markers', 'ignored-lines', 'late-resize' ].map( ( kind ) => `${ kind }-v${ version }` ) ) ] ) {
|
||||
assert.equal( getSecurityCase( `${ purpose }-at` ).expected.accepted, true );
|
||||
assert.equal( getSecurityCase( `${ purpose }-over` ).expected.accepted, false );
|
||||
}
|
||||
for ( const version of [ 2, 3 ] ) {
|
||||
assert.equal( getSecurityCase( `late-resize-v${ version }-dimensions-at` ).expected.accepted, true );
|
||||
assert.equal( getSecurityCase( `late-resize-v${ version }-dimensions-over` ).expected.accepted, false );
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'timestamp regressions retain independently pinned witnesses and arithmetic', () => {
|
||||
assert.equal( POLICY.timelineMs, 2147483647 );
|
||||
assert.equal( securityManifest.policy.timelineMs, 2147483647 );
|
||||
for ( const version of [ 1, 2, 3 ] ) {
|
||||
for ( const purpose of [ 'timeline', 'duration', 'idle-limit' ] ) {
|
||||
for ( const [ suffix, value ] of [ [ 'at', 2147483647 ], [ 'over', 2147483648 ] ] ) {
|
||||
const entry = getSecurityCase( `${ purpose }-v${ version }-${ suffix }` );
|
||||
assert.deepEqual( entry.boundary, { metric: 'timelineMs', limit: 2147483647, value } );
|
||||
assert.equal( entry.expected.jsError, suffix === 'over' ? 'time' : null );
|
||||
}
|
||||
}
|
||||
for ( const purpose of [ 'duration', 'idle-limit' ] ) assert.equal( getSecurityCase( `${ purpose }-v${ version }-zero` ).expected.accepted, true );
|
||||
}
|
||||
for ( const version of [ 1, 3 ] ) {
|
||||
for ( const suffix of [ 'at', 'over' ] ) {
|
||||
const entry = getSecurityCase( `interval-timeline-v${ version }-${ suffix }` );
|
||||
assert.equal( entry.expected.jsError, suffix === 'over' ? 'time' : null );
|
||||
const text = securityFixtureBuffer( entry.id ).toString( 'utf8' );
|
||||
const frames = version === 1 ? JSON.parse( text ).stdout : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse );
|
||||
assert.ok( frames.every( ( frame ) => frame[ 0 ] * 1000 < 2147483647 ), 'no individual interval may mask the cumulative boundary' );
|
||||
}
|
||||
for ( const [ id, a, b ] of [
|
||||
[ 'ms-rounding-over', 307699.2378567164, 1839784.4091432837 ],
|
||||
[ 'ms-sum-overflow', 2.996155224770526e303, 1.7677315826146105e305 ],
|
||||
] ) {
|
||||
const entry = getSecurityCase( `time-v${ version }-${ id }` );
|
||||
assert.equal( entry.expected.jsError, 'time' );
|
||||
assert.equal( entry.expected.accepted, false );
|
||||
assert.ok( entry.bytes < 256, 'arithmetic witnesses must stay tiny' );
|
||||
const text = securityFixtureBuffer( entry.id ).toString( 'utf8' );
|
||||
const frames = version === 1 ? JSON.parse( text ).stdout : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse );
|
||||
assert.deepEqual( frames.map( ( frame ) => frame[ 0 ] ), [ a, b ], 'the exact floating-point witness cannot silently change' );
|
||||
assert.ok( Number.isFinite( a * 1000 ) && Number.isFinite( b * 1000 ) && Number.isFinite( ( a + b ) * 1000 ) );
|
||||
assert.equal( ( a + b ) * 1000, id === 'ms-rounding-over' ? 2147483647 : 1.7976931348623155e308 );
|
||||
assert.equal( a * 1000 + b * 1000, id === 'ms-rounding-over' ? 2147483647.0000002 : Infinity );
|
||||
}
|
||||
}
|
||||
const stalled = getSecurityCase( 'time-v2-output-nonprogress' );
|
||||
assert.equal( stalled.expected.jsError, 'time' );
|
||||
assert.equal( stalled.expected.accepted, false );
|
||||
assert.ok( stalled.bytes < 100 );
|
||||
assert.deepEqual( JSON.parse( securityFixtureBuffer( stalled.id ).toString( 'utf8' ).split( '\n' )[ 1 ] ), [ 1e20, 'o', 'x' ] );
|
||||
assert.equal( 1e20 * 1000 + 1000 / 60, 1e20 * 1000, 'the real 3.17 batch deadline cannot advance at this magnitude' );
|
||||
} );
|
||||
|
||||
test( 'official native captures retain independently pinned provenance and identical output', () => {
|
||||
const provenance = JSON.parse( readFileSync( new URL( 'provenance.json', root ), 'utf8' ) );
|
||||
assert.deepEqual( provenance.artifacts.map( ( artifact ) => artifact.file ).sort(), [ 'official-v1.cast', 'official-v2.cast', 'official-v3.cast' ] );
|
||||
assert.equal( sha256( readFileSync( new URL( provenance.payload_script, root ) ) ), provenance.payload_script_sha256 );
|
||||
assert.equal( sha256( readFileSync( new URL( provenance.reproduction_script, root ) ) ), provenance.reproduction_script_sha256 );
|
||||
for ( const artifact of provenance.artifacts ) {
|
||||
const bytes = readFileSync( new URL( artifact.file, root ) );
|
||||
assert.equal( bytes.length, artifact.bytes );
|
||||
assert.equal( sha256( bytes ), artifact.sha256 );
|
||||
const text = bytes.toString( 'utf8' );
|
||||
const output = artifact.format === 'asciicast-v1' ? JSON.parse( text ).stdout.map( ( frame ) => frame[ 1 ] ).join( '' ) : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse ).filter( ( frame ) => frame[ 1 ] === 'o' ).map( ( frame ) => frame[ 2 ] ).join( '' );
|
||||
assert.equal( Buffer.byteLength( output ), provenance.verified.captured_stdout_bytes );
|
||||
assert.equal( sha256( output ), provenance.verified.captured_stdout_sha256 );
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'seeded recordings preserve equivalent visible output and timing in all formats', () => {
|
||||
const comparable = [];
|
||||
for ( const version of [ 1, 2, 3 ] ) {
|
||||
const text = securityFixtureBuffer( `seeded-v${ version }-valid` ).toString( 'utf8' );
|
||||
const frames = version === 1 ? JSON.parse( text ).stdout.map( ( frame ) => [ frame[ 0 ], 'o', frame[ 1 ] ] ) : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse );
|
||||
let time = 0;
|
||||
comparable.push( frames.map( ( frame ) => { time = version === 2 ? frame[ 0 ] : time + frame[ 0 ]; return [ time, frame[ 2 ] ]; } ) );
|
||||
assert.ok( text.includes( 'café 你好 🌱' ), 'fragmented-stream tests need actual multibyte content' );
|
||||
}
|
||||
assert.deepEqual( comparable[ 0 ], comparable[ 1 ] );
|
||||
assert.deepEqual( comparable[ 1 ], comparable[ 2 ] );
|
||||
} );
|
||||
|
||||
for ( const entry of securityCases ) {
|
||||
test( `fixture validity and independent boundary measurement: ${ entry.id }`, () => {
|
||||
assert.ok( entry.bytes > 0 && entry.bytes <= MAX_FIXTURE_BYTES );
|
||||
assert.equal( Boolean( entry.source.file ), ! Boolean( entry.source.segments ) );
|
||||
const bytes = securityFixtureBuffer( entry.id );
|
||||
assert.equal( bytes.length, entry.bytes );
|
||||
assert.equal( sha256( bytes ), entry.sha256 );
|
||||
if ( entry.validity === 'intentionally-malformed' ) {
|
||||
assert.equal( entry.expected.accepted, false );
|
||||
assert.throws( () => measure( entry, bytes ), SyntaxError );
|
||||
return;
|
||||
}
|
||||
const metrics = measure( entry, bytes );
|
||||
if ( entry.boundary ) {
|
||||
assert.equal( entry.boundary.limit, POLICY[ entry.boundary.metric ] );
|
||||
assert.equal( metrics[ entry.boundary.metric ], entry.boundary.value );
|
||||
assert.equal( entry.expected.accepted, entry.boundary.value <= entry.boundary.limit );
|
||||
// Rejections isolate their named budget. In JSONL the event and line
|
||||
// thresholds necessarily coincide for an event-only recording.
|
||||
for ( const metric of Object.keys( POLICY ) ) {
|
||||
if ( metric === entry.boundary.metric || ( entry.format === 1 ? [ 'lineBytes', 'lineTokens', 'lines' ] : [ 'v1Bytes', 'tokens' ] ).includes( metric ) ) continue;
|
||||
if ( entry.boundary.metric === 'events' && metric === 'lines' ) continue;
|
||||
assert.ok( metrics[ metric ] <= POLICY[ metric ], `${ metric } must not mask ${ entry.boundary.metric }: ${ metrics[ metric ] }` );
|
||||
}
|
||||
}
|
||||
if ( entry.metrics ) for ( const [ key, value ] of Object.entries( entry.metrics ) ) {
|
||||
assert.equal( metrics[ key === 'maximumLineBytes' ? 'lineBytes' : key ], value );
|
||||
}
|
||||
if ( entry.safePlayback ) {
|
||||
assert.equal( entry.expected.accepted, true );
|
||||
assert.ok( entry.bytes < 16384 );
|
||||
assert.ok( entry.id.startsWith( 'official-' ) || entry.id.startsWith( 'seeded-' ) );
|
||||
}
|
||||
} );
|
||||
}
|
||||
|
||||
test( 'checked-in cast files stay tiny and temporary materialization refuses overwrites', () => {
|
||||
for ( const name of readdirSync( root ).filter( ( file ) => file.endsWith( '.cast' ) ) ) {
|
||||
assert.ok( readFileSync( new URL( name, root ) ).length < 16384, `${ name } must not be a committed large payload` );
|
||||
assert.ok( securityCases.some( ( entry ) => entry.source.file === name ), `${ name } must have an explicit manifest expectation` );
|
||||
}
|
||||
const directory = mkdtempSync( join( tmpdir(), 'asciiplayer-fixture-test-' ) );
|
||||
try {
|
||||
const path = writeSecurityFixture( 'seeded-v2-valid', directory );
|
||||
assert.deepEqual( readFileSync( path ), securityFixtureBuffer( 'seeded-v2-valid' ) );
|
||||
assert.throws( () => writeSecurityFixture( 'seeded-v2-valid', directory ), { code: 'EEXIST' } );
|
||||
} finally { rmSync( directory, { recursive: true, force: true } ); }
|
||||
} );
|
||||
@@ -0,0 +1,397 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { loadRecording, RecordingLoadError, DEFAULT_LIMITS } from '../../src/recording-loader.js';
|
||||
import { securityManifest, securityCases, getSecurityCase, securityFixtureBuffer } from '../fixtures/security/generate.mjs';
|
||||
|
||||
test('shared security corpus pins the production policy and all six safe controls', () => {
|
||||
assert.equal(DEFAULT_LIMITS.timelineMs, 2147483647, 'the test horizon is independently pinned');
|
||||
assert.equal(securityManifest.schemaVersion, 1);
|
||||
for (const [name, value] of Object.entries(securityManifest.policy)) {
|
||||
assert.equal(DEFAULT_LIMITS[name], value, `the ${name} fixture boundary must match production`);
|
||||
}
|
||||
assert.deepEqual(securityCases.filter((entry) => entry.safePlayback).map((entry) => entry.id).sort(), [
|
||||
'official-v1', 'official-v2', 'official-v3',
|
||||
'seeded-v1-valid', 'seeded-v2-valid', 'seeded-v3-valid',
|
||||
]);
|
||||
});
|
||||
|
||||
/** A bounded stream, with observations rather than a replacement loader/parser. */
|
||||
function streamedFixture(bytes, chunkSizes = [16 * 1024]) {
|
||||
let offset = 0;
|
||||
let reads = 0;
|
||||
const state = { fetches: 0, cancels: 0, releases: 0, eof: 0, signal: undefined };
|
||||
const fetchImpl = async (source, options) => {
|
||||
state.fetches += 1;
|
||||
assert.equal(source, '/security-fixture.cast');
|
||||
assert.equal(options.credentials, 'same-origin');
|
||||
state.signal = options.signal;
|
||||
return {
|
||||
ok: true,
|
||||
// A false advertised length must not replace measuring actual bytes.
|
||||
headers: new Headers({ 'Content-Length': '1' }),
|
||||
body: { getReader: () => ({
|
||||
read: async () => {
|
||||
if (offset === bytes.length) {
|
||||
state.eof += 1;
|
||||
return { done: true };
|
||||
}
|
||||
const end = Math.min(offset + chunkSizes[reads++ % chunkSizes.length], bytes.length);
|
||||
const value = bytes.subarray(offset, end);
|
||||
offset = end;
|
||||
return { done: false, value };
|
||||
},
|
||||
cancel: async () => { state.cancels += 1; },
|
||||
releaseLock: () => { state.releases += 1; },
|
||||
}) },
|
||||
};
|
||||
};
|
||||
return { fetchImpl, state };
|
||||
}
|
||||
|
||||
for (const entry of securityCases) {
|
||||
test(`shared security corpus: ${entry.id}`, async (t) => {
|
||||
const bytes = await securityFixtureBuffer(entry.id);
|
||||
assert.equal(bytes.length, entry.bytes, 'fixture byte length is reproducible');
|
||||
assert.equal(createHash('sha256').update(bytes).digest('hex'), entry.sha256, 'fixture bytes match the cross-language manifest');
|
||||
const input = streamedFixture(bytes);
|
||||
const metadata = [];
|
||||
let largestParsedTree = 0;
|
||||
const parse = JSON.parse;
|
||||
t.after(() => { JSON.parse = parse; });
|
||||
JSON.parse = (text, ...args) => {
|
||||
// Version-sniffing parses short scalar keys. Only full JSON trees
|
||||
// allocate the arrays/objects that the structural guard must bound.
|
||||
if (/^\s*[\[{]/.test(text)) largestParsedTree = Math.max(largestParsedTree, Buffer.byteLength(text));
|
||||
return parse(text, ...args);
|
||||
};
|
||||
const pending = loadRecording('/security-fixture.cast', {
|
||||
fetchImpl: input.fetchImpl,
|
||||
onMetadata: (value) => metadata.push(value),
|
||||
});
|
||||
if (entry.expected.accepted) {
|
||||
const result = await pending;
|
||||
const header = entry.format === 1 ? result : result[0];
|
||||
assert.equal(header.version, entry.format);
|
||||
const cols = entry.format === 3 ? header.term.cols : header.width;
|
||||
const rows = entry.format === 3 ? header.term.rows : header.height;
|
||||
assert.deepEqual(metadata, [cols > 0 && rows > 0 ? { cols, rows } : null], 'metadata is emitted exactly once, only after complete validation');
|
||||
assert.equal(input.state.eof, 1, 'an accepted recording is validated through EOF');
|
||||
assert.equal(input.state.cancels, 0);
|
||||
assert.equal(input.state.signal.aborted, false);
|
||||
} else {
|
||||
await assert.rejects(pending, (error) => error instanceof RecordingLoadError && error.code === entry.expected.jsError,
|
||||
`expected the production ${entry.expected.jsError} guard`);
|
||||
assert.deepEqual(metadata, [], 'rejected content must not leak native-size metadata');
|
||||
assert.equal(input.state.cancels, 1, 'the rejected body reader is canceled once');
|
||||
assert.equal(input.state.signal.aborted, true, 'the rejected fetch is aborted');
|
||||
const threshold = entry.expected.noDecodeAtOrAboveBytes;
|
||||
if (threshold !== undefined) {
|
||||
assert.ok(largestParsedTree < threshold,
|
||||
`unsafe JSON at/above ${threshold} bytes reached JSON.parse: ${largestParsedTree}`);
|
||||
}
|
||||
}
|
||||
assert.equal(input.state.fetches, 1, 'validation and metadata share a single fetch');
|
||||
assert.equal(input.state.releases, 1, 'the body reader lock is released exactly once');
|
||||
});
|
||||
}
|
||||
|
||||
for (const version of [1, 2, 3]) {
|
||||
test(`seeded v${version} corpus survives byte and JSON token stream boundaries`, async () => {
|
||||
const entry = getSecurityCase(`seeded-v${version}-valid`);
|
||||
const bytes = await securityFixtureBuffer(entry.id);
|
||||
const fragmented = streamedFixture(bytes, [1, 2, 3, 5, 13]);
|
||||
const contiguous = streamedFixture(bytes, [bytes.length]);
|
||||
const metadata = [];
|
||||
const actual = await loadRecording('/security-fixture.cast', {
|
||||
fetchImpl: fragmented.fetchImpl, onMetadata: (value) => metadata.push(value),
|
||||
});
|
||||
assert.deepEqual(actual, await loadRecording('/security-fixture.cast', { fetchImpl: contiguous.fetchImpl }));
|
||||
assert.equal(metadata.length, 1);
|
||||
assert.equal(fragmented.state.fetches, 1);
|
||||
assert.equal(fragmented.state.cancels, 0);
|
||||
assert.equal(fragmented.state.releases, 1);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Exercise the actual pinned player parser/recording driver without importing
|
||||
* its DOM UI. Discover Core through the package's own entrypoint import, rather
|
||||
* than hard-coding a generated chunk hash or copying upstream parser code.
|
||||
* A package layout/version change deliberately fails this compatibility check.
|
||||
*/
|
||||
async function playerCore() {
|
||||
const entrypoint = new URL(import.meta.resolve('asciinema-player'));
|
||||
const manifest = JSON.parse(await readFile(new URL('../package.json', entrypoint), 'utf8'));
|
||||
assert.equal(manifest.version, '3.17.0');
|
||||
const source = await readFile(entrypoint, 'utf8');
|
||||
const imported = /import \{ (\w+) as Core \} from ['"]([^'"]+)['"]/.exec(source);
|
||||
assert.ok(imported, 'the pinned player entrypoint must expose its Core import for compatibility tests');
|
||||
const module = await import(new URL(imported[2], entrypoint));
|
||||
assert.equal(typeof module[imported[1]], 'function');
|
||||
return module[imported[1]];
|
||||
}
|
||||
|
||||
function expectedPlayback(data) {
|
||||
const header = Array.isArray(data) ? data[0] : data;
|
||||
let time = 0;
|
||||
const frames = header.version === 1 ? data.stdout.map(([delta, text]) => [delta, 'o', text]) : data.slice(1);
|
||||
const absolute = frames.map(([timestamp, type, text]) => {
|
||||
time = header.version === 2 ? timestamp : time + timestamp;
|
||||
return [time, type, text];
|
||||
});
|
||||
return {
|
||||
cols: (header.version === 3 ? header.term.cols : header.width) || 80,
|
||||
rows: (header.version === 3 ? header.term.rows : header.height) || 24,
|
||||
duration: time,
|
||||
events: absolute,
|
||||
output: absolute.filter((event) => event[1] === 'o').map((event) => event[2]).join(''),
|
||||
markers: absolute.filter((event) => event[1] === 'm').map((event) => [event[0], event[2]]),
|
||||
};
|
||||
}
|
||||
|
||||
async function inspectPlayer(data) {
|
||||
const Core = await playerCore();
|
||||
const events = { metadata: [], reset: [], output: [], error: [] };
|
||||
const core = new Core({ data }, {
|
||||
preload: true, speed: 1,
|
||||
logger: { debug() {}, info() {}, warn() {}, error() {} },
|
||||
});
|
||||
for (const [name, values] of Object.entries(events)) core.addEventListener(name, (value) => values.push(value));
|
||||
try {
|
||||
core.terminalReady();
|
||||
await core.init();
|
||||
const duration = core.getDuration();
|
||||
assert.ok(Number.isFinite(duration));
|
||||
assert.ok(Number.isFinite(core.getCurrentTime()));
|
||||
await core.seek('100%');
|
||||
assert.ok(Number.isFinite(core.getCurrentTime()), 'the actual seek destination remains finite');
|
||||
assert.ok(Number.isFinite(core.getProgress()), 'the actual progress calculation remains finite');
|
||||
const output = events.output.flat().join('');
|
||||
await core.seek('0%');
|
||||
assert.equal(core.getCurrentTime(), 0, 'the real driver can seek back to the start');
|
||||
assert.deepEqual(events.error, []);
|
||||
assert.equal(events.metadata.length, 1);
|
||||
return { duration, output, metadata: events.metadata[0], reset: events.reset[0] };
|
||||
} finally {
|
||||
await core.stop();
|
||||
}
|
||||
}
|
||||
|
||||
// Only known-small, accepted controls reach the real upstream parser/driver here.
|
||||
// The tiny numeric witnesses below run separately with captured timers and a hard
|
||||
// child-process deadline; no oversized payload reaches the real player.
|
||||
const playableCases = securityCases.filter((entry) => entry.safePlayback === true);
|
||||
for (const entry of playableCases) {
|
||||
test(`pinned player 3.17 parses and seeks validated ${entry.id}`, async () => {
|
||||
assert.equal(entry.expected.accepted, true);
|
||||
assert.ok(entry.bytes < 128 * 1024, 'actual-player controls must remain small');
|
||||
const bytes = await securityFixtureBuffer(entry.id);
|
||||
const data = await loadRecording('/security-fixture.cast', { fetchImpl: streamedFixture(bytes).fetchImpl });
|
||||
const text = bytes.toString('utf8');
|
||||
const original = entry.format === 1 ? JSON.parse(text) : text.split('\n')
|
||||
.filter((line, index) => index === 0 || line.startsWith('[')).map((line) => JSON.parse(line));
|
||||
assert.deepEqual(data, original, 'the guard preserves every original header and event');
|
||||
const expected = expectedPlayback(original);
|
||||
const actual = await inspectPlayer(data);
|
||||
assert.ok(Math.abs(actual.duration - expected.duration) < 1e-8);
|
||||
assert.deepEqual(actual.reset.size, { cols: expected.cols, rows: expected.rows });
|
||||
assert.equal(actual.output, expected.output, 'the real parser preserves complete terminal output');
|
||||
assert.deepEqual(actual.metadata.markers, expected.markers);
|
||||
// Independently prove both official captures and seeded mutations also
|
||||
// work through upstream's original raw-input path before our adapter.
|
||||
const raw = await inspectPlayer(new Response(bytes));
|
||||
assert.deepEqual(raw, actual);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
test('official outputs and seeded playback timelines are equivalent across all three formats', async () => {
|
||||
const controls = { official: [], seeded: [] };
|
||||
for (const version of [1, 2, 3]) {
|
||||
for (const kind of ['official', 'seeded']) {
|
||||
const id = kind === 'official' ? `official-v${version}` : `seeded-v${version}-valid`;
|
||||
const bytes = securityFixtureBuffer(id);
|
||||
const text = bytes.toString('utf8');
|
||||
const data = version === 1 ? JSON.parse(text) : text.trimEnd().split('\n').map(JSON.parse);
|
||||
controls[kind].push(expectedPlayback(data));
|
||||
}
|
||||
}
|
||||
assert.equal(controls.official[0].output, controls.official[1].output);
|
||||
assert.equal(controls.official[0].output, controls.official[2].output);
|
||||
assert.deepEqual(controls.seeded[0], controls.seeded[1]);
|
||||
assert.deepEqual(controls.seeded[0], controls.seeded[2]);
|
||||
assert.deepEqual(controls.seeded[0].events.map((event) => event[0]), [0, 1, 8, 12]);
|
||||
assert.ok(controls.seeded[0].output.includes(controls.official[0].output), 'seeded mutations retain the official captured output');
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Actual upstream Core witness, isolated from the main runner. All timers are
|
||||
* captured, never scheduled; at most three callbacks are invoked per witness.
|
||||
* The parent also kills this child after 10 seconds if an upstream change causes
|
||||
* an unexpected synchronous loop. No browser, terminal, real playback delay, or
|
||||
* large payload is involved. The arithmetic checks above are not a Core double.
|
||||
*/
|
||||
async function timestampCoreRegression() {
|
||||
const Core = await playerCore();
|
||||
const realSetTimeout = globalThis.setTimeout;
|
||||
const realClearTimeout = globalThis.clearTimeout;
|
||||
const timers = new Map();
|
||||
let timerId = 0;
|
||||
globalThis.setTimeout = (callback, delay) => {
|
||||
const id = ++timerId;
|
||||
timers.set(id, { callback, delay });
|
||||
return id;
|
||||
};
|
||||
globalThis.clearTimeout = (id) => { timers.delete(id); };
|
||||
const parseFixture = (id) => {
|
||||
const entry = getSecurityCase(id);
|
||||
assert.ok(entry.bytes < 256, 'only pinned tiny witnesses may enter this child');
|
||||
const text = securityFixtureBuffer(id).toString('utf8');
|
||||
return entry.format === 1 ? JSON.parse(text) : text.trimEnd().split('\n').map(JSON.parse);
|
||||
};
|
||||
const createCore = (data) => {
|
||||
const core = new Core({ data }, {
|
||||
preload: true, speed: 1,
|
||||
logger: { debug() {}, info() {}, warn() {}, error() {} },
|
||||
});
|
||||
const events = { output: [], error: [], ended: [] };
|
||||
for (const [name, values] of Object.entries(events)) core.addEventListener(name, (value) => values.push(value));
|
||||
core.terminalReady();
|
||||
return { core, events };
|
||||
};
|
||||
const takeTimer = () => {
|
||||
assert.equal(timers.size, 1, 'exactly one recording callback is pending');
|
||||
const [id, timer] = timers.entries().next().value;
|
||||
timers.delete(id);
|
||||
return timer;
|
||||
};
|
||||
try {
|
||||
// Deliberately bypass the guard ONLY for this fixed tiny upstream bug
|
||||
// witness. A premature timer call safely exposes non-progress without
|
||||
// waiting for 1e23 ms or advancing the clock into a synchronous loop.
|
||||
const stalled = createCore(parseFixture('time-v2-output-nonprogress'));
|
||||
try {
|
||||
await stalled.core.init();
|
||||
assert.ok(Number.isFinite(stalled.core.getDuration()));
|
||||
assert.equal(timers.size, 0, 'initial loading timeout was cleared');
|
||||
await stalled.core.play();
|
||||
let previousCallback;
|
||||
for (let n = 0; n < 3; n++) {
|
||||
const timer = takeTimer();
|
||||
assert.equal(timer.delay, 1e23, 'the unsafe upstream delay exceeds signed 32-bit timer range');
|
||||
if (previousCallback) assert.equal(timer.callback, previousCallback, 'the same unconsumed event is rescheduled');
|
||||
previousCallback = timer.callback;
|
||||
timer.callback();
|
||||
await Promise.resolve();
|
||||
assert.deepEqual(stalled.events.output, Array.from({ length: n + 1 }, () => []), 'batching emits empty output without consuming x');
|
||||
assert.deepEqual(stalled.events.ended, []);
|
||||
}
|
||||
assert.deepEqual(stalled.events.error, []);
|
||||
process.stdout.write('v2 non-progress reproduced with three captured callbacks\n');
|
||||
} finally {
|
||||
await stalled.core.stop();
|
||||
assert.equal(timers.size, 0, 'stopping removes the captured non-progress callback');
|
||||
}
|
||||
for (const version of [1, 3]) {
|
||||
const overflow = createCore(parseFixture(`time-v${version}-ms-sum-overflow`));
|
||||
try {
|
||||
await overflow.core.init();
|
||||
assert.equal(overflow.core.getDuration(), Infinity, 'real upstream interval arithmetic overflows although converted seconds sum is finite');
|
||||
await overflow.core.seek('100%');
|
||||
assert.equal(overflow.core.getCurrentTime(), Infinity);
|
||||
assert.ok(Number.isNaN(overflow.core.getProgress()), 'real upstream progress is corrupted');
|
||||
assert.deepEqual(overflow.events.error, []);
|
||||
process.stdout.write(`v${version} infinite duration/seek reproduced\n`);
|
||||
} finally {
|
||||
await overflow.core.stop();
|
||||
assert.equal(timers.size, 0);
|
||||
}
|
||||
}
|
||||
// The production loader must reject all five pinned numerical attacks
|
||||
// before their data can be handed to Core, including rounding-order bugs.
|
||||
let coreHandoffs = 0;
|
||||
for (const id of [
|
||||
'time-v2-output-nonprogress',
|
||||
'time-v1-ms-sum-overflow', 'time-v3-ms-sum-overflow',
|
||||
'time-v1-ms-rounding-over', 'time-v3-ms-rounding-over',
|
||||
]) {
|
||||
assert.equal(getSecurityCase(id).expected.jsError, 'time');
|
||||
const stream = streamedFixture(securityFixtureBuffer(id));
|
||||
const handoff = async () => {
|
||||
const data = await loadRecording('/security-fixture.cast', { fetchImpl: stream.fetchImpl });
|
||||
coreHandoffs++;
|
||||
return createCore(data);
|
||||
};
|
||||
await assert.rejects(handoff(), (error) => error instanceof RecordingLoadError && error.code === 'time');
|
||||
assert.equal(coreHandoffs, 0, 'rejected data never reaches the actual Core constructor');
|
||||
assert.equal(stream.state.cancels, 1);
|
||||
assert.equal(stream.state.signal.aborted, true);
|
||||
assert.equal(timers.size, 0, 'rejected loader leaves no captured timeouts');
|
||||
process.stdout.write(`${id} rejected before Core handoff\n`);
|
||||
}
|
||||
// Accepted exact-boundary fixtures survive actual parser preparation,
|
||||
// duration/progress arithmetic, end/start seeking and output batching.
|
||||
for (const id of [
|
||||
'timeline-v1-at', 'timeline-v2-at', 'timeline-v3-at',
|
||||
'interval-timeline-v1-at', 'interval-timeline-v3-at',
|
||||
]) {
|
||||
const bytes = securityFixtureBuffer(id);
|
||||
const data = await loadRecording('/security-fixture.cast', { fetchImpl: streamedFixture(bytes).fetchImpl });
|
||||
assert.deepEqual(data, parseFixture(id), 'near-bound timestamps are preserved without clamping');
|
||||
const expectedOutput = id.startsWith('interval-') ? 'xend' : 'x';
|
||||
const inspected = await inspectPlayer(data);
|
||||
assert.equal(inspected.duration, 2147483.647);
|
||||
assert.equal(inspected.output, expectedOutput);
|
||||
assert.equal(timers.size, 0);
|
||||
const playback = createCore(data);
|
||||
try {
|
||||
await playback.core.init();
|
||||
await playback.core.play();
|
||||
for (let n = 0; n < (id.startsWith('interval-') ? 2 : 1); n++) {
|
||||
const timer = takeTimer();
|
||||
assert.ok(Number.isFinite(timer.delay) && timer.delay >= 0 && timer.delay <= 2147483647);
|
||||
timer.callback();
|
||||
await Promise.resolve();
|
||||
}
|
||||
assert.equal(playback.events.output.flat().join(''), expectedOutput, 'accepted boundary output always advances');
|
||||
assert.equal(playback.events.ended.length, 1);
|
||||
assert.ok(Number.isFinite(playback.core.getDuration()));
|
||||
assert.ok(Number.isFinite(playback.core.getCurrentTime()));
|
||||
assert.ok(Number.isFinite(playback.core.getProgress()));
|
||||
assert.deepEqual(playback.events.error, []);
|
||||
assert.equal(timers.size, 0, 'accepted output does not reschedule a consumed event');
|
||||
process.stdout.write(`${id} actual Core init/seek/playback is finite and advances\n`);
|
||||
} finally { await playback.core.stop(); }
|
||||
}
|
||||
} finally {
|
||||
globalThis.setTimeout = realSetTimeout;
|
||||
globalThis.clearTimeout = realClearTimeout;
|
||||
}
|
||||
}
|
||||
|
||||
test('actual 3.17 Core timestamp regressions are bounded and blocked before handoff', () => {
|
||||
const script = `
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { loadRecording, RecordingLoadError } from ${JSON.stringify(new URL('../../src/recording-loader.js', import.meta.url).href)};
|
||||
import { getSecurityCase, securityFixtureBuffer } from ${JSON.stringify(new URL('../fixtures/security/generate.mjs', import.meta.url).href)};
|
||||
${playerCore.toString()}
|
||||
${streamedFixture.toString()}
|
||||
${inspectPlayer.toString()}
|
||||
await (${timestampCoreRegression.toString()})();
|
||||
process.stdout.write('bounded actual-Core timestamp witnesses passed\\n');
|
||||
`;
|
||||
const child = spawnSync(process.execPath, ['--input-type=module', '--eval', script], {
|
||||
cwd: new URL('../../', import.meta.url), timeout: 10000, maxBuffer: 64 * 1024,
|
||||
encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '' },
|
||||
});
|
||||
const diagnostics = `stdout:\n${child.stdout}\nstderr:\n${child.stderr}`;
|
||||
assert.equal(child.error, undefined, `the bounded Core witness must finish: ${child.error?.message}\n${diagnostics}`);
|
||||
assert.equal(child.signal, null, `the bounded Core witness was killed\n${diagnostics}`);
|
||||
assert.equal(child.status, 0, diagnostics);
|
||||
assert.match(child.stdout, /bounded actual-Core timestamp witnesses passed/);
|
||||
});
|
||||
Reference in New Issue
Block a user