288 lines
14 KiB
JavaScript
288 lines
14 KiB
JavaScript
// Browser diagnostics on the actual private HTTPS hosts. Records metadata only.
|
|||
|
|
import {readFile, stat, writeFile} from 'node:fs/promises';
|
||
|
|
import {lookup} from 'node:dns/promises';
|
||
|
|
import {isIP} from 'node:net';
|
||
|
|
import {resolve} from 'node:path';
|
||
|
|
import {probeWebSockets} from '../src/providers/ma/diagnostics.mjs';
|
||
|
|
|
||
|
|
const report = {at: new Date().toISOString(), scope: 'private Nginx HTTPS route', checks: {}};
|
||
|
|
const playback = process.argv.includes('--playback');
|
||
|
|
const layoutOnly = process.argv.includes('--layout-only');
|
||
|
|
const loggedIn = playback || layoutOnly || process.argv.includes('--logged-in');
|
||
|
|
const engine = process.argv.includes('--firefox') ? 'firefox' : 'chromium';
|
||
|
|
const previewModule = process.argv.includes('--preview-module');
|
||
|
|
const expect = (ok, code) => { if (!ok) throw new Error(code); };
|
||
|
|
|
||
|
|
async function privateJSON(name) {
|
||
|
|
const file = `.local/${name}.json`;
|
||
|
|
expect(((await stat(file)).mode & 0o777) === 0o600, 'private-file-mode');
|
||
|
|
return JSON.parse(await readFile(file, 'utf8'));
|
||
|
|
}
|
||
|
|
|
||
|
|
function httpsOrigin(value) {
|
||
|
|
const url = new URL(value);
|
||
|
|
expect(url.protocol === 'https:' && !url.username && !url.password && url.pathname === '/' &&
|
||
|
|
!url.search && !url.hash && (!url.port || url.port === '443') &&
|
||
|
|
/^[a-z0-9.-]+$/i.test(url.hostname) && !isIP(url.hostname), 'invalid-https-origin');
|
||
|
|
return url;
|
||
|
|
}
|
||
|
|
|
||
|
|
async function verifyPrivateResponse(response, origin, proxyIP) {
|
||
|
|
expect(response && new URL(response.url()).origin === origin, 'unexpected-navigation-origin');
|
||
|
|
expect((await response.serverAddr())?.ipAddress === proxyIP, 'unexpected-server-address');
|
||
|
|
expect(await response.securityDetails(), 'missing-tls-details');
|
||
|
|
}
|
||
|
|
|
||
|
|
async function openPrivatePage(page, url, proxyIP) {
|
||
|
|
const response = await page.goto(url.href, {waitUntil: 'domcontentloaded', timeout: 30000});
|
||
|
|
await verifyPrivateResponse(response, url.origin, proxyIP);
|
||
|
|
return response;
|
||
|
|
}
|
||
|
|
|
||
|
|
async function retainBrowserWebSocket(page) {
|
||
|
|
await page.addInitScript(() => {
|
||
|
|
Object.defineProperty(window, '__adaptiveMusicProbeNativeSocket', {value: window.WebSocket});
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
async function collectTransport(page, response, ma) {
|
||
|
|
const headers = await response.allHeaders();
|
||
|
|
const session = engine === 'chromium' ? await page.context().newCDPSession(page) : null;
|
||
|
|
const requests = new Map();
|
||
|
|
const socketResults = [];
|
||
|
|
const failedRequests = [];
|
||
|
|
const policyIssues = [];
|
||
|
|
session?.on('Network.webSocketCreated', ({requestId, url}) => {
|
||
|
|
for (const path of ['/ws', '/sendspin']) {
|
||
|
|
if (url === `wss://${ma.host}${path}`) requests.set(requestId, path);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
session?.on('Network.webSocketHandshakeResponseReceived', ({requestId, response}) => {
|
||
|
|
if (requests.has(requestId)) socketResults.push({path: requests.get(requestId), httpStatus: response.status});
|
||
|
|
});
|
||
|
|
session?.on('Network.loadingFailed', ({requestId, errorText, blockedReason}) => {
|
||
|
|
if (!requests.has(requestId)) return;
|
||
|
|
const error = /^net::ERR_[A-Z0-9_]+$/.test(errorText) ? errorText : null;
|
||
|
|
failedRequests.push({path: requests.get(requestId), error, blockedReason: blockedReason ?? null});
|
||
|
|
});
|
||
|
|
session?.on('Network.webSocketFrameError', ({requestId, errorMessage}) => {
|
||
|
|
if (!requests.has(requestId)) return;
|
||
|
|
const status = errorMessage?.match(/Unexpected response code: (\d{3})/);
|
||
|
|
const error = errorMessage?.match(/\bnet::ERR_[A-Z0-9_]+\b/);
|
||
|
|
if (status || error) failedRequests.push({path: requests.get(requestId), httpStatus: status ? Number(status[1]) : null, error: error?.[0] ?? null});
|
||
|
|
});
|
||
|
|
session?.on('Audits.issueAdded', ({issue}) => {
|
||
|
|
const detail = issue.details?.corsIssueDetails ?? issue.details?.contentSecurityPolicyIssueDetails;
|
||
|
|
const url = detail?.request?.url ?? detail?.blockedURL;
|
||
|
|
if (!URL.canParse(url) || ![ma.origin, `wss://${ma.host}`].includes(new URL(url).origin)) return;
|
||
|
|
policyIssues.push({code: issue.code, reason: detail.corsErrorStatus?.corsError ?? detail.contentSecurityPolicyViolationType});
|
||
|
|
});
|
||
|
|
try {
|
||
|
|
await session?.send('Network.enable');
|
||
|
|
await session?.send('Audits.enable');
|
||
|
|
const details = {
|
||
|
|
pageStatus: response.status(),
|
||
|
|
privatePeerVerified: true,
|
||
|
|
cspHeaderPresent: Boolean(headers['content-security-policy']),
|
||
|
|
reportOnlyCspHeaderPresent: Boolean(headers['content-security-policy-report-only']),
|
||
|
|
cspMetaPresent: await page.locator('meta[http-equiv="Content-Security-Policy" i]').count() > 0,
|
||
|
|
secureContext: await page.evaluate(() => globalThis.isSecureContext),
|
||
|
|
pageReplacesWebSocket: await page.evaluate(() => window.WebSocket !== window.__adaptiveMusicProbeNativeSocket),
|
||
|
|
upgrades: await page.evaluate(probeWebSockets, ma.origin),
|
||
|
|
handshakeReplies: socketResults,
|
||
|
|
failedRequests,
|
||
|
|
policyIssues,
|
||
|
|
};
|
||
|
|
if (details.pageReplacesWebSocket) {
|
||
|
|
details.nativeSendspinUpgrade = await page.evaluate(host => new Promise(resolve => {
|
||
|
|
const socket = new window.__adaptiveMusicProbeNativeSocket(`wss://${host}/sendspin`);
|
||
|
|
const timer = setTimeout(() => finish('upgrade-timeout'), 5000);
|
||
|
|
function finish(code) {
|
||
|
|
clearTimeout(timer);
|
||
|
|
socket.onopen = socket.onerror = socket.onclose = null;
|
||
|
|
socket.close();
|
||
|
|
resolve(code);
|
||
|
|
}
|
||
|
|
socket.onopen = () => finish('upgrade-ok');
|
||
|
|
socket.onerror = socket.onclose = () => finish('upgrade-failed');
|
||
|
|
}), ma.host);
|
||
|
|
}
|
||
|
|
return details;
|
||
|
|
} finally {
|
||
|
|
await session?.detach();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password}, progress) {
|
||
|
|
expect(typeof name === 'string' && name && typeof password === 'string' && typeof gm === 'boolean', 'invalid-test-account');
|
||
|
|
const page = await browser.newPage({viewport: {width: 1440, height: 1000}, screen: {width: 1440, height: 1000}});
|
||
|
|
if (previewModule) {
|
||
|
|
const prefix='/modules/adaptive-music/';
|
||
|
|
const root=resolve(import.meta.dirname,'..');
|
||
|
|
await page.context().route(`${foundry.origin}${prefix}**`,async route=>{
|
||
|
|
const file=new URL(route.request().url()).pathname.slice(prefix.length);
|
||
|
|
if(!/^(src\/.+\.mjs|styles\/.+\.css|vendor\/.+\.mjs)$/.test(file)||file.split('/').includes('..'))return route.continue();
|
||
|
|
await route.fulfill({path:resolve(root,file),contentType:file.endsWith('.css')?'text/css':'text/javascript'});
|
||
|
|
});
|
||
|
|
}
|
||
|
|
page.setDefaultTimeout(20000);
|
||
|
|
await retainBrowserWebSocket(page);
|
||
|
|
if (playback) await page.addInitScript(() => {
|
||
|
|
const peers = [];
|
||
|
|
const contexts = [];
|
||
|
|
const analysers = [];
|
||
|
|
const listenerAnalysers = [];
|
||
|
|
window.__adaptiveMusicTestAudio = {contexts, analysers, listenerAnalysers};
|
||
|
|
const createStream = AudioContext.prototype.createMediaStreamDestination;
|
||
|
|
AudioContext.prototype.createMediaStreamDestination = function () {
|
||
|
|
const destination = createStream.call(this);
|
||
|
|
contexts.push({context: this, destination});
|
||
|
|
return destination;
|
||
|
|
};
|
||
|
|
const createAnalyser = AudioContext.prototype.createAnalyser;
|
||
|
|
AudioContext.prototype.createAnalyser = function () {
|
||
|
|
const analyser = createAnalyser.call(this);
|
||
|
|
analysers.push(analyser);
|
||
|
|
return analyser;
|
||
|
|
};
|
||
|
|
const createSource = AudioContext.prototype.createMediaStreamSource;
|
||
|
|
AudioContext.prototype.createMediaStreamSource = function (stream) {
|
||
|
|
const source = createSource.call(this, stream);
|
||
|
|
const analyser = createAnalyser.call(this);
|
||
|
|
source.connect(analyser);
|
||
|
|
listenerAnalysers.push({context: this, stream, analyser});
|
||
|
|
return source;
|
||
|
|
};
|
||
|
|
window.__adaptiveMusicTestPeers = peers;
|
||
|
|
window.RTCPeerConnection = new Proxy(window.RTCPeerConnection, {
|
||
|
|
construct(target, args, newTarget) {
|
||
|
|
const peer = Reflect.construct(target, args, newTarget);
|
||
|
|
peers.push(peer);
|
||
|
|
return peer;
|
||
|
|
},
|
||
|
|
});
|
||
|
|
});
|
||
|
|
const url = new URL('/join', foundry);
|
||
|
|
progress('join-page');
|
||
|
|
await openPrivatePage(page, url, proxyIP);
|
||
|
|
await page.getByText(world.title, {exact: true}).first().waitFor({timeout: 30000});
|
||
|
|
expect(new URL(page.url()).pathname === '/join', 'unexpected-join-path');
|
||
|
|
|
||
|
|
progress('select-account');
|
||
|
|
const form = page.locator('#join-game-form');
|
||
|
|
const users = form.locator('select[name="userId"]');
|
||
|
|
await users.waitFor({state: 'visible'});
|
||
|
|
const option = await users.evaluate((select, name) => {
|
||
|
|
const user = [...select.options].find(option => option.label === name);
|
||
|
|
return user ? {value: user.value, disabled: user.disabled} : null;
|
||
|
|
}, name);
|
||
|
|
expect(option?.value, 'development-account-not-found');
|
||
|
|
expect(!option.disabled, 'development-account-unavailable');
|
||
|
|
await users.selectOption({value: option.value});
|
||
|
|
await form.locator('input[type="password"]').fill(password);
|
||
|
|
progress('submit-join');
|
||
|
|
const navigation = page.waitForResponse(response => response.request().isNavigationRequest() &&
|
||
|
|
response.request().frame() === page.mainFrame() && new URL(response.url()).pathname === '/game');
|
||
|
|
const [response] = await Promise.all([navigation, form.locator('[type="submit"]').click()]);
|
||
|
|
await verifyPrivateResponse(response, foundry.origin, proxyIP);
|
||
|
|
progress('wait-for-game-ready');
|
||
|
|
await page.bringToFront();
|
||
|
|
await page.waitForFunction(() => globalThis.game?.ready && game.socket?.connected, undefined, {polling: 250, timeout: 55000});
|
||
|
|
const state = await page.evaluate(({id, title, account}) => ({
|
||
|
|
worldMatches: game.world.id === id && game.world.title === title,
|
||
|
|
accountMatches: game.user.name === account,
|
||
|
|
gm: game.user.isGM,
|
||
|
|
foundryVersion: game.version,
|
||
|
|
system: game.system.id,
|
||
|
|
otherActiveGMs: game.users.filter(user => user.id !== game.user.id && user.active && user.isGM).length,
|
||
|
|
adaptiveMusicActive: game.modules.get('adaptive-music')?.active === true,
|
||
|
|
adaptiveMusicVersion: game.modules.get('adaptive-music')?.version ?? null,
|
||
|
|
}), {id: world.id, title: world.title, account: name});
|
||
|
|
expect(state.worldMatches && state.accountMatches && state.gm === gm, 'unexpected-world-account-or-role');
|
||
|
|
expect(state.foundryVersion === '14.371' && state.system === 'dnd5e', 'unexpected-foundry-or-system');
|
||
|
|
expect(state.otherActiveGMs === (state.gm ? 0 : 1), 'unexpected-active-gm-count');
|
||
|
|
expect(state.adaptiveMusicActive, 'adaptive-music-inactive');
|
||
|
|
// Keep the unattended canvases from saturating the shared headless renderer.
|
||
|
|
state.canvasTickerPaused = await page.evaluate(() => {
|
||
|
|
const ticker = globalThis.canvas?.app?.ticker;
|
||
|
|
if (!ticker?.started) return false;
|
||
|
|
ticker.stop();
|
||
|
|
return true;
|
||
|
|
});
|
||
|
|
return {page, response, state};
|
||
|
|
}
|
||
|
|
|
||
|
|
let browser, stage = 'configuration';
|
||
|
|
try {
|
||
|
|
const config = await privateJSON('live-environment');
|
||
|
|
const foundry = httpsOrigin(config.foundry), ma = httpsOrigin(config.ma);
|
||
|
|
const proxyIP = config.proxy_ip;
|
||
|
|
expect(isIP(proxyIP) === 4 && foundry.host !== ma.host, 'invalid-private-route');
|
||
|
|
const playwright = await import(process.env.AM_PLAYWRIGHT_MODULE ?? 'playwright');
|
||
|
|
stage = 'browser-launch';
|
||
|
|
if (engine === 'firefox') {
|
||
|
|
for (const host of [foundry.hostname, ma.hostname]) {
|
||
|
|
const answers = await lookup(host, {all: true});
|
||
|
|
expect(answers.length && answers.every(answer => answer.address === proxyIP), 'private-hostname-resolution-required');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
browser = await playwright[engine].launch(engine === 'chromium' ? {args: ['--no-sandbox', '--no-proxy-server',
|
||
|
|
`--host-resolver-rules=MAP ${foundry.hostname} ${proxyIP}, MAP ${ma.hostname} ${proxyIP}`]} :
|
||
|
|
{firefoxUserPrefs: {'network.trr.mode': 5, 'network.proxy.type': 0}});
|
||
|
|
report.engine = engine;
|
||
|
|
report.browser = browser.version();
|
||
|
|
report.moduleAssets = previewModule ? 'workspace module assets in the test browser' : 'installed module assets';
|
||
|
|
|
||
|
|
for (const [name, origin] of (layoutOnly ? [] : [['foundryAnonymous', foundry], ['maSameOrigin', ma]])) {
|
||
|
|
stage = name;
|
||
|
|
const page = await browser.newPage();
|
||
|
|
await retainBrowserWebSocket(page);
|
||
|
|
const response = await openPrivatePage(page, origin, proxyIP);
|
||
|
|
report.checks[name] = await collectTransport(page, response, ma);
|
||
|
|
await page.context().close();
|
||
|
|
}
|
||
|
|
|
||
|
|
if (loggedIn) {
|
||
|
|
stage = 'development-world-configuration';
|
||
|
|
const {world, accounts} = await privateJSON('foundry-development');
|
||
|
|
expect(typeof world?.id === 'string' && world.id && typeof world.title === 'string' && world.title &&
|
||
|
|
Array.isArray(accounts) && accounts.length === 3 && accounts.every((account, index) => account?.gm === (index === 0)) &&
|
||
|
|
new Set(accounts.map(account => account.name)).size === 3, 'invalid-development-world-configuration');
|
||
|
|
report.accounts = {};
|
||
|
|
const pages = [];
|
||
|
|
for (const [index, account] of (layoutOnly ? accounts.slice(0,1) : accounts).entries()) {
|
||
|
|
const login = index === 0 ? 'gm-login' : `player-${index}-login`;
|
||
|
|
const {page, response, state} = await joinWorld(browser, foundry, proxyIP, world, account, step => {
|
||
|
|
stage = `${login}-${step}`;
|
||
|
|
console.error(`Development world authentication stage: ${stage}`);
|
||
|
|
});
|
||
|
|
report.accounts[login] = state;
|
||
|
|
pages.push(page);
|
||
|
|
if (index === 0 && !layoutOnly) {
|
||
|
|
stage = 'foundryLoggedIn';
|
||
|
|
report.checks[stage] = await collectTransport(page, response, ma);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if(layoutOnly){
|
||
|
|
stage='foundry-graphical-layout';
|
||
|
|
const {checkFoundryLayout}=await import('./live_foundry_playback.mjs');
|
||
|
|
report.layout=await checkFoundryLayout(pages[0],ma);
|
||
|
|
}
|
||
|
|
if (playback) {
|
||
|
|
stage = 'installed-world-playback';
|
||
|
|
const {checkFoundryPlayback} = await import('./live_foundry_playback.mjs');
|
||
|
|
report.playback = {};
|
||
|
|
await checkFoundryPlayback({pages, ma, world, report: report.playback});
|
||
|
|
}
|
||
|
|
}
|
||
|
|
report.completed = true;
|
||
|
|
} catch (error) {
|
||
|
|
report.completed = false;
|
||
|
|
report.failure = {stage, code: /^[a-z][a-z-]+$/.test(error.message) ? error.message : error.code ?? error.name};
|
||
|
|
process.exitCode = 1;
|
||
|
|
} finally {
|
||
|
|
await browser?.close();
|
||
|
|
const resultName=previewModule?`foundry-am006-preview-${engine}`:`foundry-private-route-${engine}`;
|
||
|
|
await writeFile(`.local/${resultName}.json`, JSON.stringify(report, null, 2) + '\n', {mode: 0o600});
|
||
|
|
console.log(JSON.stringify(report, null, 2));
|
||
|
|
}
|