From ca5833c6ea4722ab71ec45c3bf468f7a42576748 Mon Sep 17 00:00:00 2001 From: Baivab Sarkar <109382325+ThisIs-Developer@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:42:02 +0530 Subject: [PATCH] fix(docker): harden HTTP runtime and verify immutable releases --- .dockerignore | 2 + .gitattributes | 2 + .github/actions/docker-verify/action.yml | 81 ++++++ .github/workflows/docker-publish.yml | 253 ++++++++++++++--- Dockerfile | 103 ++++--- desktop-app/resources/js/script.js | 32 ++- docker-compose.build.yml | 8 + docker-compose.yml | 20 +- docker/SECURITY-MAINTENANCE.md | 79 ++++++ docker/check-runtime.sh | 34 +++ docker/nginx-component.spdx.json | 40 +++ docker/nginx-main.conf | 18 ++ docker/nginx-server.conf | 44 +++ docker/promote-image.sh | 16 ++ docker/security-headers.conf | 5 + docker/verify-assembly.mjs | 33 +++ docker/verify-attestations.mjs | 39 +++ docker/verify-browser.sh | 16 ++ docker/verify-graceful.sh | 49 ++++ docker/verify-image.sh | 73 +++++ docker/verify-registry.sh | 22 ++ package-lock.json | 54 +++- package.json | 3 +- playwright.config.js | 5 +- script.js | 32 ++- sw.js | 40 ++- tests/e2e/docker-sharing.spec.js | 152 ++++++++++ tests/e2e/docker.spec.js | 109 ++++++++ tests/helpers/sharing-services.js | 65 +++++ tests/unit/docker-assembly.test.mjs | 30 ++ tests/unit/docker-attestations.test.mjs | 44 +++ tests/unit/live-room-endpoint.test.mjs | 45 +++ wiki/Docker-Deployment.md | 337 +++++++++++++---------- 33 files changed, 1616 insertions(+), 269 deletions(-) create mode 100644 .gitattributes create mode 100644 .github/actions/docker-verify/action.yml create mode 100644 docker-compose.build.yml create mode 100644 docker/SECURITY-MAINTENANCE.md create mode 100644 docker/check-runtime.sh create mode 100644 docker/nginx-component.spdx.json create mode 100644 docker/nginx-main.conf create mode 100644 docker/nginx-server.conf create mode 100644 docker/promote-image.sh create mode 100644 docker/security-headers.conf create mode 100644 docker/verify-assembly.mjs create mode 100644 docker/verify-attestations.mjs create mode 100755 docker/verify-browser.sh create mode 100755 docker/verify-graceful.sh create mode 100755 docker/verify-image.sh create mode 100644 docker/verify-registry.sh create mode 100644 tests/e2e/docker-sharing.spec.js create mode 100644 tests/e2e/docker.spec.js create mode 100644 tests/helpers/sharing-services.js create mode 100644 tests/unit/docker-assembly.test.mjs create mode 100644 tests/unit/docker-attestations.test.mjs create mode 100644 tests/unit/live-room-endpoint.test.mjs diff --git a/.dockerignore b/.dockerignore index 49b5caab..00a856ef 100644 --- a/.dockerignore +++ b/.dockerignore @@ -7,6 +7,8 @@ desktop-app wiki node_modules *.md +!sample.md +!assets/linked-workspace-guide.md LICENSE docker-compose.yml Dockerfile diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..2bba0a4e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Executed inside Linux containers, including from Windows checkouts. +docker/*.sh text eol=lf diff --git a/.github/actions/docker-verify/action.yml b/.github/actions/docker-verify/action.yml new file mode 100644 index 00000000..713819d3 --- /dev/null +++ b/.github/actions/docker-verify/action.yml @@ -0,0 +1,81 @@ +name: Verify Docker candidate +description: Tests and scans the exact candidate on its native CPU architecture +inputs: + image-ref: + description: Immutable registry digest for the native platform + required: true + architecture: + description: Native CPU architecture used to distinguish audit artifacts + required: true +runs: + using: composite + steps: + - name: NGINX, package inventory, content, headers and cache checks + shell: bash + run: bash docker/verify-image.sh '${{ inputs.image-ref }}' + - name: Verify graceful NGINX shutdown using an active transfer + shell: bash + run: bash docker/verify-graceful.sh '${{ inputs.image-ref }}' + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: '24' + cache: npm + - name: Verify host source independently + shell: bash + run: | + npm ci + npm run check:static + node --test tests/unit/docker-attestations.test.mjs tests/unit/docker-assembly.test.mjs + - name: Install Chromium + shell: bash + run: npx playwright install --with-deps chromium + - name: Run browser against the actual Docker container + shell: bash + run: bash docker/verify-browser.sh '${{ inputs.image-ref }}' + - name: Prepare reports + shell: bash + if: always() + run: mkdir -p docker-artifacts + - name: Generate inspectable SPDX SBOM for the exact candidate + uses: anchore/sbom-action@v0 + with: + image: '${{ inputs.image-ref }}' + format: spdx-json + output-file: docker-artifacts/syft-sbom.spdx.json + upload-artifact: false + upload-release-assets: false + - name: Verify custom NGINX version is represented in the generated SBOM + shell: bash + run: | + node docker/verify-attestations.mjs docker-artifacts/syft-sbom.spdx.json + - name: Full vulnerability report (all severity levels) + uses: aquasecurity/trivy-action@v0.36.0 + with: + image-ref: '${{ inputs.image-ref }}' + format: json + output: docker-artifacts/trivy-vulnerabilities.json + scanners: vuln + vuln-type: os,library + severity: UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL + exit-code: '0' + - name: Block fixable Critical/High vulnerabilities + uses: aquasecurity/trivy-action@v0.36.0 + with: + image-ref: '${{ inputs.image-ref }}' + format: table + scanners: vuln + vuln-type: os,library + severity: CRITICAL,HIGH + ignore-unfixed: true + exit-code: '1' + - name: Upload scan and browser traces + if: always() + uses: actions/upload-artifact@v4 + with: + name: docker-tested-candidate-evidence-${{ inputs.architecture }} + path: | + docker-artifacts/ + test-results/ + playwright-report/ + if-no-files-found: warn diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index ae6ec091..71b1183c 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -1,54 +1,217 @@ -name: Build and Push Docker Image - +name: Build, Verify and Publish Docker Image on: - push: - branches: [ main ] pull_request: - branches: [ main ] - + branches: [main] + push: + branches: [main] + workflow_dispatch: + schedule: + - cron: '0 4 1 * *' # Monthly non-publishing dependency refresh +concurrency: + group: docker-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} +permissions: + contents: read env: - REGISTRY: ghcr.io - IMAGE_NAME: ${{ github.repository }} + IMAGE_REPO: ghcr.io/thisis-developer/markdown-viewer jobs: - build-and-push: - runs-on: ubuntu-latest + validate: + name: Docker native ${{ matrix.arch }} + strategy: + fail-fast: false + matrix: + include: + - arch: amd64 + runner: ubuntu-24.04 + - arch: arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 45 + env: + DOCKER_PLATFORM: linux/${{ matrix.arch }} + services: + registry: + image: registry:3 + ports: + - 5000:5000 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: docker/setup-buildx-action@v3 + with: + driver-opts: network=host + - name: Build once on the native CPU with attestations + id: candidate + uses: docker/build-push-action@v6 + with: + context: . + platforms: ${{ env.DOCKER_PLATFORM }} + pull: true + push: true # Localhost only, including on PRs. + no-cache: ${{ github.event_name == 'schedule' }} + provenance: mode=max + sbom: true + tags: localhost:5000/markdown-viewer:candidate + cache-from: | + type=gha,scope=docker-${{ matrix.arch }} + type=gha,scope=buildkit + cache-to: type=gha,scope=docker-${{ matrix.arch }},mode=max + - name: Pin and inspect the exact native candidate + env: + CANDIDATE_DIGEST: ${{ steps.candidate.outputs.digest }} + run: | + set -euo pipefail + IMAGE_REF="localhost:5000/markdown-viewer@$CANDIDATE_DIGEST" + echo "IMAGE_REF=$IMAGE_REF" >> "$GITHUB_ENV" + mkdir -p docker-artifacts + printf 'candidate_index_digest=%s\n' "$CANDIDATE_DIGEST" | tee docker-artifacts/candidate-identity.txt + docker pull "$IMAGE_REF" + actual="$(docker image inspect "$IMAGE_REF" --format '{{.Os}}/{{.Architecture}}')" + test "$actual" = "$DOCKER_PLATFORM" + bash docker/verify-registry.sh "$IMAGE_REF" + - name: Test and scan that candidate on its native CPU + uses: ./.github/actions/docker-verify + with: + image-ref: ${{ env.IMAGE_REF }} + architecture: ${{ matrix.arch }} + - name: Export the tested image and attestations without changing digests + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y skopeo + mkdir -p export + skopeo copy --all --preserve-digests --src-tls-verify=false \ + "docker://$IMAGE_REF" oci-archive:export/image.tar + printf '%s\n' "${IMAGE_REF##*@}" > export/digest.txt + cp docker-artifacts/candidate-index.json export/index.json + - uses: actions/upload-artifact@v4 + with: + name: docker-candidate-${{ matrix.arch }} + path: export/ + compression-level: 0 + retention-days: 7 + if-no-files-found: error + + assemble: + name: Verify multi-platform release + needs: validate + runs-on: ubuntu-24.04 + timeout-minutes: 15 + services: + registry: + image: registry:3 + ports: + - 5000:5000 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: docker/setup-buildx-action@v3 + with: + driver-opts: network=host + - uses: actions/download-artifact@v4 + with: + pattern: docker-candidate-* + path: candidates + - name: Import tested candidates and assemble their exact manifests + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y skopeo + refs=() + for arch in amd64 arm64; do + directory="candidates/docker-candidate-$arch" + expected="$(cat "$directory/digest.txt")" + skopeo copy --all --preserve-digests --dest-tls-verify=false \ + "oci-archive:$directory/image.tar" "docker://localhost:5000/markdown-viewer:$arch" + actual="$(docker buildx imagetools inspect "localhost:5000/markdown-viewer:$arch" --format '{{.Manifest.Digest}}')" + test "$actual" = "$expected" + refs+=("localhost:5000/markdown-viewer@$expected") + done + docker buildx imagetools create --tag localhost:5000/markdown-viewer:combined "${refs[@]}" + digest="$(docker buildx imagetools inspect localhost:5000/markdown-viewer:combined --format '{{.Manifest.Digest}}')" + IMAGE_REF="localhost:5000/markdown-viewer@$digest" + echo "IMAGE_REF=$IMAGE_REF" >> "$GITHUB_ENV" + mkdir -p docker-artifacts + docker buildx imagetools inspect --raw "$IMAGE_REF" > docker-artifacts/combined-index.json + node docker/verify-assembly.mjs docker-artifacts/combined-index.json \ + candidates/docker-candidate-amd64/index.json candidates/docker-candidate-arm64/index.json + for arch in amd64 arm64; do + DOCKER_PLATFORM="linux/$arch" DOCKER_ARTIFACT_DIR="docker-artifacts/$arch" \ + bash docker/verify-registry.sh "$IMAGE_REF" + done + - name: Rehearse exact-digest promotion and export the complete release + run: | + set -euo pipefail + bash docker/promote-image.sh "$IMAGE_REF" localhost:5000/markdown-viewer verified latest + mkdir -p release + skopeo copy --all --preserve-digests --src-tls-verify=false \ + "docker://$IMAGE_REF" oci-archive:release/image.tar + printf '%s\n' "${IMAGE_REF##*@}" > release/digest.txt + - uses: actions/upload-artifact@v4 + with: + name: docker-verified-release + path: release/ + compression-level: 0 + retention-days: 7 + if-no-files-found: error + - name: Upload release assembly evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: docker-registry-rehearsal + path: docker-artifacts/ + if-no-files-found: warn + + publish: + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + needs: assemble + runs-on: ubuntu-24.04 + timeout-minutes: 15 permissions: contents: read packages: write - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - - - name: Log in to Container Registry - uses: docker/login-action@v3 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Extract metadata - id: meta - uses: docker/metadata-action@v5 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - tags: | - type=ref,event=branch - type=ref,event=pr - type=sha,prefix=sha- - type=raw,value=latest,enable={{is_default_branch}} - - - name: Build and push Docker image - uses: docker/build-push-action@v5 - with: - context: . - push: ${{ github.event_name != 'pull_request' }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max - + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: docker/setup-buildx-action@v3 + - uses: actions/download-artifact@v4 + with: + name: docker-verified-release + path: release + - name: Log in to GHCR (main only) + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Copy the verified complete release to GHCR without rebuilding + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y skopeo + expected="$(cat release/digest.txt)" + skopeo copy --all --preserve-digests --dest-authfile "$HOME/.docker/config.json" \ + oci-archive:release/image.tar "docker://$IMAGE_REPO:candidate-$GITHUB_SHA" + actual="$(docker buildx imagetools inspect "$IMAGE_REPO:candidate-$GITHUB_SHA" --format '{{.Manifest.Digest}}')" + test "$actual" = "$expected" + IMAGE_REF="$IMAGE_REPO@$expected" + for arch in amd64 arm64; do + DOCKER_PLATFORM="linux/$arch" DOCKER_ARTIFACT_DIR="docker-artifacts/$arch" \ + bash docker/verify-registry.sh "$IMAGE_REF" + done + SHORT_SHA="$(printf '%s' "$GITHUB_SHA" | cut -c1-7)" + bash docker/promote-image.sh "$IMAGE_REF" "$IMAGE_REPO" "sha-$SHORT_SHA" latest + - name: Upload immutable release audit evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: docker-publish-evidence + path: docker-artifacts/ + if-no-files-found: warn diff --git a/Dockerfile b/Dockerfile index bc7c50b4..4eacfca1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,53 @@ -# Use nginx as the base image for serving static files -FROM nginx:alpine +# syntax=docker/dockerfile:1.7 +# Build NGINX 1.31.9 from a pinned upstream source commit without TLS modules. +# Markdown Viewer runs HTTP-only; no OpenSSL libraries are needed at runtime. +# This is deliberately a two-stage build: compilers and git never reach the image. +FROM alpine:3.24 AS nginx-builder +# Keep compiler downloads cached when only the NGINX source pin changes. +RUN apk add --no-cache build-base git pcre2-dev zlib-dev +ARG NGINX_REVISION=c2c44702c2fbc572e4cfb0a52331061d7fcaca16 +RUN git clone --quiet --depth 1 --branch release-1.31.9 \ + https://github.com/nginx/nginx.git /src/nginx \ + && test "$(git -C /src/nginx rev-parse HEAD)" = "$NGINX_REVISION" \ + && cd /src/nginx \ + && ./auto/configure \ + --prefix=/usr/share/nginx \ + --sbin-path=/usr/sbin/nginx \ + --conf-path=/etc/nginx/nginx.conf \ + --error-log-path=/var/log/nginx/error.log \ + --http-log-path=/var/log/nginx/access.log \ + --pid-path=/run/nginx.pid \ + --lock-path=/run/nginx.lock \ + --http-client-body-temp-path=/var/cache/nginx/client_temp \ + --http-proxy-temp-path=/var/cache/nginx/proxy_temp \ + --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \ + --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \ + --http-scgi-temp-path=/var/cache/nginx/scgi_temp \ + --with-pcre-jit \ + && make -j2 \ + && strip objs/nginx + +FROM alpine:3.24 +LABEL org.opencontainers.image.component.nginx.version="1.31.9" \ + org.opencontainers.image.component.nginx.source="https://github.com/nginx/nginx" \ + org.opencontainers.image.component.nginx.commit="c2c44702c2fbc572e4cfb0a52331061d7fcaca16" \ + org.opencontainers.image.component.nginx.license="BSD-2-Clause" +# Supported Alpine stable packages only; SSL/crypto shared libraries are absent. +# Alpine's package manager and BusyBox TLS helper depend on OpenSSL, but +# neither is needed to serve static HTTP. Remove them through APK itself so +# the remaining APK database accurately lists the installed runtime packages. +RUN apk upgrade --no-cache \ + && apk add --no-cache pcre2 zlib \ + && apk del apk-tools ssl_client openssl libssl3 libcrypto3 \ + && addgroup -S nginx \ + && adduser -S -G nginx nginx \ + && mkdir -p /etc/nginx/conf.d /etc/nginx/snippets /var/cache/nginx /var/log/nginx /run /usr/share/nginx/html /usr/share/licenses/nginx /usr/share/doc/nginx /usr/local/share/sbom \ + && ln -sf /dev/stdout /var/log/nginx/access.log \ + && ln -sf /dev/stderr /var/log/nginx/error.log +COPY --from=nginx-builder /src/nginx/objs/nginx /usr/sbin/nginx +COPY --from=nginx-builder /src/nginx/conf/mime.types /etc/nginx/mime.types +COPY --from=nginx-builder /src/nginx/LICENSE /usr/share/licenses/nginx/LICENSE +COPY docker/nginx-main.conf /etc/nginx/nginx.conf # PERF-019: Only copy necessary web files (exclude .git, desktop-app, wiki, etc.) COPY index.html /usr/share/nginx/html/ @@ -7,55 +55,36 @@ COPY workspace-storage.js /usr/share/nginx/html/ COPY visual-settings-adapters.js /usr/share/nginx/html/ COPY visual-settings-store.js /usr/share/nginx/html/ COPY script.js /usr/share/nginx/html/ +COPY browser-drop-source.js /usr/share/nginx/html/ +COPY native-markdown-source.js /usr/share/nginx/html/ +COPY preview-worker.js /usr/share/nginx/html/ COPY styles.css /usr/share/nginx/html/ COPY sw.js /usr/share/nginx/html/ COPY RELEASE_NOTES /usr/share/nginx/html/ COPY manifest.json /usr/share/nginx/html/ COPY robots.txt /usr/share/nginx/html/ COPY sitemap.xml /usr/share/nginx/html/ +COPY sample.md /usr/share/nginx/html/ COPY assets/ /usr/share/nginx/html/assets/ COPY seo/locales.mjs /usr/share/nginx/html/seo/ COPY seo/welcome-content.mjs /usr/share/nginx/html/seo/ -# Create a custom nginx configuration with compression and security -# PERF-020: Added gzip compression for text-based assets -RUN echo 'server { \ - listen 80; \ - server_name localhost; \ - root /usr/share/nginx/html; \ - index index.html; \ - \ - # Enable gzip compression (PERF-020) \ - gzip on; \ - gzip_vary on; \ - gzip_proxied any; \ - gzip_comp_level 6; \ - gzip_min_length 256; \ - gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript image/svg+xml; \ - \ - # Handle client-side routing for SPA \ - location / { \ - try_files $uri $uri/ /index.html; \ - } \ - \ - # Cache static assets \ - location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { \ - expires 1y; \ - add_header Cache-Control "public, immutable"; \ - } \ - \ - # Security headers \ - add_header X-Frame-Options "SAMEORIGIN" always; \ - add_header X-Content-Type-Options "nosniff" always; \ - add_header X-XSS-Protection "1; mode=block" always; \ - add_header Referrer-Policy "strict-origin-when-cross-origin" always; \ - # PERF-029: Content Security Policy for defense-in-depth \ - add_header Content-Security-Policy "default-src '"'"'self'"'"'; base-uri '"'"'self'"'"'; object-src '"'"'none'"'"'; script-src '"'"'self'"'"' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net '"'"'unsafe-inline'"'"'; worker-src '"'"'self'"'"'; connect-src '"'"'self'"'"' https://api.github.com https://raw.githubusercontent.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net https://kroki.io https://www.plantuml.com https://mermaid.ink https://paulrosen.github.io; img-src '"'"'self'"'"' data: blob: https:; style-src '"'"'self'"'"' '"'"'unsafe-inline'"'"' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; font-src '"'"'self'"'"' data: https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; media-src '"'"'self'"'"' blob: data:; manifest-src '"'"'self'"'"'" always; \ - }' > /etc/nginx/conf.d/default.conf +# Reviewable HTTP server and security-header configuration +COPY docker/nginx-server.conf /etc/nginx/conf.d/default.conf +COPY docker/security-headers.conf /etc/nginx/snippets/security-headers.conf +COPY docker/check-runtime.sh /usr/local/bin/check-docker-runtime +COPY docker/nginx-component.spdx.json /usr/share/doc/nginx/component.spdx.json +# BuildKit Syft indexes embedded SPDX supplements in the image filesystem. +COPY docker/nginx-component.spdx.json /usr/local/share/sbom/nginx.spdx.json +RUN chmod 0755 /usr/local/bin/check-docker-runtime \ + && /usr/local/bin/check-docker-runtime # Expose port 80 EXPOSE 80 +STOPSIGNAL SIGQUIT +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD wget -q -O /dev/null http://127.0.0.1:80/ || exit 1 # Start nginx CMD ["nginx", "-g", "daemon off;"] diff --git a/desktop-app/resources/js/script.js b/desktop-app/resources/js/script.js index 5927d52b..0becc3e8 100644 --- a/desktop-app/resources/js/script.js +++ b/desktop-app/resources/js/script.js @@ -30400,7 +30400,7 @@ ${selector} .arrowheadPath { function getPublicAppBaseUrl() { const isLocal = window.location.origin.includes('localhost') || window.location.origin.includes('127.0.0.1') || - window.location.origin.startsWith('file://') || + window.location.protocol === 'file:' || typeof Neutralino !== 'undefined'; return isLocal @@ -30411,7 +30411,7 @@ ${selector} .arrowheadPath { function getShareApiBaseUrl() { const isLocal = window.location.origin.includes('localhost') || window.location.origin.includes('127.0.0.1') || - window.location.origin.startsWith('file://') || + window.location.protocol === 'file:' || typeof Neutralino !== 'undefined'; return isLocal ? 'https://markdownviewer.pages.dev' : window.location.origin; @@ -31245,12 +31245,11 @@ ${selector} .arrowheadPath { return wsBase + '/' + encodedRoom + query; } - if (typeof Neutralino !== 'undefined' || window.location.protocol === 'file:') { - return 'wss://markdownviewer.pages.dev/live-room/' + encodedRoom + query; - } - - const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; - return wsProtocol + '//' + window.location.host + '/live-room/' + encodedRoom + query; + // Localhost/Docker and desktop clients use the same hosted service as + // stored snapshots. Deployed web origins retain their same-origin relay. + // An explicitly configured relay above always takes precedence. + const wsBase = getShareApiBaseUrl().replace(/^http:/i, 'ws:').replace(/^https:/i, 'wss:'); + return wsBase + '/live-room/' + encodedRoom + query; } function ensureLiveShareCompressionReady() { @@ -35870,13 +35869,22 @@ ${selector} .arrowheadPath { }); } - // Register Service Worker for offline capabilities + // Register even when asynchronous startup finishes after the load event. + // A one-shot handler prevents duplicate registrations in the early path. if ('serviceWorker' in navigator) { - window.addEventListener('load', function() { + function registerMarkdownViewerServiceWorker() { navigator.serviceWorker.register('sw.js').catch(function(err) { - console.log('ServiceWorker registration failed: ', err); + console.warn('ServiceWorker registration failed:', err); + window.dispatchEvent(new CustomEvent('markdown-viewer:service-worker-error', { + detail: { message: String(err && err.message || err) } + })); }); - }); + } + if (document.readyState === 'complete') { + registerMarkdownViewerServiceWorker(); + } else { + window.addEventListener('load', registerMarkdownViewerServiceWorker, { once: true }); + } } // Wait until all editor and collaboration dependencies exist before adding the update tab. diff --git a/docker-compose.build.yml b/docker-compose.build.yml new file mode 100644 index 00000000..d20123be --- /dev/null +++ b/docker-compose.build.yml @@ -0,0 +1,8 @@ +# Developer override: +# docker compose -f docker-compose.yml -f docker-compose.build.yml up -d --build +services: + markdown-viewer: + image: markdown-viewer:dev + build: + context: . + dockerfile: Dockerfile diff --git a/docker-compose.yml b/docker-compose.yml index dc02169d..e6ad8613 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,14 +1,14 @@ -# PERF-035: Removed deprecated 'version' key (Docker Compose v2+ ignores it) - +# Pull the prebuilt release by default; no local compiler toolchain needed. services: markdown-viewer: - build: - context: . - dockerfile: Dockerfile - ports: - - "8080:80" + image: ghcr.io/thisis-developer/markdown-viewer:latest container_name: markdown-viewer + ports: + - "127.0.0.1:8080:80" restart: unless-stopped - environment: - - NGINX_HOST=localhost - - NGINX_PORT=80 + stop_grace_period: 20s + logging: + driver: local + options: + max-size: "10m" + max-file: "3" diff --git a/docker/SECURITY-MAINTENANCE.md b/docker/SECURITY-MAINTENANCE.md new file mode 100644 index 00000000..ab9b2b5d --- /dev/null +++ b/docker/SECURITY-MAINTENANCE.md @@ -0,0 +1,79 @@ +# Source-compiled NGINX: security inventory and maintenance + +**Owner:** Markdown Viewer maintainers. +**Cadence:** Review upstream NGINX and Alpine advisories monthly and on +security announcements. The scheduled monthly GitHub Actions verification +is non-publishing; it does not replace a human upstream advisory review. + +## Decision and trade-off + +The requirement is an HTTP-only image without shipping OpenSSL runtime +libraries. The Dockerfile builds upstream NGINX 1.31.9 from +release-1.31.9, verified commit +c2c44702c2fbc572e4cfb0a52331061d7fcaca16. + +An official, version-and-digest-pinned slim NGINX image simplifies compiler +and patch maintenance, but should **not** be called OpenSSL-free without +independent package and runtime-linkage inspection. Replacing this custom +binary later needs a separate product decision and corresponding tests. + +The 2026-11-20 review updates the pinned source to 1.31.9 following the +2026-11-18 upstream security release. Review advisory applicability as well +as versions: TLS, HTTP/2, HTTP/3, mail and stream are not enabled here; +the stock static configuration does not use resolver, alias or PROXY protocol. +Keep the source, runtime assertion, labels and component inventory aligned. + +## Identity and license + +- Component: nginx 1.31.9, from https://github.com/nginx/nginx +- Source commit: c2c44702c2fbc572e4cfb0a52331061d7fcaca16 +- License: BSD-2-Clause, distributed at + /usr/share/licenses/nginx/LICENSE +- Supplementary SPDX at /usr/local/share/sbom/nginx.spdx.json and + /usr/share/doc/nginx/component.spdx.json +- Binary: /usr/sbin/nginx (no SSL/QUIC build modules) +- OS inventory: /lib/apk/db/installed + +The supplementary SPDX identifies the custom binary without inventing an +Alpine APK entry. The release job must verify NGINX is present in the actual +BuildKit-attested OCI index SBOM or stop promotion. Document uncertainty if +the SBOM generator omits it. A zero-CVE OS package scan is NOT a NGINX scan. + +PRs build and test attested AMD64 and ARM64 candidates on native runners in +ephemeral localhost registries. Each architecture has independent browser, +runtime and vulnerability checks. OCI archives preserve the tested manifests +and attestations between jobs; assembly rejects missing or substituted +manifests. The combined index is verified and its promotion rehearsed before +main copies it to GHCR without rebuilding. PRs do not publish to GHCR. +Both single-platform +and multi-platform Buildx attestation output are supported; missing SPDX or +BuildKit provenance blocks promotion. This rehearses the release mechanism, +but real GHCR credentials/permissions are only exercised after merge. + +## Release/advisory review + +1. Examine https://nginx.org/en/security_advisories.html and recent upstream + releases. Compare actual affected versions, configurations and build + options with this pinned upstream-source build. +2. Inspect Alpine stable branch package advisories separately. Do not install + edge patches or misclassify upstream vs Alpine rebuild versions. +3. Validate final runtime-package inventory, NGINX executable linkage, + source version, distributed license and SBOM component metadata. +4. For a release, verify the single immutable OCI index digest is the one + tested, vulnerability-scanned and promoted. Record both the OCI manifest + digest and platform-specific image config ID; they are different. +5. Inspect the registry SBOM/provenance, browser checks, mandatory assets, + security response headers and 404 paths. +6. Compare Trivy and Docker Scout only on the same digest/platform/database + time; retain full results and don't suppress findings for a zero score. +7. Keep an immutable commit tag and exact digest to support rollback. + +Known limitations: automated OS-package scanning does not fully analyze a +source-built NGINX executable; current browser tests are not a complete +security audit. Root-master removal, read-only filesystem, production +load/peak memory, and all CDN-dependent +offline renderers require independent validation. No false zero-risk claim. + +Do not automatically delete users' Docker caches, volumes or containers. +A scoped, age-filtered build-cache cleanup is optional and trades disk space +against future cold build time. diff --git a/docker/check-runtime.sh b/docker/check-runtime.sh new file mode 100644 index 00000000..592022f8 --- /dev/null +++ b/docker/check-runtime.sh @@ -0,0 +1,34 @@ +#!/bin/sh +set -eu +db="${APK_DB_PATH:-/lib/apk/db/installed}" +if [ ! -r "$db" ] || [ ! -s "$db" ]; then + echo "FAIL: missing/unreadable APK installed-package inventory: $db" >&2; exit 1 +fi +if ! grep -q '^P:' "$db"; then + echo "FAIL: invalid APK installed-package inventory" >&2; exit 1 +fi +if grep -Eq '^P:(openssl|libssl3|libcrypto3)$' "$db"; then + echo "FAIL: OpenSSL runtime package detected" >&2; exit 1 +fi +for path in /lib/libssl* /usr/lib/libssl* /usr/local/lib/libssl* /lib/libcrypto* /usr/lib/libcrypto* /usr/local/lib/libcrypto*; do + if [ -e "$path" ] || [ -L "$path" ]; then + echo "FAIL: OpenSSL shared library found: $path" >&2; exit 1 + fi +done +if ! command -v ldd >/dev/null 2>&1; then + echo "FAIL: missing ldd" >&2; exit 1 +fi +links="$(ldd /usr/sbin/nginx 2>&1)" || { + echo "FAIL: cannot inspect nginx linkage" >&2; exit 1 +} +if printf '%s\n' "$links" | grep -Eq 'lib(ssl|crypto)|not found|Error'; then + echo "FAIL: forbidden/unresolved nginx shared library" >&2; exit 1 +fi +options="$(nginx -V 2>&1)" || { echo "FAIL: nginx -V failed" >&2; exit 1; } +if printf '%s\n' "$options" | grep -Eq -- '--with-(http_ssl|http_v3|stream_ssl)_module'; then + echo "FAIL: SSL/QUIC module enabled" >&2; exit 1 +fi +if ! printf '%s\n' "$options" | grep -Fxq 'nginx version: nginx/1.31.9'; then + echo "FAIL: NGINX version differs from SBOM" >&2; exit 1 +fi +echo "PASS: no OpenSSL packages, libraries or NGINX SSL modules" diff --git a/docker/nginx-component.spdx.json b/docker/nginx-component.spdx.json new file mode 100644 index 00000000..3c1a5658 --- /dev/null +++ b/docker/nginx-component.spdx.json @@ -0,0 +1,40 @@ +{ + "spdxVersion": "SPDX-2.3", + "dataLicense": "CC0-1.0", + "SPDXID": "SPDXRef-DOCUMENT", + "name": "Markdown-Viewer-Custom-NGINX-Component", + "documentNamespace": "https://github.com/ThisIs-Developer/Markdown-Viewer/spdx/nginx/1.31.9-c2c44702c2fbc572e4cfb0a52331061d7fcaca16", + "creationInfo": { + "creators": [ + "Organization: ThisIs-Developer" + ], + "created": "2026-11-20T00:00:00Z" + }, + "packages": [ + { + "name": "nginx", + "SPDXID": "SPDXRef-Package-nginx", + "versionInfo": "1.31.9", + "downloadLocation": "https://github.com/nginx/nginx/archive/c2c44702c2fbc572e4cfb0a52331061d7fcaca16.tar.gz", + "filesAnalyzed": false, + "licenseDeclared": "BSD-2-Clause", + "licenseConcluded": "NOASSERTION", + "copyrightText": "Copyright (C) 2002-2021 Igor Sysoev; Copyright (C) 2011-2026 Nginx, Inc.", + "sourceInfo": "Upstream release-1.31.9 pinned to commit c2c44702c2fbc572e4cfb0a52331061d7fcaca16; HTTP-only custom build", + "externalRefs": [ + { + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": "pkg:generic/nginx@1.31.9" + } + ] + } + ], + "relationships": [ + { + "spdxElementId": "SPDXRef-DOCUMENT", + "relatedSpdxElement": "SPDXRef-Package-nginx", + "relationshipType": "DESCRIBES" + } + ] +} diff --git a/docker/nginx-main.conf b/docker/nginx-main.conf new file mode 100644 index 00000000..ccb7c437 --- /dev/null +++ b/docker/nginx-main.conf @@ -0,0 +1,18 @@ +# Main process and HTTP configuration for the HTTP-only custom NGINX build. +# HTTPS/SSL is intentionally not compiled into the server. +user nginx; +worker_processes auto; +error_log /var/log/nginx/error.log notice; +pid /run/nginx.pid; + +events { + worker_connections 1024; +} + +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + sendfile on; + keepalive_timeout 65; + include /etc/nginx/conf.d/*.conf; +} diff --git a/docker/nginx-server.conf b/docker/nginx-server.conf new file mode 100644 index 00000000..47fbafae --- /dev/null +++ b/docker/nginx-server.conf @@ -0,0 +1,44 @@ +# HTTP-only Markdown Viewer. +server { + listen 80; + server_name localhost; + root /usr/share/nginx/html; + index index.html; + include /etc/nginx/snippets/security-headers.conf; + gzip on; + gzip_vary on; + gzip_proxied any; + gzip_comp_level 6; + gzip_min_length 256; + gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript image/svg+xml; + + # Stable code filenames change between releases; do not cache immutably. + location = /sw.js { + include /etc/nginx/snippets/security-headers.conf; + add_header Cache-Control "no-cache, must-revalidate" always; + try_files $uri =404; + } + location ~* \.mjs$ { + types { application/javascript mjs; } + default_type application/javascript; + include /etc/nginx/snippets/security-headers.conf; + add_header Cache-Control "no-cache, must-revalidate" always; + try_files $uri =404; + } + location ~* \.(js|css|json|md|html)$ { + include /etc/nginx/snippets/security-headers.conf; + add_header Cache-Control "no-cache, must-revalidate" always; + try_files $uri =404; + } + location ~* \.(png|jpe?g|gif|ico|svg|webp|woff2?)$ { + include /etc/nginx/snippets/security-headers.conf; + add_header Cache-Control "public, max-age=3600" always; + try_files $uri =404; + } + location / { + # Always revalidate the unversioned editor shell on online navigation. + include /etc/nginx/snippets/security-headers.conf; + add_header Cache-Control "no-cache, must-revalidate" always; + try_files $uri $uri/ /index.html; + } +} diff --git a/docker/promote-image.sh b/docker/promote-image.sh new file mode 100644 index 00000000..229c5482 --- /dev/null +++ b/docker/promote-image.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Promote the already-verified OCI index, never rebuild it. +set -euo pipefail +image="$1" +repository="$2" +shift 2 +[[ "$image" =~ @sha256:[a-f0-9]{64}$ ]] || { echo 'FAIL: immutable digest required' >&2; exit 1; } +test "$#" -gt 0 +expected="${image##*@}" +mkdir -p docker-artifacts +for tag in "$@"; do + docker buildx imagetools create --tag "$repository:$tag" "$image" + actual="$(docker buildx imagetools inspect "$repository:$tag" --format '{{ .Manifest.Digest }}')" + test "$actual" = "$expected" || { echo "FAIL: changed index digest for $tag: $actual" >&2; exit 1; } + printf 'promoted_%s=%s\n' "$tag" "$actual" | tee -a docker-artifacts/candidate-identity.txt +done diff --git a/docker/security-headers.conf b/docker/security-headers.conf new file mode 100644 index 00000000..9766a380 --- /dev/null +++ b/docker/security-headers.conf @@ -0,0 +1,5 @@ +# NGINX header inheritance requires repetition in any location using add_header. +add_header X-Frame-Options "SAMEORIGIN" always; +add_header X-Content-Type-Options "nosniff" always; +add_header Referrer-Policy "strict-origin-when-cross-origin" always; +add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; object-src 'none'; script-src 'self' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net https://esm.sh 'unsafe-inline'; worker-src 'self'; connect-src 'self' https://markdownviewer.pages.dev wss://markdownviewer.pages.dev ws://localhost:* ws://127.0.0.1:* https://api.github.com https://raw.githubusercontent.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net https://esm.sh https://kroki.io https://www.plantuml.com https://mermaid.ink https://paulrosen.github.io; img-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; font-src 'self' data: https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; media-src 'self' blob: data: https:; manifest-src 'self'" always; diff --git a/docker/verify-assembly.mjs b/docker/verify-assembly.mjs new file mode 100644 index 00000000..b5dd69ef --- /dev/null +++ b/docker/verify-assembly.mjs @@ -0,0 +1,33 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { pathToFileURL } from 'node:url'; + +export function verifyAssembly(combined, sources) { + assert.equal(combined.mediaType, 'application/vnd.oci.image.index.v1+json'); + const expected = sources.flatMap(source => { + assert.equal(source.mediaType, combined.mediaType); + assert.ok(Array.isArray(source.manifests)); + return source.manifests; + }); + const sort = manifests => [...manifests].sort((a, b) => a.digest.localeCompare(b.digest)); + assert.deepEqual(sort(combined.manifests), sort(expected), + 'Assembly changed or omitted tested manifests/attestations'); + const platforms = combined.manifests.filter(m => m.platform?.os === 'linux') + .map(m => `${m.platform.os}/${m.platform.architecture}`).sort(); + assert.deepEqual(platforms, ['linux/amd64', 'linux/arm64'], + 'Exactly one tested AMD64 and ARM64 image is required'); + for (const manifest of combined.manifests.filter(m => m.platform?.os === 'linux')) { + assert.ok(combined.manifests.some(m => + m.annotations?.['vnd.docker.reference.type'] === 'attestation-manifest' && + m.annotations?.['vnd.docker.reference.digest'] === manifest.digest), + 'Missing attestation for a tested platform'); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const [combined, ...sources] = process.argv.slice(2).map(file => JSON.parse(fs.readFileSync(file))); + assert.equal(sources.length, 2, 'Supply combined index and both tested source indexes'); + verifyAssembly(combined, sources); + console.log('PASS: combined index preserves both tested platforms and their attestations'); +} + diff --git a/docker/verify-attestations.mjs b/docker/verify-attestations.mjs new file mode 100644 index 00000000..5b004490 --- /dev/null +++ b/docker/verify-attestations.mjs @@ -0,0 +1,39 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { pathToFileURL } from 'node:url'; + +export function verifySbom(value, expectedVersion, platform = 'linux/amd64') { + // Buildx returns a direct stub for one platform and a map for multiple + // platforms. Syft emits the SPDX document directly. + const document = value?.spdxVersion ? value : + (value?.SPDX ?? value?.[platform]?.SPDX); + assert.equal(document?.spdxVersion, 'SPDX-2.3', 'Missing SPDX 2.3 inventory'); + assert.ok(Array.isArray(document.packages), 'Missing SBOM packages'); + assert.ok(document.packages.some(pkg => + pkg.name?.toLowerCase() === 'nginx' && pkg.versionInfo === expectedVersion), + `SBOM must identify nginx ${expectedVersion}`); + return document; +} + +export function verifyProvenance(value, platform = 'linux/amd64') { + const provenance = value?.SLSA ?? value?.[platform]?.SLSA; + const buildType = provenance?.buildType ?? provenance?.buildDefinition?.buildType; + const supportedBuildTypes = [ + 'https://mobyproject.org/buildkit@v1', + 'https://github.com/moby/buildkit/blob/master/docs/attestations/slsa-definitions.md' + ]; + assert.ok(supportedBuildTypes.includes(buildType), 'Missing or unrecognized BuildKit SLSA provenance'); + return provenance; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const expected = JSON.parse(fs.readFileSync(new URL('./nginx-component.spdx.json', import.meta.url))) + .packages.find(pkg => pkg.name === 'nginx').versionInfo; + const [sbomFile, provenanceFile] = process.argv.slice(2); + assert.ok(sbomFile, 'Usage: node docker/verify-attestations.mjs SBOM.json [provenance.json]'); + const platform = process.env.DOCKER_PLATFORM || 'linux/amd64'; + assert.ok(['linux/amd64', 'linux/arm64'].includes(platform), 'Unsupported Docker platform'); + verifySbom(JSON.parse(fs.readFileSync(sbomFile)), expected, platform); + if (provenanceFile) verifyProvenance(JSON.parse(fs.readFileSync(provenanceFile)), platform); + console.log(`PASS: ${platform} nginx ${expected} inventory${provenanceFile ? ' and BuildKit provenance' : ''}`); +} diff --git a/docker/verify-browser.sh b/docker/verify-browser.sh new file mode 100755 index 00000000..bc01efd4 --- /dev/null +++ b/docker/verify-browser.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail +image="$1" +name="mdv-verify-browser-$$" +cleanup() { docker rm -f "$name" >/dev/null 2>&1 || true; } +trap cleanup EXIT +docker run --rm -d --name "$name" -p 127.0.0.1:18080:80 "$image" >/dev/null +ready=0 +for i in $(seq 1 30); do + if curl -fsS --max-time 3 -o /dev/null http://127.0.0.1:18080/; then ready=1; break; fi + sleep 1 +done +test "$ready" -eq 1 || { echo "FAIL: missing browser test Docker server" >&2; exit 1; } +MARKDOWN_VIEWER_TEST_CONTAINER=1 MARKDOWN_VIEWER_TEST_PORT=18080 \ + npx playwright test tests/e2e/smoke.spec.js tests/e2e/docker.spec.js tests/e2e/docker-sharing.spec.js \ + --project=chromium --grep-invert='static build smoke check passes' diff --git a/docker/verify-graceful.sh b/docker/verify-graceful.sh new file mode 100755 index 00000000..ba5028ac --- /dev/null +++ b/docker/verify-graceful.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Disposable test: verify an in-flight HTTP transfer survives Docker's +# configured SIGQUIT graceful shutdown within the documented grace period. +set -euo pipefail +image="$1" +name="mdv-graceful-$$" +temp="$(mktemp -d)" +curl_pid='' +cleanup() { + if [ -n "$curl_pid" ]; then kill "$curl_pid" >/dev/null 2>&1 || true; fi + docker rm -f "$name" >/dev/null 2>&1 || true + rm -rf "$temp" +} +trap cleanup EXIT +# Throttle at the server as well as the client: otherwise the entire small +# response can fit in TCP buffers before stop, hiding a fast-shutdown bug. +docker run --rm -d --name "$name" -p 127.0.0.1:18081:80 --entrypoint sh "$image" -ec ' + sed -i "/server_name localhost;/a\\ limit_rate 256k;" /etc/nginx/conf.d/default.conf + exec nginx -g "daemon off;" +' >/dev/null +for i in $(seq 1 30); do + if curl -fsS --max-time 3 -o /dev/null http://127.0.0.1:18081/; then break; fi + sleep 1 +done +docker exec "$name" sh -c 'dd if=/dev/zero of=/usr/share/nginx/html/graceful-slow.bin bs=1048576 count=2 2>/dev/null' +curl --silent --show-error --fail --limit-rate 256k \ + --dump-header "$temp/slow-headers" \ + --output "$temp/slow-content" http://127.0.0.1:18081/graceful-slow.bin & +curl_pid=$! +ready=0 +for i in $(seq 1 100); do + if test -s "$temp/slow-headers" && grep -q '^HTTP/1.1 200' "$temp/slow-headers" && test -s "$temp/slow-content"; then + ready=1 + break + fi + kill -0 "$curl_pid" >/dev/null 2>&1 || break + sleep 0.1 +done +test "$ready" -eq 1 || { echo "FAIL: controlled transfer never started" >&2; exit 1; } +docker stop --time 20 "$name" >/dev/null +wait "$curl_pid" || { echo "FAIL: transfer interrupted during graceful stop" >&2; exit 1; } +curl_pid='' +bytes="$(wc -c < "$temp/slow-content" | tr -d ' ')" +test "$bytes" = 2097152 || { echo "FAIL: truncated transfer ($bytes bytes)" >&2; exit 1; } +if curl -fsS --max-time 2 -o /dev/null http://127.0.0.1:18081/; then + echo "FAIL: stopped container still accepts requests" >&2 + exit 1 +fi +echo "PASS: SIGQUIT completed 2MiB active HTTP download within 20s grace period" diff --git a/docker/verify-image.sh b/docker/verify-image.sh new file mode 100755 index 00000000..269357a0 --- /dev/null +++ b/docker/verify-image.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +set -euo pipefail +image="$1" +name="mdv-verify-image-$$" +temp="$(mktemp -d)" +cleanup() { docker rm -f "$name" >/dev/null 2>&1 || true; rm -rf "$temp"; } +trap cleanup EXIT +docker run --rm -d --name "$name" -p 127.0.0.1:18080:80 "$image" >/dev/null +docker exec "$name" nginx -t +docker exec "$name" /usr/local/bin/check-docker-runtime +docker exec "$name" test -s /usr/share/licenses/nginx/LICENSE +docker exec "$name" test -s /usr/share/doc/nginx/component.spdx.json +docker exec "$name" sh -ec ' + cp /lib/apk/db/installed /tmp/installed-test + printf "\nP:libssl3\n" >> /tmp/installed-test + if APK_DB_PATH=/tmp/installed-test /usr/local/bin/check-docker-runtime; then + echo "FAIL: forbidden library fixture accepted" >&2; exit 1 + fi + if APK_DB_PATH=/tmp/missing-inventory /usr/local/bin/check-docker-runtime; then + echo "FAIL: missing package inventory accepted" >&2; exit 1 + fi + rm -f /tmp/installed-test +' +test "$(docker image inspect "$image" --format '{{.Config.StopSignal}}')" = "SIGQUIT" +ready=0 +for i in $(seq 1 30); do + if curl -fsS --max-time 3 -o /dev/null http://127.0.0.1:18080/; then ready=1; break; fi + sleep 1 +done +test "$ready" -eq 1 || { echo "FAIL: HTTP container not ready" >&2; exit 1; } +python3 - <<'PY' > "$temp/critical-assets" +import pathlib,re,sys +source=pathlib.Path('sw.js').read_text() +match=re.search(r'const CRITICAL_ASSETS = \[(.*?)\];',source,re.S) +if not match: sys.exit('No critical asset list') +items=re.findall(r"""['"](\./[^'"]+)['"]""",match.group(1)) +if len(items)<10: sys.exit('Too few critical assets') +print('\n'.join(items)) +PY +while IFS= read -r item; do + relative="$(printf '%s' "$item" | sed 's,^\./,,')" + if [ -z "$relative" ]; then relative="index.html"; fi + test -f "$relative" + curl -fsS --max-time 10 "http://127.0.0.1:18080/$relative" -o "$temp/actual" + cmp -s "$relative" "$temp/actual" || { echo "FAIL: incorrect /$relative (SPA fallback?)" >&2; exit 1; } +done < "$temp/critical-assets" +for rel in browser-drop-source.js native-markdown-source.js preview-worker.js assets/linked-workspace-guide.md; do + test -f "$rel" + curl -fsS --max-time 10 "http://127.0.0.1:18080/$rel" -o "$temp/actual" + cmp -s "$rel" "$temp/actual" || { echo "FAIL: incorrect $rel" >&2; exit 1; } +done +for url in / /index.html /script.js /styles.css /sw.js /preview-worker.js /assets/seo-metadata.mjs /not-a-real-file.mjs; do + curl -sS -D "$temp/headers" -o /dev/null --max-time 10 "http://127.0.0.1:18080$url" + grep -iq '^x-content-type-options: nosniff' "$temp/headers" + grep -iq '^content-security-policy:' "$temp/headers" + grep -iq '^x-frame-options: SAMEORIGIN' "$temp/headers" + if [ "$url" != "/not-a-real-file.mjs" ]; then + grep -iq '^cache-control: no-cache' "$temp/headers" || { echo "FAIL: immutable mutable resource $url" >&2; exit 1; } + fi +done +for url in /not-a-real-file.mjs /not-a-real-file.js /not-a-real-file.css; do + code="$(curl -sS -o /dev/null -w '%{http_code}' "http://127.0.0.1:18080$url")" + test "$code" = 404 || { echo "FAIL: $url is $code not 404" >&2; exit 1; } +done +curl -fsSI http://127.0.0.1:18080/assets/seo-metadata.mjs | grep -Eiq '^content-type: (application|text)/javascript' +if curl -fsSI http://127.0.0.1:18080/ | grep -qi 'upgrade-insecure-requests'; then + echo "FAIL: HTTP-only image forces HTTPS" >&2; exit 1 +fi +etag="$(curl -fsSI http://127.0.0.1:18080/script.js | sed -n 's/^[Ee][Tt][Aa][Gg]:[[:space:]]*//p' | tr -d '\r' | head -1)" +test -n "$etag" +code="$(curl -sS -o /dev/null -w '%{http_code}' -H "If-None-Match: $etag" http://127.0.0.1:18080/script.js)" +test "$code" = 304 || { echo "FAIL: conditional request is $code" >&2; exit 1; } +echo "PASS: actual assets/content, missing resources, headers, cache, OpenSSL, shutdown signal" diff --git a/docker/verify-registry.sh b/docker/verify-registry.sh new file mode 100644 index 00000000..41815efe --- /dev/null +++ b/docker/verify-registry.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euo pipefail +image="$1" +platform="${DOCKER_PLATFORM:-linux/amd64}" +case "$platform" in linux/amd64|linux/arm64) ;; *) echo 'FAIL: unsupported platform' >&2; exit 1 ;; esac +architecture="${platform#linux/}" +artifacts="${DOCKER_ARTIFACT_DIR:-docker-artifacts}" +[[ "$image" =~ @sha256:[a-f0-9]{64}$ ]] || { echo 'FAIL: immutable digest required' >&2; exit 1; } +mkdir -p "$artifacts" +docker buildx imagetools inspect --raw "$image" > "$artifacts/candidate-index.json" +jq -e '.mediaType == "application/vnd.oci.image.index.v1+json"' "$artifacts/candidate-index.json" +platform_digest="$(jq -er --arg arch "$architecture" '[.manifests[] | select(.platform.os == "linux" and .platform.architecture == $arch) | .digest] | + if length == 1 then .[0] else error("Expected one native platform manifest") end' "$artifacts/candidate-index.json")" +jq -e --arg digest "$platform_digest" 'any(.manifests[]; + .annotations["vnd.docker.reference.type"] == "attestation-manifest" and + .annotations["vnd.docker.reference.digest"] == $digest)' "$artifacts/candidate-index.json" +docker buildx imagetools inspect --raw "${image%@*}@$platform_digest" > "$artifacts/candidate-platform-manifest.json" +config_digest="$(jq -er '.config.digest | select(test("^sha256:[a-f0-9]{64}$"))' "$artifacts/candidate-platform-manifest.json")" +printf 'platform=%s\nplatform_manifest_digest=%s\nimage_config_digest=%s\n' "$platform" "$platform_digest" "$config_digest" | tee -a "$artifacts/candidate-identity.txt" +docker buildx imagetools inspect "$image" --format '{{ json .SBOM }}' > "$artifacts/candidate-sbom.json" +docker buildx imagetools inspect "$image" --format '{{ json .Provenance }}' > "$artifacts/candidate-provenance.json" +node docker/verify-attestations.mjs "$artifacts/candidate-sbom.json" "$artifacts/candidate-provenance.json" diff --git a/package-lock.json b/package-lock.json index f598b7f5..b0f74a48 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,7 +28,8 @@ "mathjax-asana-font": "4.0.0-beta.7", "mathjax-stix2-font": "4.0.0-beta.7", "pako": "2.1.0", - "pdfjs-dist": "5.4.624" + "pdfjs-dist": "5.4.624", + "yjs": "13.6.10" }, "engines": { "node": ">=22 <27" @@ -1095,6 +1096,17 @@ "dev": true, "license": "MIT" }, + "node_modules/isomorphic.js": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", + "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", + "dev": true, + "license": "MIT", + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/js-yaml": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", @@ -1155,6 +1167,28 @@ "dev": true, "license": "(MIT AND Zlib)" }, + "node_modules/lib0": { + "version": "0.2.120", + "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.120.tgz", + "integrity": "sha512-/a2eRImR8sZbmMVKe2we1/KukDQkuPyPf8yol6epvCu2PH6hurjcRI3mdGFFAi0uGoRJGyns99JquZgxwW1tQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "isomorphic.js": "^0.2.4" + }, + "bin": { + "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js", + "0gentesthtml": "bin/gentesthtml.js", + "0serve": "bin/0serve.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/lie": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", @@ -1412,6 +1446,24 @@ "integrity": "sha512-Gd9+TUn5nXdwj/hFsPVx5cuHHiF5Bwuc30jZ4+ronF1qHK5O7HD0sgmXWSEgwKquT3ClLoKPVbO6qGwVwLzvAw==", "dev": true, "license": "MIT" + }, + "node_modules/yjs": { + "version": "13.6.10", + "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.10.tgz", + "integrity": "sha512-1JcyQek1vaMyrDm7Fqfa+pvHg/DURSbVo4VmeN7wjnTKB/lZrfIPhdCj7d8sboK6zLfRBJXegTjc9JlaDd8/Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lib0": "^0.2.86" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } } } } diff --git a/package.json b/package.json index 72c499a8..43529e00 100644 --- a/package.json +++ b/package.json @@ -51,6 +51,7 @@ "mathjax-asana-font": "4.0.0-beta.7", "mathjax-stix2-font": "4.0.0-beta.7", "pako": "2.1.0", - "pdfjs-dist": "5.4.624" + "pdfjs-dist": "5.4.624", + "yjs": "13.6.10" } } diff --git a/playwright.config.js b/playwright.config.js index 7adda799..a4ff1b9a 100644 --- a/playwright.config.js +++ b/playwright.config.js @@ -3,6 +3,7 @@ const { defineConfig, devices } = require('@playwright/test'); const PORT = Number(process.env.MARKDOWN_VIEWER_TEST_PORT || 4173); const HOST = '127.0.0.1'; const browserChannel = process.env.PLAYWRIGHT_CHANNEL || undefined; +const isContainerTest = process.env.MARKDOWN_VIEWER_TEST_CONTAINER === '1'; module.exports = defineConfig({ testDir: './tests/e2e', @@ -12,7 +13,7 @@ module.exports = defineConfig({ }, fullyParallel: false, reporter: [['list'], ['html', { open: 'never' }]], - webServer: { + webServer: isContainerTest ? undefined : { command: 'node tests/helpers/static-server.mjs', url: `http://${HOST}:${PORT}/`, reuseExistingServer: true, @@ -21,7 +22,7 @@ module.exports = defineConfig({ }, use: { baseURL: `http://${HOST}:${PORT}`, - serviceWorkers: 'block', + serviceWorkers: isContainerTest ? 'allow' : 'block', trace: 'on-first-retry', screenshot: 'only-on-failure', video: 'retain-on-failure' diff --git a/script.js b/script.js index 5927d52b..0becc3e8 100644 --- a/script.js +++ b/script.js @@ -30400,7 +30400,7 @@ ${selector} .arrowheadPath { function getPublicAppBaseUrl() { const isLocal = window.location.origin.includes('localhost') || window.location.origin.includes('127.0.0.1') || - window.location.origin.startsWith('file://') || + window.location.protocol === 'file:' || typeof Neutralino !== 'undefined'; return isLocal @@ -30411,7 +30411,7 @@ ${selector} .arrowheadPath { function getShareApiBaseUrl() { const isLocal = window.location.origin.includes('localhost') || window.location.origin.includes('127.0.0.1') || - window.location.origin.startsWith('file://') || + window.location.protocol === 'file:' || typeof Neutralino !== 'undefined'; return isLocal ? 'https://markdownviewer.pages.dev' : window.location.origin; @@ -31245,12 +31245,11 @@ ${selector} .arrowheadPath { return wsBase + '/' + encodedRoom + query; } - if (typeof Neutralino !== 'undefined' || window.location.protocol === 'file:') { - return 'wss://markdownviewer.pages.dev/live-room/' + encodedRoom + query; - } - - const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; - return wsProtocol + '//' + window.location.host + '/live-room/' + encodedRoom + query; + // Localhost/Docker and desktop clients use the same hosted service as + // stored snapshots. Deployed web origins retain their same-origin relay. + // An explicitly configured relay above always takes precedence. + const wsBase = getShareApiBaseUrl().replace(/^http:/i, 'ws:').replace(/^https:/i, 'wss:'); + return wsBase + '/live-room/' + encodedRoom + query; } function ensureLiveShareCompressionReady() { @@ -35870,13 +35869,22 @@ ${selector} .arrowheadPath { }); } - // Register Service Worker for offline capabilities + // Register even when asynchronous startup finishes after the load event. + // A one-shot handler prevents duplicate registrations in the early path. if ('serviceWorker' in navigator) { - window.addEventListener('load', function() { + function registerMarkdownViewerServiceWorker() { navigator.serviceWorker.register('sw.js').catch(function(err) { - console.log('ServiceWorker registration failed: ', err); + console.warn('ServiceWorker registration failed:', err); + window.dispatchEvent(new CustomEvent('markdown-viewer:service-worker-error', { + detail: { message: String(err && err.message || err) } + })); }); - }); + } + if (document.readyState === 'complete') { + registerMarkdownViewerServiceWorker(); + } else { + window.addEventListener('load', registerMarkdownViewerServiceWorker, { once: true }); + } } // Wait until all editor and collaboration dependencies exist before adding the update tab. diff --git a/sw.js b/sw.js index 574ea6aa..1ea0d6ef 100644 --- a/sw.js +++ b/sw.js @@ -10,6 +10,7 @@ const CRITICAL_ASSETS = [ './visual-settings-store.js', './script.js', './browser-drop-source.js', + './native-markdown-source.js', './preview-worker.js', './styles.css', './assets/seo-metadata.mjs', @@ -38,6 +39,7 @@ const NETWORK_FIRST_LOCAL_PATHS = new Set([ '/visual-settings-store.js', '/script.js', '/browser-drop-source.js', + '/native-markdown-source.js', '/preview-worker.js', '/styles.css', '/assets/seo-metadata.mjs', @@ -74,6 +76,29 @@ self.addEventListener('fetch', event => { const isCDN = CDN_ORIGINS.some(origin => url.hostname.includes(origin)); if (isLocal) { + // Serve the precached editor shell immediately for navigations. This + // keeps offline reloads usable even when the browser rejects network + // requests before a fetch() fallback. Revalidate in the background. + if (event.request.mode === 'navigate') { + event.respondWith(caches.open(CACHE_NAME).then(async cache => { + const cached = (await cache.match(event.request, { ignoreSearch: true })) || + (await cache.match('./index.html')) || (await cache.match('./')); + if (cached) { + event.waitUntil(fetch(event.request).then(response => { + if (response && response.ok) { + return cache.put(event.request, response.clone()); + } + }).catch(() => {})); + return cached; + } + const response = await fetch(event.request); + if (response && response.ok) { + event.waitUntil(cache.put(event.request, response.clone())); + } + return response; + })); + return; + } const localPath = url.pathname.endsWith('/') ? '/' : url.pathname; const shouldUseNetworkFirst = event.request.mode === 'navigate' || @@ -88,7 +113,20 @@ self.addEventListener('fetch', event => { cache.put(event.request, networkResponse.clone()); } return networkResponse; - }).catch(() => cache.match(event.request)); + }).catch(async () => { + // A navigation may use a slightly different request URL or cache + // mode from install-time precaching. Fall back explicitly to the + // offline editor shell rather than returning an undefined response. + const cached = await cache.match(event.request, { + ignoreSearch: event.request.mode === 'navigate' + }); + if (cached) return cached; + if (event.request.mode === 'navigate') { + return (await cache.match('./index.html')) || + (await cache.match('./')) || Response.error(); + } + return Response.error(); + }); }) ); return; diff --git a/tests/e2e/docker-sharing.spec.js b/tests/e2e/docker-sharing.spec.js new file mode 100644 index 00000000..0e2b5ef5 --- /dev/null +++ b/tests/e2e/docker-sharing.spec.js @@ -0,0 +1,152 @@ +const { test, expect } = require('@playwright/test'); +const { openApp, setEditorContent } = require('../helpers/app'); +const { installSharingServices, serviceOrigin } = require('../helpers/sharing-services'); + +test.skip(process.env.MARKDOWN_VIEWER_TEST_CONTAINER !== '1', + 'Sharing acceptance must exercise the actual Docker response headers.'); +const hosted = process.env.MARKDOWN_VIEWER_TEST_HOSTED_SHARING === '1'; + +function localLink(link, baseURL) { + return baseURL + '/' + new URL(link).hash; +} + +test('Docker security headers permit the hosted sharing API, relay and Yjs library', async ({ request }) => { + const response = await request.get('/'); + const csp = response.headers()['content-security-policy']; + const directives = Object.fromEntries(csp.split(';').map(part => { + const [name, ...sources] = part.trim().split(/\s+/); + return [name, sources]; + })); + expect(directives['script-src']).toContain('https://esm.sh'); + expect(directives['connect-src']).toEqual(expect.arrayContaining([ + serviceOrigin, 'wss://markdownviewer.pages.dev', 'https://esm.sh' + ])); + expect(directives['connect-src']).not.toContain('*'); +}); + +test('Docker opens an embedded snapshot without a storage API request', async ({ page, context, baseURL }) => { + const services = hosted ? null : await installSharingServices(context); + await openApp(page); + const content = '# Docker embedded snapshot\n\nSynthetic acceptance content.'; + await setEditorContent(page, content); + await page.locator('#share-button').click(); + await page.locator('#share-generate-btn').click(); + await expect(page.locator('#share-url-input')).toHaveValue(/#share=/); + const link = await page.locator('#share-url-input').inputValue(); + const guest = await context.newPage(); + await openApp(guest, localLink(link, baseURL), { expectEditorVisible: false }); + await expect(guest.locator('#markdown-preview')).toContainText('Synthetic acceptance content.'); + await expect(guest.locator('#markdown-editor')).toHaveJSProperty('readOnly', true); + if (services) expect(services.requests).toEqual([]); +}); + +for (const mode of ['view', 'edit']) { + test(`Docker creates and opens a stored ${mode} snapshot through the sharing API`, async ({ page, context, baseURL }) => { + test.setTimeout(hosted ? 120_000 : 60_000); + const services = hosted ? null : await installSharingServices(context); + await openApp(page); + const content = '# Docker stored snapshot\n\n' + 'Synthetic Docker acceptance text. '.repeat(120); + await setEditorContent(page, content); + let record; + page.on('response', async response => { + if (response.url() === serviceOrigin + '/api/share' && response.request().method() === 'POST' && response.ok()) { + record = await response.json(); + } + }); + try { + await page.locator('#share-button').click(); + await page.locator('#share-mode-' + mode).check(); + const created = page.waitForResponse(response => response.url() === serviceOrigin + '/api/share' && + response.request().method() === 'POST'); + await page.locator('#share-generate-btn').click(); + const response = await created; + expect(response.status()).toBe(201); + record = await response.json(); + await expect(page.locator('#share-url-input')).toHaveValue(/#id=/); + const link = await page.locator('#share-url-input').inputValue(); + const guest = await context.newPage(); + const violations = []; + guest.on('console', message => { + if (/Content Security Policy|violates.*directive/i.test(message.text())) violations.push(message.text()); + }); + await openApp(guest, localLink(link, baseURL), { expectEditorVisible: mode === 'edit' }); + await expect(guest.locator('#markdown-editor')).toHaveValue(content); + await expect(guest.locator('#markdown-editor')).toHaveJSProperty('readOnly', mode === 'view'); + await expect(guest.locator('#markdown-preview')).toContainText('Docker stored snapshot'); + expect(violations).toEqual([]); + if (services) expect(services.requests.some(request => request.method === 'GET')).toBe(true); + } finally { + if (record?.id && record?.deleteToken) { + const status = await page.evaluate(async ({ origin, record }) => { + const response = await fetch(origin + '/api/share/' + record.id, { + method: 'DELETE', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ deleteToken: record.deleteToken }) + }); + return response.status; + }, { origin: serviceOrigin, record }); + expect(status, 'Delete only the synthetic snapshot created by this test').toBe(200); + } + } + }); +} + +for (const mode of ['view', 'edit']) { + test(`Docker Live Share synchronizes a real Yjs ${mode} guest and ends the session`, async ({ page, context, baseURL }) => { + test.setTimeout(hosted ? 150_000 : 90_000); + const services = hosted ? null : await installSharingServices(context); + const violations = []; + context.on('page', guest => guest.on('console', message => { + if (/Content Security Policy|violates.*directive/i.test(message.text())) violations.push(message.text()); + })); + page.on('console', message => { + if (/Content Security Policy|violates.*directive/i.test(message.text())) violations.push(message.text()); + }); + await openApp(page); + const initial = '# Docker Live Share\n\nSynthetic host text.'; + await setEditorContent(page, initial); + let guest; + try { + await page.locator('#live-share-button').click(); + await page.locator('input[name="live-share-access-mode"][value="' + mode + '"]').check(); + await page.locator('#live-share-display-name').fill('Docker test host'); + await page.locator('#live-share-start-btn').click(); + await expect(page.locator('#live-share-status-text')).toContainText(/Connected|Room active|waiting/i); + await expect(page.locator('#live-share-url-input')).toHaveValue(/#live=/); + const invite = new URL(await page.locator('#live-share-url-input').inputValue()); + // Remove the initial document seed: receiving host content must use the + // actual WebSocket/Yjs synchronization, not merely decode the invite. + const params = new URLSearchParams(invite.hash.slice(1)); + params.delete('seed'); + invite.hash = params.toString(); + await page.locator('#live-share-modal-close-icon').click(); + guest = await context.newPage(); + // Hosted acceptance also proves Docker-to-public-web interoperability. + await openApp(guest, hosted && mode === 'view' ? invite.href : localLink(invite.href, baseURL)); + await expect(guest.locator('#markdown-editor')).toHaveValue(initial); + await expect(guest.locator('#markdown-editor')).toHaveJSProperty('readOnly', mode === 'view'); + const updated = initial + '\n\nHost update after the guest joined.'; + await setEditorContent(page, updated); + await expect(guest.locator('#markdown-editor')).toHaveValue(updated); + if (mode === 'edit') { + const reply = updated + '\n\nGuest edit returned to host.'; + await setEditorContent(guest, reply); + await expect(page.locator('#markdown-editor')).toHaveValue(reply); + } + expect(violations).toEqual([]); + if (services) { + expect(services.connections).toHaveLength(2); + expect(services.connections.map(url => url.searchParams.get('role')).sort()).toEqual([mode, 'host'].sort()); + } + await page.locator('#live-share-button').click(); + await page.locator('#live-share-end-btn').click(); + await expect(guest.locator('#live-share-button')).toHaveAttribute('aria-pressed', 'false'); + } finally { + if (await page.locator('#live-share-button').getAttribute('aria-pressed') === 'true') { + if (!await page.locator('#live-share-end-btn').isVisible()) await page.locator('#live-share-button').click(); + await page.locator('#live-share-end-btn').click(); + await expect(page.locator('#live-share-button')).toHaveAttribute('aria-pressed', 'false'); + } + } + }); +} + diff --git a/tests/e2e/docker.spec.js b/tests/e2e/docker.spec.js new file mode 100644 index 00000000..420e4d48 --- /dev/null +++ b/tests/e2e/docker.spec.js @@ -0,0 +1,109 @@ +const { test, expect } = require('@playwright/test'); + +test.skip(process.env.MARKDOWN_VIEWER_TEST_CONTAINER !== '1', + 'Docker integration tests require the real container and enabled service workers.'); + +async function waitForOfflineShell(page) { + await page.waitForFunction(async () => { + const names = await caches.keys(); + const name = names.find(item => item.startsWith('markdown-viewer-cache-')); + if (!name) return false; + const cache = await caches.open(name); + const required = ['/', '/index.html', '/script.js', '/preview-worker.js', '/sample.md']; + const results = await Promise.all(required.map(path => cache.match(new URL(path, location.origin)))); + return results.every(Boolean); + }, null, { timeout: 25_000 }); +} + + +test('the real Docker site automatically registers and activates its service worker', async ({ page }) => { + await page.goto('/'); + await expect(page.locator('#markdown-editor')).toBeVisible(); + await page.waitForFunction(async () => { + const registration = await navigator.serviceWorker.getRegistration('/'); + return Boolean(registration && registration.active && navigator.serviceWorker.controller); + }, null, { timeout: 30_000 }); + // The helper asserts successful Cache.match() on all required URLs. + // Do not reopen the cache by a non-atomic names lookup: activation may + // rotate/decommission the cache between the two browser evaluations. + await waitForOfflineShell(page); +}); + +test('the installed worker loads the editor offline after an online visit', async ({ page, context }) => { + await page.goto('/'); + await page.waitForFunction(async () => { + const r = await navigator.serviceWorker.getRegistration('/'); + return Boolean(r && r.active && navigator.serviceWorker.controller); + }, null, { timeout: 30_000 }); + await waitForOfflineShell(page); + // Await completed activation with no pending replacement, not merely a + // truthy controller reference while another install/activation is underway. + await page.waitForFunction(async () => { + const registration = await navigator.serviceWorker.ready; + return registration.active?.state === 'activated' && + !registration.installing && !registration.waiting && + navigator.serviceWorker.controller?.state === 'activated'; + }, null, { timeout: 30_000 }); + await context.setOffline(true); + await page.waitForFunction(() => navigator.onLine === false); + // Prove that the worker actually handles an offline network fetch before + // navigating; otherwise a reload failure is harder to diagnose. + const offlineFetch = await page.evaluate(async () => { + try { + const response = await fetch('/index.html'); + return { status: response.status, controlled: !!navigator.serviceWorker.controller }; + } catch (error) { + return { error: String(error), controlled: !!navigator.serviceWorker.controller }; + } + }); + expect(offlineFetch, JSON.stringify(offlineFetch)).toMatchObject({ status: 200, controlled: true }); + await page.reload({ waitUntil: 'domcontentloaded' }); + await expect(page.locator('#markdown-editor')).toBeVisible(); + await context.setOffline(false); +}); + +test('revalidation replaces a stale application cache entry without clearing documents', async ({ page }) => { + const { openApp, setEditorContent, storedDocuments } = require('../helpers/app'); + await openApp(page); + const content = '# Saved Docker document\n\nMust survive cache revalidation.'; + await setEditorContent(page, content); + await expect.poll(async () => (await storedDocuments(page)).some(doc => doc.content === content)).toBe(true); + await page.waitForFunction(() => Boolean(navigator.serviceWorker.controller), null, { timeout: 30_000 }); + const result = await page.evaluate(async () => { + const names = await caches.keys(); + const cache = await caches.open(names.find(name => name.startsWith('markdown-viewer-cache-'))); + await cache.put('/script.js', new Response('OLD-BUILD-APP-CODE', { + headers: { 'content-type': 'application/javascript' } + })); + const response = await fetch('/script.js'); + const body = await response.text(); + return { response: response.status, stale: body === 'OLD-BUILD-APP-CODE' }; + }); + expect(result.response).toBe(200); + expect(result.stale).toBe(false); + await page.reload(); + await expect(page.locator('#markdown-editor')).toHaveValue(content); + expect((await storedDocuments(page)).some(doc => doc.content === content)).toBe(true); +}); + +test('module MIME and negative asset paths are not HTML SPA fallbacks', async ({ request }) => { + const module = await request.get('/assets/seo-metadata.mjs'); + expect(module.status()).toBe(200); + expect(module.headers()['content-type']).toMatch(/javascript/); + expect(module.headers()['x-content-type-options']).toBe('nosniff'); + expect(module.headers()['content-security-policy']).toBeTruthy(); + const worker = await request.get('/preview-worker.js'); + expect(worker.status()).toBe(200); + expect(worker.headers()['content-type']).toMatch(/javascript/); + const missing = await request.get('/not-a-real-file.mjs'); + expect(missing.status()).toBe(404); +}); + +test('normal editing renders Markdown as HTML in the Docker browser', async ({ page }) => { + const { openApp, setEditorContent } = require('../helpers/app'); + const errors = await openApp(page); + await setEditorContent(page, '# Docker Preview Check\n\n**bold text**'); + await expect(page.locator('#markdown-preview')).toContainText('Docker Preview Check'); + await expect(page.locator('#markdown-preview strong')).toContainText('bold text'); + expect(errors).toEqual([]); +}); diff --git a/tests/helpers/sharing-services.js b/tests/helpers/sharing-services.js new file mode 100644 index 00000000..7454c290 --- /dev/null +++ b/tests/helpers/sharing-services.js @@ -0,0 +1,65 @@ +const path = require('node:path'); +const { pathToFileURL } = require('node:url'); +const { build } = require('esbuild'); + +const serviceOrigin = 'https://markdownviewer.pages.dev'; +const yjsUrl = 'https://esm.sh/yjs@13.6.10/es2022/yjs.mjs'; +let yjsBundle; +let shareHandler; + +// Use the real snapshot handler and Yjs implementation. Backend I/O is +// intercepted for deterministic, non-publishing CI; hosted acceptance runs +// separately without these routes to cover real CORS and WebSocket upgrades. +async function installSharingServices(context) { + const storage = new Map(); + const requests = []; + const connections = []; + const rooms = new Map(); + shareHandler ||= import(pathToFileURL(path.resolve(__dirname, '../../functions/api/share/[[id]].js')).href); + yjsBundle ||= build({ + stdin: { contents: 'export * from "yjs";', resolveDir: path.resolve(__dirname, '../..') }, + bundle: true, format: 'esm', platform: 'browser', write: false + }).then(result => result.outputFiles[0].text); + await context.route(yjsUrl, async route => route.fulfill({ + contentType: 'application/javascript', + headers: { 'access-control-allow-origin': '*' }, + body: await yjsBundle + })); + await context.route(serviceOrigin + '/api/share**', async route => { + const incoming = route.request(); + const url = new URL(incoming.url()); + requests.push({ method: incoming.method(), url: incoming.url() }); + const request = new Request(incoming.url(), { + method: incoming.method(), headers: incoming.headers(), + ...(['GET', 'HEAD'].includes(incoming.method()) ? {} : { body: incoming.postData() }) + }); + const response = await (await shareHandler).onRequest({ + request, params: { id: url.pathname.slice('/api/share'.length).replace(/^\//, '') }, + env: { SHARE_KV: { + async get(key) { return storage.get(key) ?? null; }, + async put(key, value) { storage.set(key, value); }, + async delete(key) { storage.delete(key); } + } } + }); + await route.fulfill({ + status: response.status, headers: Object.fromEntries(response.headers), + body: Buffer.from(await response.arrayBuffer()) + }); + }); + await context.routeWebSocket('wss://markdownviewer.pages.dev/live-room/**', socket => { + const url = new URL(socket.url()); + connections.push(url); + const roomKey = url.pathname + '?' + url.searchParams.get('secret'); + if (!rooms.has(roomKey)) rooms.set(roomKey, new Set()); + const peers = rooms.get(roomKey); + peers.add(socket); + socket.onMessage(message => { + for (const peer of peers) if (peer !== socket) peer.send(message); + }); + socket.onClose(() => peers.delete(socket)); + }); + return { requests, connections, storage }; +} + +module.exports = { installSharingServices, serviceOrigin }; + diff --git a/tests/unit/docker-assembly.test.mjs b/tests/unit/docker-assembly.test.mjs new file mode 100644 index 00000000..68831b84 --- /dev/null +++ b/tests/unit/docker-assembly.test.mjs @@ -0,0 +1,30 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { verifyAssembly } from '../../docker/verify-assembly.mjs'; + +const mediaType = 'application/vnd.oci.image.index.v1+json'; +const source = arch => ({ mediaType, manifests: [ + { digest: `image-${arch}`, size: 100, platform: { os: 'linux', architecture: arch } }, + { digest: `attestation-${arch}`, size: 200, platform: { os: 'unknown', architecture: 'unknown' }, + annotations: { 'vnd.docker.reference.type': 'attestation-manifest', + 'vnd.docker.reference.digest': `image-${arch}` } } +] }); +const sources = [source('amd64'), source('arm64')]; +const combined = { mediaType, manifests: sources.flatMap(s => s.manifests) }; + +test('combines the exact tested images and attestations regardless of order', () => { + verifyAssembly({ ...combined, manifests: [...combined.manifests].reverse() }, sources); +}); +test('rejects missing, substituted or extra manifests and missing architectures', () => { + for (const manifests of [combined.manifests.slice(1), + [...combined.manifests, combined.manifests[0]], + combined.manifests.map((m, i) => i === 0 ? { ...m, digest: 'untested-image' } : m)]) { + assert.throws(() => verifyAssembly({ ...combined, manifests }, sources)); + } + assert.throws(() => verifyAssembly(source('amd64'), [source('amd64')])); +}); +test('requires an attestation linked to each tested platform', () => { + const broken = sources.map(s => ({ ...s, manifests: s.manifests.slice(0, 1) })); + assert.throws(() => verifyAssembly({ mediaType, manifests: broken.flatMap(s => s.manifests) }, broken)); +}); + diff --git a/tests/unit/docker-attestations.test.mjs b/tests/unit/docker-attestations.test.mjs new file mode 100644 index 00000000..85851ee0 --- /dev/null +++ b/tests/unit/docker-attestations.test.mjs @@ -0,0 +1,44 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { verifySbom, verifyProvenance } from '../../docker/verify-attestations.mjs'; + +const inventory = { spdxVersion: 'SPDX-2.3', packages: [{ name: 'nginx', versionInfo: '1.31.9' }] }; +const provenance = { buildType: 'https://mobyproject.org/buildkit@v1' }; + +test('checks each requested architecture instead of accepting the other platform', () => { + const sbom = { 'linux/amd64': { SPDX: inventory }, 'linux/arm64': { SPDX: inventory } }; + const attestations = { 'linux/amd64': { SLSA: provenance }, 'linux/arm64': { SLSA: provenance } }; + for (const platform of ['linux/amd64', 'linux/arm64']) { + verifySbom(sbom, '1.31.9', platform); + verifyProvenance(attestations, platform); + } + assert.throws(() => verifySbom({ 'linux/amd64': sbom['linux/amd64'] }, '1.31.9', 'linux/arm64')); + assert.throws(() => verifyProvenance({ 'linux/amd64': attestations['linux/amd64'] }, 'linux/arm64')); +}); + +test('accepts Syft, single-platform Buildx and multi-platform Buildx inventory', () => { + for (const value of [inventory, { SPDX: inventory }, { 'linux/amd64': { SPDX: inventory } }]) { + assert.equal(verifySbom(value, '1.31.9'), inventory); + } +}); + +test('rejects missing inventory, wrong platform, missing NGINX and stale version', () => { + for (const value of [null, {}, { 'linux/arm64': { SPDX: inventory } }, + { ...inventory, packages: [] }, + { ...inventory, packages: [{ name: 'nginx', versionInfo: '1.31.8' }] }]) { + assert.throws(() => verifySbom(value, '1.31.9')); + } +}); + +test('requires real provenance independently of the presence of an SBOM', () => { + assert.equal(verifyProvenance({ SLSA: provenance }), provenance); + assert.equal(verifyProvenance({ 'linux/amd64': { SLSA: provenance } }), provenance); + verifyProvenance({ SLSA: { buildDefinition: provenance } }); + verifyProvenance({ SLSA: { buildDefinition: { + buildType: 'https://github.com/moby/buildkit/blob/master/docs/attestations/slsa-definitions.md' + } } }); + for (const value of [null, {}, { SPDX: inventory }, { SLSA: {} }, + { SLSA: { buildType: 'unrecognized-builder' } }]) { + assert.throws(() => verifyProvenance(value)); + } +}); diff --git a/tests/unit/live-room-endpoint.test.mjs b/tests/unit/live-room-endpoint.test.mjs new file mode 100644 index 00000000..6a04c82b --- /dev/null +++ b/tests/unit/live-room-endpoint.test.mjs @@ -0,0 +1,45 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; + +const source = fs.readFileSync(new URL('../../script.js', import.meta.url), 'utf8'); +const extract = (start, next) => source.slice(source.indexOf(' function ' + start), + source.indexOf(' function ' + next)); +const functions = extract('getShareApiBaseUrl()', 'getCurrentShareMode()') + + extract('getLiveRoomSocketUrl(', 'ensureLiveShareCompressionReady()'); + +function endpoint(href, override, desktop = false) { + const location = new URL(href); + const context = { + window: { location, MARKDOWN_VIEWER_LIVE_ROOM_URL: override }, + URLSearchParams, normalizeLiveSocketRole: role => role, + ...(desktop ? { Neutralino: {} } : {}) + }; + vm.createContext(context); + vm.runInContext(functions, context); + return context.getLiveRoomSocketUrl('room/test', 'test secret', { role: 'view', capability: 'test-cap' }); +} + +test('loopback Docker clients use the hosted secure relay', () => { + for (const origin of ['http://localhost:8095/', 'http://127.0.0.1:8080/']) { + const url = new URL(endpoint(origin)); + assert.equal(url.origin, 'wss://markdownviewer.pages.dev'); + assert.equal(url.pathname, '/live-room/room%2Ftest'); + assert.equal(url.searchParams.get('secret'), 'test secret'); + assert.equal(url.searchParams.get('role'), 'view'); + } +}); +test('web deployments retain their same-origin relay', () => { + assert.equal(new URL(endpoint('https://example.test/editor')).origin, 'wss://example.test'); +}); +test('file and desktop clients retain the hosted relay', () => { + assert.equal(new URL(endpoint('file:///C:/index.html')).origin, 'wss://markdownviewer.pages.dev'); + assert.equal(new URL(endpoint('http://desktop.local/', undefined, true)).origin, 'wss://markdownviewer.pages.dev'); +}); +test('an explicit self-hosted relay takes precedence', () => { + const url = new URL(endpoint('http://localhost:8095/', 'http://127.0.0.1:8787/live-room/')); + assert.equal(url.origin, 'ws://127.0.0.1:8787'); + assert.equal(url.pathname, '/live-room/room%2Ftest'); +}); + diff --git a/wiki/Docker-Deployment.md b/wiki/Docker-Deployment.md index 211fa2d6..7fd3eb51 100644 --- a/wiki/Docker-Deployment.md +++ b/wiki/Docker-Deployment.md @@ -1,161 +1,202 @@ -# Docker Deployment for the Markdown Viewer Web App +# Docker Deployment for Markdown Viewer -Markdown Viewer's Docker image serves the browser-based Markdown editor and viewer as a static web app with Nginx. It is useful for local networks, self-hosting, and reverse-proxy deployments. +Markdown Viewer is an HTTP-only, static browser application served by NGINX. +The runtime is custom-compiled upstream NGINX 1.31.9 on +Alpine Linux 3.24, without OpenSSL. No certificates, backend database, +Kubernetes or Node.js production server are required for ordinary local use. -## Quick Start +## Quick start: use the published image -```bash -docker run -d \ - --name markdown-viewer \ - -p 8080:80 \ - --restart unless-stopped \ - ghcr.io/thisis-developer/markdown-viewer:latest -``` +With Docker Desktop / Docker Engine running: -Open `http://localhost:8080`. +~~~sh +docker pull ghcr.io/thisis-developer/markdown-viewer:latest +docker run -d --name markdown-viewer -p 127.0.0.1:8080:80 \ + --restart unless-stopped ghcr.io/thisis-developer/markdown-viewer:latest +~~~ -## Docker Compose +Open http://localhost:8080. -The repository includes: +**Important:** The latest tag points to the published GHCR release, not an +open PR. Git clone downloads source; it does not pull or build a Docker image. +A registry pull avoids installing compiler, git and build dependencies locally. -```yaml -services: - markdown-viewer: - build: . - ports: - - "8080:80" -``` +## Host and processor support -Run: +Release images contain **linux/amd64 and linux/arm64** variants. CI builds, +runs the browser tests, and scans each on a matching native Ubuntu runner; +it then verifies that the combined release preserves both tested images and +their attestations. Docker selects the matching variant automatically. -```bash -docker compose up -d -``` - -Rebuild after local source changes: +| Host | Docker requirement | Image variant | +| --- | --- | --- | +| Linux, including Ubuntu, on Intel/AMD 64-bit | Supported Docker Engine | linux/amd64 | +| Linux on ARM64, including a supported 64-bit Raspberry Pi OS | Supported ARM64 Docker Engine | linux/arm64 | +| Windows on Intel/AMD, including Home | Docker Desktop with Linux containers / WSL 2 | linux/amd64 | +| Intel Mac | Supported Docker Desktop | linux/amd64 | +| Apple Silicon Mac | Supported Docker Desktop | linux/arm64 | +| Windows on ARM | A supported ARM64 Docker Desktop / WSL 2 installation; vendor support may be preview | linux/arm64 | -```bash -docker compose up -d --build -``` +This is Linux-container support on the two common 64-bit architectures, +not a native Windows-container image or a promise to run on every device. +32-bit x86/ARM, unsupported host OS versions and phones are not Docker +deployment targets. Phones can use the web app served by another device. +Host Docker/virtualization requirements still apply. Native Linux CI does +not replace testing every Windows/macOS Docker Desktop version or physical +device. Desktop-app installer CI is separate from Docker coverage. -Stop: +Production-style Compose now uses the prebuilt registry image: -```bash +~~~sh +docker compose up -d +docker compose logs --tail=50 docker compose down -``` - -## Building Locally - -```bash -docker build -t markdown-viewer:local . -docker run -d --name markdown-viewer-local -p 8080:80 markdown-viewer:local -``` - -The root `.dockerignore` excludes desktop build output and unrelated local files from the web container. - -## What the Container Provides - -The container serves the static browser shell: `index.html`, `workspace-storage.js`, `script.js`, `styles.css`, `sw.js`, `manifest.json`, `robots.txt`, `sitemap.xml`, and `assets/`. It provides the Editor, main-thread Preview, local storage, local imports, most exports, and CDN-loaded renderer libraries. - -On `localhost`, managed-media and stored Share Snapshot requests use the production `https://markdownviewer.pages.dev` API. Live Share defaults to the Docker origin and fails unless a compatible `/live-room` endpoint is available or `window.MARKDOWN_VIEWER_LIVE_ROOM_URL` is configured in a custom deployment. - -The container alone does not provide Cloudflare KV or Durable Objects. Self-hosted stored Share Snapshot and Live Share require separately deployed compatible endpoints. - -## Known Stock Image Limitation - -The checked-in root `Dockerfile` does not copy: - -- `preview-worker.js`; or -- `sample.md`. - -Both files are listed in `sw.js` as critical precache assets. The consequences are: - -- Documents eligible for Preview Worker rendering receive a Worker load failure and fall back to main-thread rendering; and -- Service Worker installation can fail because `cache.addAll()` rejects the complete precache when either asset returns `404`. - -This is an implementation packaging limitation, not a documentation configuration step. The documentation audit records it without changing Docker behavior. - -If you maintain a custom image, copy both files to `/usr/share/nginx/html/`, rebuild, and verify that every `CRITICAL_ASSETS` URL in `sw.js` returns `200` with the correct MIME type. - -## Nginx and Headers - -The Docker image uses `nginx:alpine`. Production deployments should keep these behaviors: - -- Serve `index.html`, `workspace-storage.js`, `script.js`, `styles.css`, `preview-worker.js`, `sw.js`, `manifest.json`, and `assets/`. -- Serve `sample.md` because the Service Worker includes it in the critical precache. -- Serve JavaScript files with correct MIME types. -- Allow Service Worker registration from the app origin. -- Send security headers that match the app's CSP and deployment policy. The current Docker image includes: - -```nginx -add_header X-Frame-Options "SAMEORIGIN" always; -add_header X-Content-Type-Options "nosniff" always; -add_header X-XSS-Protection "1; mode=block" always; -add_header Referrer-Policy "strict-origin-when-cross-origin" always; -``` - -The Dockerfile also sets a Content-Security-Policy with the external origins required by the web app. Review that policy when adding a renderer or changing lazy-loaded resources. - -Cloudflare Pages deployments use the stricter root `_headers` and `_redirects` files, including CSP, HSTS, clickjacking, permissions, cross-origin, and sensitive-path protections. When self-hosting behind Docker or another reverse proxy, keep the CSP compatible with `index.html`, lazy-loaded renderers, Share Snapshot, and Live Share instead of copying a wildcard policy. - -Use long caching carefully. `sw.js`, `index.html`, `workspace-storage.js`, `script.js`, and `styles.css` are update-sensitive; stale versions can keep old app behavior alive. - -## Reverse Proxy Examples - -Nginx: - -```nginx -server { - listen 443 ssl; - server_name markdown.example.com; - - location / { - proxy_pass http://127.0.0.1:8080; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - } -} -``` - -Caddy: - -```caddyfile -markdown.example.com { - reverse_proxy localhost:8080 -} -``` - -Traefik labels: - -```yaml -labels: - - "traefik.enable=true" - - "traefik.http.routers.mdviewer.rule=Host(`markdown.example.com`)" - - "traefik.http.routers.mdviewer.entrypoints=websecure" - - "traefik.http.routers.mdviewer.tls.certresolver=letsencrypt" - - "traefik.http.services.mdviewer.loadbalancer.server.port=80" -``` - -## Custom Sub-Paths - -Serving from a sub-path such as `/editor/` requires testing: - -- Worker URL resolution for `preview-worker.js`. -- Service Worker scope. -- Manifest path. -- Asset paths in `index.html`. -- Dynamic library loading in `script.js`. -- Share and Live Share public base URL behavior. - -Root hosting is the simplest and best-tested deployment mode. - -## Privacy Notes for Self-Hosting - -- Normal documents stay in the user's browser storage. -- Your server will serve static assets and may log normal HTTP requests. -- URL-hash Share Snapshot content is not sent to the server as an HTTP fragment, but users can paste links into other systems. -- Stored Share Snapshot and Live Share need Cloudflare or compatible services and have their own data flows. -- The stock localhost client sends consented managed-media and stored Share Snapshot requests to the production Markdown Viewer API. - -For the complete boundary, see [Privacy and Security](Privacy-and-Security.md). For diagnostics, see [Troubleshooting](Troubleshooting.md#docker-preview-or-pwa-offline-support-is-incomplete). +~~~ + +The port binds only to localhost by default. To serve LAN/Internet clients, +adjust port exposure deliberately and use the required network protection. +HTTPS for remote deployments belongs at an optional external reverse proxy, +not in this HTTP-only application image. Remote insecure origins do not offer +all localhost browser secure-context APIs. + +## Developers: compile locally + +~~~sh +git clone https://github.com/ThisIs-Developer/Markdown-Viewer.git +cd Markdown-Viewer +docker build --pull -t markdown-viewer:dev . +docker run --rm -d --name mdv-dev -p 127.0.0.1:8081:80 markdown-viewer:dev +~~~ + +Or, use the optional Compose build override: + +~~~sh +docker compose -f docker-compose.yml -f docker-compose.build.yml up -d --build +~~~ + +The source build compiles NGINX in a disposable builder stage. It may take +several minutes on a cold machine; a fully cached local rebuild can take +seconds. Do not use --no-cache for every development iteration. The builder +cache can be much larger than the final runtime image. Do not globally prune +unrelated Docker resources to save space. + +The previous Dockerfile used a precompiled nginx:alpine image. This one +compiles NGINX to omit TLS/OpenSSL, so a first source build is inherently more +work, particularly on older dual-core processors. Compiler installation is +a separate cached layer, so changing the NGINX source pin need not download +the toolchain again. Changing web files reuses the compiled server layer. +This improves repeat/update builds; it does not make a cold compile as fast +as pulling a prebuilt server. Build speed is not editor/rendering speed. + +For normal installation or updates, use docker compose pull followed by +docker compose up -d. The build override is for source development. While a +PR is open, the latest registry tag still contains the existing release. +Avoid forcing --platform linux/amd64 on an ARM device: emulation can slow +both compilation and execution. + +## Runtime behavior, tests and logs + +- NGINX listens on internal port 80. The root master launches nginx workers. + A fully non-root/container-read-only runtime is future hardening, not a + proven property of this PR. +- Docker uses SIGQUIT for graceful stop and a local HTTP healthcheck. For + larger downloads, permit an appropriate stop grace period. +- NGINX server and shared security headers are maintained as source files: + docker/nginx-server.conf and docker/security-headers.conf. +- JavaScript modules are served with JavaScript MIME, missing code returns + 404, and the Service Worker can precache all required local files. +- Stable filenames (HTML, JS, CSS, manifest and worker files) revalidate, + rather than using one-year immutable caching. ETags enable 304 responses. +- When upgrading from an older image that already sent one-year immutable + headers, perform a browser hard refresh once if old behavior persists. + New server headers cannot retroactively expire an existing browser HTTP + cache entry. Do not clear site storage: that can delete local documents. +- Normal file content is browser-local. CDN renderers are loaded lazily: + complete offline rendering requires those dependencies to have been fetched. +- The final image does not contain the APK command or OpenSSL runtime libs. + No in-container package upgrade is supported; updates are new builds. + +Basic diagnostics: + +~~~sh +docker logs --tail=100 markdown-viewer +docker exec markdown-viewer nginx -t +docker inspect markdown-viewer --format '{{json .State.Health}}' +docker scout cves ghcr.io/thisis-developer/markdown-viewer:latest +~~~ + +Scans must target the actual deployed image digest. A Trivy zero-count does +not prove a custom NGINX binary has no vulnerabilities. + +## Privacy and sharing service boundaries + +The container serves a static web client, not Cloudflare KV, Durable Objects, +or a Live Share signaling service. The normal editor stores documents in the +browser. When opened on localhost or 127.0.0.1, both stored Share Snapshot +and Live Share use the existing markdownviewer.pages.dev services. Small +snapshots remain embedded in their links. Generating a stored snapshot sends +that document to the hosted snapshot API; starting/joining Live Share sends +collaboration data through the hosted WebSocket relay. Ordinary local editing +does not start either sharing operation. Internet access is required for the +hosted services and collaboration library. + +Docker's CSP permits the specific hosted HTTPS/WSS endpoints and esm.sh Yjs +module. The hosted services already permit localhost origins. Public/LAN +custom hostnames are not automatically accepted by their origin policy: +self-host those compatible APIs or explicitly configure a trusted backend +origin policy. For custom Live Share deployments, the existing +window.MARKDOWN_VIEWER_LIVE_ROOM_URL override takes precedence over defaults; +both the HTML and NGINX CSP must permit the chosen endpoint. Use HTTPS for +remote deployments. This change does not open the backend to arbitrary origins +or deploy a backend inside the container. Standard HTTP access logging applies. + +Docker CI covers embedded and stored snapshots in view/edit modes and real +Yjs host/guest updates, read-only access, and session ending. It intercepts +backend I/O with the actual snapshot handler and a test relay to avoid writing +test documents to production on every PR. A separate opt-in acceptance run +uses the real hosted API, CDN and WebSocket service: + +~~~sh +MARKDOWN_VIEWER_TEST_CONTAINER=1 MARKDOWN_VIEWER_TEST_PORT=8080 \ +MARKDOWN_VIEWER_TEST_HOSTED_SHARING=1 \ +npx playwright test tests/e2e/docker-sharing.spec.js --project=chromium --workers=1 +~~~ + +This uses synthetic documents, deletes only snapshots created by the test, +and ends its test rooms. It also checks a Docker host with a public-web guest. + +## Release integrity and maintenance + +PR verification never writes to GHCR. Separate native AMD64/ARM64 jobs test +and scan immutable candidates in disposable local registries. OCI archives +preserve all image and attestation digests between jobs. An assembly job +combines the exact verified manifests, checks SBOM/provenance for both +architectures, and rehearses digest-preserving promotion. Main publishing +copies that complete verified release to GHCR without a rebuild, verifies +the registry digest and attestations again, then promotes release tags. +A failed architecture check or digest mismatch prevents latest promotion. + +The release includes an upstream NGINX source commit identifier, upstream +license, supplementary SPDX inventory and owner-maintained NGINX advisory +procedure (see docker/SECURITY-MAINTENANCE.md). Package scanners that enumerate +only Alpine packages do not automatically cover custom-compiled NGINX. + +Current CI validates **linux/amd64 and linux/arm64 natively**. Production-load +behavior must be tested separately before being advertised. There is no +in-container auto-updater. Record digest-specific releases for rollback rather +than relying only on the mutable latest tag. + +Performance and footprint should distinguish final image size, compressed +registry transfer, builder cache, runtime memory at peak load and cold/warm +build times. Optional compression tuning is deferred until measured. + +## Operations + +The Compose service uses Docker local log rotation. Outside Compose, the +configured host logging driver applies. Resource ceilings should follow real +measurements, not arbitrary values that might break large files. Previous +NGINX_HOST and NGINX_PORT Compose variables were removed: they did not affect +the custom hardcoded NGINX config. + +More context: Privacy-and-Security.md; Troubleshooting.md; and +docker/SECURITY-MAINTENANCE.md.