367 lines
15 KiB
JavaScript
367 lines
15 KiB
JavaScript
'use strict';
|
|
// Paste-mirroring functional test for the Browser Farm grid.
|
|
//
|
|
// Loads the REAL manager/public/index.html in jsdom, stubs the manager
|
|
// API, injects a fake Neko overlay (wrap div holding a <canvas> and a
|
|
// transparent <textarea>, exactly like the Neko client) into each cell
|
|
// iframe, then proves:
|
|
// T1 a paste in the master dispatches a paste with the SAME text into
|
|
// all 7 followers (read back the way Neko's Overlay reads it:
|
|
// e.clipboardData.getData('text/plain')), with no feedback loop
|
|
// T2 the pasted-into cell becomes Master
|
|
// T3 paste mirroring stops when Sync is OFF, and a real (untrusted)
|
|
// paste event never mirrors (loop prevention)
|
|
// T4 an empty / missing clipboardData pastes nothing into followers
|
|
// T5 (regression) keydown mirroring still works
|
|
// T6 fallback path: a follower whose window lacks ClipboardEvent and
|
|
// DataTransfer still receives the text
|
|
// T7 the Neko input selector finds the overlay textarea, not a decoy
|
|
//
|
|
// Why the test drives the grid through an instrumented copy: jsdom
|
|
// cannot produce a trusted event — every event it creates has
|
|
// isTrusted=false (a non-configurable own property), and its
|
|
// dispatchEvent rejects Proxy-wrapped events. The grid's sync handler
|
|
// only mirrors trusted (real user) input, so a real DOM paste can never
|
|
// reach the mirroring code in jsdom. The test therefore loads an
|
|
// instrumented copy of the page (the production file is NOT modified:
|
|
// the script is the same, plus one export line exposing the sync
|
|
// functions) and invokes the handler with mock trusted events, while
|
|
// the DOM wiring (cells, iframes, input detection, listener attach) is
|
|
// exercised for real. A real untrusted DOM paste is also dispatched to
|
|
// prove the isTrusted gate blocks it.
|
|
//
|
|
// jsdom (v31) does not implement ClipboardEvent or DataTransfer, so the
|
|
// test polyfills them on every window (top + each iframe) to simulate a
|
|
// real Chrome. The grid code itself does not depend on the polyfill: it
|
|
// falls back to a plain Event + a clipboardData-like object when the
|
|
// constructors are missing (see T6).
|
|
//
|
|
// Run: node paste-sync-test.js (from this directory)
|
|
// Exit code 0 = all assertions passed, 1 = at least one failed.
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { JSDOM } = require('jsdom');
|
|
|
|
const HTML_PATH = path.join(__dirname, '..', 'manager', 'public', 'index.html');
|
|
|
|
let pass = 0;
|
|
let fail = 0;
|
|
const failures = [];
|
|
function check(name, cond, detail) {
|
|
if (cond) {
|
|
pass++;
|
|
console.log(' PASS ' + name);
|
|
} else {
|
|
fail++;
|
|
failures.push(name);
|
|
console.log(' FAIL ' + name + (detail ? ' (' + detail + ')' : ''));
|
|
}
|
|
}
|
|
|
|
// Minimal ClipboardEvent / DataTransfer, enough to stand in for Chrome's.
|
|
// Neko's Overlay only calls clipboardData.getData('text/plain').
|
|
function installClipboardPolyfill(win) {
|
|
if (typeof win.DataTransfer !== 'function') {
|
|
win.DataTransfer = class DataTransfer {
|
|
constructor() {
|
|
this._data = {};
|
|
}
|
|
setData(type, value) {
|
|
this._data[type] = String(value);
|
|
}
|
|
getData(type) {
|
|
return this._data[type] || '';
|
|
}
|
|
get types() {
|
|
return Object.keys(this._data);
|
|
}
|
|
};
|
|
}
|
|
if (typeof win.ClipboardEvent !== 'function') {
|
|
win.ClipboardEvent = class ClipboardEvent extends win.Event {
|
|
constructor(type, init) {
|
|
super(type, init);
|
|
this.clipboardData = (init && init.clipboardData) || null;
|
|
}
|
|
};
|
|
}
|
|
}
|
|
|
|
function sleep(ms) {
|
|
return new Promise((r) => setTimeout(r, ms));
|
|
}
|
|
|
|
const BROWSERS = [];
|
|
for (let i = 1; i <= 8; i++) {
|
|
BROWSERS.push({
|
|
id: 'b' + i,
|
|
name: 'Browser ' + i,
|
|
uaKey: 'chrome_win',
|
|
uaLabel: 'Chrome Windows',
|
|
proxy: { type: 'direct' },
|
|
httpPort: 18080 + i,
|
|
udpStart: 52000 + (i - 1) * 100,
|
|
udpEnd: 52000 + (i - 1) * 100 + 99,
|
|
status: 'running',
|
|
token: 'tok-b' + i,
|
|
});
|
|
}
|
|
|
|
async function main() {
|
|
const html = fs.readFileSync(HTML_PATH, 'utf8');
|
|
|
|
// Instrumented copy: the production script, plus one export line so
|
|
// the test can drive the sync handler with mock trusted events (see
|
|
// the header comment for why jsdom cannot dispatch a trusted event).
|
|
// The production file is left untouched.
|
|
const scriptMatch = html.match(/<script>([\s\S]*?)<\/script>/);
|
|
if (!scriptMatch) throw new Error('no <script> in index.html');
|
|
const script = scriptMatch[1];
|
|
const exportLine =
|
|
'\n window.__farmTest = { cells: cells, onCellInput: onCellInput, mirrorInput: mirrorInput, ' +
|
|
'setSync: setSync, setMaster: setMaster, clearMaster: clearMaster, ' +
|
|
'findNekoInput: findNekoInput, attachSyncListeners: attachSyncListeners, ' +
|
|
'getSyncOn: function () { return syncOn; }, getMasterId: function () { return masterId; } };';
|
|
if (!script.includes('\n checkAuth();\n})();')) throw new Error('script ending not found for instrumentation');
|
|
const instrumented = script.replace('\n checkAuth();\n})();', '\n checkAuth();' + exportLine + '\n})();');
|
|
const testHtml = html.replace(scriptMatch[0], '<script>' + instrumented + '</script>');
|
|
|
|
const dom = new JSDOM(testHtml, {
|
|
url: 'http://localhost/',
|
|
runScripts: 'dangerously',
|
|
pretendToBeVisual: true,
|
|
beforeParse(window) {
|
|
installClipboardPolyfill(window);
|
|
// Stub the manager API: authenticated, one UA preset, 8 running
|
|
// browsers with tokens (so every cell auto-connects).
|
|
window.fetch = (url) => {
|
|
if (url === '/api/me') {
|
|
return Promise.resolve({ json: () => Promise.resolve({ authenticated: true }) });
|
|
}
|
|
if (url === '/api/ua-presets') {
|
|
return Promise.resolve({
|
|
json: () => Promise.resolve({ presets: { chrome_win: { label: 'Chrome Windows', ua: 'x' } } }),
|
|
});
|
|
}
|
|
if (url === '/api/browsers') {
|
|
return Promise.resolve({ json: () => Promise.resolve({ browsers: BROWSERS }) });
|
|
}
|
|
return Promise.reject(new Error('unexpected fetch: ' + url));
|
|
};
|
|
},
|
|
});
|
|
const win = dom.window;
|
|
const doc = win.document;
|
|
const farm = win.__farmTest;
|
|
if (!farm) throw new Error('instrumentation failed: __farmTest missing');
|
|
|
|
// Wait for checkAuth -> startGrid -> loadPresets -> refresh to build the cells.
|
|
await sleep(300);
|
|
const cells = {};
|
|
for (let i = 1; i <= 8; i++) {
|
|
const id = 'b' + i;
|
|
const iframe = doc.querySelector('#cell-' + id + ' iframe');
|
|
if (!iframe) throw new Error('cell ' + id + ' did not build');
|
|
cells[id] = { iframe };
|
|
}
|
|
check('grid builds 8 cells', Object.keys(cells).length === 8);
|
|
|
|
// Inject a fake Neko overlay into each iframe and record what Neko
|
|
// would receive: a 'paste' listener that reads clipboardData exactly
|
|
// like Overlay.onPaste does, plus counters for loop detection.
|
|
for (let i = 1; i <= 8; i++) {
|
|
const id = 'b' + i;
|
|
const iframe = cells[id].iframe;
|
|
const idoc = iframe.contentDocument;
|
|
const iwin = idoc.defaultView;
|
|
installClipboardPolyfill(iwin);
|
|
// The iframe's document is stuck in 'loading' with no root element
|
|
// (jsdom never fetches the /bN/ URL). Initialise it with a minimal
|
|
// skeleton so the fake overlay has a <body> to live in; the pending
|
|
// navigation does not replace the document afterwards (verified).
|
|
idoc.open();
|
|
idoc.write('<!DOCTYPE html><html><head></head><body></body></html>');
|
|
idoc.close();
|
|
const wrap = idoc.createElement('div');
|
|
const canvas = idoc.createElement('canvas');
|
|
const ta = idoc.createElement('textarea');
|
|
wrap.appendChild(canvas);
|
|
wrap.appendChild(ta);
|
|
idoc.body.appendChild(wrap);
|
|
cells[id].ta = ta;
|
|
cells[id].iwin = iwin;
|
|
cells[id].nekoPastes = []; // texts the fake Neko handler read
|
|
cells[id].pasteCount = 0; // every paste event seen on this textarea
|
|
cells[id].keys = []; // keydown keys seen on this textarea
|
|
ta.addEventListener('paste', (e) => {
|
|
cells[id].pasteCount++;
|
|
const t = e.clipboardData ? e.clipboardData.getData('text/plain') : '';
|
|
cells[id].nekoPastes.push(t);
|
|
});
|
|
ta.addEventListener('keydown', (e) => {
|
|
cells[id].keys.push(e.key);
|
|
});
|
|
// Trigger the grid's pollForInput (it runs on iframe load).
|
|
iframe.dispatchEvent(new win.Event('load'));
|
|
}
|
|
|
|
// The grid polls every 500ms for the Neko input; give it time to find
|
|
// the injected textareas and attach the Sync listeners.
|
|
await sleep(900);
|
|
const attached = Object.keys(farm.cells).filter((id) => farm.cells[id].inputEl).length;
|
|
check('grid found the Neko input in all 8 cells', attached === 8, 'found in ' + attached + '/8');
|
|
|
|
const syncBtn = doc.getElementById('syncBtn');
|
|
function setSync(on) {
|
|
if ((syncBtn.textContent === 'Sinkron: ON') !== on) syncBtn.click();
|
|
}
|
|
function masterBadgeVisible(id) {
|
|
const b = doc.querySelector('#cell-' + id + ' .badge.master');
|
|
return b && b.style.display !== 'none';
|
|
}
|
|
// Mock trusted events (plain objects): the grid's handler only reads
|
|
// these fields, and jsdom cannot create a trusted event. The
|
|
// clipboardData is a real DataTransfer from the master's window.
|
|
function mockPaste(text, opts) {
|
|
const o = opts || {};
|
|
let dt = null;
|
|
if (!o.noClipboardData) {
|
|
dt = new cells.b1.iwin.DataTransfer();
|
|
if (text) dt.setData('text/plain', text);
|
|
}
|
|
return { type: 'paste', isTrusted: true, clipboardData: dt };
|
|
}
|
|
function mockKey(key, code, keyCode) {
|
|
return {
|
|
type: 'keydown', isTrusted: true, key, code, location: 0,
|
|
ctrlKey: false, shiftKey: false, altKey: false, metaKey: false,
|
|
repeat: false, keyCode, which: keyCode,
|
|
};
|
|
}
|
|
function followerPastes() {
|
|
const out = {};
|
|
for (let i = 2; i <= 8; i++) out['b' + i] = cells['b' + i].nekoPastes.slice();
|
|
return out;
|
|
}
|
|
|
|
// ---- T7: the input selector finds the overlay textarea, not a decoy ----
|
|
console.log('T7: input selector vs decoy');
|
|
const decoy = cells.b1.ta.ownerDocument.createElement('textarea');
|
|
decoy.setAttribute('placeholder', 'chat');
|
|
cells.b1.ta.ownerDocument.body.appendChild(decoy); // no canvas parent: a chat box, not the Neko input
|
|
const found = farm.findNekoInput(cells.b1.ta.ownerDocument);
|
|
check('findNekoInput returns the overlay textarea, not the decoy', found === cells.b1.ta);
|
|
|
|
// ---- T1: paste in the master reaches all 7 followers with the same text ----
|
|
console.log('T1: paste mirrors to all followers');
|
|
setSync(true);
|
|
check('Sync ON', syncBtn.textContent === 'Sinkron: ON');
|
|
farm.onCellInput('b1', mockPaste('hello paste'));
|
|
await sleep(50);
|
|
// The master itself does not get a re-dispatched paste (only its own
|
|
// real one, which the mock stands in for — so it stays empty here).
|
|
let allSame = true;
|
|
let allOnce = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
const c = cells['b' + i];
|
|
if (JSON.stringify(c.nekoPastes) !== JSON.stringify(['hello paste'])) allSame = false;
|
|
if (c.pasteCount !== 1) allOnce = false;
|
|
}
|
|
check('all 7 followers received the same text', allSame, JSON.stringify(followerPastes()));
|
|
check('no feedback loop (each follower saw exactly 1 paste)', allOnce,
|
|
Object.keys(followerPastes()).map((k) => k + ':' + cells[k].pasteCount).join(' '));
|
|
|
|
// ---- T2: the pasted-into cell becomes Master ----
|
|
console.log('T2: master selection');
|
|
check('b1 is Master after pasting', masterBadgeVisible('b1'));
|
|
check('b2 is not Master', !masterBadgeVisible('b2'));
|
|
|
|
// ---- T3: Sync OFF stops mirroring; real untrusted paste never mirrors ----
|
|
console.log('T3: Sync OFF + untrusted gate');
|
|
setSync(false);
|
|
check('Sync OFF', syncBtn.textContent === 'Sinkron: OFF');
|
|
farm.onCellInput('b1', mockPaste('second paste'));
|
|
await sleep(50);
|
|
let noneNew = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) noneNew = false;
|
|
}
|
|
check('followers received nothing new while OFF', noneNew, JSON.stringify(followerPastes()));
|
|
// A real paste event dispatched on the master's textarea is untrusted
|
|
// in jsdom (as any synthetic event is in a real browser too): the
|
|
// grid's listener must ignore it, so nothing mirrors.
|
|
setSync(true);
|
|
const realPaste = new cells.b1.iwin.ClipboardEvent('paste', {
|
|
bubbles: true, cancelable: true, clipboardData: (() => {
|
|
const dt = new cells.b1.iwin.DataTransfer();
|
|
dt.setData('text/plain', 'real dom paste');
|
|
return dt;
|
|
})(),
|
|
});
|
|
cells.b1.ta.dispatchEvent(realPaste);
|
|
await sleep(50);
|
|
let stillOnlyFirst = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) stillOnlyFirst = false;
|
|
}
|
|
check('real untrusted DOM paste mirrors nothing (loop prevention)', stillOnlyFirst,
|
|
JSON.stringify(followerPastes()));
|
|
check('master got its own real paste', JSON.stringify(cells.b1.nekoPastes) === JSON.stringify(['real dom paste']),
|
|
'got ' + JSON.stringify(cells.b1.nekoPastes));
|
|
|
|
// ---- T4: empty / missing clipboardData pastes nothing ----
|
|
console.log('T4: empty clipboard does nothing');
|
|
farm.onCellInput('b1', mockPaste('')); // empty DataTransfer: getData -> ''
|
|
await sleep(50);
|
|
let emptyOk = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) emptyOk = false;
|
|
}
|
|
check('empty text pastes nothing into followers', emptyOk, JSON.stringify(followerPastes()));
|
|
farm.onCellInput('b1', mockPaste('ignored', { noClipboardData: true })); // clipboardData null
|
|
await sleep(50);
|
|
let nullOk = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) nullOk = false;
|
|
}
|
|
check('null clipboardData pastes nothing into followers', nullOk, JSON.stringify(followerPastes()));
|
|
|
|
// ---- T5 (regression): keydown mirroring still works ----
|
|
console.log('T5: keydown mirroring regression');
|
|
farm.onCellInput('b1', mockKey('a', 'KeyA', 65));
|
|
await sleep(50);
|
|
let keysOk = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
if (JSON.stringify(cells['b' + i].keys) !== JSON.stringify(['a'])) keysOk = false;
|
|
}
|
|
check('keydown mirrors to all 7 followers', keysOk,
|
|
Object.keys(cells).map((k) => k + ':' + JSON.stringify(cells[k].keys)).join(' '));
|
|
|
|
// ---- T6: fallback when a follower window lacks ClipboardEvent/DataTransfer ----
|
|
console.log('T6: fallback without ClipboardEvent/DataTransfer');
|
|
delete cells.b8.iwin.ClipboardEvent;
|
|
delete cells.b8.iwin.DataTransfer;
|
|
farm.onCellInput('b1', mockPaste('fallback text'));
|
|
await sleep(50);
|
|
check('b8 (no ClipboardEvent/DataTransfer) still received the text',
|
|
JSON.stringify(cells.b8.nekoPastes) === JSON.stringify(['hello paste', 'fallback text']),
|
|
'got ' + JSON.stringify(cells.b8.nekoPastes));
|
|
let othersOk = true;
|
|
for (let i = 2; i <= 7; i++) {
|
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste', 'fallback text'])) othersOk = false;
|
|
}
|
|
check('other followers still received the text', othersOk, JSON.stringify(followerPastes()));
|
|
|
|
// ---- summary ----
|
|
console.log('\n' + pass + ' passed, ' + fail + ' failed');
|
|
if (failures.length) console.log('failed: ' + failures.join(', '));
|
|
dom.window.close();
|
|
process.exit(fail ? 1 : 0);
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error('TEST CRASHED: ' + (e && e.stack ? e.stack : e));
|
|
process.exit(1);
|
|
});
|