diff --git a/Dockerfile b/Dockerfile index e66a3733..2f78a32d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,3 +1,28 @@ +# ---- stage 0: wasm -------------------------------------------------- +# The Rust core compiled to the browser module (R2). Same toolchain and wasm-bindgen CLI +# as docker/rust-builder.Dockerfile (keep the two ARG lines equal); scripts/wasm-build.sh +# refuses a CLI that differs from the wasm-bindgen crate in Cargo.lock. The production VPS +# never builds this image: it pulls it by digest (DEPLOY.md). +FROM rust:1.99.0-bookworm AS wasm + +ARG WASM_BINDGEN_VERSION=0.2.129 + +RUN rustup target add wasm32-unknown-unknown \ + && rustup component add rustfmt clippy \ + && cargo install wasm-bindgen-cli --version "${WASM_BINDGEN_VERSION}" --locked \ + && rm -rf /usr/local/cargo/registry + +WORKDIR /w +COPY rust-toolchain.toml Cargo.toml Cargo.lock ./ +COPY .cargo .cargo +COPY crates crates +COPY scripts/rust-env.sh scripts/wasm-build.sh scripts/ +# The build and wasm-bindgen run in one RUN: the cache-mounted target never reaches the +# layer, the generated packages/core-wasm/pkg does. +RUN --mount=type=cache,target=/usr/local/cargo/registry \ + --mount=type=cache,target=/w/target \ + WASM_BUILD_SHIPPED_ONLY=1 bash scripts/wasm-build.sh + # ---- stage 1: builder ----------------------------------------------- # Node 24 LTS (Node 20 reached end-of-life on 2026-04-30). pnpm pinned to the # same version as package.json "packageManager"; pnpm 11 needs Node >= 22.13 @@ -15,6 +40,7 @@ COPY packages/domain/package.json packages/domain/ COPY packages/anatomy/package.json packages/anatomy/ COPY packages/pdf/package.json packages/pdf/ COPY packages/supabase/package.json packages/supabase/ +COPY packages/core-wasm/package.json packages/core-wasm/ RUN pnpm install --frozen-lockfile @@ -25,13 +51,15 @@ RUN pnpm install --frozen-lockfile ARG SHEET_BUNDLE=none ENV SHEET_BUNDLE=$SHEET_BUNDLE COPY . . +COPY --from=wasm /w/packages/core-wasm/pkg packages/core-wasm/pkg RUN pnpm --filter @faunosteo/app build # ---- stage 2: runner ------------------------------------------------ FROM nginx:1.31-alpine AS runner -# Copy built static assets +# Copy built static assets; the core module is served precompressed (gzip_static) COPY --from=builder /app/apps/app/dist /usr/share/nginx/html +RUN gzip -9 -k /usr/share/nginx/html/assets/*.wasm # Copy custom nginx config and entrypoint COPY docker/nginx.conf /etc/nginx/conf.d/default.conf diff --git a/docker/csp-proof/app-image.mjs b/docker/csp-proof/app-image.mjs new file mode 100644 index 00000000..290ec620 --- /dev/null +++ b/docker/csp-proof/app-image.mjs @@ -0,0 +1,100 @@ +// Driven by docker/csp-proof/app-image.sh: 8093 = DEPLOY.md CSP without 'wasm-unsafe-eval', +// 8094 = with it. Prints one line per check; exits 1 when one fails. +import { chromium } from 'playwright-core' + +const WITHOUT = 'http://127.0.0.1:8093' +const WITH = 'http://127.0.0.1:8094' +const failures = [] +const check = (name, ok, detail = '') => { + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`) + if (!ok) failures.push(name) +} + +const browser = await chromium.launch({ executablePath: process.env.CHROME, headless: true }) + +async function page(base) { + // The app picks its language from the browser: the checks read the French strings. + const p = await browser.newPage({ locale: 'fr-FR' }) + const core = [] + const violations = [] + p.on('request', (r) => { + if (/faunosteo_wasm/.test(r.url())) core.push(r.url()) + }) + p.on('console', (m) => { + // Script and WebAssembly refusals only: the footer's external credit logo is refused by + // img-src on every page since Step 6, a known, separate matter. + const text = m.text() + if (/Content Security Policy/i.test(text) && !/Loading the image/.test(text)) violations.push(text) + }) + p.on('dialog', (d) => d.accept()) + // A caught compile error logs nothing: the violation event is the browser's own record. + await p.addInitScript(() => { + window.__csp = [] + document.addEventListener('securitypolicyviolation', (e) => + window.__csp.push(`${e.effectiveDirective} ${e.blockedURI}`), + ) + }) + return { p, core, violations, base } +} + +async function quietPages(base, label) { + for (const path of ['/login', '/app/account', '/']) { + const s = await page(base) + const response = await s.p.goto(`${base}${path}`) + await s.p.waitForTimeout(700) + check(`${label} ${path} loads without the core`, response.ok() && s.core.length === 0, `${s.core.length} core requests`) + await s.p.close() + } +} + +async function newReport(s) { + await s.p.goto(`${s.base}/new`) + // The scope disclaimer is acknowledged once per tab; it would cover the drawing. + await s.p.evaluate(() => sessionStorage.setItem('osteo:disclaimer-shown', '1')) + await s.p.fill('#prac-name', 'Dr. Proof') + await s.p.fill('#an-name', 'Mistral') + await s.p.fill('#own-name', 'Owner') + await s.p.getByRole('button', { name: 'Démarrer le bilan' }).click() +} + +// With the keyword: the editor runs the core. +const ok = await page(WITH) +const csp = (await (await ok.p.goto(`${WITH}/`)).headers())['content-security-policy'] +check('with: CSP header carries wasm-unsafe-eval', csp.includes("'wasm-unsafe-eval'")) +await newReport(ok) +await ok.p.waitForURL('**/editor', { timeout: 10_000 }).catch(() => {}) +check('with: new report created by the core, editor open', ok.p.url().endsWith('/editor')) +await ok.p.locator('[data-anno-id="c7-t1"]').first().dispatchEvent('click') +const chip = ok.p.getByRole('button', { name: /Retirer .*C7-T1/ }) +check('with: zone click applied by the core', (await chip.count()) > 0) +const wasmEncoding = await ok.p.evaluate(async () => { + const url = performance.getEntriesByType('resource').map((e) => e.name).find((n) => n.endsWith('.wasm')) + const response = await fetch(url, { headers: { 'Accept-Encoding': 'gzip' } }) + return { type: response.headers.get('content-type'), size: (await response.arrayBuffer()).byteLength } +}) +check('with: module served as application/wasm', wasmEncoding.type === 'application/wasm', JSON.stringify(wasmEncoding)) +const okEvents = (await ok.p.evaluate(() => window.__csp)).filter((v) => !v.startsWith('img-src')) +check('with: no CSP violation', ok.violations.length === 0 && okEvents.length === 0, [...ok.violations, ...okEvents].join(' | ')) +await ok.p.close() + +// Without the keyword: degraded state, nothing lost, auth pages usable. +await quietPages(WITHOUT, 'without:') +await quietPages(WITH, 'with:') +const ko = await page(WITHOUT) +await ko.p.goto(`${WITHOUT}/`) +const draft = JSON.stringify({ version: 3 }) +await ko.p.evaluate((d) => sessionStorage.setItem('osteo:draft', d), draft) +await ko.p.goto(`${WITHOUT}/editor`) +await ko.p.waitForTimeout(1500) +const notice = await ko.p.getByText('Le moteur de calcul de Faunosteo').count() +check('without: editor shows the degraded notice', notice > 0) +check('without: editor stays on /editor', ko.p.url().endsWith('/editor'), ko.p.url()) +const kept = await ko.p.evaluate(() => sessionStorage.getItem('osteo:draft')) +check('without: the draft is left untouched', kept === draft) +const koEvents = await ko.p.evaluate(() => window.__csp) +check('without: the browser refused the module (CSP)', koEvents.some((v) => v.includes('wasm-eval')), koEvents.join(' | ')) +await ko.p.close() + +await browser.close() +console.log(failures.length === 0 ? 'ALL PASS' : `FAILED: ${failures.join(', ')}`) +process.exit(failures.length === 0 ? 0 : 1) diff --git a/docker/csp-proof/app-image.sh b/docker/csp-proof/app-image.sh new file mode 100644 index 00000000..e1536ab3 --- /dev/null +++ b/docker/csp-proof/app-image.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# R2 proof (review VI.2 R2, D-R13): the application image boots under the production CSP of +# DEPLOY.md. With 'wasm-unsafe-eval' the editor runs the Rust core (new report, zone click); +# without it the editor shows the degraded state and /login stays usable; /login and +# /app/account never request the core module. Runs the real image (SHEET_BUNDLE=draft) behind +# the image's own nginx with the header added, and drives headless Chromium. +# +# CHROME=/path/to/chrome PLAYWRIGHT_NODE_MODULES=/path/to/node_modules \ +# bash docker/csp-proof/app-image.sh +# +# PLAYWRIGHT_NODE_MODULES: a node_modules holding playwright-core, outside the repository +# (no project dependency); the driver runs from a temporary directory linked to it. +# +# Result recorded in docs/development/RUST.md (R2 section). +set -euo pipefail +cd "$(dirname "$0")/../.." +work="$(mktemp -d)" +csp_line="$(grep -m1 '^add_header Content-Security-Policy' DEPLOY.md | sed -E 's/^add_header Content-Security-Policy "(.*)" always;$/\1/')" +without_csp="${csp_line/ \'wasm-unsafe-eval\'/}" +with_csp="${without_csp/script-src \'self\'/script-src \'self\' \'wasm-unsafe-eval\'}" +for variant in without with; do + if [ "$variant" = without ]; then csp="$without_csp"; else csp="$with_csp"; fi + sed "s/\${PORT}/8080/; s|^ # SPA fallback| add_header Content-Security-Policy \"$csp\" always;\n # SPA fallback|; s|^ add_header Cache-Control \"public, max-age=31536000, immutable\";| add_header Cache-Control \"public, max-age=31536000, immutable\";\n add_header Content-Security-Policy \"$csp\" always;|" docker/nginx.conf > "$work/csp-$variant.conf" +done +docker build --build-arg SHEET_BUNDLE=draft -t faunosteo:r2-csp-proof . >/dev/null 2>&1 +cleanup() { docker rm -f faunosteo_r2csp_without faunosteo_r2csp_with >/dev/null 2>&1 || true; } +trap cleanup EXIT +cleanup +for variant in without with; do + port=8093 + [ "$variant" = with ] && port=8094 + docker run -d --rm --name "faunosteo_r2csp_$variant" -p "127.0.0.1:$port:8080" \ + --entrypoint nginx \ + -v "$work/csp-$variant.conf:/etc/nginx/conf.d/default.conf:ro" \ + faunosteo:r2-csp-proof -g 'daemon off;' >/dev/null +done +sleep 1.5 +cp docker/csp-proof/app-image.mjs "$work/" +ln -s "${PLAYWRIGHT_NODE_MODULES:?set PLAYWRIGHT_NODE_MODULES}" "$work/node_modules" +node "$work/app-image.mjs" diff --git a/docker/nginx.conf b/docker/nginx.conf index b8695155..ebeaab38 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -11,8 +11,10 @@ server { try_files $uri =404; } - # Assets with long-lived cache (Vite hashes filenames) + # Assets with long-lived cache (Vite hashes filenames); the core module ships with a + # precompressed .wasm.gz sibling built into the image location /assets/ { + gzip_static on; add_header Cache-Control "public, max-age=31536000, immutable"; } diff --git a/scripts/wasm-build.sh b/scripts/wasm-build.sh index c5514b62..aed2ae90 100755 --- a/scripts/wasm-build.sh +++ b/scripts/wasm-build.sh @@ -32,11 +32,17 @@ build_module() { target/wasm32-unknown-unknown/release/faunosteo_wasm.wasm } -stamp="$(node scripts/wasm-stamp.mjs)" -build_module packages/core-wasm/pkg-proofs --features proofs -echo "$stamp" > packages/core-wasm/pkg-proofs/BUILD_STAMP -build_module packages/core-wasm/pkg -echo "$stamp" > packages/core-wasm/pkg/BUILD_STAMP +# WASM_BUILD_SHIPPED_ONLY=1 (the application image) builds pkg/ alone; the stamp needs node, +# absent from that stage, and only the test suites read it. +if [ "${WASM_BUILD_SHIPPED_ONLY:-0}" = 1 ]; then + build_module packages/core-wasm/pkg +else + stamp="$(node scripts/wasm-stamp.mjs)" + build_module packages/core-wasm/pkg-proofs --features proofs + echo "$stamp" > packages/core-wasm/pkg-proofs/BUILD_STAMP + build_module packages/core-wasm/pkg + echo "$stamp" > packages/core-wasm/pkg/BUILD_STAMP +fi # The shipped module must not carry a proof export. if grep -Eq 'panic_for_test|recurse_for_test' packages/core-wasm/pkg/faunosteo_wasm.d.ts; then