// Browser diagnostics on the actual private HTTPS hosts. Records metadata only. import {execFileSync} from 'node:child_process'; import {createHash} from 'node:crypto'; import {mkdtemp, readFile, rm, 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 nativeSheet = process.argv.includes('--native-sheet'); const layoutOnly = process.argv.includes('--layout-only')||nativeSheet; const loggedIn = playback || layoutOnly || process.argv.includes('--logged-in'); const engine = process.argv.includes('--firefox')?'firefox':process.argv.includes('--webkit')?'webkit':'chromium'; const packageOption=process.argv.indexOf('--package-preview'); const previewModule = process.argv.includes('--preview-module')||packageOption!==-1; let packageDirectory; const headed = process.argv.includes('--headed'); const long = process.argv.includes('--continuity'); const review = process.argv.includes('--review'); 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 context=await browser.newContext({viewport:{width:1440,height:1000},screen:{width:1440,height:1000}}); const page=await context.newPage(); if (previewModule) { const prefix='/modules/adaptive-music/'; const root=packageDirectory?resolve(packageDirectory,'adaptive-music'):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 packageDirectory?route.abort():route.continue(); } await route.fulfill({path:resolve(root,file),contentType:file.endsWith('.css')?'text/css':'text/javascript'}); }); } page.setDefaultTimeout(20000); if(playback) await page.context().route(`${foundry.origin}/adaptive-continuity-test.mjs`,route=>route.fulfill({ path:resolve(import.meta.dirname,'browser-continuity-worklet.mjs'),contentType:'text/javascript', })); await retainBrowserWebSocket(page); if (playback) await page.addInitScript(() => { const timeline = {gaps:0, overlaps:0, maxGapMs:0, maxOverlapMs:0, contiguous:0}; let prior; const start = AudioBufferSourceNode.prototype.start; AudioBufferSourceNode.prototype.start = function(when, offset, duration) { const {buffer,context}=this; if (buffer && context===window.__adaptiveMusicTestAudio.contexts[0]?.context && Number.isFinite(when) && when>0) { const length=(duration??buffer.duration-(offset??0))/this.playbackRate.value; if (prior?.context===context && when>=prior.start && Math.abs(when-prior.end)<0.2) { const delta=(when-prior.end)*1000; if(delta>0.1){timeline.gaps++;timeline.maxGapMs=Math.max(timeline.maxGapMs,delta);} else if(delta < -0.1){timeline.overlaps++;timeline.maxOverlapMs=Math.max(timeline.maxOverlapMs,-delta);} else timeline.contiguous++; } prior={context,start:when,end:when+length}; } return start.apply(this,arguments); }; window.__adaptiveMusicTestTimeline=timeline; 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; const modules = new WeakMap(); function measure(context,analyser,report) { if(!context.audioWorklet)return; if(!modules.has(context))modules.set(context,context.audioWorklet.addModule('/adaptive-continuity-test.mjs')); modules.get(context).then(()=>{ const node=new AudioWorkletNode(context,'adaptive-continuity-meter'); const sink=context.createGain();sink.gain.value=0; report.meterPort=node.port; node.port.onmessage=event=>{ report.continuity=event.data; if(event.data.phaseStarted)report.phaseStarted=event.data; }; analyser.connect(node).connect(sink).connect(context.destination); }).catch(()=>{report.meterFailed=true;}); } AudioContext.prototype.createAnalyser = function () { const analyser = createAnalyser.call(this); analysers.push(analyser); const report=contexts.find(entry=>entry.context===this); if(report&&!report.measuring){report.measuring=true;report.analyser=analyser;measure(this,analyser,report);} 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); const report={context: this, stream, analyser}; listenerAnalysers.push(report); measure(this,analyser,report); 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 = (!headed||review) && 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 { if(packageOption!==-1){ stage='package-preview-validation'; const archive=process.argv[packageOption+1]; expect(archive&&!archive.startsWith('-'),'package-preview-path-required'); packageDirectory=await mkdtemp('.local/v080-package-preview-'); report.runtimeAssetsSHA256=execFileSync('python3',[resolve(import.meta.dirname,'release.py'),'--runtime-sha256',archive],{encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim(); execFileSync('python3',['-m','zipfile','-e',archive,packageDirectory],{stdio:'ignore'}); report.packageSHA256=createHash('sha256').update(await readFile(archive)).digest('hex'); } 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 !== 'chromium') { 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' ? {headless: !headed, ...(review&&headed&&{ignoreDefaultArgs:['--disable-background-timer-throttling', '--disable-backgrounding-occluded-windows','--disable-renderer-backgrounding']}), args: ['--no-sandbox', '--no-proxy-server', `--host-resolver-rules=MAP ${foundry.hostname} ${proxyIP}, MAP ${ma.hostname} ${proxyIP}`]} : {headless: !headed,...(engine==='firefox'&&{firefoxUserPrefs:{'network.trr.mode':5,'network.proxy.type':0}})}); report.engine = engine; report.browser = browser.version(); report.headed = headed; report.moduleAssets = packageDirectory?'validated ZIP assets in the test browser':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,checkNativeSceneSheet}=await import('./live_foundry_playback.mjs'); if(nativeSheet)await checkNativeSceneSheet(pages[0],report); else report.layout=await checkFoundryLayout(pages[0],ma); } if (playback) { stage = 'development-world-playback'; const {checkFoundryPlayback,checkFoundryV080Review} = await import('./live_foundry_playback.mjs'); report.playback = {}; const run=review?checkFoundryV080Review:checkFoundryPlayback; await run({pages, ma, world, report: report.playback, long}); } } report.completed = true; } catch (error) { if(error.name==='SyntaxError')console.error(error.stack); 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(); if(packageDirectory)await rm(packageDirectory,{recursive:true,force:true}); const resultName=nativeSheet?`foundry-native-sheet-${engine}`:review?`foundry-v080-review-${engine}`:headed?`foundry-headed-${previewModule?'candidate':'installed'}-${engine}`: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)); }