commit 47138ddfbe9c21c08183f75e5485c2fbec70ee2f Author: magdev Date: Sat Oct 10 19:36:02 2026 +0200 BentoPDF for bau-pm, without third-party hosts (bau-pm BAU-119) BentoPDF v2.8.8 built from source at its pinned commit with BentoPDF's own air-gapped build options, every module it would load from a CDN vendored and checked against vendor.lock, a Content-Security-Policy without a single host, digital-sign-pdf and timestamp-pdf disabled because both need a third party, and the hand-off glue on every page: the AGPL source link, the hand-in of a file from bau-pm through a one-minute cookie into sessionStorage, confirmed by the tool's reaction, the hand-back of a result from every window, and the signing tool's flatten switch locked on. The zero-host gate drives all 117 enabled tool pages in Chromium and fails on any request to another origin, any CSP violation, a CSP that names a host, and a disabled id that names no page. Green on this image (3 min 52 s on a private network), red on the stock upstream image (115 findings) and on a misspelled id. CI runs it on every push, the release workflow before it pushes. Co-Authored-By: Claude Opus 5.5 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4475619 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +.git +.gitea +node_modules +*.md +!README.md diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..19c5f80 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,49 @@ +# CI - every push to dev and every pull request: the scripts linted, the image +# built from BentoPDF's pinned commit, and the gate this repository exists for +# (README, "The gate"): a page may talk to its own origin and to nobody else. +name: CI + +on: + push: + branches: [dev] + pull_request: + +jobs: + gate: + runs-on: ubuntu-latest + timeout-minutes: 120 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + + # Over stdin: the runner passes the host's Docker socket through, so a + # mounted workspace would resolve on the host and be empty. + - name: shellcheck + run: | + for f in scripts/*.sh; do + echo "-- $f" + docker run --rm -i koalaman/shellcheck:v0.11.0 - < "$f" + done + + # npm ci and the Vite build are the slow part, several minutes on the + # shared runner; the vendor stage downloads about 60 MB from npm. + - name: build the image + timeout-minutes: 60 + run: docker build --build-arg VERSION="ci-${GITHUB_SHA::8}" -t bau-pm-pdf-tools:ci . + + - name: build the gate + timeout-minutes: 15 + run: docker build -f test/Dockerfile -t bau-pm-pdf-tools-gate:ci . + + - name: gate - nothing leaves the origin + timeout-minutes: 40 + run: | + net="bau-pm-pdf-tools-ci-${GITHUB_RUN_ID}" + docker network create "$net" >/dev/null + trap 'docker rm -f -v "$net-app" >/dev/null 2>&1; docker network rm "$net" >/dev/null 2>&1' EXIT + docker run -d --name "$net-app" --network "$net" --network-alias pdf-tools bau-pm-pdf-tools:ci >/dev/null + for i in $(seq 1 30); do + docker run --rm --network "$net" bau-pm-pdf-tools-gate:ci wget -q --spider http://pdf-tools:8080/ && break + [ "$i" -eq 30 ] && { echo "the image never answered" >&2; exit 1; } + sleep 2 + done + docker run --rm --network "$net" bau-pm-pdf-tools-gate:ci node test/zero-hosts.mjs http://pdf-tools:8080 diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..500c158 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,83 @@ +# Release - runs on semver tags (vMAJOR.MINOR.BUGFIX, cut on main after a +# fast-forward from dev): the gates, the image built and checked like in CI, +# pushed to the registry, and a Gitea release with the CHANGELOG section. +# Required: secrets REGISTRY_USERNAME, REGISTRY_PASSWORD (instance-wide). +name: Release + +on: + push: + tags: ['v[0-9]+.[0-9]+.[0-9]+'] + +env: + REGISTRY: ${{ vars.REGISTRY || 'hub.bundespruefstelle.ch' }} + IMAGE: bau-pm/pdf-tools + +jobs: + release: + runs-on: ubuntu-latest + timeout-minutes: 150 + steps: + # Full history, or the ancestry gate cannot answer and would pass. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + fetch-depth: 0 + + - name: derive version from tag + run: echo "VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV" + + - name: gate - CHANGELOG has a section for this version + run: | + if ! grep -q "^## \[$VERSION\]" CHANGELOG.md; then + echo "no '## [$VERSION]' section in CHANGELOG.md - cut it from [Unreleased] first" >&2 + exit 1 + fi + + - name: gate - the tag is on main + run: | + git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main + if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then + echo "$GITHUB_SHA is not an ancestor of main - fast-forward main before tagging" >&2 + exit 1 + fi + + - name: build the image + timeout-minutes: 60 + run: | + docker build --build-arg VERSION="v$VERSION" \ + -t "$REGISTRY/$IMAGE:$VERSION" -t "$REGISTRY/$IMAGE:latest" . + + - name: gate - nothing leaves the origin + timeout-minutes: 50 + run: | + docker build -f test/Dockerfile -t bau-pm-pdf-tools-gate:release . + net="bau-pm-pdf-tools-release-${GITHUB_RUN_ID}" + docker network create "$net" >/dev/null + trap 'docker rm -f -v "$net-app" >/dev/null 2>&1; docker network rm "$net" >/dev/null 2>&1' EXIT + docker run -d --name "$net-app" --network "$net" --network-alias pdf-tools "$REGISTRY/$IMAGE:$VERSION" >/dev/null + for i in $(seq 1 30); do + docker run --rm --network "$net" bau-pm-pdf-tools-gate:release wget -q --spider http://pdf-tools:8080/ && break + [ "$i" -eq 30 ] && { echo "the image never answered" >&2; exit 1; } + sleep 2 + done + docker run --rm --network "$net" bau-pm-pdf-tools-gate:release node test/zero-hosts.mjs http://pdf-tools:8080 + + - name: push + run: | + echo "${{ secrets.REGISTRY_PASSWORD }}" \ + | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin + docker push "$REGISTRY/$IMAGE:$VERSION" + docker push "$REGISTRY/$IMAGE:latest" + echo "digest: $(docker inspect --format '{{index .RepoDigests 0}}' "$REGISTRY/$IMAGE:$VERSION")" + + # Below 1.0.0 a release is a prerelease, derived from the tag. + - name: create Gitea release with changelog notes + run: | + notes="$(awk -v ver="$VERSION" '$0 ~ "^## \\[" ver "\\]" {f=1; next} /^## \[/ {f=0} f' CHANGELOG.md)" + payload="$(printf '%s' "$notes" | python3 -c 'import json,os,sys; v=os.environ["VERSION"]; print(json.dumps({"tag_name": "v" + v, "name": "bau-pm-pdf-tools v" + v, "body": sys.stdin.read().strip(), "prerelease": v.split(".")[0] == "0"}))')" + curl -sf -X POST \ + -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + -H "Content-Type: application/json" \ + -d "$payload" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/releases" >/dev/null \ + && echo "Gitea release v$VERSION created" \ + || echo "release creation skipped (may already exist)" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..552f221 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +*.log diff --git a/.markdownlint.jsonc b/.markdownlint.jsonc new file mode 100644 index 0000000..8ba38e1 --- /dev/null +++ b/.markdownlint.jsonc @@ -0,0 +1,8 @@ +// markdownlint rules (bau-pm BAU-110), read by scripts/lint-md.sh. Managed by +// the bau-pm plugin kit (templates/plugin/): change it there, not here. +{ + // Markdown is never hard-wrapped here: one paragraph per line. + "MD013": false, + // Keep a Changelog repeats "### Added" / "### Fixed" under every release. + "MD024": { "siblings_only": true } +} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..72b5745 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- BentoPDF v2.8.8 built from source at its pinned commit with BentoPDF's air-gapped build options: Simple Mode, German by default, every module served from the image's own `/wasm/`, the CORS proxy off. +- The CDN modules vendored and checked against `vendor.lock` (PyMuPDF, Ghostscript, CoherentPDF, Tesseract with German, French, Italian and English, the OCR font, the PDF editor's Latin, Arabic and Hebrew fallback fonts). Ghostscript is served as its whole package with `gs.js` and `gs.wasm` linked at its root, because BentoPDF's own loader and PyMuPDF's wrapper expect the two different layouts (upstream's air-gap layout left `pdf-to-docx` with a 404). +- A Content-Security-Policy without any host, `img-src` included; the build fails if one survives. +- `digital-sign-pdf` and `timestamp-pdf` disabled: both need a third party by design. +- The hand-off glue on every page: a source link (AGPL), the hand-in of a file from bau-pm through a one-minute cookie into the tab's `sessionStorage`, confirmed by the tool's own reaction and retried while it has none (BentoPDF attaches its listener late, and its service worker made the glue win that race), the hand-back of a result caught in every window, the viewer's frame included, and waiting for the hand-off's details when a save comes before them, and the signing tool's flatten switch locked on. +- The zero-host gate (`test/zero-hosts.mjs`) over every tool page, in CI and in the release workflow. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1d3e7ee --- /dev/null +++ b/Dockerfile @@ -0,0 +1,109 @@ +# syntax=docker/dockerfile:1 +# +# BentoPDF for bau-pm: BentoPDF built from source at a pinned commit with +# BentoPDF's own air-gapped build options, every module it would otherwise load +# from a CDN served from this image, and bau-pm's hand-off glue added to every +# page. Nothing here edits BentoPDF's code: its documented build arguments, its +# runtime config.json, its generated header file with the hosts taken out, and +# our files beside its own. +# +# The images are upstream's: the builder and the runtime stage are the ones +# BentoPDF's Dockerfile uses. + +ARG BENTOPDF_REF=v2.8.8 +ARG BENTOPDF_COMMIT=f96cd4e5166f3d51393dfe9f3c440b5bb77802f1 +ARG NODE_IMAGE=public.ecr.aws/docker/library/node:20-alpine +ARG NGINX_IMAGE=quay.io/nginx/nginx-unprivileged:alpine-slim + +# --- BentoPDF's source, at the commit the tag must point to --- +FROM ${NODE_IMAGE} AS source +ARG BENTOPDF_REF +ARG BENTOPDF_COMMIT +RUN apk add --no-cache git +RUN git clone --quiet --depth 1 --branch "${BENTOPDF_REF}" https://github.com/alam00000/bentopdf.git /src \ + && actual=$(git -C /src rev-parse HEAD) \ + && if [ "$actual" != "${BENTOPDF_COMMIT}" ]; then \ + echo "BentoPDF ${BENTOPDF_REF} is ${actual}, expected ${BENTOPDF_COMMIT}" >&2; exit 1; \ + fi \ + && rm -rf /src/.git + +# --- The CDN modules, packed from npm and checked against vendor.lock --- +FROM ${NODE_IMAGE} AS vendor +COPY --from=source /src/bentopdf-airgap-bundle /src/bentopdf-airgap-bundle +COPY vendor.lock /vendor.lock +COPY --chmod=755 scripts/vendor.sh /usr/local/bin/vendor.sh +RUN vendor.sh /src /vendor.lock /wasm + +# --- BentoPDF's build, as BentoPDF's Dockerfile runs it --- +FROM ${NODE_IMAGE} AS builder +WORKDIR /app +COPY --from=source /src/package.json /src/package-lock.json ./ +COPY --from=source /src/vendor ./vendor +ENV HUSKY=0 +RUN npm config set fetch-retries 5 \ + && npm config set fetch-retry-mintimeout 60000 \ + && npm config set fetch-retry-maxtimeout 300000 \ + && npm config set fetch-timeout 600000 \ + && npm ci +COPY --from=source /src ./ + +# The air-gapped build: every module path is this image's own, the CORS proxy +# (used only by the X.509 tool, which config.json disables) is switched off, +# and Simple Mode drops the marketing pages. Relative paths, so the image does +# not know the hostname it will be served under. +ENV SIMPLE_MODE=true \ + DISABLE_GITHUB_STARS=true \ + COMPRESSION_MODE=all \ + BASE_URL= \ + VITE_DEFAULT_LANGUAGE=de \ + VITE_CORS_PROXY_URL= \ + VITE_WASM_PYMUPDF_URL=/wasm/pymupdf/ \ + VITE_WASM_GS_URL=/wasm/gs/ \ + VITE_WASM_CPDF_URL=/wasm/cpdf/ \ + VITE_TESSERACT_WORKER_URL=/wasm/ocr/worker.min.js \ + VITE_TESSERACT_CORE_URL=/wasm/ocr/core \ + VITE_TESSERACT_LANG_URL=/wasm/ocr/lang-data \ + VITE_TESSERACT_AVAILABLE_LANGUAGES=deu,fra,ita,eng \ + VITE_OCR_FONT_BASE_URL=/wasm/ocr/fonts \ + VITE_EMBEDPDF_FONTS_URL=/wasm/embedpdf \ + NODE_OPTIONS=--max-old-space-size=3072 +RUN npm run build + +COPY --chmod=755 scripts/finish.sh /usr/local/bin/finish.sh +RUN finish.sh /app + +# --- Upstream's runtime stage, with our files beside BentoPDF's --- +FROM ${NGINX_IMAGE} +ARG BENTOPDF_REF +ARG SOURCE_URL=https://src.bundespruefstelle.ch/magdev/bau-pm-pdf-tools +ARG VERSION=dev + +LABEL org.opencontainers.image.title="bau-pm-pdf-tools" \ + org.opencontainers.image.description="BentoPDF ${BENTOPDF_REF} for bau-pm, without third-party hosts" \ + org.opencontainers.image.source="${SOURCE_URL}" \ + org.opencontainers.image.version="${VERSION}" \ + org.opencontainers.image.licenses="AGPL-3.0-only" + +ENV DISABLE_IPV6=false \ + PORT=8080 + +USER root +RUN apk upgrade --no-cache +USER nginx + +COPY --chown=nginx:nginx --from=builder /app/dist /usr/share/nginx/html +COPY --chown=nginx:nginx --from=builder /app/nginx.conf /etc/nginx/nginx.conf +COPY --chown=nginx:nginx --from=builder /app/security-headers.conf /etc/nginx/security-headers.conf +COPY --chown=nginx:nginx --from=builder /app/security-headers-docs.conf /etc/nginx/security-headers-docs.conf +COPY --chown=nginx:nginx --chmod=755 --from=builder /app/nginx-ipv6.sh /docker-entrypoint.d/99-disable-ipv6.sh +COPY --chown=nginx:nginx --chmod=755 --from=builder /app/nginx-noindex.sh /docker-entrypoint.d/98-noindex.sh +COPY --chown=nginx:nginx --from=vendor /wasm /usr/share/nginx/html/wasm +COPY --chown=nginx:nginx config/config.json /usr/share/nginx/html/config.json +COPY --chown=nginx:nginx glue/ /usr/share/nginx/html/bau-pm/ +RUN sed -i "s#__BAU_PM_SOURCE_URL__#${SOURCE_URL}/src/tag/${VERSION}#" /usr/share/nginx/html/bau-pm/handoff.js \ + && grep -q "${SOURCE_URL}" /usr/share/nginx/html/bau-pm/handoff.js \ + && mkdir -p /etc/nginx/tmp + +EXPOSE 8080 +HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD wget --spider -q http://127.0.0.1:8080/ || exit 1 +CMD ["nginx", "-g", "daemon off;"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..eec703c --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +# bau-pm-pdf-tools + +[BentoPDF](https://github.com/alam00000/bentopdf) for [bau-pm](https://src.bundespruefstelle.ch/magdev/bau-pm): about 120 PDF tools (edit, annotate, sign, fill forms, organise, merge, split, compress, convert, OCR) that run entirely in the browser, packaged so that a page of it talks to its own origin and to **nobody else**, plus the glue that hands a PDF from bau-pm into a tool and the result back. + +This repository is public on purpose. BentoPDF is AGPL-3.0, and this is a modified version served over a network, so its source is offered to every user: each page of the running image links here, to the tag it was built from. + +## What is in the image + +- **BentoPDF built from source at a pinned commit** (`BENTOPDF_REF` and `BENTOPDF_COMMIT` in the `Dockerfile`; the build fails if the tag points elsewhere), with BentoPDF's own air-gapped build options: Simple Mode, German as the default language, every module path pointing at this image (`/wasm/...`), the CORS proxy switched off. +- **Every module BentoPDF would otherwise load from a CDN**, served from `/wasm/`: PyMuPDF and Ghostscript from BentoPDF's own repository at that commit, CoherentPDF, Tesseract with `deu`, `fra`, `ita` and `eng`, the OCR text-layer font and the PDF editor's Latin, Arabic and Hebrew fallback fonts from npm. `scripts/vendor.sh` packs each one and refuses the build when the registry's integrity differs from `vendor.lock`. The editor's CJK fonts (30 to 42 MB each) are left out; a document that needs them asks this server and gets a 404, never a third party. +- **A Content-Security-Policy without a single host**: BentoPDF's generated header file with every `http(s):` source taken out, `img-src` included (`scripts/finish.sh`, which fails the build if any host survives). +- **Two tools disabled** in `config/config.json`, because they cannot work without a third party: `digital-sign-pdf` (X.509 signing fetches certificate chains through a CORS proxy) and `timestamp-pdf` (an RFC 3161 timestamp needs an external timestamp authority). +- **The glue**, `glue/handoff.js`, added to every HTML page by `scripts/finish.sh`: the source link, the hand-in of a file from bau-pm, the hand-back of a result, and the signing tool's flatten switch locked on. See the file's header for how each works. + +Nothing of BentoPDF's code is edited: its documented build arguments, its runtime `config.json`, its generated header file with fewer hosts, and our files beside its own. + +## How bau-pm uses it + +bau-pm runs the image as its `pdf-tools` service on an origin of its own (`PDF_TOOLS_ADDRESS`, e.g. `pdf.example.ch`), behind its Caddy, which asks Redmine before serving any page, so only logged-in users get in. The design, the login gate and the hand-off protocol are bau-pm's (`PLAN.md` §2.50 there); this image only needs to be reachable on port 8080. It is static nginx: about 3 MB of memory, and it writes nothing but its temp directories, so it runs with a read-only root and three tmpfs mounts owned by uid 101 (see bau-pm's `compose.yaml`). + +## The gate + +`test/zero-hosts.mjs` drives every tool page linked from the German overview in a phone-sized Chromium: it gives each a probe file its input accepts, presses its main button, and fails on any request to another origin and on any CSP violation (a blocked request is a tool that tried to call out). It also fails when the CSP names a host, and when an id in `config.json` does not name a real page or its page still offers the tool. CI runs it on every push (`.gitea/workflows/ci.yml`), and the release workflow runs it again on the image it is about to push. + +It has teeth: fed the stock upstream image it fails with 115 findings (PyMuPDF, Pyodide and CoherentPDF from jsdelivr), and fed a misspelled disabled id it fails with "no page". + +Locally (bridged containers need no internet for it): + +```sh +docker build -t bau-pm-pdf-tools:ci . +docker build -f test/Dockerfile -t bau-pm-pdf-tools-gate:ci . +docker network create pdf-gate +docker run -d --name pdf-gate-app --network pdf-gate --network-alias pdf-tools bau-pm-pdf-tools:ci +docker run --rm --network pdf-gate bau-pm-pdf-tools-gate:ci node test/zero-hosts.mjs http://pdf-tools:8080 +docker rm -f -v pdf-gate-app && docker network rm pdf-gate +``` + +## Bumping BentoPDF + +1. Set `BENTOPDF_REF` and `BENTOPDF_COMMIT` in the `Dockerfile` to the new tag and its commit. +2. Compare the module versions BentoPDF expects (`package-lock.json` for Tesseract, `.env.production` and `src/js/utils/wasm-provider.ts` for PyMuPDF, Ghostscript and CoherentPDF, `src/js/config/editor-fonts.ts` for the editor's fonts, `src/js/config/font-mappings.ts` for the OCR font) with `vendor.lock` and `scripts/vendor.sh`, and update both together: a new version needs its integrity from the registry (`npm view @ dist.integrity`). +3. Read the diff of `scripts/generate-security-headers.mjs`, `nginx.conf` and `scripts/prepare-airgap.sh` upstream: a new directive, a new CDN or a new module layout is where a bump can break the zero-host promise. +4. Build, run the gate, and check the two disabled tools are still the only ones that need a third party. +5. Note the bump in `CHANGELOG.md`, release, and pin the new tag in bau-pm (`PDF_TOOLS_VERSION`). + +## Known upstream issues (BentoPDF v2.8.8) + +Measured on 2026-10-10 against the stock image as much as against this one, so they are upstream behaviour, not this packaging: + +- **A signature drawn in the signing tool cannot be saved.** With real touch input, pdf.js's serialisation fails (`Cannot read properties of null (reading 'serialize')`): with *Flatten PDF* on the export fails visibly, with it off pdf.js silently saves the unsigned original. A typed signature saves. +- **Flattening drops a signature on some PDFs.** BentoPDF's `flattenAnnotations` removes any annotation without an appearance stream, and on a PDF rendered by rbpdf/TCPDF (bau_pm_preflight's Vorausmass sheet) the typed signature comes back without one. On a PDF pdf-lib has re-saved once, it is kept. With flatten off, the signature stays as an annotation. + +bau_pm_preflight's tablet sign-off (its PRE-43) waits on these; see its `PLAN.md` §3.22. + +## Licence + +AGPL-3.0, as BentoPDF (`LICENSE`). The vendored modules keep their own licences; see `THIRD-PARTY.md`. diff --git a/THIRD-PARTY.md b/THIRD-PARTY.md new file mode 100644 index 0000000..4219d68 --- /dev/null +++ b/THIRD-PARTY.md @@ -0,0 +1,16 @@ +# Third-party components in the image + +The image contains BentoPDF and the modules below, unmodified, at the versions listed; the licences are as each package declares it on npm (read 2026-10-10). The source links are the corresponding source of what the image serves under `/wasm/`. + +| Component | Version | Licence | Source | +| --- | --- | --- | --- | +| BentoPDF | v2.8.8 (`f96cd4e5166f3d51393dfe9f3c440b5bb77802f1`) | AGPL-3.0 (or BentoPDF's commercial licence) | | +| PyMuPDF (WASM, `@bentopdf/pymupdf-wasm`) | 0.11.16 | AGPL-3.0-only | ; the tarball from BentoPDF's `bentopdf-airgap-bundle/` at the commit above | +| Ghostscript (WASM, `@bentopdf/gs-wasm`) | 0.1.1 | AGPL-3.0-only | ; the tarball from BentoPDF's `bentopdf-airgap-bundle/` at the commit above | +| CoherentPDF (`coherentpdf`) | 2.5.5 | AGPL-3.0-or-later | , | +| Tesseract.js (`tesseract.js`, `tesseract.js-core`) | 7.0.0 | Apache-2.0 | , | +| Tesseract language data (`@tesseract.js-data/deu`, `fra`, `ita`, `eng`) | 1.0.0 (`4.0.0_best_int`) | MIT (as published on npm) | | +| Noto Sans (OCR text layer) | noto-fonts `ffebf8c1ee449e544955a7e813c54f9b73848eac` | OFL-1.1 | | +| EmbedPDF fonts (`@embedpdf/fonts-latin`, `-arabic`, `-hebrew`) | 1.0.0 | OFL-1.1 | | + +The npm tarballs are checked against the integrity hashes in `vendor.lock`, the Noto Sans file against the SHA-256 in `scripts/vendor.sh`. diff --git a/config/config.json b/config/config.json new file mode 100644 index 0000000..d6a6d55 --- /dev/null +++ b/config/config.json @@ -0,0 +1,3 @@ +{ + "disabledTools": ["digital-sign-pdf", "timestamp-pdf"] +} diff --git a/glue/handoff.js b/glue/handoff.js new file mode 100644 index 0000000..941eaae --- /dev/null +++ b/glue/handoff.js @@ -0,0 +1,375 @@ +/* bau-pm-pdf-tools - the hand-off between bau-pm and BentoPDF's tools. + * + * Loaded by every page of this image, the PDF.js viewers' pages inside the + * tools included, as a classic script in , so it runs before BentoPDF's + * own modules. It does four things: + * + * 1. A link to this image's source on every page, because the AGPL asks the + * source of a modified version served over a network to be offered + * prominently, and BentoPDF's Simple Mode hides its own footer. + * 2. The hand-in. bau-pm's entry leaves the hand-off token in a one-minute + * cookie; it moves into sessionStorage (this tab only, gone with it), the + * cookie is deleted at once, and the file is fetched from + * /bau-pm/handoff/file and given to the tool's file input, the way a user + * picking it would. Never in a URL: a token in a redirect's Location + * header lands in every access log on the way. + * 3. The hand-back. Every BentoPDF tool saves its result the same way: a blob + * URL on an , click(), revoke. While a hand-off is active and + * may be saved, that click is caught - in the top page and in the viewer's + * frame - and offered back to bau-pm instead of the downloads folder. The + * blob is read inside click(), because the next line revokes its URL. + * 4. For the signing tool, BentoPDF's "flatten" switched on and locked, so a + * signature becomes part of the page and cannot be moved later. + * + * Nothing here talks to anything but this origin. The words of the hand-off + * come from bau-pm in the user's language; only the source link has its own. + */ +(function () { + 'use strict'; + + var KEY = 'bau-pm-handoff'; + var COOKIE = '__Host-bau_pm_handoff'; + var API = '/bau-pm/handoff'; + var SOURCE_URL = '__BAU_PM_SOURCE_URL__'; + var isTop = window.top === window; + + // --- shared state -------------------------------------------------------- + + function readState() { + try { return JSON.parse(window.sessionStorage.getItem(KEY) || 'null'); } catch (e) { return null; } + } + + function writeState(state) { + try { + if (state) { window.sessionStorage.setItem(KEY, JSON.stringify(state)); } else { window.sessionStorage.removeItem(KEY); } + } catch (e) { /* storage blocked: the hand-off lasts this page only */ } + } + + function ready(fn) { + if (document.readyState !== 'loading') { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } + } + + function fill(text, values) { + return String(text || '').replace(/%\{(\w+)\}/g, function (m, key) { + return values && values[key] != null ? values[key] : m; + }); + } + + // --- 3. the hand-back, installed first and in every window --------------- + + var nativeClick = HTMLAnchorElement.prototype.click; + HTMLAnchorElement.prototype.click = function () { + var api = null; + try { api = window.top.bauPmHandoff; } catch (e) { api = null; } + if (api && api.catches() && this.hasAttribute('download') && /^blob:/.test(this.href)) { + // Started synchronously: fetch() resolves the blob URL now, before the + // caller's revokeObjectURL on the next line. + var name = this.download; + var blob = window.fetch(this.href).then(function (r) { return r.blob(); }); + api.offer(blob, name); + return undefined; + } + return nativeClick.apply(this, arguments); + }; + + if (!isTop) { + signFrame(); + return; + } + + // --- 1. the source link -------------------------------------------------- + + var LANG = (window.location.pathname.split('/')[1] || 'en').slice(0, 2); + var SOURCE_LABEL = { de: 'Quelltext (AGPL-3.0)', fr: 'Code source (AGPL-3.0)', it: 'Codice sorgente (AGPL-3.0)' }[LANG] || + 'Source code (AGPL-3.0)'; + + var CSS = [ + '.bau-pm-source{position:fixed;left:8px;bottom:8px;z-index:2147483000;font:12px/1.4 system-ui,sans-serif;', + 'color:#d1d5db;background:rgba(17,24,39,.85);padding:2px 8px;border-radius:4px;text-decoration:none}', + '.bau-pm-source:hover,.bau-pm-source:focus{color:#fff;text-decoration:underline}', + '.bau-pm-bar{position:sticky;top:0;z-index:2147483001;display:flex;gap:12px;align-items:center;', + 'padding:10px 14px;background:#111827;color:#f9fafb;border-bottom:3px solid #F28E00;font:15px/1.4 system-ui,sans-serif}', + '.bau-pm-bar span{flex:1;min-width:0;overflow-wrap:anywhere}', + '.bau-pm-bar button,.bau-pm-sheet button,.bau-pm-sheet a{font:inherit;min-height:44px;padding:8px 16px;border-radius:6px;cursor:pointer}', + '.bau-pm-bar button{background:transparent;color:#f9fafb;border:1px solid #6b7280}', + '.bau-pm-scrim{position:fixed;inset:0;z-index:2147483002;background:rgba(0,0,0,.55);display:flex;align-items:flex-end;justify-content:center}', + '.bau-pm-sheet{width:100%;max-width:560px;background:#111827;color:#f9fafb;border-radius:12px 12px 0 0;', + 'padding:20px;display:flex;flex-direction:column;gap:12px;font:16px/1.4 system-ui,sans-serif;box-sizing:border-box}', + '.bau-pm-sheet p{margin:0;overflow-wrap:anywhere}', + '.bau-pm-sheet .bau-pm-primary{background:#F28E00;color:#1a1a1a;border:0;font-weight:600}', + '.bau-pm-sheet .bau-pm-secondary{background:transparent;color:#f9fafb;border:1px solid #6b7280;text-align:center;text-decoration:none}', + '.bau-pm-sheet .bau-pm-error{color:#fca5a5}' + ].join(''); + + ready(function () { + var style = document.createElement('style'); + style.textContent = CSS; + document.head.appendChild(style); + var link = document.createElement('a'); + link.className = 'bau-pm-source'; + link.href = SOURCE_URL; + link.rel = 'noopener'; + link.target = '_blank'; + link.textContent = SOURCE_LABEL; + document.body.appendChild(link); + }); + + // --- 2. the hand-in ------------------------------------------------------ + + var match = new RegExp('(?:^|;\\s*)' + COOKIE + '=([^;]+)').exec(document.cookie); + if (match) { + writeState({ token: decodeURIComponent(match[1].replace(/\+/g, ' ')) }); + document.cookie = COOKIE + '=; Max-Age=0; Path=/; Secure; SameSite=Strict'; + } + + var state = readState(); + var meta = null; + var receipt = null; + var file = null; + var settle = null; + // Resolves with the meta once it is here, or null when there is none. A + // save clicked before that - BentoPDF reloads the page once when its service + // worker first takes control, and the glue fetches the meta again - waits + // for it instead of slipping through as a plain download. + var metaReady = new Promise(function (resolve) { settle = resolve; }); + + window.bauPmHandoff = { + catches: function () { return meta ? !!meta.writable : !!(state && state.token); }, + offer: function (blob, name) { + metaReady.then(function (ready) { + // Not to be saved back: an ordinary download, unless the hand-off + // offers none either (the Vorausmass), when the result goes nowhere. + if (ready && ready.writable) { offer(blob, name); } else if (!ready || ready.download) { save(blob, name); } + }); + } + }; + + // A plain download, for a result that is not to be offered back. + function save(blobPromise, name) { + blobPromise.then(function (blob) { + var a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = name; + nativeClick.call(a); + window.setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000); + }); + } + + if (!state || !state.token) { settle(null); return; } + + function call(path, options) { + options = options || {}; + options.headers = options.headers || {}; + options.headers.Authorization = 'Bearer ' + state.token; + options.credentials = 'same-origin'; + options.cache = 'no-store'; + return window.fetch(API + path, options); + } + + function end() { + writeState(null); + state = null; + meta = null; + settle(null); + var bar = document.querySelector('.bau-pm-bar'); + if (bar) { bar.remove(); } + } + + call('/meta').then(function (response) { + if (!response.ok) { throw new Error(String(response.status)); } + return response.json(); + }).then(function (data) { + meta = data; + settle(data); + return call('/file'); + }).then(function (response) { + if (!response.ok) { throw new Error(String(response.status)); } + receipt = response.headers.get('X-Bau-Pm-Receipt'); + return response.blob(); + }).then(function (blob) { + file = new File([blob], meta.filename, { type: 'application/pdf' }); + ready(function () { banner(); feed(); lockFlatten(); }); + }).catch(function () { + // An expired or foreign token, or a file that is gone: nothing to hand + // over, and nothing to say that the gate's own page would not say better. + end(); + }); + + function banner() { + var bar = document.createElement('div'); + bar.className = 'bau-pm-bar'; + bar.setAttribute('role', 'status'); + var text = document.createElement('span'); + var values = { filename: meta.filename, title: meta.title }; + text.textContent = fill(meta.strings.banner, values) + + (document.querySelector('input[type=file]') ? '' : ' - ' + meta.strings.pick); + var close = document.createElement('button'); + close.type = 'button'; + close.textContent = meta.strings.dismiss; + close.addEventListener('click', end); + bar.appendChild(text); + bar.appendChild(close); + document.body.insertBefore(bar, document.body.firstChild); + } + + // The tool's own input, once per page and only while it is empty: picking + // another file by hand always wins. + // + // After the page's load event, and confirmed: BentoPDF attaches a tool's + // change listener from a module it imports after load, so a change + // dispatched too early reaches nobody - which is what happened once its + // service worker served the page from cache and this file's own fetches + // won the race. So the feed watches for the tool's reaction (new nodes in + // the page that are not ours) and dispatches again if there is none, a few + // times at most, with time enough between tries that a slow tool is not + // handed the file twice. + function feed() { + var tries = 0; + function ours(node) { + var el = node.nodeType === 1 ? node : node.parentElement; + return !!(el && el.closest && el.closest('.bau-pm-bar, .bau-pm-source, .bau-pm-scrim')); + } + function attempt() { + var input = document.querySelector('input[type=file]'); + if (!input || !/pdf/i.test(input.accept || 'pdf')) { + tries += 1; + if (tries < 60) { window.setTimeout(attempt, 250); } + return; + } + if (input.files && input.files.length && input.dataset.bauPmFed !== '1') { return; } + var transfer = new DataTransfer(); + transfer.items.add(file); + input.files = transfer.files; + input.dataset.bauPmFed = '1'; + var reacted = false; + var observer = new MutationObserver(function (records) { + if (records.some(function (r) { return !ours(r.target); })) { reacted = true; observer.disconnect(); } + }); + observer.observe(document.body, { childList: true, subtree: true }); + input.dispatchEvent(new Event('change', { bubbles: true })); + window.setTimeout(function () { + observer.disconnect(); + tries += 1; + if (!reacted && tries < 5) { attempt(); } + }, 2000); + } + if (document.readyState === 'complete') { window.setTimeout(attempt, 300); } else { + window.addEventListener('load', function () { window.setTimeout(attempt, 300); }); + } + } + + // --- 4. the signing tool ------------------------------------------------- + + function lockFlatten() { + if (meta.tool !== 'sign-pdf') { return; } + var lock = function () { + var toggle = document.getElementById('flatten-signature-toggle'); + if (!toggle || toggle.dataset.bauPmLocked) { return; } + toggle.checked = true; + toggle.dispatchEvent(new Event('change', { bubbles: true })); + toggle.disabled = true; + toggle.dataset.bauPmLocked = '1'; + var row = toggle.closest('label') || toggle.parentElement; + if (row) { row.style.display = 'none'; } + }; + lock(); + new MutationObserver(lock).observe(document.body, { childList: true, subtree: true }); + } + + // Inside the viewer's frame of the signing tool: open on the last page, + // where the sheet's signature lines are. + function signFrame() { + var path = null; + try { path = window.top.bauPmHandoff && readState() ? window.top.location.pathname : null; } catch (e) { path = null; } + if (!path || !/\/sign-pdf(\.html)?$/.test(path)) { return; } + var tries = 0; + (function attempt() { + var app = window.PDFViewerApplication; + if (app && app.pdfDocument && app.pagesCount) { + app.page = app.pagesCount; + return; + } + tries += 1; + if (tries < 80) { window.setTimeout(attempt, 250); } + })(); + } + + // --- 3. the hand-back's sheet -------------------------------------------- + + function button(label, kind) { + var b = document.createElement('button'); + b.type = 'button'; + b.className = kind; + b.textContent = label; + return b; + } + + function offer(blobPromise, name) { + var values = { title: meta.title, filename: name }; + var scrim = document.createElement('div'); + scrim.className = 'bau-pm-scrim'; + var sheet = document.createElement('div'); + sheet.className = 'bau-pm-sheet'; + sheet.setAttribute('role', 'dialog'); + sheet.setAttribute('aria-modal', 'true'); + var message = document.createElement('p'); + message.textContent = name; + var save = button(fill(meta.strings.save, values), 'bau-pm-primary'); + sheet.appendChild(message); + sheet.appendChild(save); + + if (meta.download) { + var download = button(meta.strings.download, 'bau-pm-secondary'); + download.addEventListener('click', function () { + save(blobPromise, name); + scrim.remove(); + }); + sheet.appendChild(download); + } + + var close = button(meta.strings.dismiss, 'bau-pm-secondary'); + close.addEventListener('click', function () { scrim.remove(); }); + sheet.appendChild(close); + + save.addEventListener('click', function () { + save.disabled = true; + save.textContent = meta.strings.saving; + blobPromise.then(function (blob) { + return call('/file', { + method: 'POST', + body: blob, + headers: { 'Content-Type': 'application/pdf', 'X-Bau-Pm-Receipt': receipt || '' } + }); + }).then(function (response) { + return response.json().then(function (body) { return { ok: response.ok, body: body }; }); + }).then(function (result) { + if (!result.ok) { throw new Error(result.body.error || ''); } + if (result.body.next_url) { + writeState(null); + window.location.assign(result.body.next_url); + return; + } + message.textContent = result.body.notice || meta.strings.saved; + save.remove(); + if (result.body.back_url) { + var back = document.createElement('a'); + back.className = 'bau-pm-primary'; + back.href = result.body.back_url; + back.textContent = fill(meta.strings.back, values); + back.style.textAlign = 'center'; + back.style.textDecoration = 'none'; + sheet.insertBefore(back, sheet.children[1] || null); + } + }).catch(function (error) { + message.className = 'bau-pm-error'; + message.textContent = fill(meta.strings.failed, { error: error.message }); + save.disabled = false; + save.textContent = meta.strings.retry; + }); + }); + + scrim.appendChild(sheet); + document.body.appendChild(scrim); + save.focus(); + } +})(); diff --git a/scripts/finish.sh b/scripts/finish.sh new file mode 100755 index 0000000..955db0b --- /dev/null +++ b/scripts/finish.sh @@ -0,0 +1,45 @@ +#!/bin/sh +# What this repository adds to BentoPDF's finished build, run in the +# Dockerfile's builder stage after `npm run build`: +# +# finish.sh +# +# 1. a ' + +pages=$(find "$dist" -name '*.html' | wc -l) +[ "$pages" -gt 100 ] || { echo "finish: only $pages pages in $dist" >&2; exit 1; } + +find "$dist" -name '*.html' | while read -r page; do + grep -q '' "$page" || { echo "finish: $page has no " >&2; exit 1; } + sed -i "s##$tag#" "$page" + rm -f "$page.gz" "$page.br" + gzip -9 -k -n "$page" +done +# find -exec rather than grep --include, which busybox's grep does not know. +tagged=$(find "$dist" -name '*.html' -exec grep -lF "$tag" {} + | wc -l) +[ "$tagged" -eq "$pages" ] || { echo "finish: $tagged of $pages pages carry the tag" >&2; exit 1; } +stale=$(find "$dist" -name '*.html.br' | wc -l) +[ "$stale" -eq 0 ] || { echo "finish: $stale brotli copies left" >&2; exit 1; } + +for conf in security-headers.conf security-headers-docs.conf; do + sed -E -i 's# https?:(//[^ ;"]*)?##g' "$app/$conf" + if grep -Eq 'https?:' "$app/$conf"; then + echo "finish: $conf still names a host:" >&2 + grep -Eo 'https?:[^ ;"]*' "$app/$conf" >&2 + exit 1 + fi +done + +echo "finish: $tagged pages tagged, CSP without hosts" diff --git a/scripts/vendor.sh b/scripts/vendor.sh new file mode 100755 index 0000000..d0be3fb --- /dev/null +++ b/scripts/vendor.sh @@ -0,0 +1,101 @@ +#!/bin/sh +# Lays out every module BentoPDF would otherwise fetch from a CDN under one +# directory, in the layout BentoPDF's own air-gap setup produces +# (scripts/prepare-airgap.sh upstream, its generated setup.sh). Runs in the +# Dockerfile's vendor stage. +# +# vendor.sh +# +# Every package comes through `npm pack --json`, which verifies the tarball +# against the registry; this script then compares that integrity with the one +# committed in vendor.lock and fails the build on any difference, so a package +# cannot change under a pinned version unnoticed. A missing input fails too: +# nothing here skips. +set -eu + +src=$1 +lock=$2 +out=$3 + +OCR_FONT_URL=https://rawcdn.githack.com/googlefonts/noto-fonts/ffebf8c1ee449e544955a7e813c54f9b73848eac/hinted/ttf/NotoSans/NotoSans-Regular.ttf +OCR_FONT_SHA256=b85c38ecea8a7cfb39c24e395a4007474fa5a4fc864f6ee33309eb4948d232d5 + +work=$(mktemp -d) +mkdir -p "$out/pymupdf" "$out/gs" "$out/cpdf" "$out/ocr/core" "$out/ocr/lang-data" \ + "$out/ocr/fonts" "$out/embedpdf" + +# Packs one spec into $work and checks it against the lock. Prints the tarball. +# Always called as an assignment (t=$(pack ...)): an exit inside a command +# substitution only ends the subshell, and only an assignment hands its status +# to `set -e`. +pack() { + spec=$1 + want=$(awk -v s="$spec" '$1 == s { print $2 }' "$lock") + [ -n "$want" ] || { echo "vendor: $spec is not in $lock" >&2; exit 1; } + json=$(cd "$work" && npm pack --json --silent "$spec") + got=$(printf '%s' "$json" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const p=JSON.parse(s)[0];process.stdout.write(p.integrity+"\t"+p.filename)})') + [ "${got%% *}" = "$want" ] || { + echo "vendor: $spec integrity ${got%% *} differs from the lock's $want" >&2 + exit 1 + } + echo "$work/${got#* }" +} + +# Unpacks a tarball's package/ into a directory. +unpack() { + tarball=$1 sub=$2 dest=$3 + tmp=$(mktemp -d) + tar -xzf "$tarball" -C "$tmp" + [ -e "$tmp/package/$sub" ] || { echo "vendor: $tarball has no package/$sub" >&2; exit 1; } + cp -R "$tmp/package/$sub"/. "$dest"/ + rm -rf "$tmp" +} + +# PyMuPDF and Ghostscript ship inside BentoPDF's repository, at the pinned commit. +set -- "$src"/bentopdf-airgap-bundle/bentopdf-pymupdf-wasm-*.tgz +[ -f "$1" ] || { echo "vendor: no PyMuPDF tarball in $src/bentopdf-airgap-bundle" >&2; exit 1; } +unpack "$1" . "$out/pymupdf" +set -- "$src"/bentopdf-airgap-bundle/bentopdf-gs-wasm-*.tgz +[ -f "$1" ] || { echo "vendor: no Ghostscript tarball in $src/bentopdf-airgap-bundle" >&2; exit 1; } +# Two loaders read this one directory: BentoPDF's own wants gs.js and gs.wasm +# at its root (upstream's air-gap layout copies only assets/), PyMuPDF's wrapper +# wants the package's dist/index.js under it - pdf-to-docx asked for +# /wasm/gs/dist/index.js and got a 404. The whole package, plus links at the +# root, serves both from one copy. +unpack "$1" . "$out/gs" +ln -s assets/gs.js "$out/gs/gs.js" +ln -s assets/gs.wasm "$out/gs/gs.wasm" + +t=$(pack coherentpdf@2.5.5) +unpack "$t" dist "$out/cpdf" + +tmp=$(mktemp -d) +t=$(pack tesseract.js@7.0.0) +tar -xzf "$t" -C "$tmp" +cp "$tmp/package/dist/worker.min.js" "$out/ocr/worker.min.js" +rm -rf "$tmp" +t=$(pack tesseract.js-core@7.0.0) +unpack "$t" . "$out/ocr/core" +for lang in deu fra ita eng; do + tmp=$(mktemp -d) + t=$(pack "@tesseract.js-data/$lang@1.0.0") + tar -xzf "$t" -C "$tmp" + cp "$tmp/package/4.0.0_best_int/$lang.traineddata.gz" "$out/ocr/lang-data/" + rm -rf "$tmp" +done + +wget -q -O "$out/ocr/fonts/NotoSans-Regular.ttf" "$OCR_FONT_URL" +echo "$OCR_FONT_SHA256 $out/ocr/fonts/NotoSans-Regular.ttf" | sha256sum -c -s || { + echo "vendor: the OCR font's checksum differs from $OCR_FONT_SHA256" >&2 + exit 1 +} + +# The PDF editor asks for /fonts-latin@1.0.0/fonts/NotoSans-Regular.ttf. +for pkg in latin arabic hebrew; do + mkdir -p "$out/embedpdf/fonts-$pkg@1.0.0" + t=$(pack "@embedpdf/fonts-$pkg@1.0.0") + unpack "$t" . "$out/embedpdf/fonts-$pkg@1.0.0" +done + +rm -rf "$work" +echo "vendor: $(find "$out" -type f | wc -l) files, $(du -sh "$out" | cut -f1)" diff --git a/test/Dockerfile b/test/Dockerfile new file mode 100644 index 0000000..fd59df4 --- /dev/null +++ b/test/Dockerfile @@ -0,0 +1,13 @@ +# The gate's own image (test/zero-hosts.mjs): Chromium and playwright-core, +# with the test files and the glue baked in, because the CI runner passes the +# host's Docker socket through and a mounted workspace would be empty. +FROM public.ecr.aws/docker/library/node:20-alpine +RUN apk add --no-cache chromium +WORKDIR /gate +RUN npm init -y >/dev/null && npm install --no-audit --no-fund --silent playwright-core@1.63.0 +COPY test/ ./test/ +COPY glue/ ./glue/ +RUN node --check glue/handoff.js +ENV PLAYWRIGHT_CORE=/gate/node_modules/playwright-core/index.mjs \ + CHROMIUM=/usr/bin/chromium-browser +CMD ["node", "test/zero-hosts.mjs"] diff --git a/test/fixtures/probe.pdf b/test/fixtures/probe.pdf new file mode 100644 index 0000000..7b29105 --- /dev/null +++ b/test/fixtures/probe.pdf @@ -0,0 +1,30 @@ +%PDF-1.4 +1 0 obj +<> +endobj +2 0 obj +<> +endobj +3 0 obj +<>>>>> +endobj +4 0 obj +<>stream +BT /F1 24 Tf 72 760 Td (Regierapport Probe) Tj ET +endstream +endobj +5 0 obj +<> +endobj +xref +0 6 +0000000000 65535 f +0000000009 00000 n +0000000054 00000 n +0000000105 00000 n +0000000217 00000 n +0000000313 00000 n +trailer<> +startxref +376 +%%EOF diff --git a/test/fixtures/probe.png b/test/fixtures/probe.png new file mode 100644 index 0000000..bf99d1a Binary files /dev/null and b/test/fixtures/probe.png differ diff --git a/test/zero-hosts.mjs b/test/zero-hosts.mjs new file mode 100644 index 0000000..422b983 --- /dev/null +++ b/test/zero-hosts.mjs @@ -0,0 +1,139 @@ +// The gate this repository exists for (bau-pm PLAN.md §2.50, decision 2): a +// page of the PDF tools may talk to its own origin and to nobody else. +// +// node test/zero-hosts.mjs [chromium-path] +// +// 1. The Content-Security-Policy of the start page names no host. +// 2. Every id config.json disables names a real page, and that page offers +// no tool. +// 3. Every tool page linked from the German overview is opened in a phone-sized +// Chromium, given a probe file its input accepts, and its main button +// pressed. Any request to another origin fails the gate, and so does any CSP +// violation, because a blocked request is a tool that tried to call out. +// +// Exits 0 when nothing left the origin, 1 otherwise, 2 when it could not run. +// Fed the stock upstream image once, it must fail (see README, "The gate"). +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = dirname(fileURLToPath(import.meta.url)); +const base = (process.argv[2] || '').replace(/\/$/, ''); +const executablePath = process.argv[3] || process.env.CHROMIUM || '/usr/bin/chromium'; +if (!base) { + console.error('usage: zero-hosts.mjs [chromium]'); + process.exit(2); +} + +const { chromium } = await import(process.env.PLAYWRIGHT_CORE || 'playwright-core'); +const origin = new URL(base).origin; +const probes = { + pdf: readFileSync(join(here, 'fixtures/probe.pdf')), + png: readFileSync(join(here, 'fixtures/probe.png')), +}; +const failures = []; + +// --- 1. the header ----------------------------------------------------------- +const head = await fetch(`${base}/de/`); +const csp = head.headers.get('content-security-policy') || ''; +if (!csp) failures.push('start page: no Content-Security-Policy'); +for (const host of csp.match(/https?:[^\s;]*/g) || []) { + failures.push(`CSP names a host: ${host}`); +} + +// --- 2. the disabled tools exist, and are disabled ---------------------------- +// A misspelled id in config.json disables nothing and says nothing (found on +// the first run: `digital-sign` for the page digital-sign-pdf.html), so every +// id must name a real page, and that page must not offer its tool. +const config = await (await fetch(`${base}/config.json`)).json(); +const disabled = config.disabledTools || []; +if (disabled.length === 0) failures.push('config.json disables no tool'); + +// --- 3. every tool ----------------------------------------------------------- +// The origin counts as secure even over plain HTTP on a CI network, so the +// page is cross-origin isolated as it is behind TLS in production, and the +// Office tools run the code they run there rather than a fallback. +const browser = await chromium.launch({ + executablePath, + args: ['--no-sandbox', `--unsafely-treat-insecure-origin-as-secure=${origin}`], +}); +const overview = await browser.newPage(); +await overview.goto(`${base}/de/`, { waitUntil: 'networkidle' }); +const tools = [...new Set(await overview.$$eval('a[href$=".html"]', (links) => + links.map((a) => new URL(a.href, location.href)).filter((u) => u.origin === location.origin) + .map((u) => u.pathname).filter((p) => p.startsWith('/de/'))))].sort(); +await overview.close(); +for (const id of disabled) { + const page = await browser.newPage(); + const response = await page.goto(`${base}/de/${id}.html`, { waitUntil: 'networkidle' }); + if (!response || response.status() !== 200) failures.push(`disabled tool ${id}: no page /de/${id}.html`); + else if (await page.$('input[type=file]:visible')) failures.push(`disabled tool ${id}: still offers its file input`); + if (tools.includes(`/de/${id}.html`)) failures.push(`disabled tool ${id}: still linked from the overview`); + await page.close(); +} +if (tools.length < 50) failures.push(`only ${tools.length} tool pages found on /de/`); + +function probeFor(accept) { + if (/pdf/i.test(accept)) return { name: 'probe.pdf', mimeType: 'application/pdf', buffer: probes.pdf }; + if (/image|png|jpe?g/i.test(accept)) return { name: 'probe.png', mimeType: 'image/png', buffer: probes.png }; + return null; +} + +async function run(path) { + const context = await browser.newContext({ viewport: { width: 412, height: 915 }, isMobile: true, hasTouch: true }); + await context.addInitScript(() => { + window.__violations = []; + document.addEventListener('securitypolicyviolation', (e) => + window.__violations.push(`${e.violatedDirective} ${e.blockedURI}`)); + }); + const page = await context.newPage(); + const outside = new Set(); + page.on('request', (request) => { + const url = request.url(); + if (/^(data|blob|about):/.test(url)) return; + if (new URL(url).origin !== origin) outside.add(url); + }); + page.on('dialog', (dialog) => dialog.dismiss().catch(() => {})); + try { + await page.goto(base + path, { waitUntil: 'networkidle', timeout: 30000 }); + const input = await page.$('input[type=file]'); + const file = input && probeFor((await input.getAttribute('accept')) || ''); + if (file) { + await input.setInputFiles(file); + await page.waitForTimeout(2500); + const button = await page.$('#process-btn:visible'); + if (button) { + await button.click({ timeout: 5000 }).catch(() => {}); + await page.waitForTimeout(5000); + } + } + await page.waitForLoadState('networkidle', { timeout: 15000 }).catch(() => {}); + const violations = await page.evaluate(() => window.__violations); + for (const v of violations) failures.push(`${path}: CSP violation ${v}`); + } catch (error) { + // A page that cannot be driven is not a leak; it is reported, not failed. + console.log(` note ${path}: ${error.message.split('\n')[0]}`); + } + for (const url of outside) failures.push(`${path}: request to ${url}`); + await context.close(); + return outside.size; +} + +let done = 0; +const queue = [...tools]; +await Promise.all(Array.from({ length: 4 }, async () => { + while (queue.length) { + const path = queue.shift(); + await run(path); + done += 1; + } +})); +await browser.close(); + +console.log(`zero-hosts: ${done} tool pages driven against ${origin}, CSP: ${csp ? 'present' : 'missing'}`); +if (failures.length) { + for (const f of [...new Set(failures)]) console.log(` FAIL ${f}`); + console.log(`zero-hosts: ${new Set(failures).size} failure(s)`); + process.exit(1); +} +console.log('zero-hosts: nothing left the origin'); diff --git a/vendor.lock b/vendor.lock new file mode 100644 index 0000000..0529a7b --- /dev/null +++ b/vendor.lock @@ -0,0 +1,23 @@ +# Every module BentoPDF would otherwise load from cdn.jsdelivr.net at runtime, +# pinned by version and by the registry's integrity hash. The Dockerfile's +# vendor stage packs each one with `npm pack --json` and refuses the build when +# the integrity it receives differs from the one written here. One line per +# package: . +# +# PyMuPDF (@bentopdf/pymupdf-wasm 0.11.16) and Ghostscript (@bentopdf/gs-wasm +# 0.1.1) are not listed: BentoPDF ships both tarballs in its own repository +# (bentopdf-airgap-bundle/), so they come from the pinned commit. +# +# Left out on purpose: the CJK fallback fonts of the PDF editor +# (@embedpdf/fonts-jp, -kr, -sc, -tc, 30 to 42 MB each). A document that needs +# them asks this server and gets a 404, never a third party. +coherentpdf@2.5.5 sha512-AAD3RG7lq2n34AtH352sbNDhJ82yfp2vFUp63/+Vu7snAqW0vyvY33XuhZdj6ubZUlFe1DNSSEaYcyc7+jTJ5Q== +tesseract.js@7.0.0 sha512-exPBkd+z+wM1BuMkx/Bjv43OeLBxhL5kKWsz/9JY+DXcXdiBjiAch0V49QR3oAJqCaL5qURE0vx9Eo+G5YE7mA== +tesseract.js-core@7.0.0 sha512-WnNH518NzmbSq9zgTPeoF8c+xmilS8rFIl1YKbk/ptuuc7p6cLNELNuPAzcmsYw450ca6bLa8j3t0VAtq435Vw== +@tesseract.js-data/deu@1.0.0 sha512-3ter1p2gFAiCd5CMC+PodZ9YY2UDomkKj+ytlKeeZqOUmhLx1SDnYPf5zog0g5MBbxYveW+8omI3PUflqHfZ4Q== +@tesseract.js-data/fra@1.0.0 sha512-pp58gMaoyidoBBLd5y5rnf0WW0Y1994QrGqZrYatITqIU/AReUJMykD+YY3JDgvnmgz7uAx1UmhjjuyEmV8JEA== +@tesseract.js-data/ita@1.0.0 sha512-Sx19NVYve5VAxEBDL6CWTX+evlvzV+iAS5ejJywcHVsmir/C9Tzw2fExoh97QFc06t48tYZA8VrMobsBzMAEhA== +@tesseract.js-data/eng@1.0.0 sha512-mbTumm6KQPUHyzTPQaF3ObXYnx0SqqfV2nabqFVQBwD6Kl7PhGSLSzOlfFTWy0P3BjghaSKA2W9GB19Jk+ZcTg== +@embedpdf/fonts-latin@1.0.0 sha512-LLYysdr8O6sRNzhmW3PbF3AeA8xnqvOi4XLFfIfNlW5uEZ+qsJdcfd78Q78sFJMhlaOAYFMziMMsnOzmx463rA== +@embedpdf/fonts-arabic@1.0.0 sha512-SnGvQb+LwPZQO2WjjvlmXrJZolJUfLYbLZQSaYUw1vrQyMyJKT4LewvJGG+hZ+Yz2fz7OMIQ+4Gc98mGODZtOg== +@embedpdf/fonts-hebrew@1.0.0 sha512-5HVAKGL7VqPeTxxADDrSqAFBxfmAXdP8fIqrPwJIKkqdK2643bOer8CqnnpO3/nPoFhkzxhttWMB9BGiqSW62w==