A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
test(youtube): verify hosting CSP and negative control
yhh8465277b4771
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 783681e3e..9cfdb2b86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Added+- **YouTube headless checks enforce the documented hosting policy.** Training runs under the official CSP response header as well as its exported policy. Unexpected violations fail the check; an intentionally blocked external request proves that enforcement and reporting work. The publishing guide links the independent official bundle analyzer. SDK Test Suite and device acceptance remain separate.+- **YouTube exports check stored bundle constraints.** Exports reject total packages at or above 250 MiB, individual files at or above 30 MiB, more than 8000 files and unsupported filenames. Cloud envelopes at exactly 3 MiB are rejected before staging. Recommendations and static initial-content estimates appear as warnings in both CLI and editor export results. Headless observations record local ready time and startup heap samples without claiming official transfer, peak heap or device certification.- **YouTube Playables Web exports honor host readiness and persistence.** The editor offers the channel and named example profile. Exports load the official SDK, report painted loading and interactive readiness, follow SDK pause/audio policy, and await cloud save acknowledgment before sending the saved highest score. Failed or unreadable cloud loads preserve progress; SDK no-ops disable host services. Headless SDK mock checks cover readiness, pause, reward credits and reloads; official certification and devices remain pending.diff --git a/docs/astro/src/content/docs/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/publishing/ads-sharing.mdxindex 7d57285f1..b216e87e8 100644--- a/docs/astro/src/content/docs/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/publishing/ads-sharing.mdx@@ -361,6 +361,12 @@ warnings. Static initial content is an estimate; actual compressed transferthrough gameReady must remain below 30 MiB. Verify loading and peak heap ontarget devices and in the official Test Suite.+Headless CI also applies the official guide's CSP response header and detects+policy violations, with a deliberately blocked external request as a control.+For independent static validation, run the official+[bundle analyzer](https://developers.google.com/youtube/gaming/playables/samples/bundle_analyzer).+This does not replace SDK Test Suite or device certification.+Select **YouTube Playables** in Web packaging or set`packaging.platforms.web.channel` to `"youtube"`. The Mobile Controls exampleprovides a named `youtube` profile. The official SDK loads before game code;diff --git a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdxindex f8bc93427..f28a4307f 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx@@ -320,6 +320,11 @@ Inspector 会提供测试上下文。训练示例的真实 SDK 初始化、加静态首包只是估算;截至 gameReady 的实际压缩传输须低于 30 MiB,加载速度与峰值堆内存仍须在目标设备和官方 Test Suite 中测量。+无头 CI 还施加官方指南的 CSP 响应头并捕获违规;故意访问外部地址作为+对照,确认限制和检测器生效。独立的静态复核可使用+[官方包分析器](https://developers.google.com/youtube/gaming/playables/samples/bundle_analyzer)。+它不能代替 SDK Test Suite 或设备认证。+在 Web 打包设置选择 **YouTube Playables**,或将`packaging.platforms.web.channel` 设置为 `"youtube"`。Mobile Controls提供同名导出档。官方 SDK 在游戏代码前加载:加载画面绘制后通知diff --git a/examples/mobile-controls/README.md b/examples/mobile-controls/README.mdindex 3a2f162dd..c29bf5d39 100644--- a/examples/mobile-controls/README.md+++ b/examples/mobile-controls/README.md@@ -139,6 +139,15 @@ Actual compressed transfer through gameReady must be below 30 MiB and needsruntime measurement. The headless report records local ready time and a startupheap sample, which do not certify device loading or peak gameplay heap.+The headless check serves the page with the official Test Suite guide's CSP+response header, in addition to the export's own policy. It records policy+violations and uses an intentionally blocked external request as a negative+control. The five gameplay paths must have no unexpected policy violations.+Before submission, also run the official+[bundle analyzer](https://developers.google.com/youtube/gaming/playables/samples/bundle_analyzer)+against the exported directory. Its static checks are separate from the SDK+Test Suite and physical-device acceptance.+Export with `node pipeline/bin/estella.mjs export examples/mobile-controls--profile youtube --out output/youtube-training-web`. The editor also exposesYouTube Playables under Web channel settings. The official SDK loads beforediff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 440659b57..d2bdf7def 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'test(youtube): verify hosting CSP and negative control':+ { note: 'YouTube headless checks enforce the documented hosting policy.' },'feat(youtube): validate export bundle constraints':{ note: 'YouTube exports check stored bundle constraints.' },'feat(youtube): connect Playables readiness pause and cloud saves':diff --git a/tools/tests/youtube-training.e2e.mjs b/tools/tests/youtube-training.e2e.mjsindex 425d5c00d..71ae463f3 100644--- a/tools/tests/youtube-training.e2e.mjs+++ b/tools/tests/youtube-training.e2e.mjs@@ -10,16 +10,27 @@ const files=(under='')=>fs.readdirSync(path.join(root,under),{withFileTypes:trueif(entry.isDirectory())return files(file);if(!entry.isFile())throw Error('Unsupported entry');return[file];});const identities=Object.fromEntries(files().map(file=>[file,sha(path.join(root,file))]));const report={headless:true,mode:'local-mock',status:'failed',identities,verifierSha256:sha(new URL(import.meta.url)),cases:[]};+// Official local response-header override, independent of the game's own meta policy:+// https://developers.google.com/youtube/gaming/playables/reference/test_suite_guide+const youtubeCsp="default-src 'none'; script-src 'report-sample' 'self' 'unsafe-eval' 'unsafe-inline' blob: https://www.youtube.com/game_api/v0 https://www.youtube.com/game_api/v0/ https://www.youtube.com/game_api/v1 https://www.youtube.com/game_api/v1/; object-src 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' blob: data:; media-src 'self' blob:; font-src 'self' data: https://fonts.googleapis.com https://fonts.gstatic.com; connect-src 'self' blob: data:; sandbox allow-pointer-lock allow-same-origin allow-scripts; base-uri 'self'; manifest-src 'self'; worker-src 'self' blob:";+report.responseContentSecurityPolicy=youtubeCsp;const mime={'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.wasm':'application/wasm','.png':'image/png'};const server=http.createServer((req,res)=>{try{const name=decodeURIComponent(new URL(req.url,'http://localhost').pathname).slice(1)||'index.html',file=fs.realpathSync(path.resolve(root,name));- if(!file.startsWith(root+path.sep)||!fs.statSync(file).isFile())throw Error('Outside export');res.setHeader('Content-Type',mime[path.extname(file)]??'application/octet-stream');res.end(fs.readFileSync(file));}catch{res.writeHead(404);res.end();}});+ if(!file.startsWith(root+path.sep)||!fs.statSync(file).isFile())throw Error('Outside export');res.setHeader('Content-Type',mime[path.extname(file)]??'application/octet-stream');+ if(path.extname(file)==='.html')res.setHeader('Content-Security-Policy',youtubeCsp);+ res.end(fs.readFileSync(file));}catch{res.writeHead(404);res.end();}});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const origin=`http://127.0.0.1:${server.address().port}`;const browser=await chromium.launch({headless:true,args:['--enable-unsafe-swiftshader','--use-angle=swiftshader','--mute-audio']});try {for(const mode of ['normal','local-noop','sdk-missing','load-failed','paused-boot']) {const context=await browser.newContext({viewport:{width:800,height:450}}),page=await context.newPage();- const observation={mode,status:'failed',errors:[],unexpectedRequests:[]};report.cases.push(observation);+ const observation={mode,status:'failed',errors:[],unexpectedRequests:[],cspViolations:[]};report.cases.push(observation);page.on('pageerror',error=>observation.errors.push(String(error)));+ await page.exposeFunction('__reportCsp',violation=>observation.cspViolations.push(violation));+ await page.addInitScript(()=>{window.__csp=[];window.__cspReports=0;document.addEventListener('securitypolicyviolation',event=>{+ const violation={directive:event.effectiveDirective,blockedURI:event.blockedURI,disposition:event.disposition};+ window.__csp.push(violation);void window.__reportCsp(violation).then(()=>{window.__cspReports++;});+ });});await page.addInitScript(()=>{window.__audioContexts=[];const Original=window.AudioContext;if(Original)window.AudioContext=class extends Original{constructor(...args){super(...args);__audioContexts.push(this);}};});await context.route('**/*',route=>{const url=route.request().url();if(url.startsWith(origin+'/'))return route.continue();@@ -53,6 +64,16 @@ try {await page.waitForFunction(()=>!document.getElementById('es-splash'));if(mode!=='sdk-missing') {await page.waitForFunction(()=>__events.includes('ready'));assert(await page.evaluate(()=>__firstLoading));assert.equal(await page.evaluate(()=>__readyLoading),false);observation.performance=await page.evaluate(()=>__readyPerformance);assert(observation.performance.gameReadyMs>0);}+ if(mode==='normal') {+ assert.deepEqual(observation.cspViolations,[]);+ await page.evaluate(()=>fetch('https://csp-negative.invalid/probe').catch(()=>{}));+ await page.waitForFunction(()=>__csp.some(v=>v.directive==='connect-src'&&v.blockedURI.startsWith('https://csp-negative.invalid')));+ // Wait for the reporting binding too, so the expected control is not mixed into gameplay evidence.+ await page.waitForFunction(()=>__cspReports>0);+ assert.equal(observation.cspViolations.length,1);+ assert.equal(observation.cspViolations[0].directive,'connect-src');+ report.cspNegativeControl=observation.cspViolations.pop();+ }const phase=value=>page.waitForFunction(v=>window.__estellaCooked?.probe(['DeviceStatus']).at.DeviceStatus?.text?.startsWith(v),value.toUpperCase());const click=async name=>{const box=await page.evaluate(n=>__estellaCooked.probe([n]).at[n],name);assert(box);await page.mouse.click(400+box.x,225-box.y);};const hosted=mode!=='local-noop'&&mode!=='sdk-missing';@@ -99,7 +120,8 @@ try {assert.match(observation.storage,/unavailable/);assert.equal(await page.evaluate(()=>localStorage.getItem('esengine:test')),null);}const file=mode+'.png';await page.screenshot({path:path.join(out,file)});observation.screenshot={file,sha256:sha(path.join(out,file))};- assert.deepEqual(observation.errors,[]);assert.deepEqual(observation.unexpectedRequests,[]);observation.events=await page.evaluate(()=>window.__events??[]);observation.status='passed';+ assert.deepEqual(observation.errors,[]);assert.deepEqual(observation.unexpectedRequests,[]);assert.deepEqual(observation.cspViolations,[]);+ observation.events=await page.evaluate(()=>window.__events??[]);observation.status='passed';} catch(error){observation.failure=String(error);throw error;}finally{await context.close();}}assert.deepEqual(Object.fromEntries(files().map(file=>[file,sha(path.join(root,file))])),identities);report.status='checks-passed';