mirror of
https://github.com/LamGC/wp-asciiplayer.git
synced 2026-11-26 20:55:48 +00:00
Show native cast dimensions and add Media Library recordings (1.2.2)
This commit is contained in:
@@ -47,6 +47,17 @@ Tests check the request count, stale-response cleanup, immediate Apply, error
|
||||
retry, and no requests for empty/invalid URLs or static inserter examples.
|
||||
Floating-toolbar dimension controls are checked against the collapsed sidebar,
|
||||
including keyboard focus, Escape/close/reopen, and shared attribute values.
|
||||
Both controls show the recording header's native columns and rows as placeholders
|
||||
without saving overrides. URL replacement, pending/error/invalid sources and late
|
||||
responses cover metadata cleanup; recorded resize events still control blank axes.
|
||||
Pretty-printed v1 and comment-bearing v3 fixtures also exercise actual parsing,
|
||||
native-size placeholders and playback output, alongside the existing v2 fixtures.
|
||||
|
||||
Media Library tests use WordPress's real upload dialog, file input and attachment
|
||||
tiles. They upload a valid `.cast`, select and play it without Apply URL, cancel a
|
||||
replacement, reopen to select the existing replacement, and reload the saved URL.
|
||||
A malformed `.cast` must be rejected by the real upload endpoint and shown as an
|
||||
upload error. These tests create small attachments in the isolated wp-env database.
|
||||
|
||||
## CI evidence and limits
|
||||
|
||||
@@ -68,3 +79,9 @@ References:
|
||||
- https://developer.wordpress.org/block-editor/reference-guides/packages/packages-env/
|
||||
- https://developer.wordpress.org/block-editor/reference-guides/block-api/block-api-versions/block-migration-for-iframe-editor-compatibility/
|
||||
- https://github.com/WordPress/plugin-check/blob/trunk/docs/CLI.md
|
||||
|
||||
Native recording-size hints are checked against v1/v2/v3 headers, explicit
|
||||
overrides, URL replacement, error/empty states and recorded resize events.
|
||||
The Media Library tests use actual isolated WordPress upload dialogs to upload
|
||||
validated fixtures, reject malformed casts, cancel/reopen and select an existing
|
||||
recording. No production-site media is accessed.
|
||||
|
||||
@@ -330,6 +330,14 @@ test('replacing a pending recording ignores its stale response', async ({ page }
|
||||
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).source, id
|
||||
)).toBe(latest);
|
||||
await readyPreview(block);
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
if (!await columns.isVisible()) {
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
|
||||
}
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
release();
|
||||
await expect.poll(() => oldResponseSettled).toBe(true);
|
||||
await page.waitForTimeout(750);
|
||||
@@ -337,6 +345,11 @@ test('replacing a pending recording ignores its stale response', async ({ page }
|
||||
await expect.poll(() => block.locator('.ap-term').evaluate((terminal) =>
|
||||
Number(terminal.style.getPropertyValue('--term-cols'))
|
||||
)).toBe(64);
|
||||
// A late header from the old 120-column cast must not become a hint.
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue(latest);
|
||||
} finally {
|
||||
release();
|
||||
|
||||
@@ -211,6 +211,10 @@ test('toolbar terminal dimensions are discoverable, preserve focus and synchroni
|
||||
await expect(columns).toBeFocused();
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
const after = await block.boundingBox();
|
||||
expect(Math.abs(after.width - before.width)).toBeLessThan(2);
|
||||
expect(Math.abs(after.height - before.height)).toBeLessThan(2);
|
||||
@@ -236,6 +240,9 @@ test('toolbar terminal dimensions are discoverable, preserve focus and synchroni
|
||||
await toggle.click();
|
||||
await expect(columns).toHaveValue('88');
|
||||
await expect(rows).toHaveValue('16');
|
||||
// A manual override must not become the displayed recording metadata.
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
await columns.fill('');
|
||||
await columns.press('Tab');
|
||||
await expectGrid(block, 64, 16);
|
||||
@@ -261,6 +268,8 @@ test('toolbar terminal dimensions are discoverable, preserve focus and synchroni
|
||||
const sidebarRows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
await expect(sidebarColumns).toHaveValue('88');
|
||||
await expect(sidebarRows).toHaveValue('16');
|
||||
await expect(sidebarColumns).toHaveAttribute('placeholder', '64');
|
||||
await expect(sidebarRows).toHaveAttribute('placeholder', '12');
|
||||
await sidebarRows.fill('');
|
||||
await sidebarRows.press('Tab');
|
||||
await expectGrid(block, 88, 12);
|
||||
@@ -271,6 +280,8 @@ test('toolbar terminal dimensions are discoverable, preserve focus and synchroni
|
||||
await toggle.click();
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
await popover.getByRole('button', { name: 'Close', exact: true }).click();
|
||||
const saved = await publish(page, 'Reset terminal dimensions regression');
|
||||
await page.goto(saved.url);
|
||||
@@ -291,11 +302,19 @@ test('recorded resize events remain authoritative except on explicitly overridde
|
||||
{ overrides: { cols: 80, rows: 24 }, cols: 80, rows: 24 },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
const { block } = await insertPlayer(page, { source, startAt: 2, ...entry.overrides });
|
||||
const { id, block } = await insertPlayer(page, { source, startAt: 2, ...entry.overrides });
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, entry.overrides.cols ?? 64, entry.overrides.rows ?? 12);
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expectGrid(block, entry.cols, entry.rows);
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
await openInspectorPanel(page, 'Terminal size', columns);
|
||||
// Placeholders describe the cast header, even after its resize event.
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
expect((await attributes(page, id)).cols).toBe(entry.overrides.cols);
|
||||
expect((await attributes(page, id)).rows).toBe(entry.overrides.rows);
|
||||
}
|
||||
const saved = await publish(page, 'Recording resize and explicit axes regression');
|
||||
await page.goto(saved.url);
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixtures = '/wp-content/uploads/asciiplayer-fixtures';
|
||||
|
||||
async function openEditor(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
await page.goto('/wp-admin/post-new.php');
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
function playerBlock(page, id) {
|
||||
return page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${id}"]`);
|
||||
}
|
||||
|
||||
async function insertPlayer(page, attributes = {}) {
|
||||
const id = await page.evaluate(({ name, attrs }) => {
|
||||
const block = window.wp.blocks.createBlock(name, attrs);
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, { name: blockName, attrs: attributes });
|
||||
return { id, block: playerBlock(page, id) };
|
||||
}
|
||||
|
||||
async function attributes(page, id) {
|
||||
return page.evaluate((clientId) => window.wp.data.select('core/block-editor').getBlockAttributes(clientId), id);
|
||||
}
|
||||
|
||||
async function readyPreview(block) {
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expect(block.locator('.ap-wrapper')).toHaveCount(1);
|
||||
await expect(block.locator('.ap-term')).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectGrid(block, cols, rows) {
|
||||
await expect.poll(() => block.locator('.ap-term').evaluate((terminal) => ({
|
||||
cols: Number(terminal.style.getPropertyValue('--term-cols')),
|
||||
rows: Number(terminal.style.getPropertyValue('--term-rows')),
|
||||
}))).toEqual({ cols, rows });
|
||||
}
|
||||
|
||||
async function openDimensions(page) {
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
if (!await columns.isVisible()) {
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
|
||||
}
|
||||
await expect(columns).toBeVisible();
|
||||
return { columns, rows };
|
||||
}
|
||||
|
||||
async function expectNativeSize(controls, cols, rows) {
|
||||
await expect(controls.columns).toHaveAttribute('placeholder', cols === undefined ? 'From recording' : String(cols));
|
||||
await expect(controls.rows).toHaveAttribute('placeholder', rows === undefined ? 'From recording' : String(rows));
|
||||
}
|
||||
|
||||
async function openMedia(page, block) {
|
||||
await block.getByRole('button', { name: 'Choose recording', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: 'Choose an Asciicast recording', exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
async function uploadRecording(page, dialog, name, buffer) {
|
||||
await dialog.getByRole('tab', { name: 'Upload files', exact: true }).click();
|
||||
// Native WP media uses Plupload. Its file input is intentionally hidden and
|
||||
// may live outside the modal; setInputFiles exercises the actual uploader.
|
||||
const input = page.locator('.moxie-shim input[type="file"]').last();
|
||||
await expect(input).toBeAttached();
|
||||
const response = page.waitForResponse((result) =>
|
||||
/\/wp-admin\/async-upload\.php(?:\?|$)/.test(result.url()) && result.request().method() === 'POST'
|
||||
);
|
||||
await input.setInputFiles({ name, mimeType: 'application/x-asciicast', buffer });
|
||||
return (await response).json();
|
||||
}
|
||||
|
||||
async function selectAttachment(dialog, id) {
|
||||
await dialog.getByRole('tab', { name: 'Media Library', exact: true }).click();
|
||||
const attachment = dialog.locator(`.attachment[data-id="${id}"]`);
|
||||
await expect(attachment).toBeVisible();
|
||||
// Newly uploaded files are already selected; clicking them again deselects.
|
||||
if (!await attachment.evaluate((element) => element.classList.contains('selected'))) await attachment.click();
|
||||
const confirm = dialog.locator('.media-button-select');
|
||||
await expect(confirm).toBeEnabled();
|
||||
await confirm.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
}
|
||||
|
||||
test('recording metadata follows URL changes, clears while loading or invalid, and never replaces explicit dimensions', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const original = new URL(`${fixtures}/hello.cast`, page.url()).href;
|
||||
const replacement = new URL(`${fixtures}/replacement.cast?metadata=delayed`, page.url()).href;
|
||||
const unavailable = new URL(`${fixtures}/missing.cast?metadata=error`, page.url()).href;
|
||||
const malformed = new URL(`${fixtures}/malformed.cast?metadata=valid-header`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/replacement.cast', import.meta.url));
|
||||
let release;
|
||||
let requested = false;
|
||||
const pending = new Promise((resolve) => { release = resolve; });
|
||||
await page.route(replacement, async (route) => {
|
||||
requested = true;
|
||||
await pending;
|
||||
await route.fulfill({ contentType: 'text/plain', body: recording }).catch(() => {});
|
||||
});
|
||||
await page.route(unavailable, (route) => route.fulfill({ status: 503, contentType: 'text/plain', body: 'Unavailable' }));
|
||||
await page.route(malformed, (route) => route.fulfill({
|
||||
contentType: 'text/plain', body: '{"version":2,"width":101,"height":31}\n[invalid event]\n',
|
||||
}));
|
||||
try {
|
||||
const { id, block } = await insertPlayer(page, { source: original });
|
||||
await readyPreview(block);
|
||||
const dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
await expect(dimensions.columns).toHaveValue('');
|
||||
await expect(dimensions.rows).toHaveValue('');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await dimensions.columns.fill('80');
|
||||
await dimensions.rows.fill('20');
|
||||
await dimensions.rows.press('Tab');
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 80, 20);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
|
||||
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
await input.fill(replacement);
|
||||
await expectNativeSize(dimensions);
|
||||
await expect.poll(() => requested).toBe(true);
|
||||
await expectNativeSize(dimensions);
|
||||
await expect(dimensions.columns).toHaveValue('80');
|
||||
await expect(dimensions.rows).toHaveValue('20');
|
||||
release();
|
||||
await readyPreview(block);
|
||||
await expectNativeSize(dimensions, 100, 30);
|
||||
await expectGrid(block, 80, 20);
|
||||
expect(await attributes(page, id)).toMatchObject({ source: replacement, cols: 80, rows: 20 });
|
||||
|
||||
await input.fill('javascript:alert(1)');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await expectNativeSize(dimensions);
|
||||
// Invalid drafts do not overwrite the last valid saved URL or overrides.
|
||||
expect(await attributes(page, id)).toMatchObject({ source: replacement, cols: 80, rows: 20 });
|
||||
await input.fill(original);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await readyPreview(block);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
for (const failingSource of [unavailable, malformed]) {
|
||||
await input.fill(failingSource);
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
|
||||
// Even a readable header must be discarded if the player fails.
|
||||
await expectNativeSize(dimensions);
|
||||
expect(await attributes(page, id)).toMatchObject({ source: failingSource, cols: 80, rows: 20 });
|
||||
}
|
||||
await input.fill('');
|
||||
await expect.poll(async () => (await attributes(page, id)).source).toBe('');
|
||||
await expectNativeSize(dimensions);
|
||||
expect(await attributes(page, id)).toMatchObject({ cols: 80, rows: 20 });
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
});
|
||||
|
||||
test('pretty v1 and commented v3 recordings play with native header dimensions', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
// Fixtures follow the official formats, including v1's multiline JSON and
|
||||
// v3's comments after its single-line header and relative event timestamps:
|
||||
// https://docs.asciinema.org/manual/asciicast/v1/
|
||||
// https://docs.asciinema.org/manual/asciicast/v3/
|
||||
const cases = [
|
||||
{ filename: 'v1-pretty.cast', cols: 72, rows: 18, output: 'Pretty v1 recording' },
|
||||
{ filename: 'v3-comments.cast', cols: 92, rows: 22, output: 'Commented v3 recording' },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
const source = new URL(`${fixtures}/${entry.filename}`, page.url()).href;
|
||||
const { id, block } = await insertPlayer(page, { source });
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, entry.cols, entry.rows);
|
||||
const dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, entry.cols, entry.rows);
|
||||
await expect(dimensions.columns).toHaveValue('');
|
||||
await expect(dimensions.rows).toHaveValue('');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText(entry.output);
|
||||
}
|
||||
});
|
||||
|
||||
test('native Media Library uploads, selects and replaces a cast while cancel leaves the current recording intact', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const { id, block } = await insertPlayer(page);
|
||||
const firstCast = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
|
||||
const secondCast = await readFile(new URL('../fixtures/replacement.cast', import.meta.url));
|
||||
const unique = `${Date.now()}-${testInfo.retry}`;
|
||||
let dialog = await openMedia(page, block);
|
||||
const first = await uploadRecording(page, dialog, `asciiplayer-original-${unique}.cast`, firstCast);
|
||||
expect(first.success, JSON.stringify(first)).toBe(true);
|
||||
expect(first.data.mime).toBe('application/x-asciicast');
|
||||
await selectAttachment(dialog, first.data.id);
|
||||
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
await expect(input).toHaveValue(first.data.url);
|
||||
// Selecting in the native media frame applies and autoloads, with no Apply URL click.
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 64, 12);
|
||||
let dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
expect(await attributes(page, id)).toMatchObject({ source: first.data.url });
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await block.locator('.ap-term').evaluate((element) => { element.dataset.mediaIdentity = 'original'; });
|
||||
|
||||
dialog = await openMedia(page, block);
|
||||
const second = await uploadRecording(page, dialog, `asciiplayer-replacement-${unique}.cast`, secondCast);
|
||||
expect(second.success, JSON.stringify(second)).toBe(true);
|
||||
await dialog.locator('.media-modal-close').click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(input).toHaveValue(first.data.url);
|
||||
expect((await attributes(page, id)).source).toBe(first.data.url);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
await expect(block.locator('.ap-term')).toHaveAttribute('data-media-identity', 'original');
|
||||
|
||||
// The upload above is now an existing media item. Reopen the real frame and
|
||||
// select its tile rather than changing block attributes through the store.
|
||||
dialog = await openMedia(page, block);
|
||||
await selectAttachment(dialog, second.data.id);
|
||||
await expect(input).toHaveValue(second.data.url);
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 100, 30);
|
||||
await expectNativeSize(dimensions, 100, 30);
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText('Replacement recording');
|
||||
expect((await attributes(page, id)).source).toBe(second.data.url);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
const path = testInfo.outputPath('media-library-selected-recording.png');
|
||||
await page.screenshot({ path, fullPage: true });
|
||||
await testInfo.attach('media-library-selected-recording', { path, contentType: 'image/png' });
|
||||
await page.evaluate(async () => {
|
||||
const editor = window.wp.data.dispatch('core/editor');
|
||||
editor.editPost({ title: 'Native media recording selection regression' });
|
||||
await editor.savePost();
|
||||
if (window.wp.data.select('core/editor').didPostSaveRequestFail()) throw new Error('WordPress could not save the test post.');
|
||||
});
|
||||
await page.reload();
|
||||
await page.waitForFunction((name) => window.wp?.data?.select('core/block-editor')?.getBlocks().some((entry) => entry.name === name), blockName);
|
||||
const reloaded = await page.evaluate((name) => {
|
||||
const block = window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === name);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block;
|
||||
}, blockName);
|
||||
expect(reloaded.attributes.source).toBe(second.data.url);
|
||||
expect(reloaded.attributes.cols).toBeUndefined();
|
||||
expect(reloaded.attributes.rows).toBeUndefined();
|
||||
await readyPreview(playerBlock(page, reloaded.clientId));
|
||||
dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, 100, 30);
|
||||
});
|
||||
|
||||
test('native Media Library rejects an invalid cast upload without applying a source', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const { id, block } = await insertPlayer(page);
|
||||
const dialog = await openMedia(page, block);
|
||||
const malformed = await readFile(new URL('../fixtures/malformed.cast', import.meta.url));
|
||||
const result = await uploadRecording(page, dialog, `asciiplayer-invalid-${Date.now()}-${testInfo.retry}.cast`, malformed);
|
||||
expect(result.success, JSON.stringify(result)).toBe(false);
|
||||
expect(result.data.message).toEqual(expect.any(String));
|
||||
await expect(dialog).toContainText(result.data.message);
|
||||
await expect(dialog.locator('.media-button-select')).toBeDisabled();
|
||||
await dialog.locator('.media-modal-close').click();
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('');
|
||||
expect((await attributes(page, id)).source).toBe('');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
});
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
{"version":2,"width":100,"height":30,"timestamp":1700000000,"env":{"TERM":"xterm-256color","SHELL":"/bin/sh"},"title":"Replacement recording with a different native size"}
|
||||
[0.0,"o","$ printf 'Replacement recording'\r\n"]
|
||||
[0.1,"o","Replacement recording\r\n"]
|
||||
[12.0,"o","$ "]
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"version": 1,
|
||||
"width": 72,
|
||||
"height": 18,
|
||||
"duration": 12,
|
||||
"command": "/bin/sh",
|
||||
"title": "Pretty-printed v1 integration fixture",
|
||||
"env": {
|
||||
"TERM": "xterm-256color",
|
||||
"SHELL": "/bin/sh"
|
||||
},
|
||||
"stdout": [
|
||||
[0.0, "$ printf 'Pretty v1 recording'\r\n"],
|
||||
[0.1, "Pretty v1 recording\r\n"],
|
||||
[11.9, "$ "]
|
||||
]
|
||||
}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{"version":3,"term":{"cols":92,"rows":22,"type":"xterm-256color"},"timestamp":1700000000,"title":"v3 recording with comments","env":{"SHELL":"/bin/sh"}}
|
||||
# Comments are permitted after the header in asciicast v3.
|
||||
[0.0,"o","$ printf 'Commented v3 recording'\r\n"]
|
||||
[0.1,"o","Commented v3 recording\r\n"]
|
||||
# v3 timestamps are delays from the previous event.
|
||||
[11.9,"o","$ "]
|
||||
@@ -0,0 +1,124 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MAX_HEADER_BYTES, readRecordingSize, recordingSizeFromHeader } from '../../src/recording-metadata.js';
|
||||
|
||||
test( 'original dimensions use each supported asciicast header schema', () => {
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 1, width: 132, height: 43 } ), { cols: 132, rows: 43 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 110, height: 35 } ), { cols: 110, rows: 35 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 3, term: { cols: 150, rows: 50 }, width: 1, height: 1 } ), { cols: 150, rows: 50 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 1, height: 1000 } ), { cols: 1, rows: 1000 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 1500, height: 1200 } ), { cols: 1500, rows: 1200 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: Number.MAX_SAFE_INTEGER, height: 1 } ), { cols: Number.MAX_SAFE_INTEGER, rows: 1 } );
|
||||
} );
|
||||
|
||||
test( 'missing, unsupported and invalid dimensions stay unknown, never 80 by 24', () => {
|
||||
for ( const header of [ null, undefined, '', [], {}, { width: 80, height: 24 }, { version: '2', width: 80, height: 24 }, { version: 4, width: 80, height: 24 }, { version: 3, width: 80, height: 24 }, { version: 3, term: {} } ] ) {
|
||||
assert.equal( recordingSizeFromHeader( header ), null );
|
||||
}
|
||||
for ( const invalid of [ undefined, null, '', '80', true, false, NaN, Infinity, -1, 0, 1.5, Number.MAX_SAFE_INTEGER + 1 ] ) {
|
||||
assert.equal( recordingSizeFromHeader( { version: 2, width: invalid, height: 24 } ), null );
|
||||
assert.equal( recordingSizeFromHeader( { version: 3, term: { cols: 80, rows: invalid } } ), null );
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'metadata reads the first header and preserves the full original response for playback', async () => {
|
||||
const text = '{"version":2,"width":132,"height":43}\n[1,"r","200x60"]\n[2,"o","hello"]\n';
|
||||
const response = new Response( text );
|
||||
let clones = 0;
|
||||
const clone = response.clone.bind( response );
|
||||
response.clone = () => { clones++; return clone(); };
|
||||
assert.deepEqual( await readRecordingSize( response ), { cols: 132, rows: 43 } );
|
||||
assert.equal( clones, 1 );
|
||||
assert.equal( response.bodyUsed, false );
|
||||
assert.equal( await response.text(), text );
|
||||
} );
|
||||
|
||||
test( 'v3 reads terminal metadata, not nested output or subsequent resize events', async () => {
|
||||
const text = '{"version":3,"env":{"cols":500,"rows":500},"term":{"cols":120,"rows":30}}\n[0,"r","90x20"]\n';
|
||||
const response = new Response( text );
|
||||
assert.deepEqual( await readRecordingSize( response ), { cols: 120, rows: 30 } );
|
||||
await response.text();
|
||||
} );
|
||||
|
||||
function chunkedResponse( chunks ) {
|
||||
let reads = 0;
|
||||
let canceled = false;
|
||||
return {
|
||||
response: {
|
||||
ok: true,
|
||||
body: { getReader() { throw new Error( 'Do not read the original response.' ); } },
|
||||
clone: () => ( {
|
||||
body: { getReader: () => ( {
|
||||
async read() {
|
||||
const value = chunks[ reads++ ];
|
||||
return value ? { value, done: false } : { done: true };
|
||||
},
|
||||
cancel() {
|
||||
canceled = true;
|
||||
// A real tee's cancel can wait for its other branch.
|
||||
return new Promise( () => {} );
|
||||
},
|
||||
} ) },
|
||||
} ),
|
||||
},
|
||||
get reads() { return reads; },
|
||||
get canceled() { return canceled; },
|
||||
};
|
||||
}
|
||||
|
||||
test( 'pretty-printed v1 reads dimensions before stdout and does not await tee cancellation', async () => {
|
||||
const encode = new TextEncoder();
|
||||
const stream = chunkedResponse( [
|
||||
encode.encode( '{\n "version": 1,\n "width": 104,\n' ),
|
||||
encode.encode( ' "height": 28,\n "stdout": [\n' ),
|
||||
encode.encode( `[0,${ JSON.stringify( 'output'.repeat( MAX_HEADER_BYTES ) ) }]]}` ),
|
||||
] );
|
||||
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 104, rows: 28 } );
|
||||
assert.equal( stream.reads, 2 );
|
||||
assert.equal( stream.canceled, true );
|
||||
} );
|
||||
|
||||
test( 'streaming JSON handles split UTF-8, escapes and nested objects without false fields', async () => {
|
||||
const text = JSON.stringify( { title: '尺寸 \\ " }, \\ ', env: { width: 300, height: 500 }, width: 137, height: 47, version: 1, stdout: [] } );
|
||||
const chunks = Array.from( new TextEncoder().encode( text ), ( value ) => Uint8Array.of( value ) );
|
||||
const stream = chunkedResponse( chunks );
|
||||
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 137, rows: 47 } );
|
||||
assert.ok( stream.reads < chunks.length );
|
||||
assert.equal( stream.canceled, true );
|
||||
} );
|
||||
|
||||
test( 'headers over the byte limit stay unknown without draining the recording', async () => {
|
||||
const encode = new TextEncoder();
|
||||
const stream = chunkedResponse( [
|
||||
encode.encode( '{"version":2,"title":"' + 'x'.repeat( MAX_HEADER_BYTES ) ),
|
||||
encode.encode( '","width":132,"height":43}\n[1,"o","hello"]' ),
|
||||
] );
|
||||
assert.equal( await readRecordingSize( stream.response ), null );
|
||||
assert.equal( stream.reads, 1 );
|
||||
assert.equal( stream.canceled, true );
|
||||
} );
|
||||
|
||||
test( 'byte limit accepts a complete header at its boundary and ignores larger output chunks', async () => {
|
||||
const base = '{"version":2,"width":132,"height":43,"title":"';
|
||||
const header = base + 'x'.repeat( MAX_HEADER_BYTES - base.length - 2 ) + '"}';
|
||||
const stream = chunkedResponse( [ new TextEncoder().encode( header + '\n[1,"o","' + 'x'.repeat( MAX_HEADER_BYTES ) + '"]' ) ] );
|
||||
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 132, rows: 43 } );
|
||||
assert.equal( stream.reads, 1 );
|
||||
} );
|
||||
|
||||
test( 'invalid JSON, nested lookalikes and incomplete dimensions never become defaults', async () => {
|
||||
for ( const text of [ '', 'not a cast', '<html>error</html>', '[]', '{}', '{"version":2,"env":{"width":80,"height":24}}', '{"version":2,"width":80,"height":24,}', '{"version":2,,"width":80,"height":24}', '{"version":2,"width":80,"height":24]', '{"version":2,"width":80,"height":24', '{"version":3,"term":{"cols":80}}' ] ) {
|
||||
const response = new Response( text );
|
||||
assert.equal( await readRecordingSize( response ), null, text );
|
||||
await response.text();
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'failed responses, unavailable streams and rejected reads quietly stay unknown', async () => {
|
||||
assert.equal( await readRecordingSize( { ok: false } ), null );
|
||||
assert.equal( await readRecordingSize( { ok: true, body: null } ), null );
|
||||
assert.equal( await readRecordingSize( { ok: true, body: { getReader() {} }, clone() { throw new Error( 'locked' ); } } ), null );
|
||||
const broken = chunkedResponse( [] );
|
||||
broken.response.clone = () => ( { body: { getReader: () => ( { read: () => Promise.reject( new Error( 'aborted' ) ), cancel: () => Promise.reject( new Error( 'aborted' ) ) } ) } } );
|
||||
assert.equal( await readRecordingSize( broken.response ), null );
|
||||
} );
|
||||
@@ -17,6 +17,39 @@ function ap_record( $key, $value ) {
|
||||
function add_action( $hook, $callback, $priority = 10 ) {
|
||||
ap_record( 'actions', array( $hook, $callback, $priority ) );
|
||||
}
|
||||
function add_filter( $hook, $callback, $priority = 10, $accepted_args = 1 ) {
|
||||
ap_record( 'filters', array( $hook, $callback, $priority, $accepted_args ) );
|
||||
}
|
||||
function __( $text, $domain = 'default' ) {
|
||||
return $text;
|
||||
}
|
||||
function current_user_can( $capability ) {
|
||||
return ! empty( $GLOBALS['ap_test']['capabilities'][ $capability ] );
|
||||
}
|
||||
function user_can( $user, $capability ) {
|
||||
return ! empty( $GLOBALS['ap_test']['user_capabilities'][ $user ][ $capability ] );
|
||||
}
|
||||
function is_multisite() {
|
||||
return ! empty( $GLOBALS['ap_test']['multisite'] );
|
||||
}
|
||||
function get_site_option( $key, $default = false ) {
|
||||
return $GLOBALS['ap_test']['site_options'][ $key ] ?? $default;
|
||||
}
|
||||
function get_allowed_mime_types() {
|
||||
return $GLOBALS['ap_test']['allowed_mimes'] ?? LamGC\Asciiplayer\allow_cast_upload_mime( array( 'txt' => 'text/plain', 'jpg' => 'image/jpeg' ) );
|
||||
}
|
||||
function wp_check_filetype( $filename, $mimes = null ) {
|
||||
// Mirrors core's empty-map fallback to cover explicit MIME deny-lists.
|
||||
if ( empty( $mimes ) ) {
|
||||
$mimes = get_allowed_mime_types();
|
||||
}
|
||||
foreach ( $mimes as $extension => $mime ) {
|
||||
if ( preg_match( '/\.(' . $extension . ')$/i', $filename, $matches ) ) {
|
||||
return array( 'ext' => $matches[1], 'type' => $mime );
|
||||
}
|
||||
}
|
||||
return array( 'ext' => false, 'type' => false );
|
||||
}
|
||||
function add_shortcode( $tag, $callback ) {
|
||||
ap_record( 'shortcodes', array( $tag, $callback ) );
|
||||
}
|
||||
|
||||
+4
-2
@@ -60,8 +60,8 @@ try {
|
||||
same( array( 'lamgc-asciiplayer-player-style' ), $GLOBALS['ap_test']['styles']['lamgc-asciiplayer-style']['deps'], 'Frontend style depends on player stylesheet.' );
|
||||
contains( 'window.wpAsciiplayerSettings = ', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Editor iframe receives trusted runtime URLs.' );
|
||||
same( 'before', $GLOBALS['ap_test']['inline_scripts'][0]['position'], 'Settings are available before editor boot.' );
|
||||
contains( 'player.js?ver=1.2.1', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge JavaScript cache-buster matches registered asset version.' );
|
||||
contains( 'player.css?ver=1.2.1', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge CSS cache-buster matches registered asset version.' );
|
||||
contains( 'player.js?ver=1.2.2', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge JavaScript cache-buster matches registered asset version.' );
|
||||
contains( 'player.css?ver=1.2.2', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge CSS cache-buster matches registered asset version.' );
|
||||
|
||||
// Source validation covers script, HTML, credential and relative-URL attacks.
|
||||
foreach ( array( '', 'javascript:alert(1)', 'data:text/html,test', 'file:///tmp/a.cast', '//evil.test/a.cast', '/\\evil.test/a.cast', "https://example.test/a\n.cast", 'https://x.test/" onmouseover="alert(1)', 'https://user:[email protected]/a.cast', 'https:///a.cast', 'a.cast', array( 'bad' ) ) as $source ) {
|
||||
@@ -170,6 +170,8 @@ try {
|
||||
print_late_styles();
|
||||
same( array( 'lamgc-asciiplayer-style' ), $GLOBALS['ap_test']['style_print_calls'], 'Late/widget styles print once in the footer.' );
|
||||
|
||||
require __DIR__ . '/uploads.php';
|
||||
|
||||
echo "OK: {$assertions} assertions passed.\n";
|
||||
} catch ( Throwable $error ) {
|
||||
fwrite( STDERR, $error->getMessage() . "\n" );
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
/** Upload validation contracts. Included by run.php after its assertion helpers. */
|
||||
|
||||
use function LamGC\Asciiplayer\allow_cast_upload_mime;
|
||||
use function LamGC\Asciiplayer\check_cast_filetype;
|
||||
use function LamGC\Asciiplayer\is_valid_cast_file;
|
||||
use function LamGC\Asciiplayer\validate_cast_upload;
|
||||
|
||||
use const LamGC\Asciiplayer\CAST_MAX_BYTES;
|
||||
use const LamGC\Asciiplayer\CAST_MAX_EVENTS;
|
||||
use const LamGC\Asciiplayer\CAST_MAX_LINE_BYTES;
|
||||
use const LamGC\Asciiplayer\CAST_MAX_V1_BYTES;
|
||||
use const LamGC\Asciiplayer\CAST_MIME;
|
||||
|
||||
function cast_contents_are_valid( $contents ) {
|
||||
$path = tempnam( sys_get_temp_dir(), 'ap-cast-' );
|
||||
try {
|
||||
file_put_contents( $path, $contents );
|
||||
return is_valid_cast_file( $path );
|
||||
} finally {
|
||||
unlink( $path );
|
||||
}
|
||||
}
|
||||
|
||||
$required_filters = array(
|
||||
'upload_mimes' => array( 'LamGC\\Asciiplayer\\allow_cast_upload_mime', 2 ),
|
||||
'wp_check_filetype_and_ext' => array( 'LamGC\\Asciiplayer\\check_cast_filetype', 5 ),
|
||||
'wp_handle_upload_prefilter' => array( 'LamGC\\Asciiplayer\\validate_cast_upload', 1 ),
|
||||
'wp_handle_sideload_prefilter' => array( 'LamGC\\Asciiplayer\\validate_cast_upload', 1 ),
|
||||
);
|
||||
foreach ( $GLOBALS['ap_test']['filters'] ?? array() as $filter ) {
|
||||
if ( isset( $required_filters[ $filter[0] ] ) ) {
|
||||
same( $required_filters[ $filter[0] ][0], $filter[1], 'Upload hook uses the intended callback.' );
|
||||
same( $required_filters[ $filter[0] ][1], $filter[3], 'Upload hook receives all required arguments.' );
|
||||
same( true, is_callable( $filter[1] ), 'Upload callback is callable.' );
|
||||
unset( $required_filters[ $filter[0] ] );
|
||||
}
|
||||
}
|
||||
same( array(), $required_filters, 'All safe-upload hooks are registered.' );
|
||||
|
||||
$mimes = array( 'jpg|jpeg' => 'image/jpeg', 'txt' => 'text/plain' );
|
||||
same( $mimes, allow_cast_upload_mime( $mimes ), 'Anonymous/non-uploaders get no extra MIME permissions.' );
|
||||
$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true );
|
||||
same( array_merge( $mimes, array( 'cast' => CAST_MIME ) ), allow_cast_upload_mime( $mimes ), 'Only .cast receives the canonical MIME.' );
|
||||
same( $mimes, allow_cast_upload_mime( $mimes, 42 ), 'Explicit non-uploading user does not inherit current user permissions.' );
|
||||
$GLOBALS['ap_test']['user_capabilities'][42] = array( 'upload_files' => true );
|
||||
same( CAST_MIME, allow_cast_upload_mime( $mimes, 42 )['cast'], 'An explicit eligible user can upload casts.' );
|
||||
$GLOBALS['ap_test']['multisite'] = true;
|
||||
$GLOBALS['ap_test']['site_options']['upload_filetypes'] = 'jpg jpeg txt';
|
||||
same( $mimes, allow_cast_upload_mime( $mimes ), 'Multisite network extension restrictions remain in effect.' );
|
||||
$GLOBALS['ap_test']['site_options']['upload_filetypes'] = "jpg\ncast txt";
|
||||
same( CAST_MIME, allow_cast_upload_mime( $mimes )['cast'], 'Network-authorized cast uploads are available.' );
|
||||
$GLOBALS['ap_test']['multisite'] = false;
|
||||
|
||||
$v2 = '{"version":2,"width":80,"height":24}';
|
||||
$v3 = '{"version":3,"term":{"cols":100,"rows":30}}';
|
||||
$v1 = array( 'version' => 1, 'width' => 80, 'height' => 24, 'duration' => 1.5, 'stdout' => array( array( 0.1, "Hello\r\n" ), array( 1.4, 'World' ) ) );
|
||||
foreach ( array(
|
||||
'pretty v1' => json_encode( $v1, JSON_PRETTY_PRINT ),
|
||||
'v2 output' => $v2 . "\n[0.1,\"o\",\"Hello\\r\\n\"]\n",
|
||||
'v3 relative events' => $v3 . "\n[5,\"o\",\"Hello\"]\n[0.1,\"r\",\"120x40\"]\n[0,\"x\",\"0\"]\n",
|
||||
'v3 comments' => $v3 . "\n# comment before events\n[0,\"o\",\"ok\"]\n# trailing comment\n",
|
||||
'v2 input markers resize extensions' => $v2 . "\n[0,\"i\",\"x\"]\n[0,\"m\",\"A\"]\n[1,\"r\",\"90x25\"]\n[1,\"future\",\"data\"]",
|
||||
'CRLF' => $v2 . "\r\n[0,\"o\",\"hello\"]\r\n",
|
||||
'header only' => $v2,
|
||||
'unknown header fields' => '{"version":2,"width":80,"height":24,"future":{"key":true}}' . "\n[0,\"o\",\"ok\"]\n",
|
||||
'literal terminal markup' => $v2 . "\n[0,\"o\",\"<script> is plain terminal output</script>\"]\n",
|
||||
) as $description => $contents ) {
|
||||
same( true, cast_contents_are_valid( $contents ), 'Accept valid ' . $description . '.' );
|
||||
}
|
||||
same( true, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/hello.cast' ), 'Accept repository hello recording.' );
|
||||
same( true, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/resize.cast' ), 'Accept repository resize recording.' );
|
||||
|
||||
foreach ( array(
|
||||
'empty' => '',
|
||||
'plain text' => 'Hello world',
|
||||
'JSON object' => '{"message":"arbitrary JSON"}',
|
||||
'JSON list' => '[1,2,3]',
|
||||
'HTML' => '<!doctype html><script>alert(1)</script>',
|
||||
'SVG' => '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>',
|
||||
'unsupported version' => '{"version":4,"width":80,"height":24}',
|
||||
'string version' => '{"version":"2","width":80,"height":24}',
|
||||
'zero width' => '{"version":2,"width":0,"height":24}',
|
||||
'oversized width' => '{"version":2,"width":1001,"height":24}',
|
||||
'negative height' => '{"version":2,"width":80,"height":-1}',
|
||||
'fractional width' => '{"version":2,"width":80.5,"height":24}',
|
||||
'string width' => '{"version":2,"width":"80","height":24}',
|
||||
'v3 old dimensions' => '{"version":3,"width":80,"height":24}',
|
||||
'v3 terminal array' => '{"version":3,"term":[100,30]}',
|
||||
'v1 absent stdout' => "{\n\"version\":1,\"width\":80,\"height\":24\n}",
|
||||
'v1 stdout object' => "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":{\"0\":[0,\"x\"]}\n}",
|
||||
'compact v1 unsupported by bundled player' => json_encode( $v1 ),
|
||||
'large compact v1 unsupported by bundled player' => json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_LINE_BYTES + 1 ) ) ) ),
|
||||
'v1 negative delay' => json_encode( array_merge( $v1, array( 'stdout' => array( array( -1, 'x' ) ) ) ), JSON_PRETTY_PRINT ),
|
||||
'v1 malformed later frame' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok' ), array( 0, array( 'x' ) ) ) ) ), JSON_PRETTY_PRINT ),
|
||||
'v1 extra frame element' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok', 'extra' ) ) ) ), JSON_PRETTY_PRINT ),
|
||||
'v1 bad duration' => json_encode( array_merge( $v1, array( 'duration' => '1' ) ), JSON_PRETTY_PRINT ),
|
||||
'negative event time' => $v2 . "\n[-1,\"o\",\"bad\"]\n",
|
||||
'string event time' => $v2 . "\n[\"0\",\"o\",\"bad\"]\n",
|
||||
'boolean event time' => $v2 . "\n[false,\"o\",\"bad\"]\n",
|
||||
'infinite time' => $v2 . "\n[1e999,\"o\",\"bad\"]\n",
|
||||
'milliseconds overflow' => $v2 . "\n[1e308,\"o\",\"bad\"]\n",
|
||||
'v3 cumulative milliseconds overflow' => $v3 . "\n[1e305,\"o\",\"first\"]\n[1e305,\"o\",\"second\"]\n",
|
||||
'v2 out of order' => $v2 . "\n[2,\"o\",\"first\"]\n[1,\"o\",\"second\"]\n",
|
||||
'event object' => $v2 . "\n{\"0\":0,\"1\":\"o\",\"2\":\"bad\"}\n",
|
||||
'missing event data' => $v2 . "\n[0,\"o\"]\n",
|
||||
'extra event element' => $v2 . "\n[0,\"o\",\"bad\",1]\n",
|
||||
'event data array' => $v2 . "\n[0,\"o\",[\"bad\"]]\n",
|
||||
'empty event type' => $v2 . "\n[0,\"\",\"bad\"]\n",
|
||||
'zero resize' => $v2 . "\n[0,\"r\",\"0x20\"]\n",
|
||||
'oversized resize' => $v2 . "\n[0,\"r\",\"2000x20\"]\n",
|
||||
'malformed resize' => $v2 . "\n[0,\"r\",\"80,24\"]\n",
|
||||
'bad later JSON' => $v2 . "\n[0,\"o\",\"ok\"]\n[1,\"o\",\"truncated\"\n",
|
||||
'trailing HTML' => $v2 . "\n[0,\"o\",\"ok\"]\n<script>alert(1)</script>\n",
|
||||
'trailing JSON object' => $v2 . "\n[0,\"o\",\"ok\"]\n{\"unrelated\":true}\n",
|
||||
'blank event line' => $v2 . "\n\n",
|
||||
'indented event ignored by bundled player' => $v2 . "\n [0,\"o\",\"invisible\"]\n",
|
||||
'v2 comment' => $v2 . "\n# comment\n",
|
||||
'v3 indented comment' => $v3 . "\n # not a comment\n",
|
||||
'UTF-8 BOM' => "\xef\xbb\xbf" . $v2,
|
||||
'invalid UTF-8' => $v2 . "\n[0,\"o\",\"\xff\"]\n",
|
||||
'oversized JSONL line' => $v2 . "\n[0,\"o\",\"" . str_repeat( 'a', CAST_MAX_LINE_BYTES ) . "\"]\n",
|
||||
'oversized comment line' => $v3 . "\n#" . str_repeat( 'a', CAST_MAX_LINE_BYTES ) . "\n",
|
||||
'deep JSON' => $v2 . "\n[0,\"o\"," . str_repeat( '[', 20 ) . '0' . str_repeat( ']', 20 ) . "]\n",
|
||||
) as $description => $contents ) {
|
||||
same( false, cast_contents_are_valid( $contents ), 'Reject ' . $description . '.' );
|
||||
}
|
||||
same( false, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/malformed.cast' ), 'Reject repository malformed recording.' );
|
||||
same( false, is_valid_cast_file( '/does-not-exist/asciicast.cast' ), 'Reject missing files.' );
|
||||
same( false, is_valid_cast_file( __DIR__ ), 'Reject directories.' );
|
||||
same( false, is_valid_cast_file( 'data://text/plain,' . $v2 ), 'Reject stream wrappers before opening.' );
|
||||
same( false, is_valid_cast_file( null ), 'Reject missing temporary upload path.' );
|
||||
same( true, cast_contents_are_valid( $v2 . "\n" . str_repeat( "[0,\"o\",\"x\"]\n", CAST_MAX_EVENTS ) ), 'Accept the documented event-count boundary.' );
|
||||
same( false, cast_contents_are_valid( $v2 . "\n" . str_repeat( "[0,\"o\",\"x\"]\n", CAST_MAX_EVENTS + 1 ) ), 'Reject excessive event count.' );
|
||||
same( false, cast_contents_are_valid( json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_V1_BYTES ) ) ), JSON_PRETTY_PRINT ) ), 'Bound whole-document legacy decoding.' );
|
||||
|
||||
$path = tempnam( sys_get_temp_dir(), 'ap-cast-' );
|
||||
try {
|
||||
$handle = fopen( $path, 'wb' );
|
||||
ftruncate( $handle, CAST_MAX_BYTES + 1 );
|
||||
fclose( $handle );
|
||||
same( false, is_valid_cast_file( $path ), 'Reject files over the byte limit before reading their contents.' );
|
||||
file_put_contents( $path, $v2 . "\n[0,\"o\",\"ok\"]\n" );
|
||||
clearstatcache( true, $path );
|
||||
$upload = array( 'name' => 'recording.cast', 'tmp_name' => $path, 'error' => 0, 'type' => 'text/plain', 'size' => 1 );
|
||||
same( $upload, validate_cast_upload( $upload ), 'Valid content passes without trusting or changing browser MIME or size.' );
|
||||
$denied = array( 'ext' => false, 'type' => false, 'proper_filename' => false );
|
||||
$approved = array( 'ext' => 'cast', 'type' => CAST_MIME, 'proper_filename' => false );
|
||||
foreach ( array( 'text/plain', 'application/json', 'application/octet-stream', false ) as $detected_mime ) {
|
||||
same( $approved, check_cast_filetype( $denied, $path, 'recording.cast', null, $detected_mime ), 'Content validation safely handles generic fileinfo guesses.' );
|
||||
}
|
||||
same( $approved, check_cast_filetype( $denied, $path, 'recording.CAST' ), 'Uppercase cast extension is supported.' );
|
||||
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array() ), 'An explicitly empty MIME allow-list stays empty.' );
|
||||
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'txt' => 'text/plain' ) ), 'An explicit MIME allow-list excluding cast remains restricted.' );
|
||||
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'cast' => 'text/plain' ) ), 'Only our canonical allowed type can receive the MIME override.' );
|
||||
$GLOBALS['ap_test']['allowed_mimes'] = array( 'txt' => 'text/plain' );
|
||||
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'cast' => CAST_MIME ) ), 'An explicit allow-list cannot bypass a later global MIME restriction.' );
|
||||
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Prefilter also preserves later global MIME restrictions.' );
|
||||
unset( $GLOBALS['ap_test']['allowed_mimes'] );
|
||||
$unrelated = array( 'ext' => 'svg', 'type' => 'image/svg+xml', 'proper_filename' => 'x.svg' );
|
||||
foreach ( array( 'x.json', 'x.html', 'x.svg', 'x.cast.php', "x.cast\n" ) as $filename ) {
|
||||
same( $unrelated, check_cast_filetype( $unrelated, $path, $filename ), 'Other extensions and double-extension executables remain untouched.' );
|
||||
}
|
||||
same( true, is_string( validate_cast_upload( array_merge( $upload, array( 'tmp_name' => '/missing' ) ) )['error'] ), 'Missing temporary upload fails closed.' );
|
||||
$GLOBALS['ap_test']['capabilities'] = array();
|
||||
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Upload permissions are enforced for valid content too.' );
|
||||
same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'MIME override never grants upload capability.' );
|
||||
$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true, 'unfiltered_upload' => true );
|
||||
file_put_contents( $path, $v2 . "\n<script>alert(1)</script>\n" );
|
||||
clearstatcache( true, $path );
|
||||
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Malformed content fails even with unfiltered_upload.' );
|
||||
same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'Invalid content cannot keep a previous MIME approval.' );
|
||||
$other_upload = array_merge( $upload, array( 'name' => 'ordinary.txt' ) );
|
||||
same( $other_upload, validate_cast_upload( $other_upload ), 'Other extensions keep core upload behavior.' );
|
||||
$existing_error = array_merge( $upload, array( 'error' => 'Rejected by another plugin.' ) );
|
||||
same( $existing_error, validate_cast_upload( $existing_error ), 'Existing upload errors are preserved.' );
|
||||
$php_error = array_merge( $upload, array( 'error' => 3 ) );
|
||||
same( $php_error, validate_cast_upload( $php_error ), 'PHP partial-upload errors are preserved.' );
|
||||
} finally {
|
||||
unlink( $path );
|
||||
}
|
||||
|
||||
unset( $GLOBALS['ap_test']['capabilities'], $GLOBALS['ap_test']['user_capabilities'], $GLOBALS['ap_test']['multisite'], $GLOBALS['ap_test']['site_options'], $GLOBALS['ap_test']['allowed_mimes'] );
|
||||
Reference in New Issue
Block a user