4
0

prerender-csp.mjs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import assert from 'node:assert/strict'
  2. import http from 'node:http'
  3. import { readFile } from 'node:fs/promises'
  4. import path from 'node:path'
  5. import { fileURLToPath } from 'node:url'
  6. import { chromium } from 'playwright'
  7. const web = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
  8. const expectedH1 = {
  9. es: 'Tus equipos de red, en una sola vista',
  10. en: 'Your network devices, in one view',
  11. zh: '在一个视图中查看你的网络设备',
  12. ar: 'أجهزة شبكتك في عرض واحد',
  13. hi: 'आपके नेटवर्क डिवाइस, एक ही व्यू में',
  14. pt: 'Os seus equipamentos de rede numa só vista',
  15. fr: 'Vos équipements réseau dans une seule vue',
  16. ja: 'ネットワーク機器を一つのビューに',
  17. ru: 'Все сетевые устройства в одном окне',
  18. de: 'Deine Netzwerkgeräte in einer Ansicht',
  19. }
  20. const mime = {
  21. '.html': 'text/html; charset=utf-8',
  22. '.css': 'text/css',
  23. '.js': 'text/javascript',
  24. '.png': 'image/png',
  25. '.webp': 'image/webp',
  26. '.svg': 'image/svg+xml',
  27. '.woff2': 'font/woff2',
  28. '.json': 'application/json',
  29. }
  30. const server = http.createServer(async (req, res) => {
  31. try {
  32. let pathname = decodeURIComponent(new URL(req.url, 'http://local').pathname)
  33. let root = web
  34. const localized = pathname.match(/^\/(es|en|zh|ar|hi|pt|fr|ja|ru|de)(?:\/(.*))?$/)
  35. if (localized) {
  36. root = path.join(web, 'langs', localized[1])
  37. pathname = `/${localized[2] || ''}`
  38. }
  39. if (pathname === '/') pathname = '/index.html'
  40. else if (pathname.endsWith('/')) pathname += 'index.html'
  41. else if (!path.extname(pathname)) pathname += '.html'
  42. const file = path.resolve(root, `.${pathname}`)
  43. if (!file.startsWith(`${path.resolve(root)}${path.sep}`)) throw new Error('unsafe path')
  44. const body = await readFile(file)
  45. res.writeHead(200, {
  46. 'content-type': mime[path.extname(file)] || 'application/octet-stream',
  47. 'content-security-policy': "default-src 'self'; script-src 'self' https://stats.netpulse.cloudless.club https://stat.domatix.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self' https://api.github.com",
  48. })
  49. res.end(body)
  50. } catch {
  51. res.writeHead(404)
  52. res.end('not found')
  53. }
  54. })
  55. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
  56. const base = `http://127.0.0.1:${server.address().port}`
  57. const browser = await chromium.launch({ headless: true })
  58. function watchErrors(page) {
  59. const errors = []
  60. page.on('pageerror', error => errors.push(`pageerror: ${error.message}`))
  61. page.on('console', message => {
  62. const text = message.text()
  63. const mockedAnalyticsIntegrity = text.includes('integrity') &&
  64. (text.includes('stat.domatix.com') || text.includes('stats.netpulse.cloudless.club'))
  65. if (message.type() === 'error' && !mockedAnalyticsIntegrity) errors.push(`console: ${text}`)
  66. })
  67. return errors
  68. }
  69. async function assertNoInlineScripts(page) {
  70. const count = await page.locator('script:not([src]):not([type="application/ld+json"])').count()
  71. assert.equal(count, 0, 'the prerender must not depend on executable inline scripts')
  72. }
  73. try {
  74. const context = await browser.newContext({ locale: 'es-ES' })
  75. await context.addInitScript(() => localStorage.setItem('netpulse-web-lang', 'es'))
  76. await context.route('https://stat.domatix.com/**', route => route.fulfill({ status: 200, contentType: 'text/javascript', body: '' }))
  77. await context.route('https://stats.netpulse.cloudless.club/**', route => route.fulfill({ status: 200, contentType: 'text/javascript', body: '' }))
  78. await context.route('https://api.github.com/**', route => route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }))
  79. for (const [lang, h1] of Object.entries(expectedH1)) {
  80. const page = await context.newPage()
  81. const errors = watchErrors(page)
  82. const response = await page.goto(`${base}/${lang}/integrations/`, { waitUntil: 'networkidle' })
  83. assert.equal(response.status(), 200)
  84. assert.equal(await page.locator('html').getAttribute('lang'), lang)
  85. assert.equal((await page.locator('h1').innerText()).trim(), h1)
  86. assert.equal(await page.locator('#hardware tbody tr').count(), 7)
  87. assert.equal(
  88. await page.locator('#hardware tbody th', { hasText: 'OPNsense' }).count(),
  89. 1,
  90. `${lang}: the hardware table must list OPNsense`,
  91. )
  92. assert.equal(
  93. await page.locator('#routers .card.feature h3', { hasText: 'OPNsense' }).count(),
  94. 1,
  95. `${lang}: the external agents must include OPNsense`,
  96. )
  97. await assertNoInlineScripts(page)
  98. assert.deepEqual(errors, [], `${lang}: browser errors`)
  99. await page.close()
  100. }
  101. const page = await context.newPage()
  102. const errors = watchErrors(page)
  103. await page.goto(`${base}/en/integrations/`, { waitUntil: 'networkidle' })
  104. await page.locator('#langSelect').selectOption('de')
  105. await page.waitForURL('**/de/integrations/')
  106. await page.waitForLoadState('networkidle')
  107. assert.equal(await page.locator('html').getAttribute('lang'), 'de')
  108. assert.equal((await page.locator('h1').innerText()).trim(), expectedH1.de)
  109. await assertNoInlineScripts(page)
  110. assert.deepEqual(errors, [], 'language selector: browser errors')
  111. await page.close()
  112. const source = await context.newPage()
  113. const sourceErrors = watchErrors(source)
  114. await source.goto(`${base}/integrations`, { waitUntil: 'networkidle' })
  115. await source.locator('#langSelect').selectOption('en')
  116. assert.equal(new URL(source.url()).pathname, '/integrations')
  117. assert.equal((await source.locator('h1').innerText()).trim(), expectedH1.en)
  118. assert.deepEqual(sourceErrors, [], 'source page: browser errors')
  119. await source.close()
  120. await context.close()
  121. console.log('OK: 10 localized routes, clean-URL language selection and source-page selection under CSP')
  122. } finally {
  123. await browser.close()
  124. server.close()
  125. }