tldraw/apps/dotcom/scripts/build.ts
Mime Čuvalo 6ba3fb0722
csp: followup fixes/dx/tweaks (#4159)
couple interesting things here as followups to the CSP work.
- first of all, again, good call on doing the report-only to start with
@SomeHats 🤘
- I combed through all the Sentry logs, looking for issues. a lot of
them were browser extensions and could be ignored.
- there were some other ones that needed fixing up though.

fixes in this PR:
- [x] CSP emulation in dev: make sure it's running in development so
that we can catch things locally. this is done via the meta tag.
- [x] `connect-src` add `blob`: this was breaking copy/export as svg/png
- [x] image testing: expand list of pasted image extensions to include
avif and some others
- [x] image pasting: this didn't really work in the first place because
typically even with CSP disabled, you'll mainly run into CORS issues. I
think it's a pretty crap user experience. So, I moved this logic to
actually be in the URL unfurling. Lemme know what you think! I don't
think we should proxy the actual image data - that sounds ... intense 😬
even though it would produce a better user experience technically.
- [x] investigated `manifest-src` errors: but it actually seems fine?
Weird thing here is that `manifest-src` isn't explicitly in the CSP so
it falls back to the `default-src` of `self` which is fine. Trying it on
tldraw.com it seems just fine with no errors but inexplicably some users
are hitting these errors. I'm guessing maybe it's an ad-blocker type
behavior maybe.
- [x] `font-src` add `data`: I'm actually unsure if this is quite
necessary but I _think_ embedded fonts in SVGs are causing the problem.
However, I can't reproduce this, I just don't mind adding this.


Before / After for pasting image URLs (not a CSP issue, to be clear, but
a CORS issue)

## Before
<img width="448" alt="Screenshot 2024-07-12 at 17 59 42"
src="https://github.com/user-attachments/assets/e8ce267b-48fd-49cd-b0f7-0fd20c0b9a1d">

## After
<img width="461" alt="Screenshot 2024-07-12 at 18 00 06"
src="https://github.com/user-attachments/assets/9956590d-fe37-4708-bc26-0c454f8151b4">

### Change type

- [ ] `bugfix`
- [ ] `improvement`
- [ ] `feature`
- [ ] `api`
- [x] `other`

### Release notes

- Security: more CSP work on dotcom
2024-07-16 14:20:38 +00:00

141 lines
4.1 KiB
TypeScript

import glob from 'fast-glob'
import { mkdirSync, readFileSync, writeFileSync } from 'fs'
import { exec } from '../../../scripts/lib/exec'
import { Config } from './vercel-output-config'
import { config } from 'dotenv'
import json5 from 'json5'
import { nicelog } from '../../../scripts/lib/nicelog'
import { T } from '@tldraw/validate'
import { csp } from '../src/utils/csp'
import { getMultiplayerServerURL } from '../vite.config'
const commonSecurityHeaders = {
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer-when-downgrade',
'Content-Security-Policy-Report-Only': csp,
}
// We load the list of routes that should be forwarded to our SPA's index.html here.
// It uses a jest snapshot file because deriving the set of routes from our
// react-router config works fine in our test environment, but is tricky to get running in this
// build script environment for various reasons (no global React, tsx being weird about decorators, etc).
function loadSpaRoutes() {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const routesJson = require('../src/__snapshots__/routes.test.tsx.snap')['the_routes 1']
const routes = T.arrayOf(
T.object({
reactRouterPattern: T.string,
vercelRouterPattern: T.string,
})
).validate(json5.parse(routesJson))
return routes.map((route) => ({
check: true,
src: route.vercelRouterPattern,
dest: '/index.html',
headers: commonSecurityHeaders,
}))
}
config({
path: './.env.local',
})
nicelog('The multiplayer server is', process.env.MULTIPLAYER_SERVER)
async function build() {
// make sure we have the latest routes
await exec('yarn', ['test', 'src/routes.test.tsx'])
const spaRoutes = loadSpaRoutes()
await exec('vite', ['build', '--emptyOutDir'])
await exec('yarn', ['run', '-T', 'sentry-cli', 'sourcemaps', 'inject', 'dist/assets'])
// Clear output static folder (in case we are running locally and have already built the app once before)
await exec('rm', ['-rf', '.vercel/output'])
mkdirSync('.vercel/output', { recursive: true })
await exec('cp', ['-r', 'dist', '.vercel/output/static'])
await exec('rm', ['-rf', ...glob.sync('.vercel/output/static/**/*.js.map')])
// Add fonts to preload into index.html
const assetsList = (await exec('ls', ['-1', 'dist/assets'])).split('\n').filter(Boolean)
const fontsToPreload = [
'Shantell_Sans-Tldrawish',
'IBMPlexSerif-Medium',
'IBMPlexSans-Medium',
'IBMPlexMono-Medium',
]
const indexHtml = await readFileSync('.vercel/output/static/index.html', 'utf8')
await writeFileSync(
'.vercel/output/static/index.html',
indexHtml.replace(
'<!-- $PRELOADED_FONTS -->',
fontsToPreload
.map(
(font) => `<link
rel="preload"
href="/assets/${assetsList.find((a) => a.startsWith(font))}"
as="font"
type="font/woff2"
crossorigin="anonymous"
/>`
)
.join('\n')
)
)
const multiplayerServerUrl = getMultiplayerServerURL() ?? 'http://localhost:8787'
writeFileSync(
'.vercel/output/config.json',
JSON.stringify(
{
version: 3,
routes: [
// rewrite api calls to the multiplayer server
{
src: '^/api(/(.*))?$',
dest: `${multiplayerServerUrl}$1`,
check: true,
},
// cache static assets immutably
{
src: '^/assets/(.*)$',
headers: {
'Cache-Control': 'public, max-age=31536000, immutable',
'X-Content-Type-Options': 'nosniff',
},
},
// server up index.html specifically because we want to include
// security headers. otherwise, it goes to the handle: 'miss'
// part below (and _not_ to the spaRoutes as maybe expected!)
{
check: true,
src: '/',
dest: '/index.html',
headers: commonSecurityHeaders,
},
// serve static files
{
handle: 'miss',
},
// finally handle SPA routing
...spaRoutes,
// react router will handle drawing the 404 page
{
check: true,
src: '.*',
dest: '/index.html',
status: 404,
headers: commonSecurityHeaders,
},
],
overrides: {},
} satisfies Config,
null,
2
)
)
}
build()